NFS - Properly handle NFSv3 EOF short-reads
[dragonfly.git] / sys / vfs / nfs / nfs_bio.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_bio.c   8.9 (Berkeley) 3/30/95
37  * $FreeBSD: /repoman/r/ncvs/src/sys/nfsclient/nfs_bio.c,v 1.130 2004/04/14 23:23:55 peadar Exp $
38  * $DragonFly: src/sys/vfs/nfs/nfs_bio.c,v 1.45 2008/07/18 00:09:39 dillon Exp $
39  */
40
41
42 #include <sys/param.h>
43 #include <sys/systm.h>
44 #include <sys/resourcevar.h>
45 #include <sys/signalvar.h>
46 #include <sys/proc.h>
47 #include <sys/buf.h>
48 #include <sys/vnode.h>
49 #include <sys/mount.h>
50 #include <sys/kernel.h>
51 #include <sys/mbuf.h>
52 #include <sys/msfbuf.h>
53
54 #include <vm/vm.h>
55 #include <vm/vm_extern.h>
56 #include <vm/vm_page.h>
57 #include <vm/vm_object.h>
58 #include <vm/vm_pager.h>
59 #include <vm/vnode_pager.h>
60
61 #include <sys/buf2.h>
62 #include <sys/thread2.h>
63
64 #include "rpcv2.h"
65 #include "nfsproto.h"
66 #include "nfs.h"
67 #include "nfsmount.h"
68 #include "nfsnode.h"
69 #include "xdr_subs.h"
70 #include "nfsm_subs.h"
71
72
73 static struct buf *nfs_getcacheblk(struct vnode *vp, off_t loffset,
74                                    int size, struct thread *td);
75 static int nfs_check_dirent(struct nfs_dirent *dp, int maxlen);
76 static void nfsiodone_sync(struct bio *bio);
77 static void nfs_readrpc_bio_done(nfsm_info_t info);
78 static void nfs_writerpc_bio_done(nfsm_info_t info);
79 static void nfs_commitrpc_bio_done(nfsm_info_t info);
80
81 /*
82  * Vnode op for VM getpages.
83  *
84  * nfs_getpages(struct vnode *a_vp, vm_page_t *a_m, int a_count,
85  *              int a_reqpage, vm_ooffset_t a_offset)
86  */
87 int
88 nfs_getpages(struct vop_getpages_args *ap)
89 {
90         struct thread *td = curthread;          /* XXX */
91         int i, error, nextoff, size, toff, count, npages;
92         struct uio uio;
93         struct iovec iov;
94         char *kva;
95         struct vnode *vp;
96         struct nfsmount *nmp;
97         vm_page_t *pages;
98         vm_page_t m;
99         struct msf_buf *msf;
100
101         vp = ap->a_vp;
102         nmp = VFSTONFS(vp->v_mount);
103         pages = ap->a_m;
104         count = ap->a_count;
105
106         if (vp->v_object == NULL) {
107                 kprintf("nfs_getpages: called with non-merged cache vnode??\n");
108                 return VM_PAGER_ERROR;
109         }
110
111         if ((nmp->nm_flag & NFSMNT_NFSV3) != 0 &&
112             (nmp->nm_state & NFSSTA_GOTFSINFO) == 0)
113                 (void)nfs_fsinfo(nmp, vp, td);
114
115         npages = btoc(count);
116
117         /*
118          * NOTE that partially valid pages may occur in cases other
119          * then file EOF, such as when a file is partially written and
120          * ftruncate()-extended to a larger size.   It is also possible
121          * for the valid bits to be set on garbage beyond the file EOF and
122          * clear in the area before EOF (e.g. m->valid == 0xfc), which can
123          * occur due to vtruncbuf() and the buffer cache's handling of
124          * pages which 'straddle' buffers or when b_bufsize is not a 
125          * multiple of PAGE_SIZE.... the buffer cache cannot normally
126          * clear the extra bits.  This kind of situation occurs when you
127          * make a small write() (m->valid == 0x03) and then mmap() and
128          * fault in the buffer(m->valid = 0xFF).  When NFS flushes the
129          * buffer (vinvalbuf() m->valid = 0xFC) we are left with a mess.
130          *
131          * This is combined with the possibility that the pages are partially
132          * dirty or that there is a buffer backing the pages that is dirty
133          * (even if m->dirty is 0).
134          *
135          * To solve this problem several hacks have been made:  (1) NFS
136          * guarentees that the IO block size is a multiple of PAGE_SIZE and
137          * (2) The buffer cache, when invalidating an NFS buffer, will
138          * disregard the buffer's fragmentory b_bufsize and invalidate
139          * the whole page rather then just the piece the buffer owns.
140          *
141          * This allows us to assume that a partially valid page found here
142          * is fully valid (vm_fault will zero'd out areas of the page not
143          * marked as valid).
144          */
145         m = pages[ap->a_reqpage];
146         if (m->valid != 0) {
147                 for (i = 0; i < npages; ++i) {
148                         if (i != ap->a_reqpage)
149                                 vnode_pager_freepage(pages[i]);
150                 }
151                 return(0);
152         }
153
154         /*
155          * Use an MSF_BUF as a medium to retrieve data from the pages.
156          */
157         msf_map_pagelist(&msf, pages, npages, 0);
158         KKASSERT(msf);
159         kva = msf_buf_kva(msf);
160
161         iov.iov_base = kva;
162         iov.iov_len = count;
163         uio.uio_iov = &iov;
164         uio.uio_iovcnt = 1;
165         uio.uio_offset = IDX_TO_OFF(pages[0]->pindex);
166         uio.uio_resid = count;
167         uio.uio_segflg = UIO_SYSSPACE;
168         uio.uio_rw = UIO_READ;
169         uio.uio_td = td;
170
171         error = nfs_readrpc_uio(vp, &uio);
172         msf_buf_free(msf);
173
174         if (error && ((int)uio.uio_resid == count)) {
175                 kprintf("nfs_getpages: error %d\n", error);
176                 for (i = 0; i < npages; ++i) {
177                         if (i != ap->a_reqpage)
178                                 vnode_pager_freepage(pages[i]);
179                 }
180                 return VM_PAGER_ERROR;
181         }
182
183         /*
184          * Calculate the number of bytes read and validate only that number
185          * of bytes.  Note that due to pending writes, size may be 0.  This
186          * does not mean that the remaining data is invalid!
187          */
188
189         size = count - (int)uio.uio_resid;
190
191         for (i = 0, toff = 0; i < npages; i++, toff = nextoff) {
192                 nextoff = toff + PAGE_SIZE;
193                 m = pages[i];
194
195                 m->flags &= ~PG_ZERO;
196
197                 if (nextoff <= size) {
198                         /*
199                          * Read operation filled an entire page
200                          */
201                         m->valid = VM_PAGE_BITS_ALL;
202                         vm_page_undirty(m);
203                 } else if (size > toff) {
204                         /*
205                          * Read operation filled a partial page.
206                          */
207                         m->valid = 0;
208                         vm_page_set_validclean(m, 0, size - toff);
209                         /* handled by vm_fault now        */
210                         /* vm_page_zero_invalid(m, TRUE); */
211                 } else {
212                         /*
213                          * Read operation was short.  If no error occured
214                          * we may have hit a zero-fill section.   We simply
215                          * leave valid set to 0.
216                          */
217                         ;
218                 }
219                 if (i != ap->a_reqpage) {
220                         /*
221                          * Whether or not to leave the page activated is up in
222                          * the air, but we should put the page on a page queue
223                          * somewhere (it already is in the object).  Result:
224                          * It appears that emperical results show that
225                          * deactivating pages is best.
226                          */
227
228                         /*
229                          * Just in case someone was asking for this page we
230                          * now tell them that it is ok to use.
231                          */
232                         if (!error) {
233                                 if (m->flags & PG_WANTED)
234                                         vm_page_activate(m);
235                                 else
236                                         vm_page_deactivate(m);
237                                 vm_page_wakeup(m);
238                         } else {
239                                 vnode_pager_freepage(m);
240                         }
241                 }
242         }
243         return 0;
244 }
245
246 /*
247  * Vnode op for VM putpages.
248  *
249  * nfs_putpages(struct vnode *a_vp, vm_page_t *a_m, int a_count, int a_sync,
250  *              int *a_rtvals, vm_ooffset_t a_offset)
251  */
252 int
253 nfs_putpages(struct vop_putpages_args *ap)
254 {
255         struct thread *td = curthread;
256         struct uio uio;
257         struct iovec iov;
258         char *kva;
259         int iomode, must_commit, i, error, npages, count;
260         off_t offset;
261         int *rtvals;
262         struct vnode *vp;
263         struct nfsmount *nmp;
264         struct nfsnode *np;
265         vm_page_t *pages;
266         struct msf_buf *msf;
267
268         vp = ap->a_vp;
269         np = VTONFS(vp);
270         nmp = VFSTONFS(vp->v_mount);
271         pages = ap->a_m;
272         count = ap->a_count;
273         rtvals = ap->a_rtvals;
274         npages = btoc(count);
275         offset = IDX_TO_OFF(pages[0]->pindex);
276
277         if ((nmp->nm_flag & NFSMNT_NFSV3) != 0 &&
278             (nmp->nm_state & NFSSTA_GOTFSINFO) == 0)
279                 (void)nfs_fsinfo(nmp, vp, td);
280
281         for (i = 0; i < npages; i++) {
282                 rtvals[i] = VM_PAGER_AGAIN;
283         }
284
285         /*
286          * When putting pages, do not extend file past EOF.
287          */
288
289         if (offset + count > np->n_size) {
290                 count = np->n_size - offset;
291                 if (count < 0)
292                         count = 0;
293         }
294
295         /*
296          * Use an MSF_BUF as a medium to retrieve data from the pages.
297          */
298         msf_map_pagelist(&msf, pages, npages, 0);
299         KKASSERT(msf);
300         kva = msf_buf_kva(msf);
301
302         iov.iov_base = kva;
303         iov.iov_len = count;
304         uio.uio_iov = &iov;
305         uio.uio_iovcnt = 1;
306         uio.uio_offset = offset;
307         uio.uio_resid = (size_t)count;
308         uio.uio_segflg = UIO_SYSSPACE;
309         uio.uio_rw = UIO_WRITE;
310         uio.uio_td = td;
311
312         if ((ap->a_sync & VM_PAGER_PUT_SYNC) == 0)
313             iomode = NFSV3WRITE_UNSTABLE;
314         else
315             iomode = NFSV3WRITE_FILESYNC;
316
317         error = nfs_writerpc_uio(vp, &uio, &iomode, &must_commit);
318
319         msf_buf_free(msf);
320
321         if (!error) {
322                 int nwritten = round_page(count - (int)uio.uio_resid) / PAGE_SIZE;
323                 for (i = 0; i < nwritten; i++) {
324                         rtvals[i] = VM_PAGER_OK;
325                         vm_page_undirty(pages[i]);
326                 }
327                 if (must_commit)
328                         nfs_clearcommit(vp->v_mount);
329         }
330         return rtvals[0];
331 }
332
333 /*
334  * Vnode op for read using bio
335  */
336 int
337 nfs_bioread(struct vnode *vp, struct uio *uio, int ioflag)
338 {
339         struct nfsnode *np = VTONFS(vp);
340         int biosize, i;
341         struct buf *bp = 0, *rabp;
342         struct vattr vattr;
343         struct thread *td;
344         struct nfsmount *nmp = VFSTONFS(vp->v_mount);
345         daddr_t lbn, rabn;
346         off_t raoffset;
347         off_t loffset;
348         int bcount;
349         int seqcount;
350         int nra, error = 0, n = 0, on = 0;
351
352 #ifdef DIAGNOSTIC
353         if (uio->uio_rw != UIO_READ)
354                 panic("nfs_read mode");
355 #endif
356         if (uio->uio_resid == 0)
357                 return (0);
358         if (uio->uio_offset < 0)        /* XXX VDIR cookies can be negative */
359                 return (EINVAL);
360         td = uio->uio_td;
361
362         if ((nmp->nm_flag & NFSMNT_NFSV3) != 0 &&
363             (nmp->nm_state & NFSSTA_GOTFSINFO) == 0)
364                 (void)nfs_fsinfo(nmp, vp, td);
365         if (vp->v_type != VDIR &&
366             (uio->uio_offset + uio->uio_resid) > nmp->nm_maxfilesize)
367                 return (EFBIG);
368         biosize = vp->v_mount->mnt_stat.f_iosize;
369         seqcount = (int)((off_t)(ioflag >> IO_SEQSHIFT) * biosize / BKVASIZE);
370
371         /*
372          * For nfs, cache consistency can only be maintained approximately.
373          * Although RFC1094 does not specify the criteria, the following is
374          * believed to be compatible with the reference port.
375          *
376          * NFS:         If local changes have been made and this is a
377          *              directory, the directory must be invalidated and
378          *              the attribute cache must be cleared.
379          *
380          *              GETATTR is called to synchronize the file size.
381          *
382          *              If remote changes are detected local data is flushed
383          *              and the cache is invalidated.
384          *
385          *              NOTE: In the normal case the attribute cache is not
386          *              cleared which means GETATTR may use cached data and
387          *              not immediately detect changes made on the server.
388          */
389         if ((np->n_flag & NLMODIFIED) && vp->v_type == VDIR) {
390                 nfs_invaldir(vp);
391                 error = nfs_vinvalbuf(vp, V_SAVE, 1);
392                 if (error)
393                         return (error);
394                 np->n_attrstamp = 0;
395         }
396         error = VOP_GETATTR(vp, &vattr);
397         if (error)
398                 return (error);
399         if (np->n_flag & NRMODIFIED) {
400                 if (vp->v_type == VDIR)
401                         nfs_invaldir(vp);
402                 error = nfs_vinvalbuf(vp, V_SAVE, 1);
403                 if (error)
404                         return (error);
405                 np->n_flag &= ~NRMODIFIED;
406         }
407         do {
408             if (np->n_flag & NDONTCACHE) {
409                 switch (vp->v_type) {
410                 case VREG:
411                         return (nfs_readrpc_uio(vp, uio));
412                 case VLNK:
413                         return (nfs_readlinkrpc_uio(vp, uio));
414                 case VDIR:
415                         break;
416                 default:
417                         kprintf(" NDONTCACHE: type %x unexpected\n", vp->v_type);
418                         break;
419                 };
420             }
421             switch (vp->v_type) {
422             case VREG:
423                 nfsstats.biocache_reads++;
424                 lbn = uio->uio_offset / biosize;
425                 on = uio->uio_offset & (biosize - 1);
426                 loffset = (off_t)lbn * biosize;
427
428                 /*
429                  * Start the read ahead(s), as required.
430                  */
431                 if (nmp->nm_readahead > 0 && nfs_asyncok(nmp)) {
432                     for (nra = 0; nra < nmp->nm_readahead && nra < seqcount &&
433                         (off_t)(lbn + 1 + nra) * biosize < np->n_size; nra++) {
434                         rabn = lbn + 1 + nra;
435                         raoffset = (off_t)rabn * biosize;
436                         if (findblk(vp, raoffset, FINDBLK_TEST) == NULL) {
437                             rabp = nfs_getcacheblk(vp, raoffset, biosize, td);
438                             if (!rabp)
439                                 return (EINTR);
440                             if ((rabp->b_flags & (B_CACHE|B_DELWRI)) == 0) {
441                                 rabp->b_cmd = BUF_CMD_READ;
442                                 vfs_busy_pages(vp, rabp);
443                                 nfs_asyncio(vp, &rabp->b_bio2);
444                             } else {
445                                 brelse(rabp);
446                             }
447                         }
448                     }
449                 }
450
451                 /*
452                  * Obtain the buffer cache block.  Figure out the buffer size
453                  * when we are at EOF.  If we are modifying the size of the
454                  * buffer based on an EOF condition we need to hold 
455                  * nfs_rslock() through obtaining the buffer to prevent
456                  * a potential writer-appender from messing with n_size.
457                  * Otherwise we may accidently truncate the buffer and
458                  * lose dirty data.
459                  *
460                  * Note that bcount is *not* DEV_BSIZE aligned.
461                  */
462
463 again:
464                 bcount = biosize;
465                 if (loffset >= np->n_size) {
466                         bcount = 0;
467                 } else if (loffset + biosize > np->n_size) {
468                         bcount = np->n_size - loffset;
469                 }
470                 if (bcount != biosize) {
471                         switch(nfs_rslock(np)) {
472                         case ENOLCK:
473                                 goto again;
474                                 /* not reached */
475                         case EINTR:
476                         case ERESTART:
477                                 return(EINTR);
478                                 /* not reached */
479                         default:
480                                 break;
481                         }
482                 }
483
484                 bp = nfs_getcacheblk(vp, loffset, bcount, td);
485
486                 if (bcount != biosize)
487                         nfs_rsunlock(np);
488                 if (!bp)
489                         return (EINTR);
490
491                 /*
492                  * If B_CACHE is not set, we must issue the read.  If this
493                  * fails, we return an error.
494                  */
495                 if ((bp->b_flags & B_CACHE) == 0) {
496                         bp->b_cmd = BUF_CMD_READ;
497                         bp->b_bio2.bio_done = nfsiodone_sync;
498                         bp->b_bio2.bio_flags |= BIO_SYNC;
499                         vfs_busy_pages(vp, bp);
500                         error = nfs_doio(vp, &bp->b_bio2, td);
501                         if (error) {
502                                 brelse(bp);
503                                 return (error);
504                         }
505                 }
506
507                 /*
508                  * on is the offset into the current bp.  Figure out how many
509                  * bytes we can copy out of the bp.  Note that bcount is
510                  * NOT DEV_BSIZE aligned.
511                  *
512                  * Then figure out how many bytes we can copy into the uio.
513                  */
514                 n = 0;
515                 if (on < bcount)
516                         n = (int)szmin((unsigned)(bcount - on), uio->uio_resid);
517                 break;
518             case VLNK:
519                 biosize = min(NFS_MAXPATHLEN, np->n_size);
520                 nfsstats.biocache_readlinks++;
521                 bp = nfs_getcacheblk(vp, (off_t)0, biosize, td);
522                 if (bp == NULL)
523                         return (EINTR);
524                 if ((bp->b_flags & B_CACHE) == 0) {
525                         bp->b_cmd = BUF_CMD_READ;
526                         bp->b_bio2.bio_done = nfsiodone_sync;
527                         bp->b_bio2.bio_flags |= BIO_SYNC;
528                         vfs_busy_pages(vp, bp);
529                         error = nfs_doio(vp, &bp->b_bio2, td);
530                         if (error) {
531                                 bp->b_flags |= B_ERROR | B_INVAL;
532                                 brelse(bp);
533                                 return (error);
534                         }
535                 }
536                 n = (int)szmin(uio->uio_resid, bp->b_bcount - bp->b_resid);
537                 on = 0;
538                 break;
539             case VDIR:
540                 nfsstats.biocache_readdirs++;
541                 if (np->n_direofoffset
542                     && uio->uio_offset >= np->n_direofoffset) {
543                     return (0);
544                 }
545                 lbn = (uoff_t)uio->uio_offset / NFS_DIRBLKSIZ;
546                 on = uio->uio_offset & (NFS_DIRBLKSIZ - 1);
547                 loffset = uio->uio_offset - on;
548                 bp = nfs_getcacheblk(vp, loffset, NFS_DIRBLKSIZ, td);
549                 if (bp == NULL)
550                     return (EINTR);
551
552                 if ((bp->b_flags & B_CACHE) == 0) {
553                     bp->b_cmd = BUF_CMD_READ;
554                     bp->b_bio2.bio_done = nfsiodone_sync;
555                     bp->b_bio2.bio_flags |= BIO_SYNC;
556                     vfs_busy_pages(vp, bp);
557                     error = nfs_doio(vp, &bp->b_bio2, td);
558                     if (error)
559                             brelse(bp);
560                     while (error == NFSERR_BAD_COOKIE) {
561                         kprintf("got bad cookie vp %p bp %p\n", vp, bp);
562                         nfs_invaldir(vp);
563                         error = nfs_vinvalbuf(vp, 0, 1);
564                         /*
565                          * Yuck! The directory has been modified on the
566                          * server. The only way to get the block is by
567                          * reading from the beginning to get all the
568                          * offset cookies.
569                          *
570                          * Leave the last bp intact unless there is an error.
571                          * Loop back up to the while if the error is another
572                          * NFSERR_BAD_COOKIE (double yuch!).
573                          */
574                         for (i = 0; i <= lbn && !error; i++) {
575                             if (np->n_direofoffset
576                                 && (i * NFS_DIRBLKSIZ) >= np->n_direofoffset)
577                                     return (0);
578                             bp = nfs_getcacheblk(vp, (off_t)i * NFS_DIRBLKSIZ,
579                                                  NFS_DIRBLKSIZ, td);
580                             if (!bp)
581                                 return (EINTR);
582                             if ((bp->b_flags & B_CACHE) == 0) {
583                                     bp->b_cmd = BUF_CMD_READ;
584                                     bp->b_bio2.bio_done = nfsiodone_sync;
585                                     bp->b_bio2.bio_flags |= BIO_SYNC;
586                                     vfs_busy_pages(vp, bp);
587                                     error = nfs_doio(vp, &bp->b_bio2, td);
588                                     /*
589                                      * no error + B_INVAL == directory EOF,
590                                      * use the block.
591                                      */
592                                     if (error == 0 && (bp->b_flags & B_INVAL))
593                                             break;
594                             }
595                             /*
596                              * An error will throw away the block and the
597                              * for loop will break out.  If no error and this
598                              * is not the block we want, we throw away the
599                              * block and go for the next one via the for loop.
600                              */
601                             if (error || i < lbn)
602                                     brelse(bp);
603                         }
604                     }
605                     /*
606                      * The above while is repeated if we hit another cookie
607                      * error.  If we hit an error and it wasn't a cookie error,
608                      * we give up.
609                      */
610                     if (error)
611                             return (error);
612                 }
613
614                 /*
615                  * If not eof and read aheads are enabled, start one.
616                  * (You need the current block first, so that you have the
617                  *  directory offset cookie of the next block.)
618                  */
619                 if (nmp->nm_readahead > 0 && nfs_asyncok(nmp) &&
620                     (bp->b_flags & B_INVAL) == 0 &&
621                     (np->n_direofoffset == 0 ||
622                     loffset + NFS_DIRBLKSIZ < np->n_direofoffset) &&
623                     (np->n_flag & NDONTCACHE) == 0 &&
624                     findblk(vp, loffset + NFS_DIRBLKSIZ, FINDBLK_TEST) == NULL
625                 ) {
626                         rabp = nfs_getcacheblk(vp, loffset + NFS_DIRBLKSIZ,
627                                                NFS_DIRBLKSIZ, td);
628                         if (rabp) {
629                             if ((rabp->b_flags & (B_CACHE|B_DELWRI)) == 0) {
630                                 rabp->b_cmd = BUF_CMD_READ;
631                                 vfs_busy_pages(vp, rabp);
632                                 nfs_asyncio(vp, &rabp->b_bio2);
633                             } else {
634                                 brelse(rabp);
635                             }
636                         }
637                 }
638                 /*
639                  * Unlike VREG files, whos buffer size ( bp->b_bcount ) is
640                  * chopped for the EOF condition, we cannot tell how large
641                  * NFS directories are going to be until we hit EOF.  So
642                  * an NFS directory buffer is *not* chopped to its EOF.  Now,
643                  * it just so happens that b_resid will effectively chop it
644                  * to EOF.  *BUT* this information is lost if the buffer goes
645                  * away and is reconstituted into a B_CACHE state ( due to
646                  * being VMIO ) later.  So we keep track of the directory eof
647                  * in np->n_direofoffset and chop it off as an extra step 
648                  * right here.
649                  */
650                 n = (int)szmin(uio->uio_resid,
651                                NFS_DIRBLKSIZ - bp->b_resid - on);
652                 if (np->n_direofoffset && n > np->n_direofoffset - uio->uio_offset)
653                         n = np->n_direofoffset - uio->uio_offset;
654                 break;
655             default:
656                 kprintf(" nfs_bioread: type %x unexpected\n",vp->v_type);
657                 break;
658             };
659
660             switch (vp->v_type) {
661             case VREG:
662                 if (n > 0)
663                     error = uiomove(bp->b_data + on, (int)n, uio);
664                 break;
665             case VLNK:
666                 if (n > 0)
667                     error = uiomove(bp->b_data + on, (int)n, uio);
668                 n = 0;
669                 break;
670             case VDIR:
671                 if (n > 0) {
672                     off_t old_off = uio->uio_offset;
673                     caddr_t cpos, epos;
674                     struct nfs_dirent *dp;
675
676                     /*
677                      * We are casting cpos to nfs_dirent, it must be
678                      * int-aligned.
679                      */
680                     if (on & 3) {
681                         error = EINVAL;
682                         break;
683                     }
684
685                     cpos = bp->b_data + on;
686                     epos = bp->b_data + on + n;
687                     while (cpos < epos && error == 0 && uio->uio_resid > 0) {
688                             dp = (struct nfs_dirent *)cpos;
689                             error = nfs_check_dirent(dp, (int)(epos - cpos));
690                             if (error)
691                                     break;
692                             if (vop_write_dirent(&error, uio, dp->nfs_ino,
693                                 dp->nfs_type, dp->nfs_namlen, dp->nfs_name)) {
694                                     break;
695                             }
696                             cpos += dp->nfs_reclen;
697                     }
698                     n = 0;
699                     if (error == 0)
700                             uio->uio_offset = old_off + cpos - bp->b_data - on;
701                 }
702                 /*
703                  * Invalidate buffer if caching is disabled, forcing a
704                  * re-read from the remote later.
705                  */
706                 if (np->n_flag & NDONTCACHE)
707                         bp->b_flags |= B_INVAL;
708                 break;
709             default:
710                 kprintf(" nfs_bioread: type %x unexpected\n",vp->v_type);
711             }
712             brelse(bp);
713         } while (error == 0 && uio->uio_resid > 0 && n > 0);
714         return (error);
715 }
716
717 /*
718  * Userland can supply any 'seek' offset when reading a NFS directory.
719  * Validate the structure so we don't panic the kernel.  Note that
720  * the element name is nul terminated and the nul is not included
721  * in nfs_namlen.
722  */
723 static
724 int
725 nfs_check_dirent(struct nfs_dirent *dp, int maxlen)
726 {
727         int nfs_name_off = offsetof(struct nfs_dirent, nfs_name[0]);
728
729         if (nfs_name_off >= maxlen)
730                 return (EINVAL);
731         if (dp->nfs_reclen < nfs_name_off || dp->nfs_reclen > maxlen)
732                 return (EINVAL);
733         if (nfs_name_off + dp->nfs_namlen >= dp->nfs_reclen)
734                 return (EINVAL);
735         if (dp->nfs_reclen & 3)
736                 return (EINVAL);
737         return (0);
738 }
739
740 /*
741  * Vnode op for write using bio
742  *
743  * nfs_write(struct vnode *a_vp, struct uio *a_uio, int a_ioflag,
744  *           struct ucred *a_cred)
745  */
746 int
747 nfs_write(struct vop_write_args *ap)
748 {
749         struct uio *uio = ap->a_uio;
750         struct thread *td = uio->uio_td;
751         struct vnode *vp = ap->a_vp;
752         struct nfsnode *np = VTONFS(vp);
753         int ioflag = ap->a_ioflag;
754         struct buf *bp;
755         struct vattr vattr;
756         struct nfsmount *nmp = VFSTONFS(vp->v_mount);
757         daddr_t lbn;
758         off_t loffset;
759         int n, on, error = 0, iomode, must_commit;
760         int haverslock = 0;
761         int bcount;
762         int biosize;
763
764 #ifdef DIAGNOSTIC
765         if (uio->uio_rw != UIO_WRITE)
766                 panic("nfs_write mode");
767         if (uio->uio_segflg == UIO_USERSPACE && uio->uio_td != curthread)
768                 panic("nfs_write proc");
769 #endif
770         if (vp->v_type != VREG)
771                 return (EIO);
772         if (np->n_flag & NWRITEERR) {
773                 np->n_flag &= ~NWRITEERR;
774                 return (np->n_error);
775         }
776         if ((nmp->nm_flag & NFSMNT_NFSV3) != 0 &&
777             (nmp->nm_state & NFSSTA_GOTFSINFO) == 0)
778                 (void)nfs_fsinfo(nmp, vp, td);
779
780         /*
781          * Synchronously flush pending buffers if we are in synchronous
782          * mode or if we are appending.
783          */
784         if (ioflag & (IO_APPEND | IO_SYNC)) {
785                 if (np->n_flag & NLMODIFIED) {
786                         np->n_attrstamp = 0;
787                         error = nfs_flush(vp, MNT_WAIT, td, 0);
788                         /* error = nfs_vinvalbuf(vp, V_SAVE, 1); */
789                         if (error)
790                                 return (error);
791                 }
792         }
793
794         /*
795          * If IO_APPEND then load uio_offset.  We restart here if we cannot
796          * get the append lock.
797          */
798 restart:
799         if (ioflag & IO_APPEND) {
800                 np->n_attrstamp = 0;
801                 error = VOP_GETATTR(vp, &vattr);
802                 if (error)
803                         return (error);
804                 uio->uio_offset = np->n_size;
805         }
806
807         if (uio->uio_offset < 0)
808                 return (EINVAL);
809         if ((uio->uio_offset + uio->uio_resid) > nmp->nm_maxfilesize)
810                 return (EFBIG);
811         if (uio->uio_resid == 0)
812                 return (0);
813
814         /*
815          * We need to obtain the rslock if we intend to modify np->n_size
816          * in order to guarentee the append point with multiple contending
817          * writers, to guarentee that no other appenders modify n_size
818          * while we are trying to obtain a truncated buffer (i.e. to avoid
819          * accidently truncating data written by another appender due to
820          * the race), and to ensure that the buffer is populated prior to
821          * our extending of the file.  We hold rslock through the entire
822          * operation.
823          *
824          * Note that we do not synchronize the case where someone truncates
825          * the file while we are appending to it because attempting to lock
826          * this case may deadlock other parts of the system unexpectedly.
827          */
828         if ((ioflag & IO_APPEND) ||
829             uio->uio_offset + uio->uio_resid > np->n_size) {
830                 switch(nfs_rslock(np)) {
831                 case ENOLCK:
832                         goto restart;
833                         /* not reached */
834                 case EINTR:
835                 case ERESTART:
836                         return(EINTR);
837                         /* not reached */
838                 default:
839                         break;
840                 }
841                 haverslock = 1;
842         }
843
844         /*
845          * Maybe this should be above the vnode op call, but so long as
846          * file servers have no limits, i don't think it matters
847          */
848         if (td->td_proc && uio->uio_offset + uio->uio_resid >
849               td->td_proc->p_rlimit[RLIMIT_FSIZE].rlim_cur) {
850                 lwpsignal(td->td_proc, td->td_lwp, SIGXFSZ);
851                 if (haverslock)
852                         nfs_rsunlock(np);
853                 return (EFBIG);
854         }
855
856         biosize = vp->v_mount->mnt_stat.f_iosize;
857
858         do {
859                 if ((np->n_flag & NDONTCACHE) && uio->uio_iovcnt == 1) {
860                     iomode = NFSV3WRITE_FILESYNC;
861                     error = nfs_writerpc_uio(vp, uio, &iomode, &must_commit);
862                     if (must_commit)
863                             nfs_clearcommit(vp->v_mount);
864                     break;
865                 }
866                 nfsstats.biocache_writes++;
867                 lbn = uio->uio_offset / biosize;
868                 on = uio->uio_offset & (biosize-1);
869                 loffset = uio->uio_offset - on;
870                 n = (int)szmin((unsigned)(biosize - on), uio->uio_resid);
871 again:
872                 /*
873                  * Handle direct append and file extension cases, calculate
874                  * unaligned buffer size.
875                  */
876
877                 if (uio->uio_offset == np->n_size && n) {
878                         /*
879                          * Get the buffer (in its pre-append state to maintain
880                          * B_CACHE if it was previously set).  Resize the
881                          * nfsnode after we have locked the buffer to prevent
882                          * readers from reading garbage.
883                          */
884                         bcount = on;
885                         bp = nfs_getcacheblk(vp, loffset, bcount, td);
886
887                         if (bp != NULL) {
888                                 long save;
889
890                                 np->n_size = uio->uio_offset + n;
891                                 np->n_flag |= NLMODIFIED;
892                                 vnode_pager_setsize(vp, np->n_size);
893
894                                 save = bp->b_flags & B_CACHE;
895                                 bcount += n;
896                                 allocbuf(bp, bcount);
897                                 bp->b_flags |= save;
898                         }
899                 } else {
900                         /*
901                          * Obtain the locked cache block first, and then 
902                          * adjust the file's size as appropriate.
903                          */
904                         bcount = on + n;
905                         if (loffset + bcount < np->n_size) {
906                                 if (loffset + biosize < np->n_size)
907                                         bcount = biosize;
908                                 else
909                                         bcount = np->n_size - loffset;
910                         }
911                         bp = nfs_getcacheblk(vp, loffset, bcount, td);
912                         if (uio->uio_offset + n > np->n_size) {
913                                 np->n_size = uio->uio_offset + n;
914                                 np->n_flag |= NLMODIFIED;
915                                 vnode_pager_setsize(vp, np->n_size);
916                         }
917                 }
918
919                 if (bp == NULL) {
920                         error = EINTR;
921                         break;
922                 }
923
924                 /*
925                  * Avoid a read by setting B_CACHE where the data we
926                  * intend to write covers the entire buffer.  This also
927                  * handles the normal append case as bcount will have
928                  * byte resolution.  The buffer state must also be adjusted.
929                  *
930                  * See the comments in kern/vfs_bio.c's getblk() for
931                  * more information.
932                  *
933                  * When doing a UIO_NOCOPY write the buffer is not
934                  * overwritten and we cannot just set B_CACHE unconditionally
935                  * for full-block writes.
936                  */
937                 if (on == 0 && n == bcount && uio->uio_segflg != UIO_NOCOPY) {
938                         bp->b_flags |= B_CACHE;
939                         bp->b_flags &= ~(B_ERROR | B_INVAL);
940                 }
941
942                 /*
943                  * b_resid may be set due to file EOF if we extended out.
944                  * The NFS bio code will zero the difference anyway so
945                  * just acknowledged the fact and set b_resid to 0.
946                  */
947                 if ((bp->b_flags & B_CACHE) == 0) {
948                         bp->b_cmd = BUF_CMD_READ;
949                         bp->b_bio2.bio_done = nfsiodone_sync;
950                         bp->b_bio2.bio_flags |= BIO_SYNC;
951                         vfs_busy_pages(vp, bp);
952                         error = nfs_doio(vp, &bp->b_bio2, td);
953                         if (error) {
954                                 brelse(bp);
955                                 break;
956                         }
957                         bp->b_resid = 0;
958                 }
959                 if (!bp) {
960                         error = EINTR;
961                         break;
962                 }
963                 np->n_flag |= NLMODIFIED;
964
965                 /*
966                  * If dirtyend exceeds file size, chop it down.  This should
967                  * not normally occur but there is an append race where it
968                  * might occur XXX, so we log it. 
969                  *
970                  * If the chopping creates a reverse-indexed or degenerate
971                  * situation with dirtyoff/end, we 0 both of them.
972                  */
973
974                 if (bp->b_dirtyend > bcount) {
975                         kprintf("NFS append race @%08llx:%d\n", 
976                             (long long)bp->b_bio2.bio_offset,
977                             bp->b_dirtyend - bcount);
978                         bp->b_dirtyend = bcount;
979                 }
980
981                 if (bp->b_dirtyoff >= bp->b_dirtyend)
982                         bp->b_dirtyoff = bp->b_dirtyend = 0;
983
984                 /*
985                  * If the new write will leave a contiguous dirty
986                  * area, just update the b_dirtyoff and b_dirtyend,
987                  * otherwise force a write rpc of the old dirty area.
988                  *
989                  * While it is possible to merge discontiguous writes due to 
990                  * our having a B_CACHE buffer ( and thus valid read data
991                  * for the hole), we don't because it could lead to 
992                  * significant cache coherency problems with multiple clients,
993                  * especially if locking is implemented later on.
994                  *
995                  * as an optimization we could theoretically maintain
996                  * a linked list of discontinuous areas, but we would still
997                  * have to commit them separately so there isn't much
998                  * advantage to it except perhaps a bit of asynchronization.
999                  */
1000
1001                 if (bp->b_dirtyend > 0 &&
1002                     (on > bp->b_dirtyend || (on + n) < bp->b_dirtyoff)) {
1003                         if (bwrite(bp) == EINTR) {
1004                                 error = EINTR;
1005                                 break;
1006                         }
1007                         goto again;
1008                 }
1009
1010                 error = uiomove((char *)bp->b_data + on, n, uio);
1011
1012                 /*
1013                  * Since this block is being modified, it must be written
1014                  * again and not just committed.  Since write clustering does
1015                  * not work for the stage 1 data write, only the stage 2
1016                  * commit rpc, we have to clear B_CLUSTEROK as well.
1017                  */
1018                 bp->b_flags &= ~(B_NEEDCOMMIT | B_CLUSTEROK);
1019
1020                 if (error) {
1021                         bp->b_flags |= B_ERROR;
1022                         brelse(bp);
1023                         break;
1024                 }
1025
1026                 /*
1027                  * Only update dirtyoff/dirtyend if not a degenerate 
1028                  * condition.
1029                  */
1030                 if (n) {
1031                         if (bp->b_dirtyend > 0) {
1032                                 bp->b_dirtyoff = min(on, bp->b_dirtyoff);
1033                                 bp->b_dirtyend = max((on + n), bp->b_dirtyend);
1034                         } else {
1035                                 bp->b_dirtyoff = on;
1036                                 bp->b_dirtyend = on + n;
1037                         }
1038                         vfs_bio_set_validclean(bp, on, n);
1039                 }
1040
1041                 /*
1042                  * If the lease is non-cachable or IO_SYNC do bwrite().
1043                  *
1044                  * IO_INVAL appears to be unused.  The idea appears to be
1045                  * to turn off caching in this case.  Very odd.  XXX
1046                  *
1047                  * If nfs_async is set bawrite() will use an unstable write
1048                  * (build dirty bufs on the server), so we might as well
1049                  * push it out with bawrite().  If nfs_async is not set we
1050                  * use bdwrite() to cache dirty bufs on the client.
1051                  */
1052                 if ((np->n_flag & NDONTCACHE) || (ioflag & IO_SYNC)) {
1053                         if (ioflag & IO_INVAL)
1054                                 bp->b_flags |= B_NOCACHE;
1055                         error = bwrite(bp);
1056                         if (error)
1057                                 break;
1058                         if (np->n_flag & NDONTCACHE) {
1059                                 error = nfs_vinvalbuf(vp, V_SAVE, 1);
1060                                 if (error)
1061                                         break;
1062                         }
1063                 } else if ((n + on) == biosize && nfs_async) {
1064                         bawrite(bp);
1065                 } else {
1066                         bdwrite(bp);
1067                 }
1068         } while (uio->uio_resid > 0 && n > 0);
1069
1070         if (haverslock)
1071                 nfs_rsunlock(np);
1072
1073         return (error);
1074 }
1075
1076 /*
1077  * Get an nfs cache block.
1078  *
1079  * Allocate a new one if the block isn't currently in the cache
1080  * and return the block marked busy. If the calling process is
1081  * interrupted by a signal for an interruptible mount point, return
1082  * NULL.
1083  *
1084  * The caller must carefully deal with the possible B_INVAL state of
1085  * the buffer.  nfs_startio() clears B_INVAL (and nfs_asyncio() clears it
1086  * indirectly), so synchronous reads can be issued without worrying about
1087  * the B_INVAL state.  We have to be a little more careful when dealing
1088  * with writes (see comments in nfs_write()) when extending a file past
1089  * its EOF.
1090  */
1091 static struct buf *
1092 nfs_getcacheblk(struct vnode *vp, off_t loffset, int size, struct thread *td)
1093 {
1094         struct buf *bp;
1095         struct mount *mp;
1096         struct nfsmount *nmp;
1097
1098         mp = vp->v_mount;
1099         nmp = VFSTONFS(mp);
1100
1101         if (nmp->nm_flag & NFSMNT_INT) {
1102                 bp = getblk(vp, loffset, size, GETBLK_PCATCH, 0);
1103                 while (bp == NULL) {
1104                         if (nfs_sigintr(nmp, NULL, td))
1105                                 return (NULL);
1106                         bp = getblk(vp, loffset, size, 0, 2 * hz);
1107                 }
1108         } else {
1109                 bp = getblk(vp, loffset, size, 0, 0);
1110         }
1111
1112         /*
1113          * bio2, the 'device' layer.  Since BIOs use 64 bit byte offsets
1114          * now, no translation is necessary.
1115          */
1116         bp->b_bio2.bio_offset = loffset;
1117         return (bp);
1118 }
1119
1120 /*
1121  * Flush and invalidate all dirty buffers. If another process is already
1122  * doing the flush, just wait for completion.
1123  */
1124 int
1125 nfs_vinvalbuf(struct vnode *vp, int flags, int intrflg)
1126 {
1127         struct nfsnode *np = VTONFS(vp);
1128         struct nfsmount *nmp = VFSTONFS(vp->v_mount);
1129         int error = 0, slpflag, slptimeo;
1130         thread_t td = curthread;
1131
1132         if (vp->v_flag & VRECLAIMED)
1133                 return (0);
1134
1135         if ((nmp->nm_flag & NFSMNT_INT) == 0)
1136                 intrflg = 0;
1137         if (intrflg) {
1138                 slpflag = PCATCH;
1139                 slptimeo = 2 * hz;
1140         } else {
1141                 slpflag = 0;
1142                 slptimeo = 0;
1143         }
1144         /*
1145          * First wait for any other process doing a flush to complete.
1146          */
1147         while (np->n_flag & NFLUSHINPROG) {
1148                 np->n_flag |= NFLUSHWANT;
1149                 error = tsleep((caddr_t)&np->n_flag, 0, "nfsvinval", slptimeo);
1150                 if (error && intrflg && nfs_sigintr(nmp, NULL, td))
1151                         return (EINTR);
1152         }
1153
1154         /*
1155          * Now, flush as required.
1156          */
1157         np->n_flag |= NFLUSHINPROG;
1158         error = vinvalbuf(vp, flags, slpflag, 0);
1159         while (error) {
1160                 if (intrflg && nfs_sigintr(nmp, NULL, td)) {
1161                         np->n_flag &= ~NFLUSHINPROG;
1162                         if (np->n_flag & NFLUSHWANT) {
1163                                 np->n_flag &= ~NFLUSHWANT;
1164                                 wakeup((caddr_t)&np->n_flag);
1165                         }
1166                         return (EINTR);
1167                 }
1168                 error = vinvalbuf(vp, flags, 0, slptimeo);
1169         }
1170         np->n_flag &= ~(NLMODIFIED | NFLUSHINPROG);
1171         if (np->n_flag & NFLUSHWANT) {
1172                 np->n_flag &= ~NFLUSHWANT;
1173                 wakeup((caddr_t)&np->n_flag);
1174         }
1175         return (0);
1176 }
1177
1178 /*
1179  * Return true (non-zero) if the txthread and rxthread are operational
1180  * and we do not already have too many not-yet-started BIO's built up.
1181  */
1182 int
1183 nfs_asyncok(struct nfsmount *nmp)
1184 {
1185         return (nmp->nm_bioqlen < nfs_maxasyncbio &&
1186                 nmp->nm_bioqlen < nmp->nm_maxasync_scaled / NFS_ASYSCALE &&
1187                 nmp->nm_rxstate <= NFSSVC_PENDING &&
1188                 nmp->nm_txstate <= NFSSVC_PENDING);
1189 }
1190
1191 /*
1192  * The read-ahead code calls this to queue a bio to the txthread.
1193  *
1194  * We don't touch the bio otherwise... that is, we do not even
1195  * construct or send the initial rpc.  The txthread will do it
1196  * for us.
1197  *
1198  * NOTE!  nm_bioqlen is not decremented until the request completes,
1199  *        so it does not reflect the number of bio's on bioq.
1200  */
1201 void
1202 nfs_asyncio(struct vnode *vp, struct bio *bio)
1203 {
1204         struct buf *bp = bio->bio_buf;
1205         struct nfsmount *nmp = VFSTONFS(vp->v_mount);
1206
1207         KKASSERT(vp->v_tag == VT_NFS);
1208         BUF_KERNPROC(bp);
1209         bio->bio_driver_info = vp;
1210         crit_enter();
1211         TAILQ_INSERT_TAIL(&nmp->nm_bioq, bio, bio_act);
1212         atomic_add_int(&nmp->nm_bioqlen, 1);
1213         crit_exit();
1214         nfssvc_iod_writer_wakeup(nmp);
1215 }
1216
1217 /*
1218  * nfs_dio()    - Execute a BIO operation synchronously.  The BIO will be
1219  *                completed and its error returned.  The caller is responsible
1220  *                for brelse()ing it.  ONLY USE FOR BIO_SYNC IOs!  Otherwise
1221  *                our error probe will be against an invalid pointer.
1222  *
1223  * nfs_startio()- Execute a BIO operation assynchronously.
1224  *
1225  * NOTE: nfs_asyncio() is used to initiate an asynchronous BIO operation,
1226  *       which basically just queues it to the txthread.  nfs_startio()
1227  *       actually initiates the I/O AFTER it has gotten to the txthread.
1228  *
1229  * NOTE: td might be NULL.
1230  */
1231 void
1232 nfs_startio(struct vnode *vp, struct bio *bio, struct thread *td)
1233 {
1234         struct buf *bp = bio->bio_buf;
1235         struct nfsnode *np;
1236         struct nfsmount *nmp;
1237
1238         KKASSERT(vp->v_tag == VT_NFS);
1239         np = VTONFS(vp);
1240         nmp = VFSTONFS(vp->v_mount);
1241
1242         /*
1243          * clear B_ERROR and B_INVAL state prior to initiating the I/O.  We
1244          * do this here so we do not have to do it in all the code that
1245          * calls us.
1246          */
1247         bp->b_flags &= ~(B_ERROR | B_INVAL);
1248
1249         KASSERT(bp->b_cmd != BUF_CMD_DONE,
1250                 ("nfs_doio: bp %p already marked done!", bp));
1251
1252         if (bp->b_cmd == BUF_CMD_READ) {
1253             switch (vp->v_type) {
1254             case VREG:
1255                 nfsstats.read_bios++;
1256                 nfs_readrpc_bio(vp, bio);
1257                 break;
1258             case VLNK:
1259 #if 0
1260                 bio->bio_offset = 0;
1261                 nfsstats.readlink_bios++;
1262                 nfs_readlinkrpc_bio(vp, bio);
1263 #else
1264                 nfs_doio(vp, bio, td);
1265 #endif
1266                 break;
1267             case VDIR:
1268                 /*
1269                  * NOTE: If nfs_readdirplusrpc_bio() is requested but
1270                  *       not supported, it will chain to
1271                  *       nfs_readdirrpc_bio().
1272                  */
1273 #if 0
1274                 nfsstats.readdir_bios++;
1275                 uiop->uio_offset = bio->bio_offset;
1276                 if (nmp->nm_flag & NFSMNT_RDIRPLUS)
1277                         nfs_readdirplusrpc_bio(vp, bio);
1278                 else
1279                         nfs_readdirrpc_bio(vp, bio);
1280 #else
1281                 nfs_doio(vp, bio, td);
1282 #endif
1283                 break;
1284             default:
1285                 kprintf("nfs_doio:  type %x unexpected\n",vp->v_type);
1286                 bp->b_flags |= B_ERROR;
1287                 bp->b_error = EINVAL;
1288                 biodone(bio);
1289                 break;
1290             }
1291         } else {
1292             /*
1293              * If we only need to commit, try to commit.  If this fails
1294              * it will chain through to the write.  Basically all the logic
1295              * in nfs_doio() is replicated.
1296              */
1297             KKASSERT(bp->b_cmd == BUF_CMD_WRITE);
1298             if (bp->b_flags & B_NEEDCOMMIT)
1299                 nfs_commitrpc_bio(vp, bio);
1300             else
1301                 nfs_writerpc_bio(vp, bio);
1302         }
1303 }
1304
1305 int
1306 nfs_doio(struct vnode *vp, struct bio *bio, struct thread *td)
1307 {
1308         struct buf *bp = bio->bio_buf;
1309         struct uio *uiop;
1310         struct nfsnode *np;
1311         struct nfsmount *nmp;
1312         int error = 0;
1313         int iomode, must_commit;
1314         size_t n;
1315         struct uio uio;
1316         struct iovec io;
1317
1318         KKASSERT(vp->v_tag == VT_NFS);
1319         np = VTONFS(vp);
1320         nmp = VFSTONFS(vp->v_mount);
1321         uiop = &uio;
1322         uiop->uio_iov = &io;
1323         uiop->uio_iovcnt = 1;
1324         uiop->uio_segflg = UIO_SYSSPACE;
1325         uiop->uio_td = td;
1326
1327         /*
1328          * clear B_ERROR and B_INVAL state prior to initiating the I/O.  We
1329          * do this here so we do not have to do it in all the code that
1330          * calls us.
1331          */
1332         bp->b_flags &= ~(B_ERROR | B_INVAL);
1333
1334         KASSERT(bp->b_cmd != BUF_CMD_DONE, 
1335                 ("nfs_doio: bp %p already marked done!", bp));
1336
1337         if (bp->b_cmd == BUF_CMD_READ) {
1338             io.iov_len = uiop->uio_resid = (size_t)bp->b_bcount;
1339             io.iov_base = bp->b_data;
1340             uiop->uio_rw = UIO_READ;
1341
1342             switch (vp->v_type) {
1343             case VREG:
1344                 /*
1345                  * When reading from a regular file zero-fill any residual.
1346                  * Note that this residual has nothing to do with NFS short
1347                  * reads, which nfs_readrpc_uio() will handle for us.
1348                  *
1349                  * We have to do this because when we are write extending
1350                  * a file the server may not have the same notion of
1351                  * filesize as we do.  Our BIOs should already be sized
1352                  * (b_bcount) to account for the file EOF.
1353                  */
1354                 nfsstats.read_bios++;
1355                 uiop->uio_offset = bio->bio_offset;
1356                 error = nfs_readrpc_uio(vp, uiop);
1357                 if (error == 0 && uiop->uio_resid) {
1358                         n = (size_t)bp->b_bcount - uiop->uio_resid;
1359                         bzero(bp->b_data + n, bp->b_bcount - n);
1360                         uiop->uio_resid = 0;
1361                 }
1362                 if (td && td->td_proc && (vp->v_flag & VTEXT) &&
1363                     np->n_mtime != np->n_vattr.va_mtime.tv_sec) {
1364                         uprintf("Process killed due to text file modification\n");
1365                         ksignal(td->td_proc, SIGKILL);
1366                 }
1367                 break;
1368             case VLNK:
1369                 uiop->uio_offset = 0;
1370                 nfsstats.readlink_bios++;
1371                 error = nfs_readlinkrpc_uio(vp, uiop);
1372                 break;
1373             case VDIR:
1374                 nfsstats.readdir_bios++;
1375                 uiop->uio_offset = bio->bio_offset;
1376                 if (nmp->nm_flag & NFSMNT_RDIRPLUS) {
1377                         error = nfs_readdirplusrpc_uio(vp, uiop);
1378                         if (error == NFSERR_NOTSUPP)
1379                                 nmp->nm_flag &= ~NFSMNT_RDIRPLUS;
1380                 }
1381                 if ((nmp->nm_flag & NFSMNT_RDIRPLUS) == 0)
1382                         error = nfs_readdirrpc_uio(vp, uiop);
1383                 /*
1384                  * end-of-directory sets B_INVAL but does not generate an
1385                  * error.
1386                  */
1387                 if (error == 0 && uiop->uio_resid == bp->b_bcount)
1388                         bp->b_flags |= B_INVAL;
1389                 break;
1390             default:
1391                 kprintf("nfs_doio:  type %x unexpected\n",vp->v_type);
1392                 break;
1393             };
1394             if (error) {
1395                 bp->b_flags |= B_ERROR;
1396                 bp->b_error = error;
1397             }
1398             bp->b_resid = uiop->uio_resid;
1399         } else {
1400             /* 
1401              * If we only need to commit, try to commit
1402              */
1403             KKASSERT(bp->b_cmd == BUF_CMD_WRITE);
1404             if (bp->b_flags & B_NEEDCOMMIT) {
1405                     int retv;
1406                     off_t off;
1407
1408                     off = bio->bio_offset + bp->b_dirtyoff;
1409                     retv = nfs_commitrpc_uio(vp, off,
1410                                              bp->b_dirtyend - bp->b_dirtyoff,
1411                                              td);
1412                     if (retv == 0) {
1413                             bp->b_dirtyoff = bp->b_dirtyend = 0;
1414                             bp->b_flags &= ~(B_NEEDCOMMIT | B_CLUSTEROK);
1415                             bp->b_resid = 0;
1416                             biodone(bio);
1417                             return(0);
1418                     }
1419                     if (retv == NFSERR_STALEWRITEVERF) {
1420                             nfs_clearcommit(vp->v_mount);
1421                     }
1422             }
1423
1424             /*
1425              * Setup for actual write
1426              */
1427             if (bio->bio_offset + bp->b_dirtyend > np->n_size)
1428                 bp->b_dirtyend = np->n_size - bio->bio_offset;
1429
1430             if (bp->b_dirtyend > bp->b_dirtyoff) {
1431                 io.iov_len = uiop->uio_resid = bp->b_dirtyend
1432                     - bp->b_dirtyoff;
1433                 uiop->uio_offset = bio->bio_offset + bp->b_dirtyoff;
1434                 io.iov_base = (char *)bp->b_data + bp->b_dirtyoff;
1435                 uiop->uio_rw = UIO_WRITE;
1436                 nfsstats.write_bios++;
1437
1438                 if ((bp->b_flags & (B_NEEDCOMMIT | B_NOCACHE | B_CLUSTER)) == 0)
1439                     iomode = NFSV3WRITE_UNSTABLE;
1440                 else
1441                     iomode = NFSV3WRITE_FILESYNC;
1442
1443                 must_commit = 0;
1444                 error = nfs_writerpc_uio(vp, uiop, &iomode, &must_commit);
1445
1446                 /*
1447                  * When setting B_NEEDCOMMIT also set B_CLUSTEROK to try
1448                  * to cluster the buffers needing commit.  This will allow
1449                  * the system to submit a single commit rpc for the whole
1450                  * cluster.  We can do this even if the buffer is not 100% 
1451                  * dirty (relative to the NFS blocksize), so we optimize the
1452                  * append-to-file-case.
1453                  *
1454                  * (when clearing B_NEEDCOMMIT, B_CLUSTEROK must also be
1455                  * cleared because write clustering only works for commit
1456                  * rpc's, not for the data portion of the write).
1457                  */
1458
1459                 if (!error && iomode == NFSV3WRITE_UNSTABLE) {
1460                     bp->b_flags |= B_NEEDCOMMIT;
1461                     if (bp->b_dirtyoff == 0
1462                         && bp->b_dirtyend == bp->b_bcount)
1463                         bp->b_flags |= B_CLUSTEROK;
1464                 } else {
1465                     bp->b_flags &= ~(B_NEEDCOMMIT | B_CLUSTEROK);
1466                 }
1467
1468                 /*
1469                  * For an interrupted write, the buffer is still valid
1470                  * and the write hasn't been pushed to the server yet,
1471                  * so we can't set B_ERROR and report the interruption
1472                  * by setting B_EINTR. For the async case, B_EINTR
1473                  * is not relevant, so the rpc attempt is essentially
1474                  * a noop.  For the case of a V3 write rpc not being
1475                  * committed to stable storage, the block is still
1476                  * dirty and requires either a commit rpc or another
1477                  * write rpc with iomode == NFSV3WRITE_FILESYNC before
1478                  * the block is reused. This is indicated by setting
1479                  * the B_DELWRI and B_NEEDCOMMIT flags.
1480                  *
1481                  * If the buffer is marked B_PAGING, it does not reside on
1482                  * the vp's paging queues so we cannot call bdirty().  The
1483                  * bp in this case is not an NFS cache block so we should
1484                  * be safe. XXX
1485                  */
1486                 if (error == EINTR
1487                     || (!error && (bp->b_flags & B_NEEDCOMMIT))) {
1488                         crit_enter();
1489                         bp->b_flags &= ~(B_INVAL|B_NOCACHE);
1490                         if ((bp->b_flags & B_PAGING) == 0)
1491                             bdirty(bp);
1492                         if (error)
1493                             bp->b_flags |= B_EINTR;
1494                         crit_exit();
1495                 } else {
1496                     if (error) {
1497                         bp->b_flags |= B_ERROR;
1498                         bp->b_error = np->n_error = error;
1499                         np->n_flag |= NWRITEERR;
1500                     }
1501                     bp->b_dirtyoff = bp->b_dirtyend = 0;
1502                 }
1503                 if (must_commit)
1504                     nfs_clearcommit(vp->v_mount);
1505                 bp->b_resid = uiop->uio_resid;
1506             } else {
1507                 bp->b_resid = 0;
1508             }
1509         }
1510
1511         /*
1512          * I/O was run synchronously, biodone() it and calculate the
1513          * error to return.
1514          */
1515         biodone(bio);
1516         KKASSERT(bp->b_cmd == BUF_CMD_DONE);
1517         if (bp->b_flags & B_EINTR)
1518                 return (EINTR);
1519         if (bp->b_flags & B_ERROR)
1520                 return (bp->b_error ? bp->b_error : EIO);
1521         return (0);
1522 }
1523
1524 /*
1525  * Used to aid in handling ftruncate() operations on the NFS client side.
1526  * Truncation creates a number of special problems for NFS.  We have to
1527  * throw away VM pages and buffer cache buffers that are beyond EOF, and
1528  * we have to properly handle VM pages or (potentially dirty) buffers
1529  * that straddle the truncation point.
1530  */
1531
1532 int
1533 nfs_meta_setsize(struct vnode *vp, struct thread *td, u_quad_t nsize)
1534 {
1535         struct nfsnode *np = VTONFS(vp);
1536         u_quad_t tsize = np->n_size;
1537         int biosize = vp->v_mount->mnt_stat.f_iosize;
1538         int error = 0;
1539
1540         np->n_size = nsize;
1541
1542         if (nsize < tsize) {
1543                 struct buf *bp;
1544                 off_t loffset;
1545                 int bufsize;
1546
1547                 /*
1548                  * vtruncbuf() doesn't get the buffer overlapping the 
1549                  * truncation point.  We may have a B_DELWRI and/or B_CACHE
1550                  * buffer that now needs to be truncated.
1551                  */
1552                 error = vtruncbuf(vp, nsize, biosize);
1553                 bufsize = nsize & (biosize - 1);
1554                 loffset = nsize - bufsize;
1555                 bp = nfs_getcacheblk(vp, loffset, bufsize, td);
1556                 if (bp->b_dirtyoff > bp->b_bcount)
1557                         bp->b_dirtyoff = bp->b_bcount;
1558                 if (bp->b_dirtyend > bp->b_bcount)
1559                         bp->b_dirtyend = bp->b_bcount;
1560                 bp->b_flags |= B_RELBUF;    /* don't leave garbage around */
1561                 brelse(bp);
1562         } else {
1563                 vnode_pager_setsize(vp, nsize);
1564         }
1565         return(error);
1566 }
1567
1568 /*
1569  * Synchronous completion for nfs_doio.  Call bpdone() with elseit=FALSE.
1570  * Caller is responsible for brelse()'ing the bp.
1571  */
1572 static void
1573 nfsiodone_sync(struct bio *bio)
1574 {
1575         bio->bio_flags = 0;
1576         bpdone(bio->bio_buf, 0);
1577 }
1578
1579 /*
1580  * nfs read rpc - BIO version
1581  */
1582 void
1583 nfs_readrpc_bio(struct vnode *vp, struct bio *bio)
1584 {
1585         struct buf *bp = bio->bio_buf;
1586         u_int32_t *tl;
1587         struct nfsmount *nmp;
1588         int error = 0, len, tsiz;
1589         struct nfsm_info *info;
1590
1591         info = kmalloc(sizeof(*info), M_NFSREQ, M_WAITOK);
1592         info->mrep = NULL;
1593         info->v3 = NFS_ISV3(vp);
1594
1595         nmp = VFSTONFS(vp->v_mount);
1596         tsiz = bp->b_bcount;
1597         KKASSERT(tsiz <= nmp->nm_rsize);
1598         if (bio->bio_offset + tsiz > nmp->nm_maxfilesize) {
1599                 error = EFBIG;
1600                 goto nfsmout;
1601         }
1602         nfsstats.rpccnt[NFSPROC_READ]++;
1603         len = tsiz;
1604         nfsm_reqhead(info, vp, NFSPROC_READ,
1605                      NFSX_FH(info->v3) + NFSX_UNSIGNED * 3);
1606         ERROROUT(nfsm_fhtom(info, vp));
1607         tl = nfsm_build(info, NFSX_UNSIGNED * 3);
1608         if (info->v3) {
1609                 txdr_hyper(bio->bio_offset, tl);
1610                 *(tl + 2) = txdr_unsigned(len);
1611         } else {
1612                 *tl++ = txdr_unsigned(bio->bio_offset);
1613                 *tl++ = txdr_unsigned(len);
1614                 *tl = 0;
1615         }
1616         info->bio = bio;
1617         info->done = nfs_readrpc_bio_done;
1618         nfsm_request_bio(info, vp, NFSPROC_READ, NULL,
1619                          nfs_vpcred(vp, ND_READ));
1620         return;
1621 nfsmout:
1622         kfree(info, M_NFSREQ);
1623         bp->b_error = error;
1624         bp->b_flags |= B_ERROR;
1625         biodone(bio);
1626 }
1627
1628 static void
1629 nfs_readrpc_bio_done(nfsm_info_t info)
1630 {
1631         struct nfsmount *nmp = VFSTONFS(info->vp->v_mount);
1632         struct bio *bio = info->bio;
1633         struct buf *bp = bio->bio_buf;
1634         u_int32_t *tl;
1635         int attrflag;
1636         int retlen;
1637         int eof;
1638         int error = 0;
1639
1640         KKASSERT(info->state == NFSM_STATE_DONE);
1641
1642         if (info->v3) {
1643                 ERROROUT(nfsm_postop_attr(info, info->vp, &attrflag,
1644                                          NFS_LATTR_NOSHRINK));
1645                 NULLOUT(tl = nfsm_dissect(info, 2 * NFSX_UNSIGNED));
1646                 eof = fxdr_unsigned(int, *(tl + 1));
1647         } else {
1648                 ERROROUT(nfsm_loadattr(info, info->vp, NULL));
1649                 eof = 0;
1650         }
1651         NEGATIVEOUT(retlen = nfsm_strsiz(info, nmp->nm_rsize));
1652         ERROROUT(nfsm_mtobio(info, bio, retlen));
1653         m_freem(info->mrep);
1654         info->mrep = NULL;
1655
1656         /*
1657          * No error occured, if retlen is less then bcount and no EOF
1658          * and NFSv3 a zero-fill short read occured.
1659          *
1660          * For NFSv2 a short-read indicates EOF.
1661          */
1662         if (retlen < bp->b_bcount && info->v3 && eof == 0) {
1663                 bzero(bp->b_data + retlen, bp->b_bcount - retlen);
1664                 retlen = bp->b_bcount;
1665         }
1666
1667         /*
1668          * If we hit an EOF we still zero-fill, but return the expected
1669          * b_resid anyway.  This should normally not occur since async
1670          * BIOs are not used for read-before-write case.  Races against
1671          * the server can cause it though and we don't want to leave
1672          * garbage in the buffer.
1673          */
1674         if (retlen < bp->b_bcount) {
1675                 bzero(bp->b_data + retlen, bp->b_bcount - retlen);
1676         }
1677         bp->b_resid = 0;
1678         /* bp->b_resid = bp->b_bcount - retlen; */
1679 nfsmout:
1680         kfree(info, M_NFSREQ);
1681         if (error) {
1682                 bp->b_error = error;
1683                 bp->b_flags |= B_ERROR;
1684         }
1685         biodone(bio);
1686 }
1687
1688 /*
1689  * nfs write call - BIO version
1690  */
1691 void
1692 nfs_writerpc_bio(struct vnode *vp, struct bio *bio)
1693 {
1694         struct nfsmount *nmp = VFSTONFS(vp->v_mount);
1695         struct nfsnode *np = VTONFS(vp);
1696         struct buf *bp = bio->bio_buf;
1697         u_int32_t *tl;
1698         int len;
1699         int iomode;
1700         int error = 0;
1701         struct nfsm_info *info;
1702         off_t offset;
1703
1704         /*
1705          * Setup for actual write.  Just clean up the bio if there
1706          * is nothing to do.
1707          */
1708         if (bio->bio_offset + bp->b_dirtyend > np->n_size)
1709                 bp->b_dirtyend = np->n_size - bio->bio_offset;
1710
1711         if (bp->b_dirtyend <= bp->b_dirtyoff) {
1712                 bp->b_resid = 0;
1713                 biodone(bio);
1714                 return;
1715         }
1716         len = bp->b_dirtyend - bp->b_dirtyoff;
1717         offset = bio->bio_offset + bp->b_dirtyoff;
1718         if (offset + len > nmp->nm_maxfilesize) {
1719                 bp->b_flags |= B_ERROR;
1720                 bp->b_error = EFBIG;
1721                 biodone(bio);
1722                 return;
1723         }
1724         bp->b_resid = len;
1725         nfsstats.write_bios++;
1726
1727         info = kmalloc(sizeof(*info), M_NFSREQ, M_WAITOK);
1728         info->mrep = NULL;
1729         info->v3 = NFS_ISV3(vp);
1730         info->info_writerpc.must_commit = 0;
1731         if ((bp->b_flags & (B_NEEDCOMMIT | B_NOCACHE | B_CLUSTER)) == 0)
1732                 iomode = NFSV3WRITE_UNSTABLE;
1733         else
1734                 iomode = NFSV3WRITE_FILESYNC;
1735
1736         KKASSERT(len <= nmp->nm_wsize);
1737
1738         nfsstats.rpccnt[NFSPROC_WRITE]++;
1739         nfsm_reqhead(info, vp, NFSPROC_WRITE,
1740                      NFSX_FH(info->v3) + 5 * NFSX_UNSIGNED + nfsm_rndup(len));
1741         ERROROUT(nfsm_fhtom(info, vp));
1742         if (info->v3) {
1743                 tl = nfsm_build(info, 5 * NFSX_UNSIGNED);
1744                 txdr_hyper(offset, tl);
1745                 tl += 2;
1746                 *tl++ = txdr_unsigned(len);
1747                 *tl++ = txdr_unsigned(iomode);
1748                 *tl = txdr_unsigned(len);
1749         } else {
1750                 u_int32_t x;
1751
1752                 tl = nfsm_build(info, 4 * NFSX_UNSIGNED);
1753                 /* Set both "begin" and "current" to non-garbage. */
1754                 x = txdr_unsigned((u_int32_t)offset);
1755                 *tl++ = x;      /* "begin offset" */
1756                 *tl++ = x;      /* "current offset" */
1757                 x = txdr_unsigned(len);
1758                 *tl++ = x;      /* total to this offset */
1759                 *tl = x;        /* size of this write */
1760         }
1761         ERROROUT(nfsm_biotom(info, bio, bp->b_dirtyoff, len));
1762         info->bio = bio;
1763         info->done = nfs_writerpc_bio_done;
1764         nfsm_request_bio(info, vp, NFSPROC_WRITE, NULL,
1765                          nfs_vpcred(vp, ND_WRITE));
1766         return;
1767 nfsmout:
1768         kfree(info, M_NFSREQ);
1769         bp->b_error = error;
1770         bp->b_flags |= B_ERROR;
1771         biodone(bio);
1772 }
1773
1774 static void
1775 nfs_writerpc_bio_done(nfsm_info_t info)
1776 {
1777         struct nfsmount *nmp = VFSTONFS(info->vp->v_mount);
1778         struct nfsnode *np = VTONFS(info->vp);
1779         struct bio *bio = info->bio;
1780         struct buf *bp = bio->bio_buf;
1781         int wccflag = NFSV3_WCCRATTR;
1782         int iomode = NFSV3WRITE_FILESYNC;
1783         int commit;
1784         int rlen;
1785         int error;
1786         int len = bp->b_resid;  /* b_resid was set to shortened length */
1787         u_int32_t *tl;
1788
1789         if (info->v3) {
1790                 /*
1791                  * The write RPC returns a before and after mtime.  The
1792                  * nfsm_wcc_data() macro checks the before n_mtime
1793                  * against the before time and stores the after time
1794                  * in the nfsnode's cached vattr and n_mtime field.
1795                  * The NRMODIFIED bit will be set if the before
1796                  * time did not match the original mtime.
1797                  */
1798                 wccflag = NFSV3_WCCCHK;
1799                 ERROROUT(nfsm_wcc_data(info, info->vp, &wccflag));
1800                 if (error == 0) {
1801                         NULLOUT(tl = nfsm_dissect(info, 2 * NFSX_UNSIGNED + NFSX_V3WRITEVERF));
1802                         rlen = fxdr_unsigned(int, *tl++);
1803                         if (rlen == 0) {
1804                                 error = NFSERR_IO;
1805                                 m_freem(info->mrep);
1806                                 info->mrep = NULL;
1807                                 goto nfsmout;
1808                         } else if (rlen < len) {
1809 #if 0
1810                                 /*
1811                                  * XXX what do we do here?
1812                                  */
1813                                 backup = len - rlen;
1814                                 uiop->uio_iov->iov_base = (char *)uiop->uio_iov->iov_base - backup;
1815                                 uiop->uio_iov->iov_len += backup;
1816                                 uiop->uio_offset -= backup;
1817                                 uiop->uio_resid += backup;
1818                                 len = rlen;
1819 #endif
1820                         }
1821                         commit = fxdr_unsigned(int, *tl++);
1822
1823                         /*
1824                          * Return the lowest committment level
1825                          * obtained by any of the RPCs.
1826                          */
1827                         if (iomode == NFSV3WRITE_FILESYNC)
1828                                 iomode = commit;
1829                         else if (iomode == NFSV3WRITE_DATASYNC &&
1830                                 commit == NFSV3WRITE_UNSTABLE)
1831                                 iomode = commit;
1832                         if ((nmp->nm_state & NFSSTA_HASWRITEVERF) == 0){
1833                             bcopy(tl, (caddr_t)nmp->nm_verf, NFSX_V3WRITEVERF);
1834                             nmp->nm_state |= NFSSTA_HASWRITEVERF;
1835                         } else if (bcmp(tl, nmp->nm_verf, NFSX_V3WRITEVERF)) {
1836                             info->info_writerpc.must_commit = 1;
1837                             bcopy(tl, (caddr_t)nmp->nm_verf, NFSX_V3WRITEVERF);
1838                         }
1839                 }
1840         } else {
1841                 ERROROUT(nfsm_loadattr(info, info->vp, NULL));
1842         }
1843         m_freem(info->mrep);
1844         info->mrep = NULL;
1845         len = 0;
1846 nfsmout:
1847         if (info->vp->v_mount->mnt_flag & MNT_ASYNC)
1848                 iomode = NFSV3WRITE_FILESYNC;
1849         bp->b_resid = len;
1850
1851         /*
1852          * End of RPC.  Now clean up the bp.
1853          *
1854          * When setting B_NEEDCOMMIT also set B_CLUSTEROK to try
1855          * to cluster the buffers needing commit.  This will allow
1856          * the system to submit a single commit rpc for the whole
1857          * cluster.  We can do this even if the buffer is not 100%
1858          * dirty (relative to the NFS blocksize), so we optimize the
1859          * append-to-file-case.
1860          *
1861          * (when clearing B_NEEDCOMMIT, B_CLUSTEROK must also be
1862          * cleared because write clustering only works for commit
1863          * rpc's, not for the data portion of the write).
1864          */
1865         if (!error && iomode == NFSV3WRITE_UNSTABLE) {
1866                 bp->b_flags |= B_NEEDCOMMIT;
1867                 if (bp->b_dirtyoff == 0 && bp->b_dirtyend == bp->b_bcount)
1868                         bp->b_flags |= B_CLUSTEROK;
1869         } else {
1870                 bp->b_flags &= ~(B_NEEDCOMMIT | B_CLUSTEROK);
1871         }
1872
1873         /*
1874          * For an interrupted write, the buffer is still valid
1875          * and the write hasn't been pushed to the server yet,
1876          * so we can't set B_ERROR and report the interruption
1877          * by setting B_EINTR. For the async case, B_EINTR
1878          * is not relevant, so the rpc attempt is essentially
1879          * a noop.  For the case of a V3 write rpc not being
1880          * committed to stable storage, the block is still
1881          * dirty and requires either a commit rpc or another
1882          * write rpc with iomode == NFSV3WRITE_FILESYNC before
1883          * the block is reused. This is indicated by setting
1884          * the B_DELWRI and B_NEEDCOMMIT flags.
1885          *
1886          * If the buffer is marked B_PAGING, it does not reside on
1887          * the vp's paging queues so we cannot call bdirty().  The
1888          * bp in this case is not an NFS cache block so we should
1889          * be safe. XXX
1890          */
1891         if (error == EINTR || (!error && (bp->b_flags & B_NEEDCOMMIT))) {
1892                 crit_enter();
1893                 bp->b_flags &= ~(B_INVAL|B_NOCACHE);
1894                 if ((bp->b_flags & B_PAGING) == 0)
1895                         bdirty(bp);
1896                 if (error)
1897                         bp->b_flags |= B_EINTR;
1898                 crit_exit();
1899         } else {
1900                 if (error) {
1901                         bp->b_flags |= B_ERROR;
1902                         bp->b_error = np->n_error = error;
1903                         np->n_flag |= NWRITEERR;
1904                 }
1905                 bp->b_dirtyoff = bp->b_dirtyend = 0;
1906         }
1907         if (info->info_writerpc.must_commit)
1908                 nfs_clearcommit(info->vp->v_mount);
1909         kfree(info, M_NFSREQ);
1910         if (error) {
1911                 bp->b_flags |= B_ERROR;
1912                 bp->b_error = error;
1913         }
1914         biodone(bio);
1915 }
1916
1917 /*
1918  * Nfs Version 3 commit rpc - BIO version
1919  *
1920  * This function issues the commit rpc and will chain to a write
1921  * rpc if necessary.
1922  */
1923 void
1924 nfs_commitrpc_bio(struct vnode *vp, struct bio *bio)
1925 {
1926         struct nfsmount *nmp = VFSTONFS(vp->v_mount);
1927         struct buf *bp = bio->bio_buf;
1928         struct nfsm_info *info;
1929         int error = 0;
1930         u_int32_t *tl;
1931
1932         if ((nmp->nm_state & NFSSTA_HASWRITEVERF) == 0) {
1933                 bp->b_dirtyoff = bp->b_dirtyend = 0;
1934                 bp->b_flags &= ~(B_NEEDCOMMIT | B_CLUSTEROK);
1935                 bp->b_resid = 0;
1936                 biodone(bio);
1937                 return;
1938         }
1939
1940         info = kmalloc(sizeof(*info), M_NFSREQ, M_WAITOK);
1941         info->mrep = NULL;
1942         info->v3 = 1;
1943
1944         nfsstats.rpccnt[NFSPROC_COMMIT]++;
1945         nfsm_reqhead(info, vp, NFSPROC_COMMIT, NFSX_FH(1));
1946         ERROROUT(nfsm_fhtom(info, vp));
1947         tl = nfsm_build(info, 3 * NFSX_UNSIGNED);
1948         txdr_hyper(bio->bio_offset + bp->b_dirtyoff, tl);
1949         tl += 2;
1950         *tl = txdr_unsigned(bp->b_dirtyend - bp->b_dirtyoff);
1951         info->bio = bio;
1952         info->done = nfs_commitrpc_bio_done;
1953         nfsm_request_bio(info, vp, NFSPROC_COMMIT, NULL,
1954                          nfs_vpcred(vp, ND_WRITE));
1955         return;
1956 nfsmout:
1957         /*
1958          * Chain to write RPC on (early) error
1959          */
1960         kfree(info, M_NFSREQ);
1961         nfs_writerpc_bio(vp, bio);
1962 }
1963
1964 static void
1965 nfs_commitrpc_bio_done(nfsm_info_t info)
1966 {
1967         struct nfsmount *nmp = VFSTONFS(info->vp->v_mount);
1968         struct bio *bio = info->bio;
1969         struct buf *bp = bio->bio_buf;
1970         u_int32_t *tl;
1971         int wccflag = NFSV3_WCCRATTR;
1972         int error = 0;
1973
1974         ERROROUT(nfsm_wcc_data(info, info->vp, &wccflag));
1975         if (error == 0) {
1976                 NULLOUT(tl = nfsm_dissect(info, NFSX_V3WRITEVERF));
1977                 if (bcmp(nmp->nm_verf, tl, NFSX_V3WRITEVERF)) {
1978                         bcopy(tl, nmp->nm_verf, NFSX_V3WRITEVERF);
1979                         error = NFSERR_STALEWRITEVERF;
1980                 }
1981         }
1982         m_freem(info->mrep);
1983         info->mrep = NULL;
1984
1985         /*
1986          * On completion we must chain to a write bio if an
1987          * error occurred.
1988          */
1989 nfsmout:
1990         kfree(info, M_NFSREQ);
1991         if (error == 0) {
1992                 bp->b_dirtyoff = bp->b_dirtyend = 0;
1993                 bp->b_flags &= ~(B_NEEDCOMMIT | B_CLUSTEROK);
1994                 bp->b_resid = 0;
1995                 biodone(bio);
1996         } else {
1997                 nfs_writerpc_bio(info->vp, bio);
1998         }
1999 }
2000