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