kernel: Remove numerous #include <sys/thread2.h>.
[dragonfly.git] / sys / vfs / nfs / nfs_vnops.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  * 3. 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  *      @(#)nfs_vnops.c 8.16 (Berkeley) 5/27/95
33  * $FreeBSD: src/sys/nfs/nfs_vnops.c,v 1.150.2.5 2001/12/20 19:56:28 dillon Exp $
34  */
35
36
37 /*
38  * vnode op calls for Sun NFS version 2 and 3
39  */
40
41 #include "opt_inet.h"
42
43 #include <sys/param.h>
44 #include <sys/kernel.h>
45 #include <sys/systm.h>
46 #include <sys/resourcevar.h>
47 #include <sys/proc.h>
48 #include <sys/mount.h>
49 #include <sys/buf.h>
50 #include <sys/malloc.h>
51 #include <sys/mbuf.h>
52 #include <sys/namei.h>
53 #include <sys/nlookup.h>
54 #include <sys/socket.h>
55 #include <sys/vnode.h>
56 #include <sys/dirent.h>
57 #include <sys/fcntl.h>
58 #include <sys/lockf.h>
59 #include <sys/stat.h>
60 #include <sys/sysctl.h>
61 #include <sys/conf.h>
62
63 #include <vm/vm.h>
64 #include <vm/vm_extern.h>
65
66 #include <sys/buf2.h>
67
68 #include <vfs/fifofs/fifo.h>
69 #include <vfs/ufs/dir.h>
70
71 #undef DIRBLKSIZ
72
73 #include "rpcv2.h"
74 #include "nfsproto.h"
75 #include "nfs.h"
76 #include "nfsmount.h"
77 #include "nfsnode.h"
78 #include "xdr_subs.h"
79 #include "nfsm_subs.h"
80
81 #include <net/if.h>
82 #include <netinet/in.h>
83 #include <netinet/in_var.h>
84
85 /* Defs */
86 #define TRUE    1
87 #define FALSE   0
88
89 static int      nfsfifo_read (struct vop_read_args *);
90 static int      nfsfifo_write (struct vop_write_args *);
91 static int      nfsfifo_close (struct vop_close_args *);
92 static int      nfs_setattrrpc (struct vnode *,struct vattr *,struct ucred *,struct thread *);
93 static  int     nfs_lookup (struct vop_old_lookup_args *);
94 static  int     nfs_create (struct vop_old_create_args *);
95 static  int     nfs_mknod (struct vop_old_mknod_args *);
96 static  int     nfs_open (struct vop_open_args *);
97 static  int     nfs_close (struct vop_close_args *);
98 static  int     nfs_access (struct vop_access_args *);
99 static  int     nfs_getattr (struct vop_getattr_args *);
100 static  int     nfs_setattr (struct vop_setattr_args *);
101 static  int     nfs_read (struct vop_read_args *);
102 static  int     nfs_mmap (struct vop_mmap_args *);
103 static  int     nfs_fsync (struct vop_fsync_args *);
104 static  int     nfs_remove (struct vop_old_remove_args *);
105 static  int     nfs_link (struct vop_old_link_args *);
106 static  int     nfs_rename (struct vop_old_rename_args *);
107 static  int     nfs_mkdir (struct vop_old_mkdir_args *);
108 static  int     nfs_rmdir (struct vop_old_rmdir_args *);
109 static  int     nfs_symlink (struct vop_old_symlink_args *);
110 static  int     nfs_readdir (struct vop_readdir_args *);
111 static  int     nfs_bmap (struct vop_bmap_args *);
112 static  int     nfs_strategy (struct vop_strategy_args *);
113 static  int     nfs_lookitup (struct vnode *, const char *, int,
114                         struct ucred *, struct thread *, struct nfsnode **);
115 static  int     nfs_sillyrename (struct vnode *,struct vnode *,struct componentname *);
116 static int      nfs_laccess (struct vop_access_args *);
117 static int      nfs_readlink (struct vop_readlink_args *);
118 static int      nfs_print (struct vop_print_args *);
119 static int      nfs_advlock (struct vop_advlock_args *);
120 static int      nfs_kqfilter (struct vop_kqfilter_args *ap);
121
122 static  int     nfs_nresolve (struct vop_nresolve_args *);
123 /*
124  * Global vfs data structures for nfs
125  */
126 struct vop_ops nfsv2_vnode_vops = {
127         .vop_default =          vop_defaultop,
128         .vop_access =           nfs_access,
129         .vop_advlock =          nfs_advlock,
130         .vop_bmap =             nfs_bmap,
131         .vop_close =            nfs_close,
132         .vop_old_create =       nfs_create,
133         .vop_fsync =            nfs_fsync,
134         .vop_getattr =          nfs_getattr,
135         .vop_getpages =         vop_stdgetpages,
136         .vop_putpages =         vop_stdputpages,
137         .vop_inactive =         nfs_inactive,
138         .vop_old_link =         nfs_link,
139         .vop_old_lookup =       nfs_lookup,
140         .vop_old_mkdir =        nfs_mkdir,
141         .vop_old_mknod =        nfs_mknod,
142         .vop_mmap =             nfs_mmap,
143         .vop_open =             nfs_open,
144         .vop_print =            nfs_print,
145         .vop_read =             nfs_read,
146         .vop_readdir =          nfs_readdir,
147         .vop_readlink =         nfs_readlink,
148         .vop_reclaim =          nfs_reclaim,
149         .vop_old_remove =       nfs_remove,
150         .vop_old_rename =       nfs_rename,
151         .vop_old_rmdir =        nfs_rmdir,
152         .vop_setattr =          nfs_setattr,
153         .vop_strategy =         nfs_strategy,
154         .vop_old_symlink =      nfs_symlink,
155         .vop_write =            nfs_write,
156         .vop_nresolve =         nfs_nresolve,
157         .vop_kqfilter =         nfs_kqfilter
158 };
159
160 /*
161  * Special device vnode ops
162  */
163 struct vop_ops nfsv2_spec_vops = {
164         .vop_default =          vop_defaultop,
165         .vop_access =           nfs_laccess,
166         .vop_close =            nfs_close,
167         .vop_fsync =            nfs_fsync,
168         .vop_getattr =          nfs_getattr,
169         .vop_inactive =         nfs_inactive,
170         .vop_print =            nfs_print,
171         .vop_read =             vop_stdnoread,
172         .vop_reclaim =          nfs_reclaim,
173         .vop_setattr =          nfs_setattr,
174         .vop_write =            vop_stdnowrite
175 };
176
177 struct vop_ops nfsv2_fifo_vops = {
178         .vop_default =          fifo_vnoperate,
179         .vop_access =           nfs_laccess,
180         .vop_close =            nfsfifo_close,
181         .vop_fsync =            nfs_fsync,
182         .vop_getattr =          nfs_getattr,
183         .vop_inactive =         nfs_inactive,
184         .vop_print =            nfs_print,
185         .vop_read =             nfsfifo_read,
186         .vop_reclaim =          nfs_reclaim,
187         .vop_setattr =          nfs_setattr,
188         .vop_write =            nfsfifo_write
189 };
190
191 static int      nfs_mknodrpc (struct vnode *dvp, struct vnode **vpp,
192                                   struct componentname *cnp,
193                                   struct vattr *vap);
194 static int      nfs_removerpc (struct vnode *dvp, const char *name,
195                                    int namelen,
196                                    struct ucred *cred, struct thread *td);
197 static int      nfs_renamerpc (struct vnode *fdvp, const char *fnameptr,
198                                    int fnamelen, struct vnode *tdvp,
199                                    const char *tnameptr, int tnamelen,
200                                    struct ucred *cred, struct thread *td);
201 static int      nfs_renameit (struct vnode *sdvp,
202                                   struct componentname *scnp,
203                                   struct sillyrename *sp);
204
205 SYSCTL_DECL(_vfs_nfs);
206
207 static int nfs_flush_on_rename = 1;
208 SYSCTL_INT(_vfs_nfs, OID_AUTO, flush_on_rename, CTLFLAG_RW, 
209            &nfs_flush_on_rename, 0, "flush fvp prior to rename");
210 static int nfs_flush_on_hlink = 0;
211 SYSCTL_INT(_vfs_nfs, OID_AUTO, flush_on_hlink, CTLFLAG_RW, 
212            &nfs_flush_on_hlink, 0, "flush fvp prior to hard link");
213
214 static int      nfsaccess_cache_timeout = NFS_DEFATTRTIMO;
215 SYSCTL_INT(_vfs_nfs, OID_AUTO, access_cache_timeout, CTLFLAG_RW, 
216            &nfsaccess_cache_timeout, 0, "NFS ACCESS cache timeout");
217
218 static int      nfsneg_cache_timeout = NFS_MINATTRTIMO;
219 SYSCTL_INT(_vfs_nfs, OID_AUTO, neg_cache_timeout, CTLFLAG_RW, 
220            &nfsneg_cache_timeout, 0, "NFS NEGATIVE NAMECACHE timeout");
221
222 static int      nfspos_cache_timeout = NFS_MINATTRTIMO;
223 SYSCTL_INT(_vfs_nfs, OID_AUTO, pos_cache_timeout, CTLFLAG_RW, 
224            &nfspos_cache_timeout, 0, "NFS POSITIVE NAMECACHE timeout");
225
226 static int      nfsv3_commit_on_close = 0;
227 SYSCTL_INT(_vfs_nfs, OID_AUTO, nfsv3_commit_on_close, CTLFLAG_RW, 
228            &nfsv3_commit_on_close, 0, "write+commit on close, else only write");
229 #if 0
230 SYSCTL_INT(_vfs_nfs, OID_AUTO, access_cache_hits, CTLFLAG_RD, 
231            &nfsstats.accesscache_hits, 0, "NFS ACCESS cache hit count");
232
233 SYSCTL_INT(_vfs_nfs, OID_AUTO, access_cache_misses, CTLFLAG_RD, 
234            &nfsstats.accesscache_misses, 0, "NFS ACCESS cache miss count");
235 #endif
236
237 #define NFSV3ACCESS_ALL (NFSV3ACCESS_READ | NFSV3ACCESS_MODIFY          \
238                          | NFSV3ACCESS_EXTEND | NFSV3ACCESS_EXECUTE     \
239                          | NFSV3ACCESS_DELETE | NFSV3ACCESS_LOOKUP)
240
241 static __inline
242 void
243 nfs_knote(struct vnode *vp, int flags)
244 {
245         if (flags)
246                 KNOTE(&vp->v_pollinfo.vpi_kqinfo.ki_note, flags);
247 }
248
249 /*
250  * Returns whether a name component is a degenerate '.' or '..'.
251  */
252 static __inline
253 int
254 nlcdegenerate(struct nlcomponent *nlc)
255 {
256         if (nlc->nlc_namelen == 1 && nlc->nlc_nameptr[0] == '.')
257                 return(1);
258         if (nlc->nlc_namelen == 2 &&
259             nlc->nlc_nameptr[0] == '.' && nlc->nlc_nameptr[1] == '.')
260                 return(1);
261         return(0);
262 }
263
264 static int
265 nfs3_access_otw(struct vnode *vp, int wmode,
266                 struct thread *td, struct ucred *cred)
267 {
268         struct nfsnode *np = VTONFS(vp);
269         int attrflag;
270         int error = 0;
271         u_int32_t *tl;
272         u_int32_t rmode;
273         struct nfsm_info info;
274
275         info.mrep = NULL;
276         info.v3 = 1;
277
278         nfsstats.rpccnt[NFSPROC_ACCESS]++;
279         nfsm_reqhead(&info, vp, NFSPROC_ACCESS,
280                      NFSX_FH(info.v3) + NFSX_UNSIGNED);
281         ERROROUT(nfsm_fhtom(&info, vp));
282         tl = nfsm_build(&info, NFSX_UNSIGNED);
283         *tl = txdr_unsigned(wmode); 
284         NEGKEEPOUT(nfsm_request(&info, vp, NFSPROC_ACCESS, td, cred, &error));
285         ERROROUT(nfsm_postop_attr(&info, vp, &attrflag, NFS_LATTR_NOSHRINK));
286         if (error == 0) {
287                 NULLOUT(tl = nfsm_dissect(&info, NFSX_UNSIGNED));
288                 rmode = fxdr_unsigned(u_int32_t, *tl);
289                 np->n_mode = rmode;
290                 np->n_modeuid = cred->cr_uid;
291                 np->n_modestamp = mycpu->gd_time_seconds;
292         }
293         m_freem(info.mrep);
294         info.mrep = NULL;
295 nfsmout:
296         return error;
297 }
298
299 /*
300  * nfs access vnode op.
301  * For nfs version 2, just return ok. File accesses may fail later.
302  * For nfs version 3, use the access rpc to check accessibility. If file modes
303  * are changed on the server, accesses might still fail later.
304  *
305  * nfs_access(struct vnode *a_vp, int a_mode, struct ucred *a_cred)
306  */
307 static int
308 nfs_access(struct vop_access_args *ap)
309 {
310         struct ucred *cred;
311         struct vnode *vp = ap->a_vp;
312         thread_t td = curthread;
313         int error = 0;
314         u_int32_t mode, wmode;
315         struct nfsnode *np = VTONFS(vp);
316         struct nfsmount *nmp = VFSTONFS(vp->v_mount);
317         int v3 = NFS_ISV3(vp);
318
319         lwkt_gettoken(&nmp->nm_token);
320
321         /*
322          * Disallow write attempts on filesystems mounted read-only;
323          * unless the file is a socket, fifo, or a block or character
324          * device resident on the filesystem.
325          */
326         if ((ap->a_mode & VWRITE) && (vp->v_mount->mnt_flag & MNT_RDONLY)) {
327                 switch (vp->v_type) {
328                 case VREG:
329                 case VDIR:
330                 case VLNK:
331                         lwkt_reltoken(&nmp->nm_token);
332                         return (EROFS);
333                 default:
334                         break;
335                 }
336         }
337
338         /*
339          * The NFS protocol passes only the effective uid/gid over the wire but
340          * we need to check access against real ids if AT_EACCESS not set.
341          * Handle this case by cloning the credentials and setting the
342          * effective ids to the real ones.
343          *
344          * The crdup() here can cause a lot of ucred structures to build-up
345          * (up to maxvnodes), so do our best to avoid it.
346          */
347         if (ap->a_flags & AT_EACCESS) {
348                 cred = crhold(ap->a_cred);
349         } else {
350                 cred = ap->a_cred;
351                 if (cred->cr_uid == cred->cr_ruid &&
352                     cred->cr_gid == cred->cr_rgid) {
353                         cred = crhold(ap->a_cred);
354                 } else {
355                         cred = crdup(ap->a_cred);
356                         cred->cr_uid = cred->cr_ruid;
357                         cred->cr_gid = cred->cr_rgid;
358                 }
359         }
360
361         /*
362          * For nfs v3, check to see if we have done this recently, and if
363          * so return our cached result instead of making an ACCESS call.
364          * If not, do an access rpc, otherwise you are stuck emulating
365          * ufs_access() locally using the vattr. This may not be correct,
366          * since the server may apply other access criteria such as
367          * client uid-->server uid mapping that we do not know about.
368          */
369         if (v3) {
370                 if (ap->a_mode & VREAD)
371                         mode = NFSV3ACCESS_READ;
372                 else
373                         mode = 0;
374                 if (vp->v_type != VDIR) {
375                         if (ap->a_mode & VWRITE)
376                                 mode |= (NFSV3ACCESS_MODIFY | NFSV3ACCESS_EXTEND);
377                         if (ap->a_mode & VEXEC)
378                                 mode |= NFSV3ACCESS_EXECUTE;
379                 } else {
380                         if (ap->a_mode & VWRITE)
381                                 mode |= (NFSV3ACCESS_MODIFY | NFSV3ACCESS_EXTEND |
382                                          NFSV3ACCESS_DELETE);
383                         if (ap->a_mode & VEXEC)
384                                 mode |= NFSV3ACCESS_LOOKUP;
385                 }
386                 /* XXX safety belt, only make blanket request if caching */
387                 if (nfsaccess_cache_timeout > 0) {
388                         wmode = NFSV3ACCESS_READ | NFSV3ACCESS_MODIFY | 
389                                 NFSV3ACCESS_EXTEND | NFSV3ACCESS_EXECUTE | 
390                                 NFSV3ACCESS_DELETE | NFSV3ACCESS_LOOKUP;
391                 } else {
392                         wmode = mode;
393                 }
394
395                 /*
396                  * Does our cached result allow us to give a definite yes to
397                  * this request?
398                  */
399                 if (np->n_modestamp && 
400                    (mycpu->gd_time_seconds < (np->n_modestamp + nfsaccess_cache_timeout)) &&
401                    (cred->cr_uid == np->n_modeuid) &&
402                    ((np->n_mode & mode) == mode)) {
403                         nfsstats.accesscache_hits++;
404                 } else {
405                         /*
406                          * Either a no, or a don't know.  Go to the wire.
407                          */
408                         nfsstats.accesscache_misses++;
409                         error = nfs3_access_otw(vp, wmode, td, cred);
410                         if (!error) {
411                                 if ((np->n_mode & mode) != mode) {
412                                         error = EACCES;
413                                 }
414                         }
415                 }
416         } else {
417                 if ((error = nfs_laccess(ap)) != 0) {
418                         crfree(cred);
419                         lwkt_reltoken(&nmp->nm_token);
420                         return (error);
421                 }
422
423                 /*
424                  * Attempt to prevent a mapped root from accessing a file
425                  * which it shouldn't.  We try to read a byte from the file
426                  * if the user is root and the file is not zero length.
427                  * After calling nfs_laccess, we should have the correct
428                  * file size cached.
429                  */
430                 if (cred->cr_uid == 0 && (ap->a_mode & VREAD)
431                     && VTONFS(vp)->n_size > 0) {
432                         struct iovec aiov;
433                         struct uio auio;
434                         char buf[1];
435
436                         aiov.iov_base = buf;
437                         aiov.iov_len = 1;
438                         auio.uio_iov = &aiov;
439                         auio.uio_iovcnt = 1;
440                         auio.uio_offset = 0;
441                         auio.uio_resid = 1;
442                         auio.uio_segflg = UIO_SYSSPACE;
443                         auio.uio_rw = UIO_READ;
444                         auio.uio_td = td;
445
446                         if (vp->v_type == VREG) {
447                                 error = nfs_readrpc_uio(vp, &auio);
448                         } else if (vp->v_type == VDIR) {
449                                 char* bp;
450                                 bp = kmalloc(NFS_DIRBLKSIZ, M_TEMP, M_WAITOK);
451                                 aiov.iov_base = bp;
452                                 aiov.iov_len = auio.uio_resid = NFS_DIRBLKSIZ;
453                                 error = nfs_readdirrpc_uio(vp, &auio);
454                                 kfree(bp, M_TEMP);
455                         } else if (vp->v_type == VLNK) {
456                                 error = nfs_readlinkrpc_uio(vp, &auio);
457                         } else {
458                                 error = EACCES;
459                         }
460                 }
461         }
462         /*
463          * [re]record creds for reading and/or writing if access
464          * was granted.  Assume the NFS server will grant read access
465          * for execute requests.
466          */
467         if (error == 0) {
468                 if ((ap->a_mode & (VREAD|VEXEC)) && cred != np->n_rucred) {
469                         crhold(cred);
470                         if (np->n_rucred)
471                                 crfree(np->n_rucred);
472                         np->n_rucred = cred;
473                 }
474                 if ((ap->a_mode & VWRITE) && cred != np->n_wucred) {
475                         crhold(cred);
476                         if (np->n_wucred)
477                                 crfree(np->n_wucred);
478                         np->n_wucred = cred;
479                 }
480         }
481         lwkt_reltoken(&nmp->nm_token);
482         crfree(cred);
483
484         return(error);
485 }
486
487 /*
488  * nfs open vnode op
489  * Check to see if the type is ok
490  * and that deletion is not in progress.
491  * For paged in text files, you will need to flush the page cache
492  * if consistency is lost.
493  *
494  * nfs_open(struct vnode *a_vp, int a_mode, struct ucred *a_cred,
495  *          struct file *a_fp)
496  */
497 /* ARGSUSED */
498 static int
499 nfs_open(struct vop_open_args *ap)
500 {
501         struct vnode *vp = ap->a_vp;
502         struct nfsnode *np = VTONFS(vp);
503         struct nfsmount *nmp = VFSTONFS(vp->v_mount);
504         struct vattr vattr;
505         int error;
506
507         lwkt_gettoken(&nmp->nm_token);
508
509         if (vp->v_type != VREG && vp->v_type != VDIR && vp->v_type != VLNK) {
510 #ifdef DIAGNOSTIC
511                 kprintf("open eacces vtyp=%d\n",vp->v_type);
512 #endif
513                 lwkt_reltoken(&nmp->nm_token);
514                 return (EOPNOTSUPP);
515         }
516
517         /*
518          * Save valid creds for reading and writing for later RPCs.
519          */
520         if ((ap->a_mode & FREAD) && ap->a_cred != np->n_rucred) {
521                 crhold(ap->a_cred);
522                 if (np->n_rucred)
523                         crfree(np->n_rucred);
524                 np->n_rucred = ap->a_cred;
525         }
526         if ((ap->a_mode & FWRITE) && ap->a_cred != np->n_wucred) {
527                 crhold(ap->a_cred);
528                 if (np->n_wucred)
529                         crfree(np->n_wucred);
530                 np->n_wucred = ap->a_cred;
531         }
532
533         /*
534          * Clear the attribute cache only if opening with write access.  It
535          * is unclear if we should do this at all here, but we certainly
536          * should not clear the cache unconditionally simply because a file
537          * is being opened.
538          */
539         if (ap->a_mode & FWRITE)
540                 np->n_attrstamp = 0;
541
542         /*
543          * For normal NFS, reconcile changes made locally verses 
544          * changes made remotely.  Note that VOP_GETATTR only goes
545          * to the wire if the cached attribute has timed out or been
546          * cleared.
547          *
548          * If local modifications have been made clear the attribute
549          * cache to force an attribute and modified time check.  If
550          * GETATTR detects that the file has been changed by someone
551          * other then us it will set NRMODIFIED.
552          *
553          * If we are opening a directory and local changes have been
554          * made we have to invalidate the cache in order to ensure
555          * that we get the most up-to-date information from the
556          * server.  XXX
557          */
558         if (np->n_flag & NLMODIFIED) {
559                 np->n_attrstamp = 0;
560                 if (vp->v_type == VDIR) {
561                         error = nfs_vinvalbuf(vp, V_SAVE, 1);
562                         if (error == EINTR) {
563                                 lwkt_reltoken(&nmp->nm_token);
564                                 return (error);
565                         }
566                         nfs_invaldir(vp);
567                 }
568         }
569         error = VOP_GETATTR(vp, &vattr);
570         if (error) {
571                 lwkt_reltoken(&nmp->nm_token);
572                 return (error);
573         }
574         if (np->n_flag & NRMODIFIED) {
575                 if (vp->v_type == VDIR)
576                         nfs_invaldir(vp);
577                 error = nfs_vinvalbuf(vp, V_SAVE, 1);
578                 if (error == EINTR) {
579                         lwkt_reltoken(&nmp->nm_token);
580                         return (error);
581                 }
582                 np->n_flag &= ~NRMODIFIED;
583         }
584         error = vop_stdopen(ap);
585         lwkt_reltoken(&nmp->nm_token);
586
587         return error;
588 }
589
590 /*
591  * nfs close vnode op
592  * What an NFS client should do upon close after writing is a debatable issue.
593  * Most NFS clients push delayed writes to the server upon close, basically for
594  * two reasons:
595  * 1 - So that any write errors may be reported back to the client process
596  *     doing the close system call. By far the two most likely errors are
597  *     NFSERR_NOSPC and NFSERR_DQUOT to indicate space allocation failure.
598  * 2 - To put a worst case upper bound on cache inconsistency between
599  *     multiple clients for the file.
600  * There is also a consistency problem for Version 2 of the protocol w.r.t.
601  * not being able to tell if other clients are writing a file concurrently,
602  * since there is no way of knowing if the changed modify time in the reply
603  * is only due to the write for this client.
604  * (NFS Version 3 provides weak cache consistency data in the reply that
605  *  should be sufficient to detect and handle this case.)
606  *
607  * The current code does the following:
608  * for NFS Version 2 - play it safe and flush/invalidate all dirty buffers
609  * for NFS Version 3 - flush dirty buffers to the server but don't invalidate
610  *                     or commit them (this satisfies 1 and 2 except for the
611  *                     case where the server crashes after this close but
612  *                     before the commit RPC, which is felt to be "good
613  *                     enough". Changing the last argument to nfs_flush() to
614  *                     a 1 would force a commit operation, if it is felt a
615  *                     commit is necessary now.
616  * for NQNFS         - do nothing now, since 2 is dealt with via leases and
617  *                     1 should be dealt with via an fsync() system call for
618  *                     cases where write errors are important.
619  *
620  * nfs_close(struct vnode *a_vp, int a_fflag)
621  */
622 /* ARGSUSED */
623 static int
624 nfs_close(struct vop_close_args *ap)
625 {
626         struct vnode *vp = ap->a_vp;
627         struct nfsnode *np = VTONFS(vp);
628         struct nfsmount *nmp = VFSTONFS(vp->v_mount);
629         int error = 0;
630         thread_t td = curthread;
631
632         vn_lock(vp, LK_UPGRADE | LK_RETRY); /* XXX */
633         lwkt_gettoken(&nmp->nm_token);
634
635         if (vp->v_type == VREG) {
636             if (np->n_flag & NLMODIFIED) {
637                 if (NFS_ISV3(vp)) {
638                     /*
639                      * Under NFSv3 we have dirty buffers to dispose of.  We
640                      * must flush them to the NFS server.  We have the option
641                      * of waiting all the way through the commit rpc or just
642                      * waiting for the initial write.  The default is to only
643                      * wait through the initial write so the data is in the
644                      * server's cache, which is roughly similar to the state
645                      * a standard disk subsystem leaves the file in on close().
646                      *
647                      * We cannot clear the NLMODIFIED bit in np->n_flag due to
648                      * potential races with other processes, and certainly
649                      * cannot clear it if we don't commit.
650                      */
651                     int cm = nfsv3_commit_on_close ? 1 : 0;
652                     error = nfs_flush(vp, MNT_WAIT, td, cm);
653                     /* np->n_flag &= ~NLMODIFIED; */
654                 } else {
655                     error = nfs_vinvalbuf(vp, V_SAVE, 1);
656                 }
657                 np->n_attrstamp = 0;
658             }
659             if (np->n_flag & NWRITEERR) {
660                 np->n_flag &= ~NWRITEERR;
661                 error = np->n_error;
662             }
663         }
664         vop_stdclose(ap);
665         lwkt_reltoken(&nmp->nm_token);
666
667         return (error);
668 }
669
670 /*
671  * nfs getattr call from vfs.
672  *
673  * nfs_getattr(struct vnode *a_vp, struct vattr *a_vap)
674  */
675 static int
676 nfs_getattr(struct vop_getattr_args *ap)
677 {
678         struct vnode *vp = ap->a_vp;
679         struct nfsnode *np = VTONFS(vp);
680         struct nfsmount *nmp;
681         int error = 0;
682         thread_t td = curthread;
683         struct nfsm_info info;
684
685         info.mrep = NULL;
686         info.v3 = NFS_ISV3(vp);
687         nmp = VFSTONFS(vp->v_mount);
688
689         lwkt_gettoken(&nmp->nm_token);
690         
691         /*
692          * Update local times for special files.
693          */
694         if (np->n_flag & (NACC | NUPD))
695                 np->n_flag |= NCHG;
696         /*
697          * First look in the cache.
698          */
699         if (nfs_getattrcache(vp, ap->a_vap) == 0)
700                 goto done;
701
702         if (info.v3 && nfsaccess_cache_timeout > 0) {
703                 nfsstats.accesscache_misses++;
704                 nfs3_access_otw(vp, NFSV3ACCESS_ALL, td, nfs_vpcred(vp, ND_CHECK));
705                 if (nfs_getattrcache(vp, ap->a_vap) == 0)
706                         goto done;
707         }
708
709         nfsstats.rpccnt[NFSPROC_GETATTR]++;
710         nfsm_reqhead(&info, vp, NFSPROC_GETATTR, NFSX_FH(info.v3));
711         ERROROUT(nfsm_fhtom(&info, vp));
712         NEGKEEPOUT(nfsm_request(&info, vp, NFSPROC_GETATTR, td,
713                                 nfs_vpcred(vp, ND_CHECK), &error));
714         if (error == 0) {
715                 ERROROUT(nfsm_loadattr(&info, vp, ap->a_vap));
716         }
717         m_freem(info.mrep);
718         info.mrep = NULL;
719 done:
720         /*
721          * NFS doesn't support chflags flags.  If the nfs mount was
722          * made -o cache set the UF_CACHE bit for swapcache.
723          */
724         if ((nmp->nm_flag & NFSMNT_CACHE) && (vp->v_flag & VROOT))
725                 ap->a_vap->va_flags |= UF_CACHE;
726 nfsmout:
727         lwkt_reltoken(&nmp->nm_token);
728         return (error);
729 }
730
731 /*
732  * nfs setattr call.
733  *
734  * nfs_setattr(struct vnode *a_vp, struct vattr *a_vap, struct ucred *a_cred)
735  */
736 static int
737 nfs_setattr(struct vop_setattr_args *ap)
738 {
739         struct vnode *vp = ap->a_vp;
740         struct nfsnode *np = VTONFS(vp);
741         struct nfsmount *nmp = VFSTONFS(vp->v_mount);
742         struct vattr *vap = ap->a_vap;
743         int error = 0;
744         int kflags = 0;
745         off_t tsize;
746         thread_t td = curthread;
747
748 #ifndef nolint
749         tsize = (off_t)0;
750 #endif
751         /*
752          * Setting of flags is not supported.
753          */
754         if (vap->va_flags != VNOVAL)
755                 return (EOPNOTSUPP);
756
757         /*
758          * Disallow write attempts if the filesystem is mounted read-only.
759          */
760         if ((vap->va_flags != VNOVAL || vap->va_uid != (uid_t)VNOVAL ||
761             vap->va_gid != (gid_t)VNOVAL || vap->va_atime.tv_sec != VNOVAL ||
762             vap->va_mtime.tv_sec != VNOVAL || vap->va_mode != (mode_t)VNOVAL) &&
763             (vp->v_mount->mnt_flag & MNT_RDONLY))
764                 return (EROFS);
765
766         lwkt_gettoken(&nmp->nm_token);
767
768         if (vap->va_size != VNOVAL) {
769                 /*
770                  * truncation requested
771                  */
772                 switch (vp->v_type) {
773                 case VDIR:
774                         lwkt_reltoken(&nmp->nm_token);
775                         return (EISDIR);
776                 case VCHR:
777                 case VBLK:
778                 case VSOCK:
779                 case VFIFO:
780                         if (vap->va_mtime.tv_sec == VNOVAL &&
781                             vap->va_atime.tv_sec == VNOVAL &&
782                             vap->va_mode == (mode_t)VNOVAL &&
783                             vap->va_uid == (uid_t)VNOVAL &&
784                             vap->va_gid == (gid_t)VNOVAL) {
785                                 lwkt_reltoken(&nmp->nm_token);
786                                 return (0);
787                         }
788                         vap->va_size = VNOVAL;
789                         break;
790                 default:
791                         /*
792                          * Disallow write attempts if the filesystem is
793                          * mounted read-only.
794                          */
795                         if (vp->v_mount->mnt_flag & MNT_RDONLY) {
796                                 lwkt_reltoken(&nmp->nm_token);
797                                 return (EROFS);
798                         }
799
800                         tsize = np->n_size;
801 again:
802                         error = nfs_meta_setsize(vp, td, vap->va_size, 0);
803
804 #if 0
805                         if (np->n_flag & NLMODIFIED) {
806                             if (vap->va_size == 0)
807                                 error = nfs_vinvalbuf(vp, 0, 1);
808                             else
809                                 error = nfs_vinvalbuf(vp, V_SAVE, 1);
810                         }
811 #endif
812                         /*
813                          * note: this loop case almost always happens at 
814                          * least once per truncation.
815                          */
816                         if (error == 0 && np->n_size != vap->va_size)
817                                 goto again;
818                         np->n_vattr.va_size = vap->va_size;
819                         kflags |= NOTE_WRITE;
820                         if (tsize < vap->va_size)
821                                 kflags |= NOTE_EXTEND;
822                         break;
823                 }
824         } else if ((np->n_flag & NLMODIFIED) && vp->v_type == VREG) {
825                 /*
826                  * What to do.  If we are modifying the mtime we lose
827                  * mtime detection of changes made by the server or other
828                  * clients.  But programs like rsync/rdist/cpdup are going
829                  * to call utimes a lot.  We don't want to piecemeal sync.
830                  *
831                  * For now sync if any prior remote changes were detected,
832                  * but allow us to lose track of remote changes made during
833                  * the utimes operation.
834                  */
835                 if (np->n_flag & NRMODIFIED)
836                         error = nfs_vinvalbuf(vp, V_SAVE, 1);
837                 if (error == EINTR) {
838                         lwkt_reltoken(&nmp->nm_token);
839                         return (error);
840                 }
841                 if (error == 0) {
842                         if (vap->va_mtime.tv_sec != VNOVAL) {
843                                 np->n_mtime = vap->va_mtime.tv_sec;
844                         }
845                 }
846         }
847         error = nfs_setattrrpc(vp, vap, ap->a_cred, td);
848         if (error == 0)
849                 kflags |= NOTE_EXTEND;
850
851         /*
852          * Sanity check if a truncation was issued.  This should only occur
853          * if multiple processes are racing on the same file.
854          */
855         if (error == 0 && vap->va_size != VNOVAL && 
856             np->n_size != vap->va_size) {
857                 kprintf("NFS ftruncate: server disagrees on the file size: "
858                         "%jd/%jd/%jd\n",
859                         (intmax_t)tsize,
860                         (intmax_t)vap->va_size,
861                         (intmax_t)np->n_size);
862                 goto again;
863         }
864         if (error && vap->va_size != VNOVAL) {
865                 np->n_size = np->n_vattr.va_size = tsize;
866                 nfs_meta_setsize(vp, td, np->n_size, 0);
867         }
868         lwkt_reltoken(&nmp->nm_token);
869         nfs_knote(vp, kflags);
870
871         return (error);
872 }
873
874 /*
875  * Do an nfs setattr rpc.
876  */
877 static int
878 nfs_setattrrpc(struct vnode *vp, struct vattr *vap,
879                struct ucred *cred, struct thread *td)
880 {
881         struct nfsv2_sattr *sp;
882         struct nfsnode *np = VTONFS(vp);
883         u_int32_t *tl;
884         int error = 0, wccflag = NFSV3_WCCRATTR;
885         struct nfsm_info info;
886
887         info.mrep = NULL;
888         info.v3 = NFS_ISV3(vp);
889
890         nfsstats.rpccnt[NFSPROC_SETATTR]++;
891         nfsm_reqhead(&info, vp, NFSPROC_SETATTR,
892                      NFSX_FH(info.v3) + NFSX_SATTR(info.v3));
893         ERROROUT(nfsm_fhtom(&info, vp));
894         if (info.v3) {
895                 nfsm_v3attrbuild(&info, vap, TRUE);
896                 tl = nfsm_build(&info, NFSX_UNSIGNED);
897                 *tl = nfs_false;
898         } else {
899                 sp = nfsm_build(&info, NFSX_V2SATTR);
900                 if (vap->va_mode == (mode_t)VNOVAL)
901                         sp->sa_mode = nfs_xdrneg1;
902                 else
903                         sp->sa_mode = vtonfsv2_mode(vp->v_type, vap->va_mode);
904                 if (vap->va_uid == (uid_t)VNOVAL)
905                         sp->sa_uid = nfs_xdrneg1;
906                 else
907                         sp->sa_uid = txdr_unsigned(vap->va_uid);
908                 if (vap->va_gid == (gid_t)VNOVAL)
909                         sp->sa_gid = nfs_xdrneg1;
910                 else
911                         sp->sa_gid = txdr_unsigned(vap->va_gid);
912                 sp->sa_size = txdr_unsigned(vap->va_size);
913                 txdr_nfsv2time(&vap->va_atime, &sp->sa_atime);
914                 txdr_nfsv2time(&vap->va_mtime, &sp->sa_mtime);
915         }
916         NEGKEEPOUT(nfsm_request(&info, vp, NFSPROC_SETATTR, td, cred, &error));
917         if (info.v3) {
918                 np->n_modestamp = 0;
919                 ERROROUT(nfsm_wcc_data(&info, vp, &wccflag));
920         } else {
921                 ERROROUT(nfsm_loadattr(&info, vp, NULL));
922         }
923         m_freem(info.mrep);
924         info.mrep = NULL;
925 nfsmout:
926         return (error);
927 }
928
929 static
930 void
931 nfs_cache_setvp(struct nchandle *nch, struct vnode *vp, int nctimeout)
932 {
933         if (nctimeout == 0)
934                 nctimeout = 1;
935         else
936                 nctimeout *= hz;
937         cache_setvp(nch, vp);
938         cache_settimeout(nch, nctimeout);
939 }
940
941 /*
942  * NEW API CALL - replaces nfs_lookup().  However, we cannot remove 
943  * nfs_lookup() until all remaining new api calls are implemented.
944  *
945  * Resolve a namecache entry.  This function is passed a locked ncp and
946  * must call nfs_cache_setvp() on it as appropriate to resolve the entry.
947  */
948 static int
949 nfs_nresolve(struct vop_nresolve_args *ap)
950 {
951         struct thread *td = curthread;
952         struct namecache *ncp;
953         struct nfsmount *nmp;
954         struct nfsnode *np;
955         struct vnode *dvp;
956         struct vnode *nvp;
957         nfsfh_t *fhp;
958         int attrflag;
959         int fhsize;
960         int error;
961         int tmp_error;
962         int len;
963         struct nfsm_info info;
964
965         dvp = ap->a_dvp;
966         nmp = VFSTONFS(dvp->v_mount);
967
968         lwkt_gettoken(&nmp->nm_token);
969
970         if ((error = vget(dvp, LK_SHARED)) != 0) {
971                 lwkt_reltoken(&nmp->nm_token);
972                 return (error);
973         }
974
975         info.mrep = NULL;
976         info.v3 = NFS_ISV3(dvp);
977
978         nvp = NULL;
979         nfsstats.lookupcache_misses++;
980         nfsstats.rpccnt[NFSPROC_LOOKUP]++;
981         ncp = ap->a_nch->ncp;
982         len = ncp->nc_nlen;
983         nfsm_reqhead(&info, dvp, NFSPROC_LOOKUP,
984                      NFSX_FH(info.v3) + NFSX_UNSIGNED + nfsm_rndup(len));
985         ERROROUT(nfsm_fhtom(&info, dvp));
986         ERROROUT(nfsm_strtom(&info, ncp->nc_name, len, NFS_MAXNAMLEN));
987         NEGKEEPOUT(nfsm_request(&info, dvp, NFSPROC_LOOKUP, td,
988                                 ap->a_cred, &error));
989         if (error) {
990                 /*
991                  * Cache negatve lookups to reduce NFS traffic, but use
992                  * a fast timeout.  Otherwise use a timeout of 1 tick.
993                  * XXX we should add a namecache flag for no-caching
994                  * to uncache the negative hit as soon as possible, but
995                  * we cannot simply destroy the entry because it is used
996                  * as a placeholder by the caller.
997                  *
998                  * The refactored nfs code will overwrite a non-zero error
999                  * with 0 when we use ERROROUT(), so don't here.
1000                  */
1001                 if (error == ENOENT)
1002                         nfs_cache_setvp(ap->a_nch, NULL, nfsneg_cache_timeout);
1003                 tmp_error = nfsm_postop_attr(&info, dvp, &attrflag,
1004                                              NFS_LATTR_NOSHRINK);
1005                 if (tmp_error) {
1006                         error = tmp_error;
1007                         goto nfsmout;
1008                 }
1009                 m_freem(info.mrep);
1010                 info.mrep = NULL;
1011                 goto nfsmout;
1012         }
1013
1014         /*
1015          * Success, get the file handle, do various checks, and load 
1016          * post-operation data from the reply packet.  Theoretically
1017          * we should never be looking up "." so, theoretically, we
1018          * should never get the same file handle as our directory.  But
1019          * we check anyway. XXX
1020          *
1021          * Note that no timeout is set for the positive cache hit.  We
1022          * assume, theoretically, that ESTALE returns will be dealt with
1023          * properly to handle NFS races and in anycase we cannot depend
1024          * on a timeout to deal with NFS open/create/excl issues so instead
1025          * of a bad hack here the rest of the NFS client code needs to do
1026          * the right thing.
1027          */
1028         NEGATIVEOUT(fhsize = nfsm_getfh(&info, &fhp));
1029
1030         np = VTONFS(dvp);
1031         if (NFS_CMPFH(np, fhp, fhsize)) {
1032                 vref(dvp);
1033                 nvp = dvp;
1034         } else {
1035                 error = nfs_nget(dvp->v_mount, fhp, fhsize, &np, NULL);
1036                 if (error) {
1037                         m_freem(info.mrep);
1038                         info.mrep = NULL;
1039                         vput(dvp);
1040                         lwkt_reltoken(&nmp->nm_token);
1041                         return (error);
1042                 }
1043                 nvp = NFSTOV(np);
1044         }
1045         if (info.v3) {
1046                 ERROROUT(nfsm_postop_attr(&info, nvp, &attrflag,
1047                                           NFS_LATTR_NOSHRINK));
1048                 ERROROUT(nfsm_postop_attr(&info, dvp, &attrflag,
1049                                           NFS_LATTR_NOSHRINK));
1050         } else {
1051                 ERROROUT(nfsm_loadattr(&info, nvp, NULL));
1052         }
1053         nfs_cache_setvp(ap->a_nch, nvp, nfspos_cache_timeout);
1054         m_freem(info.mrep);
1055         info.mrep = NULL;
1056 nfsmout:
1057         lwkt_reltoken(&nmp->nm_token);
1058         vput(dvp);
1059         if (nvp) {
1060                 if (nvp == dvp)
1061                         vrele(nvp);
1062                 else
1063                         vput(nvp);
1064         }
1065         return (error);
1066 }
1067
1068 /*
1069  * 'cached' nfs directory lookup
1070  *
1071  * NOTE: cannot be removed until NFS implements all the new n*() API calls.
1072  *
1073  * nfs_lookup(struct vnode *a_dvp, struct vnode **a_vpp,
1074  *            struct componentname *a_cnp)
1075  */
1076 static int
1077 nfs_lookup(struct vop_old_lookup_args *ap)
1078 {
1079         struct componentname *cnp = ap->a_cnp;
1080         struct vnode *dvp = ap->a_dvp;
1081         struct vnode **vpp = ap->a_vpp;
1082         int flags = cnp->cn_flags;
1083         struct vnode *newvp;
1084         struct vnode *notvp;
1085         struct nfsmount *nmp;
1086         long len;
1087         nfsfh_t *fhp;
1088         struct nfsnode *np;
1089         int lockparent, wantparent, attrflag, fhsize;
1090         int error;
1091         int tmp_error;
1092         struct nfsm_info info;
1093
1094         info.mrep = NULL;
1095         info.v3 = NFS_ISV3(dvp);
1096         error = 0;
1097
1098         notvp = (cnp->cn_flags & CNP_NOTVP) ? cnp->cn_notvp : NULL;
1099
1100         /*
1101          * Read-only mount check and directory check.
1102          */
1103         *vpp = NULLVP;
1104         if ((dvp->v_mount->mnt_flag & MNT_RDONLY) &&
1105             (cnp->cn_nameiop == NAMEI_DELETE || cnp->cn_nameiop == NAMEI_RENAME))
1106                 return (EROFS);
1107
1108         if (dvp->v_type != VDIR)
1109                 return (ENOTDIR);
1110
1111         /*
1112          * Look it up in the cache.  Note that ENOENT is only returned if we
1113          * previously entered a negative hit (see later on).  The additional
1114          * nfsneg_cache_timeout check causes previously cached results to
1115          * be instantly ignored if the negative caching is turned off.
1116          */
1117         lockparent = flags & CNP_LOCKPARENT;
1118         wantparent = flags & (CNP_LOCKPARENT|CNP_WANTPARENT);
1119         nmp = VFSTONFS(dvp->v_mount);
1120         np = VTONFS(dvp);
1121
1122         lwkt_gettoken(&nmp->nm_token);
1123
1124         /*
1125          * Go to the wire.
1126          */
1127         error = 0;
1128         newvp = NULLVP;
1129         nfsstats.lookupcache_misses++;
1130         nfsstats.rpccnt[NFSPROC_LOOKUP]++;
1131         len = cnp->cn_namelen;
1132         nfsm_reqhead(&info, dvp, NFSPROC_LOOKUP,
1133                      NFSX_FH(info.v3) + NFSX_UNSIGNED + nfsm_rndup(len));
1134         ERROROUT(nfsm_fhtom(&info, dvp));
1135         ERROROUT(nfsm_strtom(&info, cnp->cn_nameptr, len, NFS_MAXNAMLEN));
1136         NEGKEEPOUT(nfsm_request(&info, dvp, NFSPROC_LOOKUP, cnp->cn_td,
1137                                 cnp->cn_cred, &error));
1138         if (error) {
1139                 tmp_error = nfsm_postop_attr(&info, dvp, &attrflag,
1140                                              NFS_LATTR_NOSHRINK);
1141                 if (tmp_error) {
1142                         error = tmp_error;
1143                         goto nfsmout;
1144                 }
1145
1146                 m_freem(info.mrep);
1147                 info.mrep = NULL;
1148                 goto nfsmout;
1149         }
1150         NEGATIVEOUT(fhsize = nfsm_getfh(&info, &fhp));
1151
1152         /*
1153          * Handle RENAME case...
1154          */
1155         if (cnp->cn_nameiop == NAMEI_RENAME && wantparent) {
1156                 if (NFS_CMPFH(np, fhp, fhsize)) {
1157                         m_freem(info.mrep);
1158                         info.mrep = NULL;
1159                         lwkt_reltoken(&nmp->nm_token);
1160                         return (EISDIR);
1161                 }
1162                 error = nfs_nget(dvp->v_mount, fhp, fhsize, &np, notvp);
1163                 if (error) {
1164                         m_freem(info.mrep);
1165                         info.mrep = NULL;
1166                         lwkt_reltoken(&nmp->nm_token);
1167                         return (error);
1168                 }
1169                 newvp = NFSTOV(np);
1170                 if (info.v3) {
1171                         ERROROUT(nfsm_postop_attr(&info, newvp, &attrflag,
1172                                                   NFS_LATTR_NOSHRINK));
1173                         ERROROUT(nfsm_postop_attr(&info, dvp, &attrflag,
1174                                                   NFS_LATTR_NOSHRINK));
1175                 } else {
1176                         ERROROUT(nfsm_loadattr(&info, newvp, NULL));
1177                 }
1178                 *vpp = newvp;
1179                 m_freem(info.mrep);
1180                 info.mrep = NULL;
1181                 if (!lockparent) {
1182                         vn_unlock(dvp);
1183                         cnp->cn_flags |= CNP_PDIRUNLOCK;
1184                 }
1185                 lwkt_reltoken(&nmp->nm_token);
1186                 return (0);
1187         }
1188
1189         if (flags & CNP_ISDOTDOT) {
1190                 vn_unlock(dvp);
1191                 cnp->cn_flags |= CNP_PDIRUNLOCK;
1192                 error = nfs_nget(dvp->v_mount, fhp, fhsize, &np, notvp);
1193                 if (error) {
1194                         vn_lock(dvp, LK_EXCLUSIVE | LK_RETRY);
1195                         cnp->cn_flags &= ~CNP_PDIRUNLOCK;
1196                         lwkt_reltoken(&nmp->nm_token);
1197                         return (error); /* NOTE: return error from nget */
1198                 }
1199                 newvp = NFSTOV(np);
1200                 if (lockparent) {
1201                         error = vn_lock(dvp, LK_EXCLUSIVE | LK_FAILRECLAIM);
1202                         if (error) {
1203                                 vput(newvp);
1204                                 lwkt_reltoken(&nmp->nm_token);
1205                                 return (error);
1206                         }
1207                         cnp->cn_flags |= CNP_PDIRUNLOCK;
1208                 }
1209         } else if (NFS_CMPFH(np, fhp, fhsize)) {
1210                 vref(dvp);
1211                 newvp = dvp;
1212         } else {
1213                 error = nfs_nget(dvp->v_mount, fhp, fhsize, &np, notvp);
1214                 if (error) {
1215                         m_freem(info.mrep);
1216                         info.mrep = NULL;
1217                         lwkt_reltoken(&nmp->nm_token);
1218                         return (error);
1219                 }
1220                 if (!lockparent) {
1221                         vn_unlock(dvp);
1222                         cnp->cn_flags |= CNP_PDIRUNLOCK;
1223                 }
1224                 newvp = NFSTOV(np);
1225         }
1226         if (info.v3) {
1227                 ERROROUT(nfsm_postop_attr(&info, newvp, &attrflag,
1228                                           NFS_LATTR_NOSHRINK));
1229                 ERROROUT(nfsm_postop_attr(&info, dvp, &attrflag,
1230                                           NFS_LATTR_NOSHRINK));
1231         } else {
1232                 ERROROUT(nfsm_loadattr(&info, newvp, NULL));
1233         }
1234 #if 0
1235         /* XXX MOVE TO nfs_nremove() */
1236         if ((cnp->cn_flags & CNP_MAKEENTRY) &&
1237             cnp->cn_nameiop != NAMEI_DELETE) {
1238                 np->n_ctime = np->n_vattr.va_ctime.tv_sec; /* XXX */
1239         }
1240 #endif
1241         *vpp = newvp;
1242         m_freem(info.mrep);
1243         info.mrep = NULL;
1244 nfsmout:
1245         if (error) {
1246                 if (newvp != NULLVP) {
1247                         vrele(newvp);
1248                         *vpp = NULLVP;
1249                 }
1250                 if ((cnp->cn_nameiop == NAMEI_CREATE || 
1251                      cnp->cn_nameiop == NAMEI_RENAME) &&
1252                     error == ENOENT) {
1253                         if (!lockparent) {
1254                                 vn_unlock(dvp);
1255                                 cnp->cn_flags |= CNP_PDIRUNLOCK;
1256                         }
1257                         if (dvp->v_mount->mnt_flag & MNT_RDONLY)
1258                                 error = EROFS;
1259                         else
1260                                 error = EJUSTRETURN;
1261                 }
1262         }
1263         lwkt_reltoken(&nmp->nm_token);
1264         return (error);
1265 }
1266
1267 /*
1268  * nfs read call.
1269  * Just call nfs_bioread() to do the work.
1270  *
1271  * nfs_read(struct vnode *a_vp, struct uio *a_uio, int a_ioflag,
1272  *          struct ucred *a_cred)
1273  */
1274 static int
1275 nfs_read(struct vop_read_args *ap)
1276 {
1277         struct vnode *vp = ap->a_vp;
1278         struct nfsmount *nmp = VFSTONFS(vp->v_mount);
1279         int error;
1280
1281         lwkt_gettoken(&nmp->nm_token);
1282         error = nfs_bioread(vp, ap->a_uio, ap->a_ioflag);
1283         lwkt_reltoken(&nmp->nm_token);
1284
1285         return error;
1286 }
1287
1288 /*
1289  * nfs readlink call
1290  *
1291  * nfs_readlink(struct vnode *a_vp, struct uio *a_uio, struct ucred *a_cred)
1292  */
1293 static int
1294 nfs_readlink(struct vop_readlink_args *ap)
1295 {
1296         struct vnode *vp = ap->a_vp;
1297         struct nfsmount *nmp = VFSTONFS(vp->v_mount);
1298         int error;
1299
1300         if (vp->v_type != VLNK)
1301                 return (EINVAL);
1302
1303         lwkt_gettoken(&nmp->nm_token);
1304         error = nfs_bioread(vp, ap->a_uio, 0);
1305         lwkt_reltoken(&nmp->nm_token);
1306
1307         return error;
1308 }
1309
1310 /*
1311  * Do a readlink rpc.
1312  * Called by nfs_doio() from below the buffer cache.
1313  */
1314 int
1315 nfs_readlinkrpc_uio(struct vnode *vp, struct uio *uiop)
1316 {
1317         int error = 0, len, attrflag;
1318         struct nfsm_info info;
1319
1320         info.mrep = NULL;
1321         info.v3 = NFS_ISV3(vp);
1322
1323         nfsstats.rpccnt[NFSPROC_READLINK]++;
1324         nfsm_reqhead(&info, vp, NFSPROC_READLINK, NFSX_FH(info.v3));
1325         ERROROUT(nfsm_fhtom(&info, vp));
1326         NEGKEEPOUT(nfsm_request(&info, vp, NFSPROC_READLINK, uiop->uio_td,
1327                                 nfs_vpcred(vp, ND_CHECK), &error));
1328         if (info.v3) {
1329                 ERROROUT(nfsm_postop_attr(&info, vp, &attrflag,
1330                                           NFS_LATTR_NOSHRINK));
1331         }
1332         if (!error) {
1333                 NEGATIVEOUT(len = nfsm_strsiz(&info, NFS_MAXPATHLEN));
1334                 if (len == NFS_MAXPATHLEN) {
1335                         struct nfsnode *np = VTONFS(vp);
1336                         if (np->n_size && np->n_size < NFS_MAXPATHLEN)
1337                                 len = np->n_size;
1338                 }
1339                 ERROROUT(nfsm_mtouio(&info, uiop, len));
1340         }
1341         m_freem(info.mrep);
1342         info.mrep = NULL;
1343 nfsmout:
1344         return (error);
1345 }
1346
1347 /*
1348  * nfs synchronous read rpc using UIO
1349  */
1350 int
1351 nfs_readrpc_uio(struct vnode *vp, struct uio *uiop)
1352 {
1353         u_int32_t *tl;
1354         struct nfsmount *nmp;
1355         int error = 0, len, retlen, tsiz, eof, attrflag;
1356         struct nfsm_info info;
1357         off_t tmp_off;
1358
1359         info.mrep = NULL;
1360         info.v3 = NFS_ISV3(vp);
1361
1362 #ifndef nolint
1363         eof = 0;
1364 #endif
1365         nmp = VFSTONFS(vp->v_mount);
1366
1367         tsiz = uiop->uio_resid;
1368         tmp_off = uiop->uio_offset + tsiz;
1369         if (tmp_off > nmp->nm_maxfilesize || tmp_off < uiop->uio_offset)
1370                 return (EFBIG);
1371         tmp_off = uiop->uio_offset;
1372         while (tsiz > 0) {
1373                 nfsstats.rpccnt[NFSPROC_READ]++;
1374                 len = (tsiz > nmp->nm_rsize) ? nmp->nm_rsize : tsiz;
1375                 nfsm_reqhead(&info, vp, NFSPROC_READ,
1376                              NFSX_FH(info.v3) + NFSX_UNSIGNED * 3);
1377                 ERROROUT(nfsm_fhtom(&info, vp));
1378                 tl = nfsm_build(&info, NFSX_UNSIGNED * 3);
1379                 if (info.v3) {
1380                         txdr_hyper(uiop->uio_offset, tl);
1381                         *(tl + 2) = txdr_unsigned(len);
1382                 } else {
1383                         *tl++ = txdr_unsigned(uiop->uio_offset);
1384                         *tl++ = txdr_unsigned(len);
1385                         *tl = 0;
1386                 }
1387                 NEGKEEPOUT(nfsm_request(&info, vp, NFSPROC_READ, uiop->uio_td,
1388                                         nfs_vpcred(vp, ND_READ), &error));
1389                 if (info.v3) {
1390                         ERROROUT(nfsm_postop_attr(&info, vp, &attrflag,
1391                                                  NFS_LATTR_NOSHRINK));
1392                         NULLOUT(tl = nfsm_dissect(&info, 2 * NFSX_UNSIGNED));
1393                         eof = fxdr_unsigned(int, *(tl + 1));
1394                 } else {
1395                         ERROROUT(nfsm_loadattr(&info, vp, NULL));
1396                 }
1397                 NEGATIVEOUT(retlen = nfsm_strsiz(&info, len));
1398                 ERROROUT(nfsm_mtouio(&info, uiop, retlen));
1399                 m_freem(info.mrep);
1400                 info.mrep = NULL;
1401
1402                 /*
1403                  * Handle short-read from server (NFSv3).  If EOF is not
1404                  * flagged (and no error occurred), but retlen is less
1405                  * then the request size, we must zero-fill the remainder.
1406                  */
1407                 if (retlen < len && info.v3 && eof == 0) {
1408                         ERROROUT(uiomovez(len - retlen, uiop));
1409                         retlen = len;
1410                 }
1411                 tsiz -= retlen;
1412
1413                 /*
1414                  * Terminate loop on EOF or zero-length read.
1415                  *
1416                  * For NFSv2 a short-read indicates EOF, not zero-fill,
1417                  * and also terminates the loop.
1418                  */
1419                 if (info.v3) {
1420                         if (eof || retlen == 0)
1421                                 tsiz = 0;
1422                 } else if (retlen < len) {
1423                         tsiz = 0;
1424                 }
1425         }
1426 nfsmout:
1427         return (error);
1428 }
1429
1430 /*
1431  * nfs write call
1432  */
1433 int
1434 nfs_writerpc_uio(struct vnode *vp, struct uio *uiop,
1435                  int *iomode, int *must_commit)
1436 {
1437         u_int32_t *tl;
1438         int32_t backup;
1439         struct nfsmount *nmp = VFSTONFS(vp->v_mount);
1440         int error = 0, len, tsiz, wccflag = NFSV3_WCCRATTR, rlen, commit;
1441         int  committed = NFSV3WRITE_FILESYNC;
1442         struct nfsm_info info;
1443
1444         info.mrep = NULL;
1445         info.v3 = NFS_ISV3(vp);
1446
1447 #ifndef DIAGNOSTIC
1448         if (uiop->uio_iovcnt != 1)
1449                 panic("nfs: writerpc iovcnt > 1");
1450 #endif
1451         *must_commit = 0;
1452         tsiz = uiop->uio_resid;
1453         if (uiop->uio_offset + tsiz > nmp->nm_maxfilesize)
1454                 return (EFBIG);
1455         while (tsiz > 0) {
1456                 nfsstats.rpccnt[NFSPROC_WRITE]++;
1457                 len = (tsiz > nmp->nm_wsize) ? nmp->nm_wsize : tsiz;
1458                 nfsm_reqhead(&info, vp, NFSPROC_WRITE,
1459                              NFSX_FH(info.v3) + 5 * NFSX_UNSIGNED +
1460                              nfsm_rndup(len));
1461                 ERROROUT(nfsm_fhtom(&info, vp));
1462                 if (info.v3) {
1463                         tl = nfsm_build(&info, 5 * NFSX_UNSIGNED);
1464                         txdr_hyper(uiop->uio_offset, tl);
1465                         tl += 2;
1466                         *tl++ = txdr_unsigned(len);
1467                         *tl++ = txdr_unsigned(*iomode);
1468                         *tl = txdr_unsigned(len);
1469                 } else {
1470                         u_int32_t x;
1471
1472                         tl = nfsm_build(&info, 4 * NFSX_UNSIGNED);
1473                         /* Set both "begin" and "current" to non-garbage. */
1474                         x = txdr_unsigned((u_int32_t)uiop->uio_offset);
1475                         *tl++ = x;      /* "begin offset" */
1476                         *tl++ = x;      /* "current offset" */
1477                         x = txdr_unsigned(len);
1478                         *tl++ = x;      /* total to this offset */
1479                         *tl = x;        /* size of this write */
1480                 }
1481                 ERROROUT(nfsm_uiotom(&info, uiop, len));
1482                 NEGKEEPOUT(nfsm_request(&info, vp, NFSPROC_WRITE, uiop->uio_td,
1483                                         nfs_vpcred(vp, ND_WRITE), &error));
1484                 if (info.v3) {
1485                         /*
1486                          * The write RPC returns a before and after mtime.  The
1487                          * nfsm_wcc_data() macro checks the before n_mtime
1488                          * against the before time and stores the after time
1489                          * in the nfsnode's cached vattr and n_mtime field.
1490                          * The NRMODIFIED bit will be set if the before
1491                          * time did not match the original mtime.
1492                          */
1493                         wccflag = NFSV3_WCCCHK;
1494                         ERROROUT(nfsm_wcc_data(&info, vp, &wccflag));
1495                         if (error == 0) {
1496                                 NULLOUT(tl = nfsm_dissect(&info, 2 * NFSX_UNSIGNED + NFSX_V3WRITEVERF));
1497                                 rlen = fxdr_unsigned(int, *tl++);
1498                                 if (rlen == 0) {
1499                                         error = NFSERR_IO;
1500                                         m_freem(info.mrep);
1501                                         info.mrep = NULL;
1502                                         break;
1503                                 } else if (rlen < len) {
1504                                         backup = len - rlen;
1505                                         uiop->uio_iov->iov_base = (char *)uiop->uio_iov->iov_base - backup;
1506                                         uiop->uio_iov->iov_len += backup;
1507                                         uiop->uio_offset -= backup;
1508                                         uiop->uio_resid += backup;
1509                                         len = rlen;
1510                                 }
1511                                 commit = fxdr_unsigned(int, *tl++);
1512
1513                                 /*
1514                                  * Return the lowest committment level
1515                                  * obtained by any of the RPCs.
1516                                  */
1517                                 if (committed == NFSV3WRITE_FILESYNC)
1518                                         committed = commit;
1519                                 else if (committed == NFSV3WRITE_DATASYNC &&
1520                                         commit == NFSV3WRITE_UNSTABLE)
1521                                         committed = commit;
1522                                 if ((nmp->nm_state & NFSSTA_HASWRITEVERF) == 0){
1523                                     bcopy((caddr_t)tl, (caddr_t)nmp->nm_verf,
1524                                         NFSX_V3WRITEVERF);
1525                                     nmp->nm_state |= NFSSTA_HASWRITEVERF;
1526                                 } else if (bcmp((caddr_t)tl,
1527                                     (caddr_t)nmp->nm_verf, NFSX_V3WRITEVERF)) {
1528                                     *must_commit = 1;
1529                                     bcopy((caddr_t)tl, (caddr_t)nmp->nm_verf,
1530                                         NFSX_V3WRITEVERF);
1531                                 }
1532                         }
1533                 } else {
1534                         ERROROUT(nfsm_loadattr(&info, vp, NULL));
1535                 }
1536                 m_freem(info.mrep);
1537                 info.mrep = NULL;
1538                 if (error)
1539                         break;
1540                 tsiz -= len;
1541         }
1542 nfsmout:
1543         if (vp->v_mount->mnt_flag & MNT_ASYNC)
1544                 committed = NFSV3WRITE_FILESYNC;
1545         *iomode = committed;
1546         if (error)
1547                 uiop->uio_resid = tsiz;
1548         return (error);
1549 }
1550
1551 /*
1552  * nfs mknod rpc
1553  * For NFS v2 this is a kludge. Use a create rpc but with the IFMT bits of the
1554  * mode set to specify the file type and the size field for rdev.
1555  */
1556 static int
1557 nfs_mknodrpc(struct vnode *dvp, struct vnode **vpp, struct componentname *cnp,
1558              struct vattr *vap)
1559 {
1560         struct nfsv2_sattr *sp;
1561         u_int32_t *tl;
1562         struct vnode *newvp = NULL;
1563         struct nfsnode *np = NULL;
1564         struct vattr vattr;
1565         int error = 0, wccflag = NFSV3_WCCRATTR, gotvp = 0;
1566         int rmajor, rminor;
1567         struct nfsm_info info;
1568
1569         info.mrep = NULL;
1570         info.v3 = NFS_ISV3(dvp);
1571
1572         if (vap->va_type == VCHR || vap->va_type == VBLK) {
1573                 rmajor = txdr_unsigned(vap->va_rmajor);
1574                 rminor = txdr_unsigned(vap->va_rminor);
1575         } else if (vap->va_type == VFIFO || vap->va_type == VSOCK) {
1576                 rmajor = nfs_xdrneg1;
1577                 rminor = nfs_xdrneg1;
1578         } else {
1579                 return (EOPNOTSUPP);
1580         }
1581         if ((error = VOP_GETATTR(dvp, &vattr)) != 0) {
1582                 return (error);
1583         }
1584         nfsstats.rpccnt[NFSPROC_MKNOD]++;
1585         nfsm_reqhead(&info, dvp, NFSPROC_MKNOD,
1586                      NFSX_FH(info.v3) + 4 * NFSX_UNSIGNED +
1587                      nfsm_rndup(cnp->cn_namelen) + NFSX_SATTR(info.v3));
1588         ERROROUT(nfsm_fhtom(&info, dvp));
1589         ERROROUT(nfsm_strtom(&info, cnp->cn_nameptr, cnp->cn_namelen,
1590                              NFS_MAXNAMLEN));
1591         if (info.v3) {
1592                 tl = nfsm_build(&info, NFSX_UNSIGNED);
1593                 *tl++ = vtonfsv3_type(vap->va_type);
1594                 nfsm_v3attrbuild(&info, vap, FALSE);
1595                 if (vap->va_type == VCHR || vap->va_type == VBLK) {
1596                         tl = nfsm_build(&info, 2 * NFSX_UNSIGNED);
1597                         *tl++ = txdr_unsigned(vap->va_rmajor);
1598                         *tl = txdr_unsigned(vap->va_rminor);
1599                 }
1600         } else {
1601                 sp = nfsm_build(&info, NFSX_V2SATTR);
1602                 sp->sa_mode = vtonfsv2_mode(vap->va_type, vap->va_mode);
1603                 sp->sa_uid = nfs_xdrneg1;
1604                 sp->sa_gid = nfs_xdrneg1;
1605                 sp->sa_size = makeudev(rmajor, rminor);
1606                 txdr_nfsv2time(&vap->va_atime, &sp->sa_atime);
1607                 txdr_nfsv2time(&vap->va_mtime, &sp->sa_mtime);
1608         }
1609         NEGKEEPOUT(nfsm_request(&info, dvp, NFSPROC_MKNOD, cnp->cn_td,
1610                                 cnp->cn_cred, &error));
1611         if (!error) {
1612                 ERROROUT(nfsm_mtofh(&info, dvp, &newvp, &gotvp));
1613                 if (!gotvp) {
1614                         if (newvp) {
1615                                 vput(newvp);
1616                                 newvp = NULL;
1617                         }
1618                         error = nfs_lookitup(dvp, cnp->cn_nameptr,
1619                             cnp->cn_namelen, cnp->cn_cred, cnp->cn_td, &np);
1620                         if (!error)
1621                                 newvp = NFSTOV(np);
1622                 }
1623         }
1624         if (info.v3) {
1625                 ERROROUT(nfsm_wcc_data(&info, dvp, &wccflag));
1626         }
1627         m_freem(info.mrep);
1628         info.mrep = NULL;
1629 nfsmout:
1630         if (error) {
1631                 if (newvp)
1632                         vput(newvp);
1633         } else {
1634                 *vpp = newvp;
1635         }
1636         VTONFS(dvp)->n_flag |= NLMODIFIED;
1637         if (!wccflag)
1638                 VTONFS(dvp)->n_attrstamp = 0;
1639         return (error);
1640 }
1641
1642 /*
1643  * nfs mknod vop
1644  * just call nfs_mknodrpc() to do the work.
1645  *
1646  * nfs_mknod(struct vnode *a_dvp, struct vnode **a_vpp,
1647  *           struct componentname *a_cnp, struct vattr *a_vap)
1648  */
1649 /* ARGSUSED */
1650 static int
1651 nfs_mknod(struct vop_old_mknod_args *ap)
1652 {
1653         struct nfsmount *nmp = VFSTONFS(ap->a_dvp->v_mount);
1654         int error;
1655
1656         lwkt_gettoken(&nmp->nm_token);
1657         error = nfs_mknodrpc(ap->a_dvp, ap->a_vpp, ap->a_cnp, ap->a_vap);
1658         lwkt_reltoken(&nmp->nm_token);
1659         if (error == 0)
1660                 nfs_knote(ap->a_dvp, NOTE_WRITE);
1661
1662         return error;
1663 }
1664
1665 static u_long create_verf;
1666 /*
1667  * nfs file create call
1668  *
1669  * nfs_create(struct vnode *a_dvp, struct vnode **a_vpp,
1670  *            struct componentname *a_cnp, struct vattr *a_vap)
1671  */
1672 static int
1673 nfs_create(struct vop_old_create_args *ap)
1674 {
1675         struct vnode *dvp = ap->a_dvp;
1676         struct vattr *vap = ap->a_vap;
1677         struct nfsmount *nmp = VFSTONFS(dvp->v_mount);
1678         struct componentname *cnp = ap->a_cnp;
1679         struct nfsv2_sattr *sp;
1680         u_int32_t *tl;
1681         struct nfsnode *np = NULL;
1682         struct vnode *newvp = NULL;
1683         int error = 0, wccflag = NFSV3_WCCRATTR, gotvp = 0, fmode = 0;
1684         struct vattr vattr;
1685         struct nfsm_info info;
1686
1687         info.mrep = NULL;
1688         info.v3 = NFS_ISV3(dvp);
1689         lwkt_gettoken(&nmp->nm_token);
1690
1691         /*
1692          * Oops, not for me..
1693          */
1694         if (vap->va_type == VSOCK) {
1695                 error = nfs_mknodrpc(dvp, ap->a_vpp, cnp, vap);
1696                 lwkt_reltoken(&nmp->nm_token);
1697                 return error;
1698         }
1699
1700         if ((error = VOP_GETATTR(dvp, &vattr)) != 0) {
1701                 lwkt_reltoken(&nmp->nm_token);
1702                 return (error);
1703         }
1704         if (vap->va_vaflags & VA_EXCLUSIVE)
1705                 fmode |= O_EXCL;
1706 again:
1707         nfsstats.rpccnt[NFSPROC_CREATE]++;
1708         nfsm_reqhead(&info, dvp, NFSPROC_CREATE,
1709                      NFSX_FH(info.v3) + 2 * NFSX_UNSIGNED +
1710                      nfsm_rndup(cnp->cn_namelen) + NFSX_SATTR(info.v3));
1711         ERROROUT(nfsm_fhtom(&info, dvp));
1712         ERROROUT(nfsm_strtom(&info, cnp->cn_nameptr, cnp->cn_namelen,
1713                              NFS_MAXNAMLEN));
1714         if (info.v3) {
1715                 tl = nfsm_build(&info, NFSX_UNSIGNED);
1716                 if (fmode & O_EXCL) {
1717                         *tl = txdr_unsigned(NFSV3CREATE_EXCLUSIVE);
1718                         tl = nfsm_build(&info, NFSX_V3CREATEVERF);
1719 #ifdef INET
1720                         if (!TAILQ_EMPTY(&in_ifaddrheads[mycpuid]))
1721                                 *tl++ = IA_SIN(TAILQ_FIRST(&in_ifaddrheads[mycpuid])->ia)->sin_addr.s_addr;
1722                         else
1723 #endif
1724                                 *tl++ = create_verf;
1725                         *tl = ++create_verf;
1726                 } else {
1727                         *tl = txdr_unsigned(NFSV3CREATE_UNCHECKED);
1728                         nfsm_v3attrbuild(&info, vap, FALSE);
1729                 }
1730         } else {
1731                 sp = nfsm_build(&info, NFSX_V2SATTR);
1732                 sp->sa_mode = vtonfsv2_mode(vap->va_type, vap->va_mode);
1733                 sp->sa_uid = nfs_xdrneg1;
1734                 sp->sa_gid = nfs_xdrneg1;
1735                 sp->sa_size = 0;
1736                 txdr_nfsv2time(&vap->va_atime, &sp->sa_atime);
1737                 txdr_nfsv2time(&vap->va_mtime, &sp->sa_mtime);
1738         }
1739         NEGKEEPOUT(nfsm_request(&info, dvp, NFSPROC_CREATE, cnp->cn_td,
1740                                 cnp->cn_cred, &error));
1741         if (error == 0) {
1742                 ERROROUT(nfsm_mtofh(&info, dvp, &newvp, &gotvp));
1743                 if (!gotvp) {
1744                         if (newvp) {
1745                                 vput(newvp);
1746                                 newvp = NULL;
1747                         }
1748                         error = nfs_lookitup(dvp, cnp->cn_nameptr,
1749                             cnp->cn_namelen, cnp->cn_cred, cnp->cn_td, &np);
1750                         if (!error)
1751                                 newvp = NFSTOV(np);
1752                 }
1753         }
1754         if (info.v3) {
1755                 if (error == 0)
1756                         error = nfsm_wcc_data(&info, dvp, &wccflag);
1757                 else
1758                         (void)nfsm_wcc_data(&info, dvp, &wccflag);
1759         }
1760         m_freem(info.mrep);
1761         info.mrep = NULL;
1762 nfsmout:
1763         if (error) {
1764                 if (info.v3 && (fmode & O_EXCL) && error == NFSERR_NOTSUPP) {
1765                         KKASSERT(newvp == NULL);
1766                         fmode &= ~O_EXCL;
1767                         goto again;
1768                 }
1769         } else if (info.v3 && (fmode & O_EXCL)) {
1770                 /*
1771                  * We are normally called with only a partially initialized
1772                  * VAP.  Since the NFSv3 spec says that server may use the
1773                  * file attributes to store the verifier, the spec requires
1774                  * us to do a SETATTR RPC. FreeBSD servers store the verifier
1775                  * in atime, but we can't really assume that all servers will
1776                  * so we ensure that our SETATTR sets both atime and mtime.
1777                  */
1778                 if (vap->va_mtime.tv_sec == VNOVAL)
1779                         vfs_timestamp(&vap->va_mtime);
1780                 if (vap->va_atime.tv_sec == VNOVAL)
1781                         vap->va_atime = vap->va_mtime;
1782                 error = nfs_setattrrpc(newvp, vap, cnp->cn_cred, cnp->cn_td);
1783         }
1784         if (error == 0) {
1785                 /*
1786                  * The new np may have enough info for access
1787                  * checks, make sure rucred and wucred are
1788                  * initialized for read and write rpc's.
1789                  */
1790                 np = VTONFS(newvp);
1791                 if (np->n_rucred == NULL)
1792                         np->n_rucred = crhold(cnp->cn_cred);
1793                 if (np->n_wucred == NULL)
1794                         np->n_wucred = crhold(cnp->cn_cred);
1795                 *ap->a_vpp = newvp;
1796                 nfs_knote(dvp, NOTE_WRITE);
1797         } else if (newvp) {
1798                 vput(newvp);
1799         }
1800         VTONFS(dvp)->n_flag |= NLMODIFIED;
1801         if (!wccflag)
1802                 VTONFS(dvp)->n_attrstamp = 0;
1803         lwkt_reltoken(&nmp->nm_token);
1804         return (error);
1805 }
1806
1807 /*
1808  * nfs file remove call
1809  * To try and make nfs semantics closer to ufs semantics, a file that has
1810  * other processes using the vnode is renamed instead of removed and then
1811  * removed later on the last close.
1812  * - If v_refcnt > 1
1813  *        If a rename is not already in the works
1814  *           call nfs_sillyrename() to set it up
1815  *     else
1816  *        do the remove rpc
1817  *
1818  * nfs_remove(struct vnode *a_dvp, struct vnode *a_vp,
1819  *            struct componentname *a_cnp)
1820  */
1821 static int
1822 nfs_remove(struct vop_old_remove_args *ap)
1823 {
1824         struct vnode *vp = ap->a_vp;
1825         struct vnode *dvp = ap->a_dvp;
1826         struct nfsmount *nmp = VFSTONFS(dvp->v_mount);
1827         struct componentname *cnp = ap->a_cnp;
1828         struct nfsnode *np = VTONFS(vp);
1829         int error = 0;
1830         struct vattr vattr;
1831
1832         lwkt_gettoken(&nmp->nm_token);
1833 #ifndef DIAGNOSTIC
1834         if (VREFCNT(vp) < 1)
1835                 panic("nfs_remove: bad v_refcnt");
1836 #endif
1837         if (vp->v_type == VDIR) {
1838                 error = EPERM;
1839         } else if (VREFCNT(vp) == 1 || (np->n_sillyrename &&
1840                    VOP_GETATTR(vp, &vattr) == 0 && vattr.va_nlink > 1)) {
1841                 /*
1842                  * Force finalization so the VOP_INACTIVE() call is not delayed.
1843                  * This prevents cred structures from building up in nfsnodes
1844                  * for deleted files.
1845                  */
1846                 atomic_set_int(&vp->v_refcnt, VREF_FINALIZE);
1847                 np->n_flag |= NREMOVED;
1848
1849                 /*
1850                  * Throw away biocache buffers, mainly to avoid
1851                  * unnecessary delayed writes later.
1852                  */
1853                 error = nfs_vinvalbuf(vp, 0, 1);
1854                 /* Do the rpc */
1855                 if (error != EINTR) {
1856                         error = nfs_removerpc(dvp, cnp->cn_nameptr,
1857                                               cnp->cn_namelen,
1858                                               cnp->cn_cred, cnp->cn_td);
1859                 }
1860
1861                 /*
1862                  * Kludge City: If the first reply to the remove rpc is lost..
1863                  *   the reply to the retransmitted request will be ENOENT
1864                  *   since the file was in fact removed
1865                  *   Therefore, we cheat and return success.
1866                  */
1867                 if (error == ENOENT)
1868                         error = 0;
1869         } else if (!np->n_sillyrename) {
1870                 error = nfs_sillyrename(dvp, vp, cnp);
1871         }
1872         np->n_attrstamp = 0;
1873         lwkt_reltoken(&nmp->nm_token);
1874         if (error == 0) {
1875                 nfs_knote(vp, NOTE_DELETE);
1876                 nfs_knote(dvp, NOTE_WRITE);
1877         }
1878
1879         return (error);
1880 }
1881
1882 /*
1883  * nfs file remove rpc called from nfs_inactive
1884  *
1885  * NOTE: s_dvp can be VBAD during a forced unmount.
1886  */
1887 int
1888 nfs_removeit(struct sillyrename *sp)
1889 {
1890         if (sp->s_dvp->v_type == VBAD)
1891                 return(0);
1892         return (nfs_removerpc(sp->s_dvp, sp->s_name, sp->s_namlen,
1893                 sp->s_cred, NULL));
1894 }
1895
1896 /*
1897  * Nfs remove rpc, called from nfs_remove() and nfs_removeit().
1898  */
1899 static int
1900 nfs_removerpc(struct vnode *dvp, const char *name, int namelen,
1901               struct ucred *cred, struct thread *td)
1902 {
1903         int error = 0, wccflag = NFSV3_WCCRATTR;
1904         struct nfsm_info info;
1905
1906         info.mrep = NULL;
1907         info.v3 = NFS_ISV3(dvp);
1908
1909         nfsstats.rpccnt[NFSPROC_REMOVE]++;
1910         nfsm_reqhead(&info, dvp, NFSPROC_REMOVE,
1911                      NFSX_FH(info.v3) + NFSX_UNSIGNED + nfsm_rndup(namelen));
1912         ERROROUT(nfsm_fhtom(&info, dvp));
1913         ERROROUT(nfsm_strtom(&info, name, namelen, NFS_MAXNAMLEN));
1914         NEGKEEPOUT(nfsm_request(&info, dvp, NFSPROC_REMOVE, td, cred, &error));
1915         if (info.v3) {
1916                 ERROROUT(nfsm_wcc_data(&info, dvp, &wccflag));
1917         }
1918         m_freem(info.mrep);
1919         info.mrep = NULL;
1920 nfsmout:
1921         VTONFS(dvp)->n_flag |= NLMODIFIED;
1922         if (!wccflag)
1923                 VTONFS(dvp)->n_attrstamp = 0;
1924         return (error);
1925 }
1926
1927 /*
1928  * nfs file rename call
1929  *
1930  * nfs_rename(struct vnode *a_fdvp, struct vnode *a_fvp,
1931  *            struct componentname *a_fcnp, struct vnode *a_tdvp,
1932  *            struct vnode *a_tvp, struct componentname *a_tcnp)
1933  */
1934 static int
1935 nfs_rename(struct vop_old_rename_args *ap)
1936 {
1937         struct vnode *fvp = ap->a_fvp;
1938         struct vnode *tvp = ap->a_tvp;
1939         struct vnode *fdvp = ap->a_fdvp;
1940         struct vnode *tdvp = ap->a_tdvp;
1941         struct componentname *tcnp = ap->a_tcnp;
1942         struct componentname *fcnp = ap->a_fcnp;
1943         struct nfsmount *nmp = VFSTONFS(fdvp->v_mount);
1944         int error;
1945
1946         lwkt_gettoken(&nmp->nm_token);
1947
1948         /*
1949          * Force finalization so the VOP_INACTIVE() call is not delayed.
1950          * This prevents cred structures from building up in nfsnodes
1951          * for deleted files.
1952          */
1953         if (tvp) {
1954                 atomic_set_int(&tvp->v_refcnt, VREF_FINALIZE);
1955                 if (VTONFS(tvp))
1956                         VTONFS(tvp)->n_flag |= NREMOVED;
1957         }
1958
1959         /* Check for cross-device rename */
1960         if ((fvp->v_mount != tdvp->v_mount) ||
1961             (tvp && (fvp->v_mount != tvp->v_mount))) {
1962                 error = EXDEV;
1963                 goto out;
1964         }
1965
1966         /*
1967          * We shouldn't have to flush fvp on rename for most server-side
1968          * filesystems as the file handle should not change.  Unfortunately
1969          * the inode for some filesystems (msdosfs) might be tied to the
1970          * file name or directory position so to be completely safe
1971          * vfs.nfs.flush_on_rename is set by default.  Clear to improve
1972          * performance.
1973          *
1974          * We must flush tvp on rename because it might become stale on the
1975          * server after the rename.
1976          */
1977         if (nfs_flush_on_rename)
1978             VOP_FSYNC(fvp, MNT_WAIT, 0);
1979         if (tvp)
1980             VOP_FSYNC(tvp, MNT_WAIT, 0);
1981
1982         /*
1983          * If the tvp exists and is in use, sillyrename it before doing the
1984          * rename of the new file over it.
1985          *
1986          * XXX Can't sillyrename a directory.
1987          *
1988          * We do not attempt to do any namecache purges in this old API
1989          * routine.  The new API compat functions have access to the actual
1990          * namecache structures and will do it for us.
1991          */
1992         if (tvp && VREFCNT(tvp) > 1 && !VTONFS(tvp)->n_sillyrename &&
1993                 tvp->v_type != VDIR && !nfs_sillyrename(tdvp, tvp, tcnp)) {
1994                 nfs_knote(tvp, NOTE_DELETE);
1995                 vput(tvp);
1996                 tvp = NULL;
1997         } else if (tvp) {
1998                 nfs_knote(tvp, NOTE_DELETE);
1999         }
2000
2001         error = nfs_renamerpc(fdvp, fcnp->cn_nameptr, fcnp->cn_namelen,
2002                 tdvp, tcnp->cn_nameptr, tcnp->cn_namelen, tcnp->cn_cred,
2003                 tcnp->cn_td);
2004
2005 out:
2006         if (error == 0) {
2007                 nfs_knote(fdvp, NOTE_WRITE);
2008                 nfs_knote(tdvp, NOTE_WRITE);
2009                 nfs_knote(fvp, NOTE_RENAME);
2010         }
2011         lwkt_reltoken(&nmp->nm_token);
2012         if (tdvp == tvp)
2013                 vrele(tdvp);
2014         else
2015                 vput(tdvp);
2016         if (tvp)
2017                 vput(tvp);
2018         vrele(fdvp);
2019         vrele(fvp);
2020         /*
2021          * Kludge: Map ENOENT => 0 assuming that it is a reply to a retry.
2022          */
2023         if (error == ENOENT)
2024                 error = 0;
2025         return (error);
2026 }
2027
2028 /*
2029  * nfs file rename rpc called from nfs_remove() above
2030  */
2031 static int
2032 nfs_renameit(struct vnode *sdvp, struct componentname *scnp,
2033              struct sillyrename *sp)
2034 {
2035         return (nfs_renamerpc(sdvp, scnp->cn_nameptr, scnp->cn_namelen,
2036                 sdvp, sp->s_name, sp->s_namlen, scnp->cn_cred, scnp->cn_td));
2037 }
2038
2039 /*
2040  * Do an nfs rename rpc. Called from nfs_rename() and nfs_renameit().
2041  */
2042 static int
2043 nfs_renamerpc(struct vnode *fdvp, const char *fnameptr, int fnamelen,
2044               struct vnode *tdvp, const char *tnameptr, int tnamelen,
2045               struct ucred *cred, struct thread *td)
2046 {
2047         int error = 0, fwccflag = NFSV3_WCCRATTR, twccflag = NFSV3_WCCRATTR;
2048         struct nfsm_info info;
2049
2050         info.mrep = NULL;
2051         info.v3 = NFS_ISV3(fdvp);
2052
2053         nfsstats.rpccnt[NFSPROC_RENAME]++;
2054         nfsm_reqhead(&info, fdvp, NFSPROC_RENAME,
2055                     (NFSX_FH(info.v3) + NFSX_UNSIGNED)*2 +
2056                     nfsm_rndup(fnamelen) + nfsm_rndup(tnamelen));
2057         ERROROUT(nfsm_fhtom(&info, fdvp));
2058         ERROROUT(nfsm_strtom(&info, fnameptr, fnamelen, NFS_MAXNAMLEN));
2059         ERROROUT(nfsm_fhtom(&info, tdvp));
2060         ERROROUT(nfsm_strtom(&info, tnameptr, tnamelen, NFS_MAXNAMLEN));
2061         NEGKEEPOUT(nfsm_request(&info, fdvp, NFSPROC_RENAME, td, cred, &error));
2062         if (info.v3) {
2063                 ERROROUT(nfsm_wcc_data(&info, fdvp, &fwccflag));
2064                 ERROROUT(nfsm_wcc_data(&info, tdvp, &twccflag));
2065         }
2066         m_freem(info.mrep);
2067         info.mrep = NULL;
2068 nfsmout:
2069         VTONFS(fdvp)->n_flag |= NLMODIFIED;
2070         VTONFS(tdvp)->n_flag |= NLMODIFIED;
2071         if (!fwccflag)
2072                 VTONFS(fdvp)->n_attrstamp = 0;
2073         if (!twccflag)
2074                 VTONFS(tdvp)->n_attrstamp = 0;
2075         return (error);
2076 }
2077
2078 /*
2079  * nfs hard link create call
2080  *
2081  * nfs_link(struct vnode *a_tdvp, struct vnode *a_vp,
2082  *          struct componentname *a_cnp)
2083  */
2084 static int
2085 nfs_link(struct vop_old_link_args *ap)
2086 {
2087         struct vnode *vp = ap->a_vp;
2088         struct vnode *tdvp = ap->a_tdvp;
2089         struct nfsmount *nmp = VFSTONFS(tdvp->v_mount);
2090         struct componentname *cnp = ap->a_cnp;
2091         int error = 0, wccflag = NFSV3_WCCRATTR, attrflag = 0;
2092         struct nfsm_info info;
2093
2094         if (vp->v_mount != tdvp->v_mount) {
2095                 return (EXDEV);
2096         }
2097         lwkt_gettoken(&nmp->nm_token);
2098
2099         /*
2100          * The attribute cache may get out of sync with the server on link.
2101          * Pushing writes to the server before handle was inherited from
2102          * long long ago and it is unclear if we still need to do this.
2103          * Defaults to off.
2104          */
2105         if (nfs_flush_on_hlink)
2106                 VOP_FSYNC(vp, MNT_WAIT, 0);
2107
2108         info.mrep = NULL;
2109         info.v3 = NFS_ISV3(vp);
2110
2111         nfsstats.rpccnt[NFSPROC_LINK]++;
2112         nfsm_reqhead(&info, vp, NFSPROC_LINK,
2113                      NFSX_FH(info.v3) * 2 + NFSX_UNSIGNED +
2114                      nfsm_rndup(cnp->cn_namelen));
2115         ERROROUT(nfsm_fhtom(&info, vp));
2116         ERROROUT(nfsm_fhtom(&info, tdvp));
2117         ERROROUT(nfsm_strtom(&info, cnp->cn_nameptr, cnp->cn_namelen,
2118                              NFS_MAXNAMLEN));
2119         NEGKEEPOUT(nfsm_request(&info, vp, NFSPROC_LINK, cnp->cn_td,
2120                                 cnp->cn_cred, &error));
2121         if (info.v3) {
2122                 ERROROUT(nfsm_postop_attr(&info, vp, &attrflag,
2123                                          NFS_LATTR_NOSHRINK));
2124                 ERROROUT(nfsm_wcc_data(&info, tdvp, &wccflag));
2125         }
2126         m_freem(info.mrep);
2127         info.mrep = NULL;
2128 nfsmout:
2129         VTONFS(tdvp)->n_flag |= NLMODIFIED;
2130         if (!attrflag)
2131                 VTONFS(vp)->n_attrstamp = 0;
2132         if (!wccflag)
2133                 VTONFS(tdvp)->n_attrstamp = 0;
2134         /*
2135          * Kludge: Map EEXIST => 0 assuming that it is a reply to a retry.
2136          */
2137         if (error == EEXIST)
2138                 error = 0;
2139         lwkt_reltoken(&nmp->nm_token);
2140         if (error == 0) {
2141                 nfs_knote(vp, NOTE_LINK);
2142                 nfs_knote(tdvp, NOTE_WRITE);
2143         }
2144
2145         return (error);
2146 }
2147
2148 /*
2149  * nfs symbolic link create call
2150  *
2151  * nfs_symlink(struct vnode *a_dvp, struct vnode **a_vpp,
2152  *              struct componentname *a_cnp, struct vattr *a_vap,
2153  *              char *a_target)
2154  */
2155 static int
2156 nfs_symlink(struct vop_old_symlink_args *ap)
2157 {
2158         struct vnode *dvp = ap->a_dvp;
2159         struct vattr *vap = ap->a_vap;
2160         struct nfsmount *nmp = VFSTONFS(dvp->v_mount);
2161         struct componentname *cnp = ap->a_cnp;
2162         struct nfsv2_sattr *sp;
2163         int slen, error = 0, wccflag = NFSV3_WCCRATTR, gotvp;
2164         struct vnode *newvp = NULL;
2165         struct nfsm_info info;
2166
2167         info.mrep = NULL;
2168         info.v3 = NFS_ISV3(dvp);
2169         lwkt_gettoken(&nmp->nm_token);
2170
2171         nfsstats.rpccnt[NFSPROC_SYMLINK]++;
2172         slen = strlen(ap->a_target);
2173         nfsm_reqhead(&info, dvp, NFSPROC_SYMLINK,
2174                      NFSX_FH(info.v3) + 2*NFSX_UNSIGNED +
2175                      nfsm_rndup(cnp->cn_namelen) +
2176                      nfsm_rndup(slen) + NFSX_SATTR(info.v3));
2177         ERROROUT(nfsm_fhtom(&info, dvp));
2178         ERROROUT(nfsm_strtom(&info, cnp->cn_nameptr, cnp->cn_namelen,
2179                              NFS_MAXNAMLEN));
2180         if (info.v3) {
2181                 nfsm_v3attrbuild(&info, vap, FALSE);
2182         }
2183         ERROROUT(nfsm_strtom(&info, ap->a_target, slen, NFS_MAXPATHLEN));
2184         if (info.v3 == 0) {
2185                 sp = nfsm_build(&info, NFSX_V2SATTR);
2186                 sp->sa_mode = vtonfsv2_mode(VLNK, vap->va_mode);
2187                 sp->sa_uid = nfs_xdrneg1;
2188                 sp->sa_gid = nfs_xdrneg1;
2189                 sp->sa_size = nfs_xdrneg1;
2190                 txdr_nfsv2time(&vap->va_atime, &sp->sa_atime);
2191                 txdr_nfsv2time(&vap->va_mtime, &sp->sa_mtime);
2192         }
2193
2194         /*
2195          * Issue the NFS request and get the rpc response.
2196          *
2197          * Only NFSv3 responses returning an error of 0 actually return
2198          * a file handle that can be converted into newvp without having
2199          * to do an extra lookup rpc.
2200          */
2201         NEGKEEPOUT(nfsm_request(&info, dvp, NFSPROC_SYMLINK, cnp->cn_td,
2202                                 cnp->cn_cred, &error));
2203         if (info.v3) {
2204                 if (error == 0) {
2205                        ERROROUT(nfsm_mtofh(&info, dvp, &newvp, &gotvp));
2206                 }
2207                 ERROROUT(nfsm_wcc_data(&info, dvp, &wccflag));
2208         }
2209
2210         /*
2211          * out code jumps -> here, mrep is also freed.
2212          */
2213
2214         m_freem(info.mrep);
2215         info.mrep = NULL;
2216 nfsmout:
2217
2218         /*
2219          * If we get an EEXIST error, silently convert it to no-error
2220          * in case of an NFS retry.
2221          */
2222         if (error == EEXIST)
2223                 error = 0;
2224
2225         /*
2226          * If we do not have (or no longer have) an error, and we could
2227          * not extract the newvp from the response due to the request being
2228          * NFSv2 or the error being EEXIST.  We have to do a lookup in order
2229          * to obtain a newvp to return.  
2230          */
2231         if (error == 0 && newvp == NULL) {
2232                 struct nfsnode *np = NULL;
2233
2234                 error = nfs_lookitup(dvp, cnp->cn_nameptr, cnp->cn_namelen,
2235                                      cnp->cn_cred, cnp->cn_td, &np);
2236                 if (!error)
2237                         newvp = NFSTOV(np);
2238         }
2239         if (error) {
2240                 if (newvp)
2241                         vput(newvp);
2242         } else {
2243                 *ap->a_vpp = newvp;
2244         }
2245         VTONFS(dvp)->n_flag |= NLMODIFIED;
2246         if (!wccflag)
2247                 VTONFS(dvp)->n_attrstamp = 0;
2248         if (error == 0 && *ap->a_vpp)
2249                 nfs_knote(*ap->a_vpp, NOTE_WRITE);
2250         lwkt_reltoken(&nmp->nm_token);
2251
2252         return (error);
2253 }
2254
2255 /*
2256  * nfs make dir call
2257  *
2258  * nfs_mkdir(struct vnode *a_dvp, struct vnode **a_vpp,
2259  *           struct componentname *a_cnp, struct vattr *a_vap)
2260  */
2261 static int
2262 nfs_mkdir(struct vop_old_mkdir_args *ap)
2263 {
2264         struct vnode *dvp = ap->a_dvp;
2265         struct vattr *vap = ap->a_vap;
2266         struct nfsmount *nmp = VFSTONFS(dvp->v_mount);
2267         struct componentname *cnp = ap->a_cnp;
2268         struct nfsv2_sattr *sp;
2269         struct nfsnode *np = NULL;
2270         struct vnode *newvp = NULL;
2271         struct vattr vattr;
2272         int error = 0, wccflag = NFSV3_WCCRATTR;
2273         int gotvp = 0;
2274         int len;
2275         struct nfsm_info info;
2276
2277         info.mrep = NULL;
2278         info.v3 = NFS_ISV3(dvp);
2279         lwkt_gettoken(&nmp->nm_token);
2280
2281         if ((error = VOP_GETATTR(dvp, &vattr)) != 0) {
2282                 lwkt_reltoken(&nmp->nm_token);
2283                 return (error);
2284         }
2285         len = cnp->cn_namelen;
2286         nfsstats.rpccnt[NFSPROC_MKDIR]++;
2287         nfsm_reqhead(&info, dvp, NFSPROC_MKDIR,
2288                      NFSX_FH(info.v3) + NFSX_UNSIGNED +
2289                      nfsm_rndup(len) + NFSX_SATTR(info.v3));
2290         ERROROUT(nfsm_fhtom(&info, dvp));
2291         ERROROUT(nfsm_strtom(&info, cnp->cn_nameptr, len, NFS_MAXNAMLEN));
2292         if (info.v3) {
2293                 nfsm_v3attrbuild(&info, vap, FALSE);
2294         } else {
2295                 sp = nfsm_build(&info, NFSX_V2SATTR);
2296                 sp->sa_mode = vtonfsv2_mode(VDIR, vap->va_mode);
2297                 sp->sa_uid = nfs_xdrneg1;
2298                 sp->sa_gid = nfs_xdrneg1;
2299                 sp->sa_size = nfs_xdrneg1;
2300                 txdr_nfsv2time(&vap->va_atime, &sp->sa_atime);
2301                 txdr_nfsv2time(&vap->va_mtime, &sp->sa_mtime);
2302         }
2303         NEGKEEPOUT(nfsm_request(&info, dvp, NFSPROC_MKDIR, cnp->cn_td,
2304                     cnp->cn_cred, &error));
2305         if (error == 0) {
2306                 ERROROUT(nfsm_mtofh(&info, dvp, &newvp, &gotvp));
2307         }
2308         if (info.v3) {
2309                 ERROROUT(nfsm_wcc_data(&info, dvp, &wccflag));
2310         }
2311         m_freem(info.mrep);
2312         info.mrep = NULL;
2313 nfsmout:
2314         VTONFS(dvp)->n_flag |= NLMODIFIED;
2315         if (!wccflag)
2316                 VTONFS(dvp)->n_attrstamp = 0;
2317         /*
2318          * Kludge: Map EEXIST => 0 assuming that you have a reply to a retry
2319          * if we can succeed in looking up the directory.
2320          */
2321         if (error == EEXIST || (!error && !gotvp)) {
2322                 if (newvp) {
2323                         vrele(newvp);
2324                         newvp = NULL;
2325                 }
2326                 error = nfs_lookitup(dvp, cnp->cn_nameptr, len, cnp->cn_cred,
2327                         cnp->cn_td, &np);
2328                 if (!error) {
2329                         newvp = NFSTOV(np);
2330                         if (newvp->v_type != VDIR)
2331                                 error = EEXIST;
2332                 }
2333         }
2334         if (error) {
2335                 if (newvp)
2336                         vrele(newvp);
2337         } else {
2338                 nfs_knote(dvp, NOTE_WRITE | NOTE_LINK);
2339                 *ap->a_vpp = newvp;
2340         }
2341         lwkt_reltoken(&nmp->nm_token);
2342         return (error);
2343 }
2344
2345 /*
2346  * nfs remove directory call
2347  *
2348  * nfs_rmdir(struct vnode *a_dvp, struct vnode *a_vp,
2349  *           struct componentname *a_cnp)
2350  */
2351 static int
2352 nfs_rmdir(struct vop_old_rmdir_args *ap)
2353 {
2354         struct vnode *vp = ap->a_vp;
2355         struct vnode *dvp = ap->a_dvp;
2356         struct nfsmount *nmp = VFSTONFS(dvp->v_mount);
2357         struct componentname *cnp = ap->a_cnp;
2358         int error = 0, wccflag = NFSV3_WCCRATTR;
2359         struct nfsm_info info;
2360
2361         info.mrep = NULL;
2362         info.v3 = NFS_ISV3(dvp);
2363
2364         if (dvp == vp)
2365                 return (EINVAL);
2366
2367         lwkt_gettoken(&nmp->nm_token);
2368
2369         nfsstats.rpccnt[NFSPROC_RMDIR]++;
2370         nfsm_reqhead(&info, dvp, NFSPROC_RMDIR,
2371                      NFSX_FH(info.v3) + NFSX_UNSIGNED +
2372                      nfsm_rndup(cnp->cn_namelen));
2373         ERROROUT(nfsm_fhtom(&info, dvp));
2374         ERROROUT(nfsm_strtom(&info, cnp->cn_nameptr, cnp->cn_namelen,
2375                  NFS_MAXNAMLEN));
2376         NEGKEEPOUT(nfsm_request(&info, dvp, NFSPROC_RMDIR, cnp->cn_td,
2377                                 cnp->cn_cred, &error));
2378         if (info.v3) {
2379                 ERROROUT(nfsm_wcc_data(&info, dvp, &wccflag));
2380         }
2381         m_freem(info.mrep);
2382         info.mrep = NULL;
2383 nfsmout:
2384         VTONFS(dvp)->n_flag |= NLMODIFIED;
2385         if (!wccflag)
2386                 VTONFS(dvp)->n_attrstamp = 0;
2387         /*
2388          * Kludge: Map ENOENT => 0 assuming that you have a reply to a retry.
2389          */
2390         if (error == ENOENT)
2391                 error = 0;
2392         else
2393                 nfs_knote(dvp, NOTE_WRITE | NOTE_LINK);
2394         lwkt_reltoken(&nmp->nm_token);
2395
2396         return (error);
2397 }
2398
2399 /*
2400  * nfs readdir call
2401  *
2402  * nfs_readdir(struct vnode *a_vp, struct uio *a_uio, struct ucred *a_cred)
2403  */
2404 static int
2405 nfs_readdir(struct vop_readdir_args *ap)
2406 {
2407         struct vnode *vp = ap->a_vp;
2408         struct nfsnode *np = VTONFS(vp);
2409         struct nfsmount *nmp = VFSTONFS(vp->v_mount);
2410         struct uio *uio = ap->a_uio;
2411         int tresid, error;
2412         struct vattr vattr;
2413
2414         if (vp->v_type != VDIR)
2415                 return (EPERM);
2416
2417         error = vn_lock(vp, LK_EXCLUSIVE | LK_RETRY | LK_FAILRECLAIM);
2418         if (error)
2419                 return (error);
2420
2421         lwkt_gettoken(&nmp->nm_token);
2422
2423         /*
2424          * If we have a valid EOF offset cache we must call VOP_GETATTR()
2425          * and then check that is still valid, or if this is an NQNFS mount
2426          * we call NQNFS_CKCACHEABLE() instead of VOP_GETATTR().  Note that
2427          * VOP_GETATTR() does not necessarily go to the wire.
2428          */
2429         if (np->n_direofoffset > 0 && uio->uio_offset >= np->n_direofoffset &&
2430             (np->n_flag & (NLMODIFIED|NRMODIFIED)) == 0) {
2431                 if (VOP_GETATTR(vp, &vattr) == 0 &&
2432                     (np->n_flag & (NLMODIFIED|NRMODIFIED)) == 0
2433                 ) {
2434                         nfsstats.direofcache_hits++;
2435                         goto done;
2436                 }
2437         }
2438
2439         /*
2440          * Call nfs_bioread() to do the real work.  nfs_bioread() does its
2441          * own cache coherency checks so we do not have to.
2442          */
2443         tresid = uio->uio_resid;
2444         error = nfs_bioread(vp, uio, 0);
2445
2446         if (!error && uio->uio_resid == tresid)
2447                 nfsstats.direofcache_misses++;
2448 done:
2449         lwkt_reltoken(&nmp->nm_token);
2450         vn_unlock(vp);
2451
2452         return (error);
2453 }
2454
2455 /*
2456  * Readdir rpc call.  nfs_bioread->nfs_doio->nfs_readdirrpc.
2457  *
2458  * Note that for directories, nfs_bioread maintains the underlying nfs-centric
2459  * offset/block and converts the nfs formatted directory entries for userland
2460  * consumption as well as deals with offsets into the middle of blocks.
2461  * nfs_doio only deals with logical blocks.  In particular, uio_offset will
2462  * be block-bounded.  It must convert to cookies for the actual RPC.
2463  */
2464 int
2465 nfs_readdirrpc_uio(struct vnode *vp, struct uio *uiop)
2466 {
2467         int len, left;
2468         struct nfs_dirent *dp = NULL;
2469         u_int32_t *tl;
2470         nfsuint64 *cookiep;
2471         caddr_t cp;
2472         nfsuint64 cookie;
2473         struct nfsmount *nmp = VFSTONFS(vp->v_mount);
2474         struct nfsnode *dnp = VTONFS(vp);
2475         u_quad_t fileno;
2476         int error = 0, tlen, more_dirs = 1, blksiz = 0, bigenough = 1;
2477         int attrflag;
2478         struct nfsm_info info;
2479
2480         info.mrep = NULL;
2481         info.v3 = NFS_ISV3(vp);
2482
2483 #ifndef DIAGNOSTIC
2484         if (uiop->uio_iovcnt != 1 || (uiop->uio_offset & (DIRBLKSIZ - 1)) ||
2485                 (uiop->uio_resid & (DIRBLKSIZ - 1)))
2486                 panic("nfs readdirrpc bad uio");
2487 #endif
2488
2489         /*
2490          * If there is no cookie, assume directory was stale.
2491          */
2492         cookiep = nfs_getcookie(dnp, uiop->uio_offset, 0);
2493         if (cookiep)
2494                 cookie = *cookiep;
2495         else
2496                 return (NFSERR_BAD_COOKIE);
2497         /*
2498          * Loop around doing readdir rpc's of size nm_readdirsize
2499          * truncated to a multiple of DIRBLKSIZ.
2500          * The stopping criteria is EOF or buffer full.
2501          */
2502         while (more_dirs && bigenough) {
2503                 nfsstats.rpccnt[NFSPROC_READDIR]++;
2504                 nfsm_reqhead(&info, vp, NFSPROC_READDIR,
2505                              NFSX_FH(info.v3) + NFSX_READDIR(info.v3));
2506                 ERROROUT(nfsm_fhtom(&info, vp));
2507                 if (info.v3) {
2508                         tl = nfsm_build(&info, 5 * NFSX_UNSIGNED);
2509                         *tl++ = cookie.nfsuquad[0];
2510                         *tl++ = cookie.nfsuquad[1];
2511                         *tl++ = dnp->n_cookieverf.nfsuquad[0];
2512                         *tl++ = dnp->n_cookieverf.nfsuquad[1];
2513                 } else {
2514                         /*
2515                          * WARNING!  HAMMER DIRECTORIES WILL NOT WORK WELL
2516                          * WITH NFSv2!!!  There's nothing I can really do
2517                          * about it other than to hope the server supports
2518                          * rdirplus w/NFSv2.
2519                          */
2520                         tl = nfsm_build(&info, 2 * NFSX_UNSIGNED);
2521                         *tl++ = cookie.nfsuquad[0];
2522                 }
2523                 *tl = txdr_unsigned(nmp->nm_readdirsize);
2524                 NEGKEEPOUT(nfsm_request(&info, vp, NFSPROC_READDIR,
2525                                         uiop->uio_td,
2526                                         nfs_vpcred(vp, ND_READ), &error));
2527                 if (info.v3) {
2528                         ERROROUT(nfsm_postop_attr(&info, vp, &attrflag,
2529                                                   NFS_LATTR_NOSHRINK));
2530                         NULLOUT(tl = nfsm_dissect(&info, 2 * NFSX_UNSIGNED));
2531                         dnp->n_cookieverf.nfsuquad[0] = *tl++;
2532                         dnp->n_cookieverf.nfsuquad[1] = *tl;
2533                 }
2534                 NULLOUT(tl = nfsm_dissect(&info, NFSX_UNSIGNED));
2535                 more_dirs = fxdr_unsigned(int, *tl);
2536         
2537                 /* loop thru the dir entries, converting them to std form */
2538                 while (more_dirs && bigenough) {
2539                         if (info.v3) {
2540                                 NULLOUT(tl = nfsm_dissect(&info, 3 * NFSX_UNSIGNED));
2541                                 fileno = fxdr_hyper(tl);
2542                                 len = fxdr_unsigned(int, *(tl + 2));
2543                         } else {
2544                                 NULLOUT(tl = nfsm_dissect(&info, 2 * NFSX_UNSIGNED));
2545                                 fileno = fxdr_unsigned(u_quad_t, *tl++);
2546                                 len = fxdr_unsigned(int, *tl);
2547                         }
2548                         if (len <= 0 || len > NFS_MAXNAMLEN) {
2549                                 error = EBADRPC;
2550                                 m_freem(info.mrep);
2551                                 info.mrep = NULL;
2552                                 goto nfsmout;
2553                         }
2554
2555                         /*
2556                          * len is the number of bytes in the path element
2557                          * name, not including the \0 termination.
2558                          *
2559                          * tlen is the number of bytes w have to reserve for
2560                          * the path element name.
2561                          */
2562                         tlen = nfsm_rndup(len);
2563                         if (tlen == len)
2564                                 tlen += 4;      /* To ensure null termination */
2565
2566                         /*
2567                          * If the entry would cross a DIRBLKSIZ boundary, 
2568                          * extend the previous nfs_dirent to cover the
2569                          * remaining space.
2570                          */
2571                         left = DIRBLKSIZ - blksiz;
2572                         if ((tlen + sizeof(struct nfs_dirent)) > left) {
2573                                 dp->nfs_reclen += left;
2574                                 uiop->uio_iov->iov_base = (char *)uiop->uio_iov->iov_base + left;
2575                                 uiop->uio_iov->iov_len -= left;
2576                                 uiop->uio_offset += left;
2577                                 uiop->uio_resid -= left;
2578                                 blksiz = 0;
2579                         }
2580                         if ((tlen + sizeof(struct nfs_dirent)) > uiop->uio_resid)
2581                                 bigenough = 0;
2582                         if (bigenough) {
2583                                 dp = (struct nfs_dirent *)uiop->uio_iov->iov_base;
2584                                 dp->nfs_ino = fileno;
2585                                 dp->nfs_namlen = len;
2586                                 dp->nfs_reclen = tlen + sizeof(struct nfs_dirent);
2587                                 dp->nfs_type = DT_UNKNOWN;
2588                                 blksiz += dp->nfs_reclen;
2589                                 if (blksiz == DIRBLKSIZ)
2590                                         blksiz = 0;
2591                                 uiop->uio_offset += sizeof(struct nfs_dirent);
2592                                 uiop->uio_resid -= sizeof(struct nfs_dirent);
2593                                 uiop->uio_iov->iov_base = (char *)uiop->uio_iov->iov_base + sizeof(struct nfs_dirent);
2594                                 uiop->uio_iov->iov_len -= sizeof(struct nfs_dirent);
2595                                 ERROROUT(nfsm_mtouio(&info, uiop, len));
2596
2597                                 /*
2598                                  * The uiop has advanced by nfs_dirent + len
2599                                  * but really needs to advance by
2600                                  * nfs_dirent + tlen
2601                                  */
2602                                 cp = uiop->uio_iov->iov_base;
2603                                 tlen -= len;
2604                                 *cp = '\0';     /* null terminate */
2605                                 uiop->uio_iov->iov_base = (char *)uiop->uio_iov->iov_base + tlen;
2606                                 uiop->uio_iov->iov_len -= tlen;
2607                                 uiop->uio_offset += tlen;
2608                                 uiop->uio_resid -= tlen;
2609                         } else {
2610                                 /*
2611                                  * NFS strings must be rounded up (nfsm_myouio
2612                                  * handled that in the bigenough case).
2613                                  */
2614                                 ERROROUT(nfsm_adv(&info, nfsm_rndup(len)));
2615                         }
2616                         if (info.v3) {
2617                                 NULLOUT(tl = nfsm_dissect(&info, 3 * NFSX_UNSIGNED));
2618                         } else {
2619                                 NULLOUT(tl = nfsm_dissect(&info, 2 * NFSX_UNSIGNED));
2620                         }
2621
2622                         /*
2623                          * If we were able to accomodate the last entry,
2624                          * get the cookie for the next one.  Otherwise
2625                          * hold-over the cookie for the one we were not
2626                          * able to accomodate.
2627                          */
2628                         if (bigenough) {
2629                                 cookie.nfsuquad[0] = *tl++;
2630                                 if (info.v3)
2631                                         cookie.nfsuquad[1] = *tl++;
2632                         } else if (info.v3) {
2633                                 tl += 2;
2634                         } else {
2635                                 tl++;
2636                         }
2637                         more_dirs = fxdr_unsigned(int, *tl);
2638                 }
2639                 /*
2640                  * If at end of rpc data, get the eof boolean
2641                  */
2642                 if (!more_dirs) {
2643                         NULLOUT(tl = nfsm_dissect(&info, NFSX_UNSIGNED));
2644                         more_dirs = (fxdr_unsigned(int, *tl) == 0);
2645                 }
2646                 m_freem(info.mrep);
2647                 info.mrep = NULL;
2648         }
2649         /*
2650          * Fill last record, iff any, out to a multiple of DIRBLKSIZ
2651          * by increasing d_reclen for the last record.
2652          */
2653         if (blksiz > 0) {
2654                 left = DIRBLKSIZ - blksiz;
2655                 dp->nfs_reclen += left;
2656                 uiop->uio_iov->iov_base = (char *)uiop->uio_iov->iov_base + left;
2657                 uiop->uio_iov->iov_len -= left;
2658                 uiop->uio_offset += left;
2659                 uiop->uio_resid -= left;
2660         }
2661
2662         if (bigenough) {
2663                 /*
2664                  * We hit the end of the directory, update direofoffset.
2665                  */
2666                 dnp->n_direofoffset = uiop->uio_offset;
2667         } else {
2668                 /*
2669                  * There is more to go, insert the link cookie so the
2670                  * next block can be read.
2671                  */
2672                 if (uiop->uio_resid > 0)
2673                         kprintf("EEK! readdirrpc resid > 0\n");
2674                 cookiep = nfs_getcookie(dnp, uiop->uio_offset, 1);
2675                 *cookiep = cookie;
2676         }
2677 nfsmout:
2678         return (error);
2679 }
2680
2681 /*
2682  * NFS V3 readdir plus RPC. Used in place of nfs_readdirrpc().
2683  */
2684 int
2685 nfs_readdirplusrpc_uio(struct vnode *vp, struct uio *uiop)
2686 {
2687         int len, left;
2688         struct nfs_dirent *dp;
2689         u_int32_t *tl;
2690         struct vnode *newvp;
2691         nfsuint64 *cookiep;
2692         caddr_t dpossav1, dpossav2;
2693         caddr_t cp;
2694         struct mbuf *mdsav1, *mdsav2;
2695         nfsuint64 cookie;
2696         struct nfsmount *nmp = VFSTONFS(vp->v_mount);
2697         struct nfsnode *dnp = VTONFS(vp), *np;
2698         nfsfh_t *fhp;
2699         u_quad_t fileno;
2700         int error = 0, tlen, more_dirs = 1, blksiz = 0, doit, bigenough = 1, i;
2701         int attrflag, fhsize;
2702         struct nchandle nch;
2703         struct nchandle dnch;
2704         struct nlcomponent nlc;
2705         struct nfsm_info info;
2706
2707         info.mrep = NULL;
2708         info.v3 = 1;
2709
2710 #ifndef nolint
2711         dp = NULL;
2712 #endif
2713 #ifndef DIAGNOSTIC
2714         if (uiop->uio_iovcnt != 1 || (uiop->uio_offset & (DIRBLKSIZ - 1)) ||
2715                 (uiop->uio_resid & (DIRBLKSIZ - 1)))
2716                 panic("nfs readdirplusrpc bad uio");
2717 #endif
2718         /*
2719          * Obtain the namecache record for the directory so we have something
2720          * to use as a basis for creating the entries.  This function will
2721          * return a held (but not locked) ncp.  The ncp may be disconnected
2722          * from the tree and cannot be used for upward traversals, and the
2723          * ncp may be unnamed.  Note that other unrelated operations may 
2724          * cause the ncp to be named at any time.
2725          *
2726          * We have to lock the ncp to prevent a lock order reversal when
2727          * rdirplus does nlookups of the children, because the vnode is
2728          * locked and has to stay that way.
2729          */
2730         cache_fromdvp(vp, NULL, 0, &dnch);
2731         bzero(&nlc, sizeof(nlc));
2732         newvp = NULLVP;
2733
2734         /*
2735          * If there is no cookie, assume directory was stale.
2736          */
2737         cookiep = nfs_getcookie(dnp, uiop->uio_offset, 0);
2738         if (cookiep) {
2739                 cookie = *cookiep;
2740         } else {
2741                 if (dnch.ncp)
2742                         cache_drop(&dnch);
2743                 return (NFSERR_BAD_COOKIE);
2744         }
2745
2746         /*
2747          * Loop around doing readdir rpc's of size nm_readdirsize
2748          * truncated to a multiple of DIRBLKSIZ.
2749          * The stopping criteria is EOF or buffer full.
2750          */
2751         while (more_dirs && bigenough) {
2752                 nfsstats.rpccnt[NFSPROC_READDIRPLUS]++;
2753                 nfsm_reqhead(&info, vp, NFSPROC_READDIRPLUS,
2754                              NFSX_FH(info.v3) + 6 * NFSX_UNSIGNED);
2755                 ERROROUT(nfsm_fhtom(&info, vp));
2756                 tl = nfsm_build(&info, 6 * NFSX_UNSIGNED);
2757                 *tl++ = cookie.nfsuquad[0];
2758                 *tl++ = cookie.nfsuquad[1];
2759                 *tl++ = dnp->n_cookieverf.nfsuquad[0];
2760                 *tl++ = dnp->n_cookieverf.nfsuquad[1];
2761                 *tl++ = txdr_unsigned(nmp->nm_readdirsize);
2762                 *tl = txdr_unsigned(nmp->nm_rsize);
2763                 NEGKEEPOUT(nfsm_request(&info, vp, NFSPROC_READDIRPLUS,
2764                                         uiop->uio_td,
2765                                         nfs_vpcred(vp, ND_READ), &error));
2766                 ERROROUT(nfsm_postop_attr(&info, vp, &attrflag,
2767                                           NFS_LATTR_NOSHRINK));
2768                 NULLOUT(tl = nfsm_dissect(&info, 3 * NFSX_UNSIGNED));
2769                 dnp->n_cookieverf.nfsuquad[0] = *tl++;
2770                 dnp->n_cookieverf.nfsuquad[1] = *tl++;
2771                 more_dirs = fxdr_unsigned(int, *tl);
2772
2773                 /* loop thru the dir entries, doctoring them to 4bsd form */
2774                 while (more_dirs && bigenough) {
2775                         NULLOUT(tl = nfsm_dissect(&info, 3 * NFSX_UNSIGNED));
2776                         fileno = fxdr_hyper(tl);
2777                         len = fxdr_unsigned(int, *(tl + 2));
2778                         if (len <= 0 || len > NFS_MAXNAMLEN) {
2779                                 error = EBADRPC;
2780                                 m_freem(info.mrep);
2781                                 info.mrep = NULL;
2782                                 goto nfsmout;
2783                         }
2784                         tlen = nfsm_rndup(len);
2785                         if (tlen == len)
2786                                 tlen += 4;      /* To ensure null termination*/
2787                         left = DIRBLKSIZ - blksiz;
2788                         if ((tlen + sizeof(struct nfs_dirent)) > left) {
2789                                 dp->nfs_reclen += left;
2790                                 uiop->uio_iov->iov_base = (char *)uiop->uio_iov->iov_base + left;
2791                                 uiop->uio_iov->iov_len -= left;
2792                                 uiop->uio_offset += left;
2793                                 uiop->uio_resid -= left;
2794                                 blksiz = 0;
2795                         }
2796                         if ((tlen + sizeof(struct nfs_dirent)) > uiop->uio_resid)
2797                                 bigenough = 0;
2798                         if (bigenough) {
2799                                 dp = (struct nfs_dirent *)uiop->uio_iov->iov_base;
2800                                 dp->nfs_ino = fileno;
2801                                 dp->nfs_namlen = len;
2802                                 dp->nfs_reclen = tlen + sizeof(struct nfs_dirent);
2803                                 dp->nfs_type = DT_UNKNOWN;
2804                                 blksiz += dp->nfs_reclen;
2805                                 if (blksiz == DIRBLKSIZ)
2806                                         blksiz = 0;
2807                                 uiop->uio_offset += sizeof(struct nfs_dirent);
2808                                 uiop->uio_resid -= sizeof(struct nfs_dirent);
2809                                 uiop->uio_iov->iov_base = (char *)uiop->uio_iov->iov_base + sizeof(struct nfs_dirent);
2810                                 uiop->uio_iov->iov_len -= sizeof(struct nfs_dirent);
2811                                 nlc.nlc_nameptr = uiop->uio_iov->iov_base;
2812                                 nlc.nlc_namelen = len;
2813                                 ERROROUT(nfsm_mtouio(&info, uiop, len));
2814                                 cp = uiop->uio_iov->iov_base;
2815                                 tlen -= len;
2816                                 *cp = '\0';
2817                                 uiop->uio_iov->iov_base = (char *)uiop->uio_iov->iov_base + tlen;
2818                                 uiop->uio_iov->iov_len -= tlen;
2819                                 uiop->uio_offset += tlen;
2820                                 uiop->uio_resid -= tlen;
2821                         } else {
2822                                 ERROROUT(nfsm_adv(&info, nfsm_rndup(len)));
2823                         }
2824                         NULLOUT(tl = nfsm_dissect(&info, 3 * NFSX_UNSIGNED));
2825                         if (bigenough) {
2826                                 cookie.nfsuquad[0] = *tl++;
2827                                 cookie.nfsuquad[1] = *tl++;
2828                         } else {
2829                                 tl += 2;
2830                         }
2831
2832                         /*
2833                          * Since the attributes are before the file handle
2834                          * (sigh), we must skip over the attributes and then
2835                          * come back and get them.
2836                          */
2837                         attrflag = fxdr_unsigned(int, *tl);
2838                         if (attrflag) {
2839                             dpossav1 = info.dpos;
2840                             mdsav1 = info.md;
2841                             ERROROUT(nfsm_adv(&info, NFSX_V3FATTR));
2842                             NULLOUT(tl = nfsm_dissect(&info, NFSX_UNSIGNED));
2843                             doit = fxdr_unsigned(int, *tl);
2844                             if (doit) {
2845                                 NEGATIVEOUT(fhsize = nfsm_getfh(&info, &fhp));
2846                             }
2847                             if (doit && bigenough && !nlcdegenerate(&nlc) &&
2848                                 !NFS_CMPFH(dnp, fhp, fhsize)
2849                             ) {
2850                                 if (dnch.ncp) {
2851 #if 0
2852                                     kprintf("NFS/READDIRPLUS, ENTER %*.*s\n",
2853                                         nlc.nlc_namelen, nlc.nlc_namelen,
2854                                         nlc.nlc_nameptr);
2855 #endif
2856                                     /*
2857                                      * This is a bit hokey but there isn't
2858                                      * much we can do about it.  We can't
2859                                      * hold the directory vp locked while
2860                                      * doing lookups and gets.
2861                                      */
2862                                     nch = cache_nlookup_nonblock(&dnch, &nlc);
2863                                     if (nch.ncp == NULL)
2864                                         goto rdfail;
2865                                     cache_setunresolved(&nch);
2866                                     error = nfs_nget_nonblock(vp->v_mount, fhp,
2867                                                               fhsize, &np,
2868                                                               NULL);
2869                                     if (error) {
2870                                         cache_put(&nch);
2871                                         goto rdfail;
2872                                     }
2873                                     newvp = NFSTOV(np);
2874                                     dpossav2 = info.dpos;
2875                                     info.dpos = dpossav1;
2876                                     mdsav2 = info.md;
2877                                     info.md = mdsav1;
2878                                     ERROROUT(nfsm_loadattr(&info, newvp, NULL));
2879                                     info.dpos = dpossav2;
2880                                     info.md = mdsav2;
2881                                     dp->nfs_type =
2882                                             IFTODT(VTTOIF(np->n_vattr.va_type));
2883                                     nfs_cache_setvp(&nch, newvp,
2884                                                     nfspos_cache_timeout);
2885                                     vput(newvp);
2886                                     newvp = NULLVP;
2887                                     cache_put(&nch);
2888                                 } else {
2889 rdfail:
2890                                     ;
2891 #if 0
2892                                     kprintf("Warning: NFS/rddirplus, "
2893                                             "UNABLE TO ENTER %*.*s\n",
2894                                         nlc.nlc_namelen, nlc.nlc_namelen,
2895                                         nlc.nlc_nameptr);
2896 #endif
2897                                 }
2898                             }
2899                         } else {
2900                             /* Just skip over the file handle */
2901                             NULLOUT(tl = nfsm_dissect(&info, NFSX_UNSIGNED));
2902                             i = fxdr_unsigned(int, *tl);
2903                             ERROROUT(nfsm_adv(&info, nfsm_rndup(i)));
2904                         }
2905                         NULLOUT(tl = nfsm_dissect(&info, NFSX_UNSIGNED));
2906                         more_dirs = fxdr_unsigned(int, *tl);
2907                 }
2908                 /*
2909                  * If at end of rpc data, get the eof boolean
2910                  */
2911                 if (!more_dirs) {
2912                         NULLOUT(tl = nfsm_dissect(&info, NFSX_UNSIGNED));
2913                         more_dirs = (fxdr_unsigned(int, *tl) == 0);
2914                 }
2915                 m_freem(info.mrep);
2916                 info.mrep = NULL;
2917         }
2918         /*
2919          * Fill last record, iff any, out to a multiple of DIRBLKSIZ
2920          * by increasing d_reclen for the last record.
2921          */
2922         if (blksiz > 0) {
2923                 left = DIRBLKSIZ - blksiz;
2924                 dp->nfs_reclen += left;
2925                 uiop->uio_iov->iov_base = (char *)uiop->uio_iov->iov_base + left;
2926                 uiop->uio_iov->iov_len -= left;
2927                 uiop->uio_offset += left;
2928                 uiop->uio_resid -= left;
2929         }
2930
2931         /*
2932          * We are now either at the end of the directory or have filled the
2933          * block.
2934          */
2935         if (bigenough) {
2936                 dnp->n_direofoffset = uiop->uio_offset;
2937         } else {
2938                 if (uiop->uio_resid > 0)
2939                         kprintf("EEK! readdirplusrpc resid > 0\n");
2940                 cookiep = nfs_getcookie(dnp, uiop->uio_offset, 1);
2941                 *cookiep = cookie;
2942         }
2943 nfsmout:
2944         if (newvp != NULLVP) {
2945                 if (newvp == vp)
2946                         vrele(newvp);
2947                 else
2948                         vput(newvp);
2949                 newvp = NULLVP;
2950         }
2951         if (dnch.ncp)
2952                 cache_drop(&dnch);
2953         return (error);
2954 }
2955
2956 /*
2957  * Silly rename. To make the NFS filesystem that is stateless look a little
2958  * more like the "ufs" a remove of an active vnode is translated to a rename
2959  * to a funny looking filename that is removed by nfs_inactive on the
2960  * nfsnode. There is the potential for another process on a different client
2961  * to create the same funny name between the nfs_lookitup() fails and the
2962  * nfs_rename() completes, but...
2963  */
2964 static int
2965 nfs_sillyrename(struct vnode *dvp, struct vnode *vp, struct componentname *cnp)
2966 {
2967         struct sillyrename *sp;
2968         struct nfsnode *np;
2969         int error;
2970
2971         /*
2972          * Force finalization so the VOP_INACTIVE() call is not delayed.
2973          * This prevents cred structures from building up in nfsnodes
2974          * for deleted files.
2975          */
2976         atomic_set_int(&vp->v_refcnt, VREF_FINALIZE);
2977         np = VTONFS(vp);
2978         np->n_flag |= NREMOVED;
2979
2980         /*
2981          * We previously purged dvp instead of vp.  I don't know why, it
2982          * completely destroys performance.  We can't do it anyway with the
2983          * new VFS API since we would be breaking the namecache topology.
2984          */
2985         cache_purge(vp);        /* XXX */
2986 #ifndef DIAGNOSTIC
2987         if (vp->v_type == VDIR)
2988                 panic("nfs: sillyrename dir");
2989 #endif
2990         sp = kmalloc(sizeof(struct sillyrename), M_NFSREQ, M_WAITOK);
2991         sp->s_cred = crdup(cnp->cn_cred);
2992         sp->s_dvp = dvp;
2993         vref(dvp);
2994
2995         /* Fudge together a funny name */
2996         sp->s_namlen = ksprintf(sp->s_name, ".nfsA%08x4.4",
2997                                 (int)(intptr_t)cnp->cn_td);
2998
2999         /* Try lookitups until we get one that isn't there */
3000         while (nfs_lookitup(dvp, sp->s_name, sp->s_namlen, sp->s_cred,
3001                 cnp->cn_td, NULL) == 0) {
3002                 sp->s_name[4]++;
3003                 if (sp->s_name[4] > 'z') {
3004                         error = EINVAL;
3005                         goto bad;
3006                 }
3007         }
3008         error = nfs_renameit(dvp, cnp, sp);
3009         if (error)
3010                 goto bad;
3011         error = nfs_lookitup(dvp, sp->s_name, sp->s_namlen, sp->s_cred,
3012                 cnp->cn_td, &np);
3013         np->n_sillyrename = sp;
3014         return (0);
3015 bad:
3016         vrele(sp->s_dvp);
3017         crfree(sp->s_cred);
3018         kfree((caddr_t)sp, M_NFSREQ);
3019
3020         return (error);
3021 }
3022
3023 /*
3024  * Look up a file name and optionally either update the file handle or
3025  * allocate an nfsnode, depending on the value of npp.
3026  * npp == NULL  --> just do the lookup
3027  * *npp == NULL --> allocate a new nfsnode and make sure attributes are
3028  *                      handled too
3029  * *npp != NULL --> update the file handle in the vnode
3030  */
3031 static int
3032 nfs_lookitup(struct vnode *dvp, const char *name, int len, struct ucred *cred,
3033              struct thread *td, struct nfsnode **npp)
3034 {
3035         struct vnode *newvp = NULL;
3036         struct nfsnode *np, *dnp = VTONFS(dvp);
3037         int error = 0, fhlen, attrflag;
3038         nfsfh_t *nfhp;
3039         struct nfsm_info info;
3040
3041         info.mrep = NULL;
3042         info.v3 = NFS_ISV3(dvp);
3043
3044         nfsstats.rpccnt[NFSPROC_LOOKUP]++;
3045         nfsm_reqhead(&info, dvp, NFSPROC_LOOKUP,
3046                      NFSX_FH(info.v3) + NFSX_UNSIGNED + nfsm_rndup(len));
3047         ERROROUT(nfsm_fhtom(&info, dvp));
3048         ERROROUT(nfsm_strtom(&info, name, len, NFS_MAXNAMLEN));
3049         NEGKEEPOUT(nfsm_request(&info, dvp, NFSPROC_LOOKUP, td, cred, &error));
3050         if (npp && !error) {
3051                 NEGATIVEOUT(fhlen = nfsm_getfh(&info, &nfhp));
3052                 if (*npp) {
3053                     np = *npp;
3054                     if (np->n_fhsize > NFS_SMALLFH && fhlen <= NFS_SMALLFH) {
3055                         kfree((caddr_t)np->n_fhp, M_NFSBIGFH);
3056                         np->n_fhp = &np->n_fh;
3057                     } else if (np->n_fhsize <= NFS_SMALLFH && fhlen>NFS_SMALLFH)
3058                         np->n_fhp =(nfsfh_t *)kmalloc(fhlen,M_NFSBIGFH,M_WAITOK);
3059                     bcopy((caddr_t)nfhp, (caddr_t)np->n_fhp, fhlen);
3060                     np->n_fhsize = fhlen;
3061                     newvp = NFSTOV(np);
3062                 } else if (NFS_CMPFH(dnp, nfhp, fhlen)) {
3063                     vref(dvp);
3064                     newvp = dvp;
3065                 } else {
3066                     error = nfs_nget(dvp->v_mount, nfhp, fhlen, &np, NULL);
3067                     if (error) {
3068                         m_freem(info.mrep);
3069                         info.mrep = NULL;
3070                         return (error);
3071                     }
3072                     newvp = NFSTOV(np);
3073                 }
3074                 if (info.v3) {
3075                         ERROROUT(nfsm_postop_attr(&info, newvp, &attrflag,
3076                                                   NFS_LATTR_NOSHRINK));
3077                         if (!attrflag && *npp == NULL) {
3078                                 m_freem(info.mrep);
3079                                 info.mrep = NULL;
3080                                 if (newvp == dvp)
3081                                         vrele(newvp);
3082                                 else
3083                                         vput(newvp);
3084                                 return (ENOENT);
3085                         }
3086                 } else {
3087                         ERROROUT(nfsm_loadattr(&info, newvp, NULL));
3088                 }
3089         }
3090         m_freem(info.mrep);
3091         info.mrep = NULL;
3092 nfsmout:
3093         if (npp && *npp == NULL) {
3094                 if (error) {
3095                         if (newvp) {
3096                                 if (newvp == dvp)
3097                                         vrele(newvp);
3098                                 else
3099                                         vput(newvp);
3100                         }
3101                 } else
3102                         *npp = np;
3103         }
3104         return (error);
3105 }
3106
3107 /*
3108  * Nfs Version 3 commit rpc
3109  *
3110  * We call it 'uio' to distinguish it from 'bio' but there is no real uio
3111  * involved.
3112  */
3113 int
3114 nfs_commitrpc_uio(struct vnode *vp, u_quad_t offset, int cnt, struct thread *td)
3115 {
3116         struct nfsmount *nmp = VFSTONFS(vp->v_mount);
3117         int error = 0, wccflag = NFSV3_WCCRATTR;
3118         struct nfsm_info info;
3119         u_int32_t *tl;
3120
3121         info.mrep = NULL;
3122         info.v3 = 1;
3123         
3124         if ((nmp->nm_state & NFSSTA_HASWRITEVERF) == 0)
3125                 return (0);
3126         nfsstats.rpccnt[NFSPROC_COMMIT]++;
3127         nfsm_reqhead(&info, vp, NFSPROC_COMMIT, NFSX_FH(1));
3128         ERROROUT(nfsm_fhtom(&info, vp));
3129         tl = nfsm_build(&info, 3 * NFSX_UNSIGNED);
3130         txdr_hyper(offset, tl);
3131         tl += 2;
3132         *tl = txdr_unsigned(cnt);
3133         NEGKEEPOUT(nfsm_request(&info, vp, NFSPROC_COMMIT, td,
3134                                 nfs_vpcred(vp, ND_WRITE), &error));
3135         ERROROUT(nfsm_wcc_data(&info, vp, &wccflag));
3136         if (!error) {
3137                 NULLOUT(tl = nfsm_dissect(&info, NFSX_V3WRITEVERF));
3138                 if (bcmp((caddr_t)nmp->nm_verf, (caddr_t)tl,
3139                         NFSX_V3WRITEVERF)) {
3140                         bcopy((caddr_t)tl, (caddr_t)nmp->nm_verf,
3141                                 NFSX_V3WRITEVERF);
3142                         error = NFSERR_STALEWRITEVERF;
3143                 }
3144         }
3145         m_freem(info.mrep);
3146         info.mrep = NULL;
3147 nfsmout:
3148         return (error);
3149 }
3150
3151 /*
3152  * Kludge City..
3153  * - make nfs_bmap() essentially a no-op that does no translation
3154  * - do nfs_strategy() by doing I/O with nfs_readrpc/nfs_writerpc
3155  *   (Maybe I could use the process's page mapping, but I was concerned that
3156  *    Kernel Write might not be enabled and also figured copyout() would do
3157  *    a lot more work than bcopy() and also it currently happens in the
3158  *    context of the swapper process (2).
3159  *
3160  * nfs_bmap(struct vnode *a_vp, off_t a_loffset,
3161  *          off_t *a_doffsetp, int *a_runp, int *a_runb)
3162  */
3163 static int
3164 nfs_bmap(struct vop_bmap_args *ap)
3165 {
3166         /* no token lock required */
3167         if (ap->a_doffsetp != NULL)
3168                 *ap->a_doffsetp = ap->a_loffset;
3169         if (ap->a_runp != NULL)
3170                 *ap->a_runp = 0;
3171         if (ap->a_runb != NULL)
3172                 *ap->a_runb = 0;
3173         return (0);
3174 }
3175
3176 /*
3177  * Strategy routine.
3178  */
3179 static int
3180 nfs_strategy(struct vop_strategy_args *ap)
3181 {
3182         struct bio *bio = ap->a_bio;
3183         struct bio *nbio;
3184         struct buf *bp __debugvar = bio->bio_buf;
3185         struct nfsmount *nmp = VFSTONFS(ap->a_vp->v_mount);
3186         struct thread *td;
3187         int error;
3188
3189         KASSERT(bp->b_cmd != BUF_CMD_DONE,
3190                 ("nfs_strategy: buffer %p unexpectedly marked done", bp));
3191         KASSERT(BUF_LOCKINUSE(bp),
3192                 ("nfs_strategy: buffer %p not locked", bp));
3193
3194         if (bio->bio_flags & BIO_SYNC)
3195                 td = curthread; /* XXX */
3196         else
3197                 td = NULL;
3198
3199         lwkt_gettoken(&nmp->nm_token);
3200
3201         /*
3202          * We probably don't need to push an nbio any more since no
3203          * block conversion is required due to the use of 64 bit byte
3204          * offsets, but do it anyway.
3205          *
3206          * NOTE: When NFS callers itself via this strategy routines and
3207          *       sets up a synchronous I/O, it expects the I/O to run
3208          *       synchronously (its bio_done routine just assumes it),
3209          *       so for now we have to honor the bit.
3210          */
3211         nbio = push_bio(bio);
3212         nbio->bio_offset = bio->bio_offset;
3213         nbio->bio_flags = bio->bio_flags & BIO_SYNC;
3214
3215         /*
3216          * If the op is asynchronous and an i/o daemon is waiting
3217          * queue the request, wake it up and wait for completion
3218          * otherwise just do it ourselves.
3219          */
3220         if (bio->bio_flags & BIO_SYNC) {
3221                 error = nfs_doio(ap->a_vp, nbio, td);
3222         } else {
3223                 nfs_asyncio(ap->a_vp, nbio);
3224                 error = 0;
3225         }
3226         lwkt_reltoken(&nmp->nm_token);
3227
3228         return (error);
3229 }
3230
3231 /*
3232  * Mmap a file
3233  *
3234  * NB Currently unsupported.
3235  *
3236  * nfs_mmap(struct vnode *a_vp, int a_fflags, struct ucred *a_cred)
3237  */
3238 /* ARGSUSED */
3239 static int
3240 nfs_mmap(struct vop_mmap_args *ap)
3241 {
3242         /* no token lock required */
3243         return (EINVAL);
3244 }
3245
3246 /*
3247  * fsync vnode op. Just call nfs_flush() with commit == 1.
3248  *
3249  * nfs_fsync(struct vnode *a_vp, int a_waitfor)
3250  */
3251 /* ARGSUSED */
3252 static int
3253 nfs_fsync(struct vop_fsync_args *ap)
3254 {
3255         struct nfsmount *nmp = VFSTONFS(ap->a_vp->v_mount);
3256         int error;
3257
3258         lwkt_gettoken(&nmp->nm_token);
3259
3260         /*
3261          * NOTE: Because attributes are set synchronously we currently
3262          *       do not have to implement vsetisdirty()/vclrisdirty().
3263          */
3264         error = nfs_flush(ap->a_vp, ap->a_waitfor, curthread, 1);
3265
3266         lwkt_reltoken(&nmp->nm_token);
3267
3268         return error;
3269 }
3270
3271 /*
3272  * Flush all the blocks associated with a vnode.   Dirty NFS buffers may be
3273  * in one of two states:  If B_NEEDCOMMIT is clear then the buffer contains
3274  * new NFS data which needs to be written to the server.  If B_NEEDCOMMIT is
3275  * set the buffer contains data that has already been written to the server
3276  * and which now needs a commit RPC.
3277  *
3278  * If commit is 0 we only take one pass and only flush buffers containing new
3279  * dirty data.
3280  *
3281  * If commit is 1 we take two passes, issuing a commit RPC in the second
3282  * pass.
3283  *
3284  * If waitfor is MNT_WAIT and commit is 1, we loop as many times as required
3285  * to completely flush all pending data.
3286  *
3287  * Note that the RB_SCAN code properly handles the case where the
3288  * callback might block and directly or indirectly (another thread) cause
3289  * the RB tree to change.
3290  */
3291
3292 #ifndef NFS_COMMITBVECSIZ
3293 #define NFS_COMMITBVECSIZ       16
3294 #endif
3295
3296 struct nfs_flush_info {
3297         enum { NFI_FLUSHNEW, NFI_COMMIT } mode;
3298         struct thread *td;
3299         struct vnode *vp;
3300         int waitfor;
3301         int slpflag;
3302         int slptimeo;
3303         int loops;
3304         struct buf *bvary[NFS_COMMITBVECSIZ];
3305         int bvsize;
3306         off_t beg_off;
3307         off_t end_off;
3308 };
3309
3310 static int nfs_flush_bp(struct buf *bp, void *data);
3311 static int nfs_flush_docommit(struct nfs_flush_info *info, int error);
3312
3313 int
3314 nfs_flush(struct vnode *vp, int waitfor, struct thread *td, int commit)
3315 {
3316         struct nfsnode *np = VTONFS(vp);
3317         struct nfsmount *nmp = VFSTONFS(vp->v_mount);
3318         struct nfs_flush_info info;
3319         int error;
3320
3321         bzero(&info, sizeof(info));
3322         info.td = td;
3323         info.vp = vp;
3324         info.waitfor = waitfor;
3325         info.slpflag = (nmp->nm_flag & NFSMNT_INT) ? PCATCH : 0;
3326         info.loops = 0;
3327         lwkt_gettoken(&vp->v_token);
3328
3329         do {
3330                 /*
3331                  * Flush mode
3332                  */
3333                 info.mode = NFI_FLUSHNEW;
3334                 error = RB_SCAN(buf_rb_tree, &vp->v_rbdirty_tree, NULL, 
3335                                 nfs_flush_bp, &info);
3336
3337                 /*
3338                  * Take a second pass if committing and no error occured.  
3339                  * Clean up any left over collection (whether an error 
3340                  * occurs or not).
3341                  */
3342                 if (commit && error == 0) {
3343                         info.mode = NFI_COMMIT;
3344                         error = RB_SCAN(buf_rb_tree, &vp->v_rbdirty_tree, NULL, 
3345                                         nfs_flush_bp, &info);
3346                         if (info.bvsize)
3347                                 error = nfs_flush_docommit(&info, error);
3348                 }
3349
3350                 /*
3351                  * Wait for pending I/O to complete before checking whether
3352                  * any further dirty buffers exist.
3353                  */
3354                 while (waitfor == MNT_WAIT &&
3355                        bio_track_active(&vp->v_track_write)) {
3356                         error = bio_track_wait(&vp->v_track_write,
3357                                                info.slpflag, info.slptimeo);
3358                         if (error) {
3359                                 /*
3360                                  * We have to be able to break out if this 
3361                                  * is an 'intr' mount.
3362                                  */
3363                                 if (nfs_sigintr(nmp, NULL, td)) {
3364                                         error = -EINTR;
3365                                         break;
3366                                 }
3367
3368                                 /*
3369                                  * Since we do not process pending signals,
3370                                  * once we get a PCATCH our tsleep() will no
3371                                  * longer sleep, switch to a fixed timeout
3372                                  * instead.
3373                                  */
3374                                 if (info.slpflag == PCATCH) {
3375                                         info.slpflag = 0;
3376                                         info.slptimeo = 2 * hz;
3377                                 }
3378                                 error = 0;
3379                         }
3380                 }
3381                 ++info.loops;
3382                 /*
3383                  * Loop if we are flushing synchronous as well as committing,
3384                  * and dirty buffers are still present.  Otherwise we might livelock.
3385                  */
3386         } while (waitfor == MNT_WAIT && commit && 
3387                  error == 0 && !RB_EMPTY(&vp->v_rbdirty_tree));
3388
3389         /*
3390          * The callbacks have to return a negative error to terminate the
3391          * RB scan.
3392          */
3393         if (error < 0)
3394                 error = -error;
3395
3396         /*
3397          * Deal with any error collection
3398          */
3399         if (np->n_flag & NWRITEERR) {
3400                 error = np->n_error;
3401                 np->n_flag &= ~NWRITEERR;
3402         }
3403         lwkt_reltoken(&vp->v_token);
3404         return (error);
3405 }
3406
3407 static
3408 int
3409 nfs_flush_bp(struct buf *bp, void *data)
3410 {
3411         struct nfs_flush_info *info = data;
3412         int lkflags;
3413         int error;
3414         off_t toff;
3415
3416         error = 0;
3417         switch(info->mode) {
3418         case NFI_FLUSHNEW:
3419                 error = BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT);
3420                 if (error && info->loops && info->waitfor == MNT_WAIT) {
3421                         error = BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT);
3422                         if (error) {
3423                                 lkflags = LK_EXCLUSIVE | LK_SLEEPFAIL;
3424                                 if (info->slpflag & PCATCH)
3425                                         lkflags |= LK_PCATCH;
3426                                 error = BUF_TIMELOCK(bp, lkflags, "nfsfsync",
3427                                                      info->slptimeo);
3428                         }
3429                 }
3430
3431                 /*
3432                  * Ignore locking errors
3433                  */
3434                 if (error) {
3435                         error = 0;
3436                         break;
3437                 }
3438
3439                 /*
3440                  * The buffer may have changed out from under us, even if
3441                  * we did not block (MPSAFE).  Check again now that it is
3442                  * locked.
3443                  */
3444                 if (bp->b_vp == info->vp &&
3445                     (bp->b_flags & (B_DELWRI | B_NEEDCOMMIT)) == B_DELWRI) {
3446                         bremfree(bp);
3447                         bawrite(bp);
3448                 } else {
3449                         BUF_UNLOCK(bp);
3450                 }
3451                 break;
3452         case NFI_COMMIT:
3453                 /*
3454                  * Only process buffers in need of a commit which we can
3455                  * immediately lock.  This may prevent a buffer from being
3456                  * committed, but the normal flush loop will block on the
3457                  * same buffer so we shouldn't get into an endless loop.
3458                  */
3459                 if ((bp->b_flags & (B_DELWRI | B_NEEDCOMMIT)) != 
3460                     (B_DELWRI | B_NEEDCOMMIT)) {
3461                         break;
3462                 }
3463                 if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT))
3464                         break;
3465
3466                 /*
3467                  * We must recheck after successfully locking the buffer.
3468                  */
3469                 if (bp->b_vp != info->vp ||
3470                     (bp->b_flags & (B_DELWRI | B_NEEDCOMMIT)) !=
3471                     (B_DELWRI | B_NEEDCOMMIT)) {
3472                         BUF_UNLOCK(bp);
3473                         break;
3474                 }
3475
3476                 /*
3477                  * NOTE: storing the bp in the bvary[] basically sets
3478                  * it up for a commit operation.
3479                  *
3480                  * We must call vfs_busy_pages() now so the commit operation
3481                  * is interlocked with user modifications to memory mapped
3482                  * pages.  The b_dirtyoff/b_dirtyend range is not correct
3483                  * until after the pages have been busied.
3484                  *
3485                  * Note: to avoid loopback deadlocks, we do not
3486                  * assign b_runningbufspace.
3487                  */
3488                 bremfree(bp);
3489                 bp->b_cmd = BUF_CMD_WRITE;
3490                 vfs_busy_pages(bp->b_vp, bp);
3491                 info->bvary[info->bvsize] = bp;
3492                 toff = bp->b_bio2.bio_offset + bp->b_dirtyoff;
3493                 if (info->bvsize == 0 || toff < info->beg_off)
3494                         info->beg_off = toff;
3495                 toff += (off_t)(bp->b_dirtyend - bp->b_dirtyoff);
3496                 if (info->bvsize == 0 || toff > info->end_off)
3497                         info->end_off = toff;
3498                 ++info->bvsize;
3499                 if (info->bvsize == NFS_COMMITBVECSIZ) {
3500                         error = nfs_flush_docommit(info, 0);
3501                         KKASSERT(info->bvsize == 0);
3502                 }
3503         }
3504         return (error);
3505 }
3506
3507 static
3508 int
3509 nfs_flush_docommit(struct nfs_flush_info *info, int error)
3510 {
3511         struct vnode *vp;
3512         struct buf *bp;
3513         off_t bytes;
3514         int retv;
3515         int i;
3516
3517         vp = info->vp;
3518
3519         if (info->bvsize > 0) {
3520                 /*
3521                  * Commit data on the server, as required.  Note that
3522                  * nfs_commit will use the vnode's cred for the commit.
3523                  * The NFSv3 commit RPC is limited to a 32 bit byte count.
3524                  */
3525                 bytes = info->end_off - info->beg_off;
3526                 if (bytes > 0x40000000)
3527                         bytes = 0x40000000;
3528                 if (error) {
3529                         retv = -error;
3530                 } else {
3531                         retv = nfs_commitrpc_uio(vp, info->beg_off,
3532                                                  (int)bytes, info->td);
3533                         if (retv == NFSERR_STALEWRITEVERF)
3534                                 nfs_clearcommit(vp->v_mount);
3535                 }
3536
3537                 /*
3538                  * Now, either mark the blocks I/O done or mark the
3539                  * blocks dirty, depending on whether the commit
3540                  * succeeded.
3541                  */
3542                 for (i = 0; i < info->bvsize; ++i) {
3543                         bp = info->bvary[i];
3544                         if (retv || (bp->b_flags & B_NEEDCOMMIT) == 0) {
3545                                 /*
3546                                  * Either an error or the original
3547                                  * vfs_busy_pages() cleared B_NEEDCOMMIT
3548                                  * due to finding new dirty VM pages in
3549                                  * the buffer.
3550                                  *
3551                                  * Leave B_DELWRI intact.
3552                                  */
3553                                 bp->b_flags &= ~(B_NEEDCOMMIT | B_CLUSTEROK);
3554                                 vfs_unbusy_pages(bp);
3555                                 bp->b_cmd = BUF_CMD_DONE;
3556                                 bqrelse(bp);
3557                         } else {
3558                                 /*
3559                                  * Success, remove B_DELWRI ( bundirty() ).
3560                                  *
3561                                  * b_dirtyoff/b_dirtyend seem to be NFS 
3562                                  * specific.  We should probably move that
3563                                  * into bundirty(). XXX
3564                                  *
3565                                  * We are faking an I/O write, we have to 
3566                                  * start the transaction in order to
3567                                  * immediately biodone() it.
3568                                  */
3569                                 bundirty(bp);
3570                                 bp->b_flags &= ~B_ERROR;
3571                                 bp->b_flags &= ~(B_NEEDCOMMIT | B_CLUSTEROK);
3572                                 bp->b_dirtyoff = bp->b_dirtyend = 0;
3573                                 biodone(&bp->b_bio1);
3574                         }
3575                 }
3576                 info->bvsize = 0;
3577         }
3578         return (error);
3579 }
3580
3581 /*
3582  * NFS advisory byte-level locks.
3583  * Currently unsupported.
3584  *
3585  * nfs_advlock(struct vnode *a_vp, caddr_t a_id, int a_op, struct flock *a_fl,
3586  *              int a_flags)
3587  */
3588 static int
3589 nfs_advlock(struct vop_advlock_args *ap)
3590 {
3591         struct nfsnode *np = VTONFS(ap->a_vp);
3592
3593         /* no token lock currently required */
3594         /*
3595          * The following kludge is to allow diskless support to work
3596          * until a real NFS lockd is implemented. Basically, just pretend
3597          * that this is a local lock.
3598          */
3599         return (lf_advlock(ap, &(np->n_lockf), np->n_size));
3600 }
3601
3602 /*
3603  * Print out the contents of an nfsnode.
3604  *
3605  * nfs_print(struct vnode *a_vp)
3606  */
3607 static int
3608 nfs_print(struct vop_print_args *ap)
3609 {
3610         struct vnode *vp = ap->a_vp;
3611         struct nfsnode *np = VTONFS(vp);
3612
3613         kprintf("tag VT_NFS, fileid %lld fsid 0x%x",
3614                 (long long)np->n_vattr.va_fileid, np->n_vattr.va_fsid);
3615         if (vp->v_type == VFIFO)
3616                 fifo_printinfo(vp);
3617         kprintf("\n");
3618         return (0);
3619 }
3620
3621 /*
3622  * nfs special file access vnode op.
3623  *
3624  * nfs_laccess(struct vnode *a_vp, int a_mode, struct ucred *a_cred)
3625  */
3626 static int
3627 nfs_laccess(struct vop_access_args *ap)
3628 {
3629         struct nfsmount *nmp = VFSTONFS(ap->a_vp->v_mount);
3630         struct vattr vattr;
3631         int error;
3632
3633         lwkt_gettoken(&nmp->nm_token);
3634         error = VOP_GETATTR(ap->a_vp, &vattr);
3635         if (error == 0) {
3636                 error = vop_helper_access(ap, vattr.va_uid, vattr.va_gid, 
3637                                           vattr.va_mode, 0);
3638         }
3639         lwkt_reltoken(&nmp->nm_token);
3640
3641         return (error);
3642 }
3643
3644 /*
3645  * Read wrapper for fifos.
3646  *
3647  * nfsfifo_read(struct vnode *a_vp, struct uio *a_uio, int a_ioflag,
3648  *              struct ucred *a_cred)
3649  */
3650 static int
3651 nfsfifo_read(struct vop_read_args *ap)
3652 {
3653         struct nfsnode *np = VTONFS(ap->a_vp);
3654
3655         /* no token access required */
3656         /*
3657          * Set access flag.
3658          */
3659         np->n_flag |= NACC;
3660         getnanotime(&np->n_atim);
3661         return (VOCALL(&fifo_vnode_vops, &ap->a_head));
3662 }
3663
3664 /*
3665  * Write wrapper for fifos.
3666  *
3667  * nfsfifo_write(struct vnode *a_vp, struct uio *a_uio, int a_ioflag,
3668  *               struct ucred *a_cred)
3669  */
3670 static int
3671 nfsfifo_write(struct vop_write_args *ap)
3672 {
3673         struct nfsnode *np = VTONFS(ap->a_vp);
3674
3675         /* no token access required */
3676         /*
3677          * Set update flag.
3678          */
3679         np->n_flag |= NUPD;
3680         getnanotime(&np->n_mtim);
3681         return (VOCALL(&fifo_vnode_vops, &ap->a_head));
3682 }
3683
3684 /*
3685  * Close wrapper for fifos.
3686  *
3687  * Update the times on the nfsnode then do fifo close.
3688  *
3689  * nfsfifo_close(struct vnode *a_vp, int a_fflag)
3690  */
3691 static int
3692 nfsfifo_close(struct vop_close_args *ap)
3693 {
3694         struct vnode *vp = ap->a_vp;
3695         struct nfsnode *np = VTONFS(vp);
3696         struct vattr vattr;
3697         struct timespec ts;
3698
3699         /* no token access required */
3700
3701         vn_lock(vp, LK_UPGRADE | LK_RETRY); /* XXX */
3702         if (np->n_flag & (NACC | NUPD)) {
3703                 getnanotime(&ts);
3704                 if (np->n_flag & NACC)
3705                         np->n_atim = ts;
3706                 if (np->n_flag & NUPD)
3707                         np->n_mtim = ts;
3708                 np->n_flag |= NCHG;
3709                 if (VREFCNT(vp) == 1 &&
3710                     (vp->v_mount->mnt_flag & MNT_RDONLY) == 0) {
3711                         VATTR_NULL(&vattr);
3712                         if (np->n_flag & NACC)
3713                                 vattr.va_atime = np->n_atim;
3714                         if (np->n_flag & NUPD)
3715                                 vattr.va_mtime = np->n_mtim;
3716                         (void)VOP_SETATTR(vp, &vattr, nfs_vpcred(vp, ND_WRITE));
3717                 }
3718         }
3719         return (VOCALL(&fifo_vnode_vops, &ap->a_head));
3720 }
3721
3722 /************************************************************************
3723  *                          KQFILTER OPS                                *
3724  ************************************************************************/
3725
3726 static void filt_nfsdetach(struct knote *kn);
3727 static int filt_nfsread(struct knote *kn, long hint);
3728 static int filt_nfswrite(struct knote *kn, long hint);
3729 static int filt_nfsvnode(struct knote *kn, long hint);
3730
3731 static struct filterops nfsread_filtops =
3732         { FILTEROP_ISFD | FILTEROP_MPSAFE,
3733           NULL, filt_nfsdetach, filt_nfsread };
3734 static struct filterops nfswrite_filtops =
3735         { FILTEROP_ISFD | FILTEROP_MPSAFE,
3736           NULL, filt_nfsdetach, filt_nfswrite };
3737 static struct filterops nfsvnode_filtops =
3738         { FILTEROP_ISFD | FILTEROP_MPSAFE,
3739           NULL, filt_nfsdetach, filt_nfsvnode };
3740
3741 static int
3742 nfs_kqfilter (struct vop_kqfilter_args *ap)
3743 {
3744         struct vnode *vp = ap->a_vp;
3745         struct knote *kn = ap->a_kn;
3746
3747         switch (kn->kn_filter) {
3748         case EVFILT_READ:
3749                 kn->kn_fop = &nfsread_filtops;
3750                 break;
3751         case EVFILT_WRITE:
3752                 kn->kn_fop = &nfswrite_filtops;
3753                 break;
3754         case EVFILT_VNODE:
3755                 kn->kn_fop = &nfsvnode_filtops;
3756                 break;
3757         default:
3758                 return (EOPNOTSUPP);
3759         }
3760
3761         kn->kn_hook = (caddr_t)vp;
3762
3763         knote_insert(&vp->v_pollinfo.vpi_kqinfo.ki_note, kn);
3764
3765         return(0);
3766 }
3767
3768 static void
3769 filt_nfsdetach(struct knote *kn)
3770 {
3771         struct vnode *vp = (void *)kn->kn_hook;
3772
3773         knote_remove(&vp->v_pollinfo.vpi_kqinfo.ki_note, kn);
3774 }
3775
3776 static int
3777 filt_nfsread(struct knote *kn, long hint)
3778 {
3779         struct vnode *vp = (void *)kn->kn_hook;
3780         struct nfsnode *node = VTONFS(vp);
3781         off_t off;
3782
3783         if (hint == NOTE_REVOKE) {
3784                 kn->kn_flags |= (EV_EOF | EV_NODATA | EV_ONESHOT);
3785                 return(1);
3786         }
3787
3788         /*
3789          * Interlock against MP races when performing this function. XXX
3790          */
3791         /* TMPFS_NODE_LOCK_SH(node); */
3792         off = node->n_size - kn->kn_fp->f_offset;
3793         kn->kn_data = (off < INTPTR_MAX) ? off : INTPTR_MAX;
3794         if (kn->kn_sfflags & NOTE_OLDAPI) {
3795                 /* TMPFS_NODE_UNLOCK(node); */
3796                 return(1);
3797         }
3798         if (kn->kn_data == 0) {
3799                 kn->kn_data = (off < INTPTR_MAX) ? off : INTPTR_MAX;
3800         }
3801         /* TMPFS_NODE_UNLOCK(node); */
3802         return (kn->kn_data != 0);
3803 }
3804
3805 static int
3806 filt_nfswrite(struct knote *kn, long hint)
3807 {
3808         if (hint == NOTE_REVOKE)
3809                 kn->kn_flags |= (EV_EOF | EV_NODATA | EV_ONESHOT);
3810         kn->kn_data = 0;
3811         return (1);
3812 }
3813
3814 static int
3815 filt_nfsvnode(struct knote *kn, long hint)
3816 {
3817         if (kn->kn_sfflags & hint)
3818                 kn->kn_fflags |= hint;
3819         if (hint == NOTE_REVOKE) {
3820                 kn->kn_flags |= (EV_EOF | EV_NODATA);
3821                 return (1);
3822         }
3823         return (kn->kn_fflags != 0);
3824 }