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