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