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