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