Merge branch 'master' of ssh://crater.dragonflybsd.org/repository/git/dragonfly
[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/buf2.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/thread2.h>
62
63 #include "rpcv2.h"
64 #include "nfsproto.h"
65 #include "nfs.h"
66 #include "nfsmount.h"
67 #include "nfsnode.h"
68
69 static struct buf *nfs_getcacheblk(struct vnode *vp, off_t loffset,
70                                    int size, struct thread *td);
71 static int nfs_check_dirent(struct nfs_dirent *dp, int maxlen);
72 static void nfsiodone_sync(struct bio *bio);
73
74 extern int nfs_pbuf_freecnt;
75 extern struct nfsstats nfsstats;
76
77 /*
78  * Vnode op for VM getpages.
79  *
80  * nfs_getpages(struct vnode *a_vp, vm_page_t *a_m, int a_count,
81  *              int a_reqpage, vm_ooffset_t a_offset)
82  */
83 int
84 nfs_getpages(struct vop_getpages_args *ap)
85 {
86         struct thread *td = curthread;          /* XXX */
87         int i, error, nextoff, size, toff, count, npages;
88         struct uio uio;
89         struct iovec iov;
90         char *kva;
91         struct vnode *vp;
92         struct nfsmount *nmp;
93         vm_page_t *pages;
94         vm_page_t m;
95         struct msf_buf *msf;
96
97         vp = ap->a_vp;
98         nmp = VFSTONFS(vp->v_mount);
99         pages = ap->a_m;
100         count = ap->a_count;
101
102         if (vp->v_object == NULL) {
103                 kprintf("nfs_getpages: called with non-merged cache vnode??\n");
104                 return VM_PAGER_ERROR;
105         }
106
107         if ((nmp->nm_flag & NFSMNT_NFSV3) != 0 &&
108             (nmp->nm_state & NFSSTA_GOTFSINFO) == 0)
109                 (void)nfs_fsinfo(nmp, vp, td);
110
111         npages = btoc(count);
112
113         /*
114          * NOTE that partially valid pages may occur in cases other
115          * then file EOF, such as when a file is partially written and
116          * ftruncate()-extended to a larger size.   It is also possible
117          * for the valid bits to be set on garbage beyond the file EOF and
118          * clear in the area before EOF (e.g. m->valid == 0xfc), which can
119          * occur due to vtruncbuf() and the buffer cache's handling of
120          * pages which 'straddle' buffers or when b_bufsize is not a 
121          * multiple of PAGE_SIZE.... the buffer cache cannot normally
122          * clear the extra bits.  This kind of situation occurs when you
123          * make a small write() (m->valid == 0x03) and then mmap() and
124          * fault in the buffer(m->valid = 0xFF).  When NFS flushes the
125          * buffer (vinvalbuf() m->valid = 0xFC) we are left with a mess.
126          *
127          * This is combined with the possibility that the pages are partially
128          * dirty or that there is a buffer backing the pages that is dirty
129          * (even if m->dirty is 0).
130          *
131          * To solve this problem several hacks have been made:  (1) NFS
132          * guarentees that the IO block size is a multiple of PAGE_SIZE and
133          * (2) The buffer cache, when invalidating an NFS buffer, will
134          * disregard the buffer's fragmentory b_bufsize and invalidate
135          * the whole page rather then just the piece the buffer owns.
136          *
137          * This allows us to assume that a partially valid page found here
138          * is fully valid (vm_fault will zero'd out areas of the page not
139          * marked as valid).
140          */
141         m = pages[ap->a_reqpage];
142         if (m->valid != 0) {
143                 for (i = 0; i < npages; ++i) {
144                         if (i != ap->a_reqpage)
145                                 vnode_pager_freepage(pages[i]);
146                 }
147                 return(0);
148         }
149
150         /*
151          * Use an MSF_BUF as a medium to retrieve data from the pages.
152          */
153         msf_map_pagelist(&msf, pages, npages, 0);
154         KKASSERT(msf);
155         kva = msf_buf_kva(msf);
156
157         iov.iov_base = kva;
158         iov.iov_len = count;
159         uio.uio_iov = &iov;
160         uio.uio_iovcnt = 1;
161         uio.uio_offset = IDX_TO_OFF(pages[0]->pindex);
162         uio.uio_resid = count;
163         uio.uio_segflg = UIO_SYSSPACE;
164         uio.uio_rw = UIO_READ;
165         uio.uio_td = td;
166
167         error = nfs_readrpc(vp, &uio);
168         msf_buf_free(msf);
169
170         if (error && (uio.uio_resid == count)) {
171                 kprintf("nfs_getpages: error %d\n", error);
172                 for (i = 0; i < npages; ++i) {
173                         if (i != ap->a_reqpage)
174                                 vnode_pager_freepage(pages[i]);
175                 }
176                 return VM_PAGER_ERROR;
177         }
178
179         /*
180          * Calculate the number of bytes read and validate only that number
181          * of bytes.  Note that due to pending writes, size may be 0.  This
182          * does not mean that the remaining data is invalid!
183          */
184
185         size = count - uio.uio_resid;
186
187         for (i = 0, toff = 0; i < npages; i++, toff = nextoff) {
188                 nextoff = toff + PAGE_SIZE;
189                 m = pages[i];
190
191                 m->flags &= ~PG_ZERO;
192
193                 if (nextoff <= size) {
194                         /*
195                          * Read operation filled an entire page
196                          */
197                         m->valid = VM_PAGE_BITS_ALL;
198                         vm_page_undirty(m);
199                 } else if (size > toff) {
200                         /*
201                          * Read operation filled a partial page.
202                          */
203                         m->valid = 0;
204                         vm_page_set_validclean(m, 0, size - toff);
205                         /* handled by vm_fault now        */
206                         /* vm_page_zero_invalid(m, TRUE); */
207                 } else {
208                         /*
209                          * Read operation was short.  If no error occured
210                          * we may have hit a zero-fill section.   We simply
211                          * leave valid set to 0.
212                          */
213                         ;
214                 }
215                 if (i != ap->a_reqpage) {
216                         /*
217                          * Whether or not to leave the page activated is up in
218                          * the air, but we should put the page on a page queue
219                          * somewhere (it already is in the object).  Result:
220                          * It appears that emperical results show that
221                          * deactivating pages is best.
222                          */
223
224                         /*
225                          * Just in case someone was asking for this page we
226                          * now tell them that it is ok to use.
227                          */
228                         if (!error) {
229                                 if (m->flags & PG_WANTED)
230                                         vm_page_activate(m);
231                                 else
232                                         vm_page_deactivate(m);
233                                 vm_page_wakeup(m);
234                         } else {
235                                 vnode_pager_freepage(m);
236                         }
237                 }
238         }
239         return 0;
240 }
241
242 /*
243  * Vnode op for VM putpages.
244  *
245  * nfs_putpages(struct vnode *a_vp, vm_page_t *a_m, int a_count, int a_sync,
246  *              int *a_rtvals, vm_ooffset_t a_offset)
247  */
248 int
249 nfs_putpages(struct vop_putpages_args *ap)
250 {
251         struct thread *td = curthread;
252         struct uio uio;
253         struct iovec iov;
254         char *kva;
255         int iomode, must_commit, i, error, npages, count;
256         off_t offset;
257         int *rtvals;
258         struct vnode *vp;
259         struct nfsmount *nmp;
260         struct nfsnode *np;
261         vm_page_t *pages;
262         struct msf_buf *msf;
263
264         vp = ap->a_vp;
265         np = VTONFS(vp);
266         nmp = VFSTONFS(vp->v_mount);
267         pages = ap->a_m;
268         count = ap->a_count;
269         rtvals = ap->a_rtvals;
270         npages = btoc(count);
271         offset = IDX_TO_OFF(pages[0]->pindex);
272
273         if ((nmp->nm_flag & NFSMNT_NFSV3) != 0 &&
274             (nmp->nm_state & NFSSTA_GOTFSINFO) == 0)
275                 (void)nfs_fsinfo(nmp, vp, td);
276
277         for (i = 0; i < npages; i++) {
278                 rtvals[i] = VM_PAGER_AGAIN;
279         }
280
281         /*
282          * When putting pages, do not extend file past EOF.
283          */
284
285         if (offset + count > np->n_size) {
286                 count = np->n_size - offset;
287                 if (count < 0)
288                         count = 0;
289         }
290
291         /*
292          * Use an MSF_BUF as a medium to retrieve data from the pages.
293          */
294         msf_map_pagelist(&msf, pages, npages, 0);
295         KKASSERT(msf);
296         kva = msf_buf_kva(msf);
297
298         iov.iov_base = kva;
299         iov.iov_len = count;
300         uio.uio_iov = &iov;
301         uio.uio_iovcnt = 1;
302         uio.uio_offset = offset;
303         uio.uio_resid = count;
304         uio.uio_segflg = UIO_SYSSPACE;
305         uio.uio_rw = UIO_WRITE;
306         uio.uio_td = td;
307
308         if ((ap->a_sync & VM_PAGER_PUT_SYNC) == 0)
309             iomode = NFSV3WRITE_UNSTABLE;
310         else
311             iomode = NFSV3WRITE_FILESYNC;
312
313         error = nfs_writerpc(vp, &uio, &iomode, &must_commit);
314
315         msf_buf_free(msf);
316
317         if (!error) {
318                 int nwritten = round_page(count - uio.uio_resid) / PAGE_SIZE;
319                 for (i = 0; i < nwritten; i++) {
320                         rtvals[i] = VM_PAGER_OK;
321                         vm_page_undirty(pages[i]);
322                 }
323                 if (must_commit)
324                         nfs_clearcommit(vp->v_mount);
325         }
326         return rtvals[0];
327 }
328
329 /*
330  * Vnode op for read using bio
331  */
332 int
333 nfs_bioread(struct vnode *vp, struct uio *uio, int ioflag)
334 {
335         struct nfsnode *np = VTONFS(vp);
336         int biosize, i;
337         struct buf *bp = 0, *rabp;
338         struct vattr vattr;
339         struct thread *td;
340         struct nfsmount *nmp = VFSTONFS(vp->v_mount);
341         daddr_t lbn, rabn;
342         off_t raoffset;
343         off_t loffset;
344         int bcount;
345         int seqcount;
346         int nra, error = 0, n = 0, on = 0;
347
348 #ifdef DIAGNOSTIC
349         if (uio->uio_rw != UIO_READ)
350                 panic("nfs_read mode");
351 #endif
352         if (uio->uio_resid == 0)
353                 return (0);
354         if (uio->uio_offset < 0)        /* XXX VDIR cookies can be negative */
355                 return (EINVAL);
356         td = uio->uio_td;
357
358         if ((nmp->nm_flag & NFSMNT_NFSV3) != 0 &&
359             (nmp->nm_state & NFSSTA_GOTFSINFO) == 0)
360                 (void)nfs_fsinfo(nmp, vp, td);
361         if (vp->v_type != VDIR &&
362             (uio->uio_offset + uio->uio_resid) > nmp->nm_maxfilesize)
363                 return (EFBIG);
364         biosize = vp->v_mount->mnt_stat.f_iosize;
365         seqcount = (int)((off_t)(ioflag >> IO_SEQSHIFT) * biosize / BKVASIZE);
366
367         /*
368          * For nfs, cache consistency can only be maintained approximately.
369          * Although RFC1094 does not specify the criteria, the following is
370          * believed to be compatible with the reference port.
371          *
372          * NFS:         If local changes have been made and this is a
373          *              directory, the directory must be invalidated and
374          *              the attribute cache must be cleared.
375          *
376          *              GETATTR is called to synchronize the file size.
377          *
378          *              If remote changes are detected local data is flushed
379          *              and the cache is invalidated.
380          *
381          *              NOTE: In the normal case the attribute cache is not
382          *              cleared which means GETATTR may use cached data and
383          *              not immediately detect changes made on the server.
384          */
385         if ((np->n_flag & NLMODIFIED) && vp->v_type == VDIR) {
386                 nfs_invaldir(vp);
387                 error = nfs_vinvalbuf(vp, V_SAVE, 1);
388                 if (error)
389                         return (error);
390                 np->n_attrstamp = 0;
391         }
392         error = VOP_GETATTR(vp, &vattr);
393         if (error)
394                 return (error);
395         if (np->n_flag & NRMODIFIED) {
396                 if (vp->v_type == VDIR)
397                         nfs_invaldir(vp);
398                 error = nfs_vinvalbuf(vp, V_SAVE, 1);
399                 if (error)
400                         return (error);
401                 np->n_flag &= ~NRMODIFIED;
402         }
403         do {
404             if (np->n_flag & NDONTCACHE) {
405                 switch (vp->v_type) {
406                 case VREG:
407                         return (nfs_readrpc(vp, uio));
408                 case VLNK:
409                         return (nfs_readlinkrpc(vp, uio));
410                 case VDIR:
411                         break;
412                 default:
413                         kprintf(" NDONTCACHE: type %x unexpected\n", vp->v_type);
414                         break;
415                 };
416             }
417             switch (vp->v_type) {
418             case VREG:
419                 nfsstats.biocache_reads++;
420                 lbn = uio->uio_offset / biosize;
421                 on = uio->uio_offset & (biosize - 1);
422                 loffset = (off_t)lbn * biosize;
423
424                 /*
425                  * Start the read ahead(s), as required.
426                  */
427                 if (nmp->nm_readahead > 0) {
428                     for (nra = 0; nra < nmp->nm_readahead && nra < seqcount &&
429                         (off_t)(lbn + 1 + nra) * biosize < np->n_size; nra++) {
430                         rabn = lbn + 1 + nra;
431                         raoffset = (off_t)rabn * biosize;
432                         if (findblk(vp, raoffset, FINDBLK_TEST) == NULL) {
433                             rabp = nfs_getcacheblk(vp, raoffset, biosize, td);
434                             if (!rabp)
435                                 return (EINTR);
436                             if ((rabp->b_flags & (B_CACHE|B_DELWRI)) == 0) {
437                                 rabp->b_cmd = BUF_CMD_READ;
438                                 vfs_busy_pages(vp, rabp);
439                                 if (nfs_asyncio(vp, &rabp->b_bio2, td)) {
440                                     rabp->b_flags |= B_INVAL|B_ERROR;
441                                     vfs_unbusy_pages(rabp);
442                                     brelse(rabp);
443                                     break;
444                                 }
445                             } else {
446                                 brelse(rabp);
447                             }
448                         }
449                     }
450                 }
451
452                 /*
453                  * Obtain the buffer cache block.  Figure out the buffer size
454                  * when we are at EOF.  If we are modifying the size of the
455                  * buffer based on an EOF condition we need to hold 
456                  * nfs_rslock() through obtaining the buffer to prevent
457                  * a potential writer-appender from messing with n_size.
458                  * Otherwise we may accidently truncate the buffer and
459                  * lose dirty data.
460                  *
461                  * Note that bcount is *not* DEV_BSIZE aligned.
462                  */
463
464 again:
465                 bcount = biosize;
466                 if (loffset >= np->n_size) {
467                         bcount = 0;
468                 } else if (loffset + biosize > np->n_size) {
469                         bcount = np->n_size - loffset;
470                 }
471                 if (bcount != biosize) {
472                         switch(nfs_rslock(np)) {
473                         case ENOLCK:
474                                 goto again;
475                                 /* not reached */
476                         case EINTR:
477                         case ERESTART:
478                                 return(EINTR);
479                                 /* not reached */
480                         default:
481                                 break;
482                         }
483                 }
484
485                 bp = nfs_getcacheblk(vp, loffset, bcount, td);
486
487                 if (bcount != biosize)
488                         nfs_rsunlock(np);
489                 if (!bp)
490                         return (EINTR);
491
492                 /*
493                  * If B_CACHE is not set, we must issue the read.  If this
494                  * fails, we return an error.
495                  */
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
517                 n = 0;
518                 if (on < bcount)
519                         n = min((unsigned)(bcount - on), uio->uio_resid);
520                 break;
521             case VLNK:
522                 biosize = min(NFS_MAXPATHLEN, np->n_size);
523                 nfsstats.biocache_readlinks++;
524                 bp = nfs_getcacheblk(vp, (off_t)0, biosize, td);
525                 if (bp == NULL)
526                         return (EINTR);
527                 if ((bp->b_flags & B_CACHE) == 0) {
528                     bp->b_cmd = BUF_CMD_READ;
529                     bp->b_bio2.bio_done = nfsiodone_sync;
530                     bp->b_bio2.bio_flags |= BIO_SYNC;
531                     vfs_busy_pages(vp, bp);
532                     error = nfs_doio(vp, &bp->b_bio2, td);
533                     if (error) {
534                         bp->b_flags |= B_ERROR | B_INVAL;
535                         brelse(bp);
536                         return (error);
537                     }
538                 }
539                 n = min(uio->uio_resid, bp->b_bcount - bp->b_resid);
540                 on = 0;
541                 break;
542             case VDIR:
543                 nfsstats.biocache_readdirs++;
544                 if (np->n_direofoffset
545                     && uio->uio_offset >= np->n_direofoffset) {
546                     return (0);
547                 }
548                 lbn = (uoff_t)uio->uio_offset / NFS_DIRBLKSIZ;
549                 on = uio->uio_offset & (NFS_DIRBLKSIZ - 1);
550                 loffset = uio->uio_offset - on;
551                 bp = nfs_getcacheblk(vp, loffset, NFS_DIRBLKSIZ, td);
552                 if (bp == NULL)
553                     return (EINTR);
554
555                 if ((bp->b_flags & B_CACHE) == 0) {
556                     bp->b_cmd = BUF_CMD_READ;
557                     bp->b_bio2.bio_done = nfsiodone_sync;
558                     bp->b_bio2.bio_flags |= BIO_SYNC;
559                     vfs_busy_pages(vp, bp);
560                     error = nfs_doio(vp, &bp->b_bio2, td);
561                     if (error) {
562                             brelse(bp);
563                     }
564                     while (error == NFSERR_BAD_COOKIE) {
565                         kprintf("got bad cookie vp %p bp %p\n", vp, bp);
566                         nfs_invaldir(vp);
567                         error = nfs_vinvalbuf(vp, 0, 1);
568                         /*
569                          * Yuck! The directory has been modified on the
570                          * server. The only way to get the block is by
571                          * reading from the beginning to get all the
572                          * offset cookies.
573                          *
574                          * Leave the last bp intact unless there is an error.
575                          * Loop back up to the while if the error is another
576                          * NFSERR_BAD_COOKIE (double yuch!).
577                          */
578                         for (i = 0; i <= lbn && !error; i++) {
579                             if (np->n_direofoffset
580                                 && (i * NFS_DIRBLKSIZ) >= np->n_direofoffset)
581                                     return (0);
582                             bp = nfs_getcacheblk(vp, (off_t)i * NFS_DIRBLKSIZ,
583                                                  NFS_DIRBLKSIZ, td);
584                             if (!bp)
585                                 return (EINTR);
586                             if ((bp->b_flags & B_CACHE) == 0) {
587                                     bp->b_cmd = BUF_CMD_READ;
588                                     bp->b_bio2.bio_done = nfsiodone_sync;
589                                     bp->b_bio2.bio_flags |= BIO_SYNC;
590                                     vfs_busy_pages(vp, bp);
591                                     error = nfs_doio(vp, &bp->b_bio2, td);
592                                     /*
593                                      * no error + B_INVAL == directory EOF,
594                                      * use the block.
595                                      */
596                                     if (error == 0 && (bp->b_flags & B_INVAL))
597                                             break;
598                             }
599                             /*
600                              * An error will throw away the block and the
601                              * for loop will break out.  If no error and this
602                              * is not the block we want, we throw away the
603                              * block and go for the next one via the for loop.
604                              */
605                             if (error || i < lbn)
606                                     brelse(bp);
607                         }
608                     }
609                     /*
610                      * The above while is repeated if we hit another cookie
611                      * error.  If we hit an error and it wasn't a cookie error,
612                      * we give up.
613                      */
614                     if (error)
615                             return (error);
616                 }
617
618                 /*
619                  * If not eof and read aheads are enabled, start one.
620                  * (You need the current block first, so that you have the
621                  *  directory offset cookie of the next block.)
622                  */
623                 if (nmp->nm_readahead > 0 &&
624                     (bp->b_flags & B_INVAL) == 0 &&
625                     (np->n_direofoffset == 0 ||
626                     loffset + NFS_DIRBLKSIZ < np->n_direofoffset) &&
627                     (np->n_flag & NDONTCACHE) == 0 &&
628                     findblk(vp, loffset + NFS_DIRBLKSIZ, FINDBLK_TEST) == NULL
629                 ) {
630                         rabp = nfs_getcacheblk(vp, loffset + NFS_DIRBLKSIZ,
631                                                NFS_DIRBLKSIZ, td);
632                         if (rabp) {
633                             if ((rabp->b_flags & (B_CACHE|B_DELWRI)) == 0) {
634                                 rabp->b_cmd = BUF_CMD_READ;
635                                 vfs_busy_pages(vp, rabp);
636                                 if (nfs_asyncio(vp, &rabp->b_bio2, td)) {
637                                     rabp->b_flags |= B_INVAL|B_ERROR;
638                                     vfs_unbusy_pages(rabp);
639                                     brelse(rabp);
640                                 }
641                             } else {
642                                 brelse(rabp);
643                             }
644                         }
645                 }
646                 /*
647                  * Unlike VREG files, whos buffer size ( bp->b_bcount ) is
648                  * chopped for the EOF condition, we cannot tell how large
649                  * NFS directories are going to be until we hit EOF.  So
650                  * an NFS directory buffer is *not* chopped to its EOF.  Now,
651                  * it just so happens that b_resid will effectively chop it
652                  * to EOF.  *BUT* this information is lost if the buffer goes
653                  * away and is reconstituted into a B_CACHE state ( due to
654                  * being VMIO ) later.  So we keep track of the directory eof
655                  * in np->n_direofoffset and chop it off as an extra step 
656                  * right here.
657                  */
658                 n = lmin(uio->uio_resid, NFS_DIRBLKSIZ - bp->b_resid - on);
659                 if (np->n_direofoffset && n > np->n_direofoffset - uio->uio_offset)
660                         n = np->n_direofoffset - uio->uio_offset;
661                 break;
662             default:
663                 kprintf(" nfs_bioread: type %x unexpected\n",vp->v_type);
664                 break;
665             };
666
667             switch (vp->v_type) {
668             case VREG:
669                 if (n > 0)
670                     error = uiomove(bp->b_data + on, (int)n, uio);
671                 break;
672             case VLNK:
673                 if (n > 0)
674                     error = uiomove(bp->b_data + on, (int)n, uio);
675                 n = 0;
676                 break;
677             case VDIR:
678                 if (n > 0) {
679                     off_t old_off = uio->uio_offset;
680                     caddr_t cpos, epos;
681                     struct nfs_dirent *dp;
682
683                     /*
684                      * We are casting cpos to nfs_dirent, it must be
685                      * int-aligned.
686                      */
687                     if (on & 3) {
688                         error = EINVAL;
689                         break;
690                     }
691
692                     cpos = bp->b_data + on;
693                     epos = bp->b_data + on + n;
694                     while (cpos < epos && error == 0 && uio->uio_resid > 0) {
695                             dp = (struct nfs_dirent *)cpos;
696                             error = nfs_check_dirent(dp, (int)(epos - cpos));
697                             if (error)
698                                     break;
699                             if (vop_write_dirent(&error, uio, dp->nfs_ino,
700                                 dp->nfs_type, dp->nfs_namlen, dp->nfs_name)) {
701                                     break;
702                             }
703                             cpos += dp->nfs_reclen;
704                     }
705                     n = 0;
706                     if (error == 0)
707                             uio->uio_offset = old_off + cpos - bp->b_data - on;
708                 }
709                 /*
710                  * Invalidate buffer if caching is disabled, forcing a
711                  * re-read from the remote later.
712                  */
713                 if (np->n_flag & NDONTCACHE)
714                         bp->b_flags |= B_INVAL;
715                 break;
716             default:
717                 kprintf(" nfs_bioread: type %x unexpected\n",vp->v_type);
718             }
719             brelse(bp);
720         } while (error == 0 && uio->uio_resid > 0 && n > 0);
721         return (error);
722 }
723
724 /*
725  * Userland can supply any 'seek' offset when reading a NFS directory.
726  * Validate the structure so we don't panic the kernel.  Note that
727  * the element name is nul terminated and the nul is not included
728  * in nfs_namlen.
729  */
730 static
731 int
732 nfs_check_dirent(struct nfs_dirent *dp, int maxlen)
733 {
734         int nfs_name_off = offsetof(struct nfs_dirent, nfs_name[0]);
735
736         if (nfs_name_off >= maxlen)
737                 return (EINVAL);
738         if (dp->nfs_reclen < nfs_name_off || dp->nfs_reclen > maxlen)
739                 return (EINVAL);
740         if (nfs_name_off + dp->nfs_namlen >= dp->nfs_reclen)
741                 return (EINVAL);
742         if (dp->nfs_reclen & 3)
743                 return (EINVAL);
744         return (0);
745 }
746
747 /*
748  * Vnode op for write using bio
749  *
750  * nfs_write(struct vnode *a_vp, struct uio *a_uio, int a_ioflag,
751  *           struct ucred *a_cred)
752  */
753 int
754 nfs_write(struct vop_write_args *ap)
755 {
756         struct uio *uio = ap->a_uio;
757         struct thread *td = uio->uio_td;
758         struct vnode *vp = ap->a_vp;
759         struct nfsnode *np = VTONFS(vp);
760         int ioflag = ap->a_ioflag;
761         struct buf *bp;
762         struct vattr vattr;
763         struct nfsmount *nmp = VFSTONFS(vp->v_mount);
764         daddr_t lbn;
765         off_t loffset;
766         int n, on, error = 0, iomode, must_commit;
767         int haverslock = 0;
768         int bcount;
769         int biosize;
770
771 #ifdef DIAGNOSTIC
772         if (uio->uio_rw != UIO_WRITE)
773                 panic("nfs_write mode");
774         if (uio->uio_segflg == UIO_USERSPACE && uio->uio_td != curthread)
775                 panic("nfs_write proc");
776 #endif
777         if (vp->v_type != VREG)
778                 return (EIO);
779         if (np->n_flag & NWRITEERR) {
780                 np->n_flag &= ~NWRITEERR;
781                 return (np->n_error);
782         }
783         if ((nmp->nm_flag & NFSMNT_NFSV3) != 0 &&
784             (nmp->nm_state & NFSSTA_GOTFSINFO) == 0)
785                 (void)nfs_fsinfo(nmp, vp, td);
786
787         /*
788          * Synchronously flush pending buffers if we are in synchronous
789          * mode or if we are appending.
790          */
791         if (ioflag & (IO_APPEND | IO_SYNC)) {
792                 if (np->n_flag & NLMODIFIED) {
793                         np->n_attrstamp = 0;
794                         error = nfs_flush(vp, MNT_WAIT, td, 0);
795                         /* error = nfs_vinvalbuf(vp, V_SAVE, 1); */
796                         if (error)
797                                 return (error);
798                 }
799         }
800
801         /*
802          * If IO_APPEND then load uio_offset.  We restart here if we cannot
803          * get the append lock.
804          */
805 restart:
806         if (ioflag & IO_APPEND) {
807                 np->n_attrstamp = 0;
808                 error = VOP_GETATTR(vp, &vattr);
809                 if (error)
810                         return (error);
811                 uio->uio_offset = np->n_size;
812         }
813
814         if (uio->uio_offset < 0)
815                 return (EINVAL);
816         if ((uio->uio_offset + uio->uio_resid) > nmp->nm_maxfilesize)
817                 return (EFBIG);
818         if (uio->uio_resid == 0)
819                 return (0);
820
821         /*
822          * We need to obtain the rslock if we intend to modify np->n_size
823          * in order to guarentee the append point with multiple contending
824          * writers, to guarentee that no other appenders modify n_size
825          * while we are trying to obtain a truncated buffer (i.e. to avoid
826          * accidently truncating data written by another appender due to
827          * the race), and to ensure that the buffer is populated prior to
828          * our extending of the file.  We hold rslock through the entire
829          * operation.
830          *
831          * Note that we do not synchronize the case where someone truncates
832          * the file while we are appending to it because attempting to lock
833          * this case may deadlock other parts of the system unexpectedly.
834          */
835         if ((ioflag & IO_APPEND) ||
836             uio->uio_offset + uio->uio_resid > np->n_size) {
837                 switch(nfs_rslock(np)) {
838                 case ENOLCK:
839                         goto restart;
840                         /* not reached */
841                 case EINTR:
842                 case ERESTART:
843                         return(EINTR);
844                         /* not reached */
845                 default:
846                         break;
847                 }
848                 haverslock = 1;
849         }
850
851         /*
852          * Maybe this should be above the vnode op call, but so long as
853          * file servers have no limits, i don't think it matters
854          */
855         if (td->td_proc && uio->uio_offset + uio->uio_resid >
856               td->td_proc->p_rlimit[RLIMIT_FSIZE].rlim_cur) {
857                 lwpsignal(td->td_proc, td->td_lwp, SIGXFSZ);
858                 if (haverslock)
859                         nfs_rsunlock(np);
860                 return (EFBIG);
861         }
862
863         biosize = vp->v_mount->mnt_stat.f_iosize;
864
865         do {
866                 if ((np->n_flag & NDONTCACHE) && uio->uio_iovcnt == 1) {
867                     iomode = NFSV3WRITE_FILESYNC;
868                     error = nfs_writerpc(vp, uio, &iomode, &must_commit);
869                     if (must_commit)
870                             nfs_clearcommit(vp->v_mount);
871                     break;
872                 }
873                 nfsstats.biocache_writes++;
874                 lbn = uio->uio_offset / biosize;
875                 on = uio->uio_offset & (biosize-1);
876                 loffset = uio->uio_offset - on;
877                 n = min((unsigned)(biosize - on), uio->uio_resid);
878 again:
879                 /*
880                  * Handle direct append and file extension cases, calculate
881                  * unaligned buffer size.
882                  */
883
884                 if (uio->uio_offset == np->n_size && n) {
885                         /*
886                          * Get the buffer (in its pre-append state to maintain
887                          * B_CACHE if it was previously set).  Resize the
888                          * nfsnode after we have locked the buffer to prevent
889                          * readers from reading garbage.
890                          */
891                         bcount = on;
892                         bp = nfs_getcacheblk(vp, loffset, bcount, td);
893
894                         if (bp != NULL) {
895                                 long save;
896
897                                 np->n_size = uio->uio_offset + n;
898                                 np->n_flag |= NLMODIFIED;
899                                 vnode_pager_setsize(vp, np->n_size);
900
901                                 save = bp->b_flags & B_CACHE;
902                                 bcount += n;
903                                 allocbuf(bp, bcount);
904                                 bp->b_flags |= save;
905                         }
906                 } else {
907                         /*
908                          * Obtain the locked cache block first, and then 
909                          * adjust the file's size as appropriate.
910                          */
911                         bcount = on + n;
912                         if (loffset + bcount < np->n_size) {
913                                 if (loffset + biosize < np->n_size)
914                                         bcount = biosize;
915                                 else
916                                         bcount = np->n_size - loffset;
917                         }
918                         bp = nfs_getcacheblk(vp, loffset, bcount, td);
919                         if (uio->uio_offset + n > np->n_size) {
920                                 np->n_size = uio->uio_offset + n;
921                                 np->n_flag |= NLMODIFIED;
922                                 vnode_pager_setsize(vp, np->n_size);
923                         }
924                 }
925
926                 if (bp == NULL) {
927                         error = EINTR;
928                         break;
929                 }
930
931                 /*
932                  * Issue a READ if B_CACHE is not set.  In special-append
933                  * mode, B_CACHE is based on the buffer prior to the write
934                  * op and is typically set, avoiding the read.  If a read
935                  * is required in special append mode, the server will
936                  * probably send us a short-read since we extended the file
937                  * on our end, resulting in b_resid == 0 and, thusly, 
938                  * B_CACHE getting set.
939                  *
940                  * We can also avoid issuing the read if the write covers
941                  * the entire buffer.  We have to make sure the buffer state
942                  * is reasonable in this case since we will not be initiating
943                  * I/O.  See the comments in kern/vfs_bio.c's getblk() for
944                  * more information.
945                  *
946                  * B_CACHE may also be set due to the buffer being cached
947                  * normally.
948                  *
949                  * When doing a UIO_NOCOPY write the buffer is not
950                  * overwritten and we cannot just set B_CACHE unconditionally
951                  * for full-block writes.
952                  */
953
954                 if (on == 0 && n == bcount && uio->uio_segflg != UIO_NOCOPY) {
955                         bp->b_flags |= B_CACHE;
956                         bp->b_flags &= ~(B_ERROR | B_INVAL);
957                 }
958
959                 if ((bp->b_flags & B_CACHE) == 0) {
960                         bp->b_cmd = BUF_CMD_READ;
961                         bp->b_bio2.bio_done = nfsiodone_sync;
962                         bp->b_bio2.bio_flags |= BIO_SYNC;
963                         vfs_busy_pages(vp, bp);
964                         error = nfs_doio(vp, &bp->b_bio2, td);
965                         if (error) {
966                                 brelse(bp);
967                                 break;
968                         }
969                 }
970                 if (!bp) {
971                         error = EINTR;
972                         break;
973                 }
974                 np->n_flag |= NLMODIFIED;
975
976                 /*
977                  * If dirtyend exceeds file size, chop it down.  This should
978                  * not normally occur but there is an append race where it
979                  * might occur XXX, so we log it. 
980                  *
981                  * If the chopping creates a reverse-indexed or degenerate
982                  * situation with dirtyoff/end, we 0 both of them.
983                  */
984
985                 if (bp->b_dirtyend > bcount) {
986                         kprintf("NFS append race @%08llx:%d\n", 
987                             (long long)bp->b_bio2.bio_offset,
988                             bp->b_dirtyend - bcount);
989                         bp->b_dirtyend = bcount;
990                 }
991
992                 if (bp->b_dirtyoff >= bp->b_dirtyend)
993                         bp->b_dirtyoff = bp->b_dirtyend = 0;
994
995                 /*
996                  * If the new write will leave a contiguous dirty
997                  * area, just update the b_dirtyoff and b_dirtyend,
998                  * otherwise force a write rpc of the old dirty area.
999                  *
1000                  * While it is possible to merge discontiguous writes due to 
1001                  * our having a B_CACHE buffer ( and thus valid read data
1002                  * for the hole), we don't because it could lead to 
1003                  * significant cache coherency problems with multiple clients,
1004                  * especially if locking is implemented later on.
1005                  *
1006                  * as an optimization we could theoretically maintain
1007                  * a linked list of discontinuous areas, but we would still
1008                  * have to commit them separately so there isn't much
1009                  * advantage to it except perhaps a bit of asynchronization.
1010                  */
1011
1012                 if (bp->b_dirtyend > 0 &&
1013                     (on > bp->b_dirtyend || (on + n) < bp->b_dirtyoff)) {
1014                         if (bwrite(bp) == EINTR) {
1015                                 error = EINTR;
1016                                 break;
1017                         }
1018                         goto again;
1019                 }
1020
1021                 error = uiomove((char *)bp->b_data + on, n, uio);
1022
1023                 /*
1024                  * Since this block is being modified, it must be written
1025                  * again and not just committed.  Since write clustering does
1026                  * not work for the stage 1 data write, only the stage 2
1027                  * commit rpc, we have to clear B_CLUSTEROK as well.
1028                  */
1029                 bp->b_flags &= ~(B_NEEDCOMMIT | B_CLUSTEROK);
1030
1031                 if (error) {
1032                         bp->b_flags |= B_ERROR;
1033                         brelse(bp);
1034                         break;
1035                 }
1036
1037                 /*
1038                  * Only update dirtyoff/dirtyend if not a degenerate 
1039                  * condition.
1040                  */
1041                 if (n) {
1042                         if (bp->b_dirtyend > 0) {
1043                                 bp->b_dirtyoff = min(on, bp->b_dirtyoff);
1044                                 bp->b_dirtyend = max((on + n), bp->b_dirtyend);
1045                         } else {
1046                                 bp->b_dirtyoff = on;
1047                                 bp->b_dirtyend = on + n;
1048                         }
1049                         vfs_bio_set_validclean(bp, on, n);
1050                 }
1051
1052                 /*
1053                  * If the lease is non-cachable or IO_SYNC do bwrite().
1054                  *
1055                  * IO_INVAL appears to be unused.  The idea appears to be
1056                  * to turn off caching in this case.  Very odd.  XXX
1057                  *
1058                  * If nfs_async is set bawrite() will use an unstable write
1059                  * (build dirty bufs on the server), so we might as well
1060                  * push it out with bawrite().  If nfs_async is not set we
1061                  * use bdwrite() to cache dirty bufs on the client.
1062                  */
1063                 if ((np->n_flag & NDONTCACHE) || (ioflag & IO_SYNC)) {
1064                         if (ioflag & IO_INVAL)
1065                                 bp->b_flags |= B_NOCACHE;
1066                         error = bwrite(bp);
1067                         if (error)
1068                                 break;
1069                         if (np->n_flag & NDONTCACHE) {
1070                                 error = nfs_vinvalbuf(vp, V_SAVE, 1);
1071                                 if (error)
1072                                         break;
1073                         }
1074                 } else if ((n + on) == biosize && nfs_async) {
1075                         bawrite(bp);
1076                 } else {
1077                         bdwrite(bp);
1078                 }
1079         } while (uio->uio_resid > 0 && n > 0);
1080
1081         if (haverslock)
1082                 nfs_rsunlock(np);
1083
1084         return (error);
1085 }
1086
1087 /*
1088  * Get an nfs cache block.
1089  *
1090  * Allocate a new one if the block isn't currently in the cache
1091  * and return the block marked busy. If the calling process is
1092  * interrupted by a signal for an interruptible mount point, return
1093  * NULL.
1094  *
1095  * The caller must carefully deal with the possible B_INVAL state of
1096  * the buffer.  nfs_doio() clears B_INVAL (and nfs_asyncio() clears it
1097  * indirectly), so synchronous reads can be issued without worrying about
1098  * the B_INVAL state.  We have to be a little more careful when dealing
1099  * with writes (see comments in nfs_write()) when extending a file past
1100  * its EOF.
1101  */
1102 static struct buf *
1103 nfs_getcacheblk(struct vnode *vp, off_t loffset, int size, struct thread *td)
1104 {
1105         struct buf *bp;
1106         struct mount *mp;
1107         struct nfsmount *nmp;
1108
1109         mp = vp->v_mount;
1110         nmp = VFSTONFS(mp);
1111
1112         if (nmp->nm_flag & NFSMNT_INT) {
1113                 bp = getblk(vp, loffset, size, GETBLK_PCATCH, 0);
1114                 while (bp == NULL) {
1115                         if (nfs_sigintr(nmp, NULL, td))
1116                                 return (NULL);
1117                         bp = getblk(vp, loffset, size, 0, 2 * hz);
1118                 }
1119         } else {
1120                 bp = getblk(vp, loffset, size, 0, 0);
1121         }
1122
1123         /*
1124          * bio2, the 'device' layer.  Since BIOs use 64 bit byte offsets
1125          * now, no translation is necessary.
1126          */
1127         bp->b_bio2.bio_offset = loffset;
1128         return (bp);
1129 }
1130
1131 /*
1132  * Flush and invalidate all dirty buffers. If another process is already
1133  * doing the flush, just wait for completion.
1134  */
1135 int
1136 nfs_vinvalbuf(struct vnode *vp, int flags, int intrflg)
1137 {
1138         struct nfsnode *np = VTONFS(vp);
1139         struct nfsmount *nmp = VFSTONFS(vp->v_mount);
1140         int error = 0, slpflag, slptimeo;
1141         thread_t td = curthread;
1142
1143         if (vp->v_flag & VRECLAIMED)
1144                 return (0);
1145
1146         if ((nmp->nm_flag & NFSMNT_INT) == 0)
1147                 intrflg = 0;
1148         if (intrflg) {
1149                 slpflag = PCATCH;
1150                 slptimeo = 2 * hz;
1151         } else {
1152                 slpflag = 0;
1153                 slptimeo = 0;
1154         }
1155         /*
1156          * First wait for any other process doing a flush to complete.
1157          */
1158         while (np->n_flag & NFLUSHINPROG) {
1159                 np->n_flag |= NFLUSHWANT;
1160                 error = tsleep((caddr_t)&np->n_flag, 0, "nfsvinval", slptimeo);
1161                 if (error && intrflg && nfs_sigintr(nmp, NULL, td))
1162                         return (EINTR);
1163         }
1164
1165         /*
1166          * Now, flush as required.
1167          */
1168         np->n_flag |= NFLUSHINPROG;
1169         error = vinvalbuf(vp, flags, slpflag, 0);
1170         while (error) {
1171                 if (intrflg && nfs_sigintr(nmp, NULL, td)) {
1172                         np->n_flag &= ~NFLUSHINPROG;
1173                         if (np->n_flag & NFLUSHWANT) {
1174                                 np->n_flag &= ~NFLUSHWANT;
1175                                 wakeup((caddr_t)&np->n_flag);
1176                         }
1177                         return (EINTR);
1178                 }
1179                 error = vinvalbuf(vp, flags, 0, slptimeo);
1180         }
1181         np->n_flag &= ~(NLMODIFIED | NFLUSHINPROG);
1182         if (np->n_flag & NFLUSHWANT) {
1183                 np->n_flag &= ~NFLUSHWANT;
1184                 wakeup((caddr_t)&np->n_flag);
1185         }
1186         return (0);
1187 }
1188
1189 /*
1190  * Initiate asynchronous I/O. Return an error if no nfsiods are available.
1191  * This is mainly to avoid queueing async I/O requests when the nfsiods
1192  * are all hung on a dead server.
1193  *
1194  * Note: nfs_asyncio() does not clear (B_ERROR|B_INVAL) but when the bp
1195  * is eventually dequeued by the async daemon, nfs_doio() *will*.
1196  */
1197 int
1198 nfs_asyncio(struct vnode *vp, struct bio *bio, struct thread *td)
1199 {
1200         struct buf *bp = bio->bio_buf;
1201         struct nfsmount *nmp;
1202
1203         KKASSERT(vp->v_tag == VT_NFS);
1204         nmp = VFSTONFS(vp->v_mount);
1205
1206         /*
1207          * If no async daemons then return EIO to force caller to run the rpc
1208          * synchronously.
1209          */
1210         if (nmp->nm_rxstate > NFSSVC_PENDING)
1211                 return (EIO);
1212
1213         BUF_KERNPROC(bp);
1214
1215         /*
1216          * The passed bio's buffer is not necessary associated with
1217          * the NFS vnode it is being written to.  Store the NFS vnode
1218          * in the BIO driver info.
1219          */
1220         bio->bio_driver_info = vp;
1221         TAILQ_INSERT_TAIL(&nmp->nm_bioq, bio, bio_act);
1222         nmp->nm_bioqlen++;
1223         nfssvc_iod_writer_wakeup(nmp);
1224         return (0);
1225 }
1226
1227 /*
1228  * Do an I/O operation to/from a cache block. This may be called
1229  * synchronously or from an nfsiod.  The BIO is normalized for DEV_BSIZE.
1230  *
1231  * A locked, completed I/O is returned and the caller is responsible for
1232  * brelse()'ing it.
1233  *
1234  * NOTE! TD MIGHT BE NULL
1235  */
1236 int
1237 nfs_doio(struct vnode *vp, struct bio *bio, struct thread *td)
1238 {
1239         struct buf *bp = bio->bio_buf;
1240         struct uio *uiop;
1241         struct nfsnode *np;
1242         struct nfsmount *nmp;
1243         int error = 0, iomode, must_commit = 0;
1244         struct uio uio;
1245         struct iovec io;
1246
1247         KKASSERT(vp->v_tag == VT_NFS);
1248         np = VTONFS(vp);
1249         nmp = VFSTONFS(vp->v_mount);
1250         uiop = &uio;
1251         uiop->uio_iov = &io;
1252         uiop->uio_iovcnt = 1;
1253         uiop->uio_segflg = UIO_SYSSPACE;
1254         uiop->uio_td = td;
1255
1256         /*
1257          * clear B_ERROR and B_INVAL state prior to initiating the I/O.  We
1258          * do this here so we do not have to do it in all the code that
1259          * calls us.
1260          */
1261         bp->b_flags &= ~(B_ERROR | B_INVAL);
1262
1263
1264         KASSERT(bp->b_cmd != BUF_CMD_DONE, 
1265                 ("nfs_doio: bp %p already marked done!", bp));
1266
1267         if (bp->b_cmd == BUF_CMD_READ) {
1268             io.iov_len = uiop->uio_resid = bp->b_bcount;
1269             io.iov_base = bp->b_data;
1270             uiop->uio_rw = UIO_READ;
1271
1272             switch (vp->v_type) {
1273             case VREG:
1274                 uiop->uio_offset = bio->bio_offset;
1275                 nfsstats.read_bios++;
1276                 error = nfs_readrpc(vp, uiop);
1277
1278                 if (!error) {
1279                     if (uiop->uio_resid) {
1280                         /*
1281                          * If we had a short read with no error, we must have
1282                          * hit a file hole.  We should zero-fill the remainder.
1283                          * This can also occur if the server hits the file EOF.
1284                          *
1285                          * Holes used to be able to occur due to pending 
1286                          * writes, but that is not possible any longer.
1287                          */
1288                         int nread = bp->b_bcount - uiop->uio_resid;
1289                         int left  = uiop->uio_resid;
1290
1291                         if (left > 0)
1292                                 bzero((char *)bp->b_data + nread, left);
1293                         uiop->uio_resid = 0;
1294                     }
1295                 }
1296                 if (td && td->td_proc && (vp->v_flag & VTEXT) &&
1297                     np->n_mtime != np->n_vattr.va_mtime.tv_sec) {
1298                         uprintf("Process killed due to text file modification\n");
1299                         ksignal(td->td_proc, SIGKILL);
1300                 }
1301                 break;
1302             case VLNK:
1303                 uiop->uio_offset = 0;
1304                 nfsstats.readlink_bios++;
1305                 error = nfs_readlinkrpc(vp, uiop);
1306                 break;
1307             case VDIR:
1308                 nfsstats.readdir_bios++;
1309                 uiop->uio_offset = bio->bio_offset;
1310                 if (nmp->nm_flag & NFSMNT_RDIRPLUS) {
1311                         error = nfs_readdirplusrpc(vp, uiop);
1312                         if (error == NFSERR_NOTSUPP)
1313                                 nmp->nm_flag &= ~NFSMNT_RDIRPLUS;
1314                 }
1315                 if ((nmp->nm_flag & NFSMNT_RDIRPLUS) == 0)
1316                         error = nfs_readdirrpc(vp, uiop);
1317                 /*
1318                  * end-of-directory sets B_INVAL but does not generate an
1319                  * error.
1320                  */
1321                 if (error == 0 && uiop->uio_resid == bp->b_bcount)
1322                         bp->b_flags |= B_INVAL;
1323                 break;
1324             default:
1325                 kprintf("nfs_doio:  type %x unexpected\n",vp->v_type);
1326                 break;
1327             };
1328             if (error) {
1329                 bp->b_flags |= B_ERROR;
1330                 bp->b_error = error;
1331             }
1332         } else {
1333             /* 
1334              * If we only need to commit, try to commit
1335              */
1336             KKASSERT(bp->b_cmd == BUF_CMD_WRITE);
1337             if (bp->b_flags & B_NEEDCOMMIT) {
1338                     int retv;
1339                     off_t off;
1340
1341                     off = bio->bio_offset + bp->b_dirtyoff;
1342                     retv = nfs_commit(vp, off, 
1343                                 bp->b_dirtyend - bp->b_dirtyoff, td);
1344                     if (retv == 0) {
1345                             bp->b_dirtyoff = bp->b_dirtyend = 0;
1346                             bp->b_flags &= ~(B_NEEDCOMMIT | B_CLUSTEROK);
1347                             bp->b_resid = 0;
1348                             biodone(bio);
1349                             return (0);
1350                     }
1351                     if (retv == NFSERR_STALEWRITEVERF) {
1352                             nfs_clearcommit(vp->v_mount);
1353                     }
1354             }
1355
1356             /*
1357              * Setup for actual write
1358              */
1359
1360             if (bio->bio_offset + bp->b_dirtyend > np->n_size)
1361                 bp->b_dirtyend = np->n_size - bio->bio_offset;
1362
1363             if (bp->b_dirtyend > bp->b_dirtyoff) {
1364                 io.iov_len = uiop->uio_resid = bp->b_dirtyend
1365                     - bp->b_dirtyoff;
1366                 uiop->uio_offset = bio->bio_offset + bp->b_dirtyoff;
1367                 io.iov_base = (char *)bp->b_data + bp->b_dirtyoff;
1368                 uiop->uio_rw = UIO_WRITE;
1369                 nfsstats.write_bios++;
1370
1371                 if ((bp->b_flags & (B_NEEDCOMMIT | B_NOCACHE | B_CLUSTER)) == 0)
1372                     iomode = NFSV3WRITE_UNSTABLE;
1373                 else
1374                     iomode = NFSV3WRITE_FILESYNC;
1375
1376                 error = nfs_writerpc(vp, uiop, &iomode, &must_commit);
1377
1378                 /*
1379                  * When setting B_NEEDCOMMIT also set B_CLUSTEROK to try
1380                  * to cluster the buffers needing commit.  This will allow
1381                  * the system to submit a single commit rpc for the whole
1382                  * cluster.  We can do this even if the buffer is not 100% 
1383                  * dirty (relative to the NFS blocksize), so we optimize the
1384                  * append-to-file-case.
1385                  *
1386                  * (when clearing B_NEEDCOMMIT, B_CLUSTEROK must also be
1387                  * cleared because write clustering only works for commit
1388                  * rpc's, not for the data portion of the write).
1389                  */
1390
1391                 if (!error && iomode == NFSV3WRITE_UNSTABLE) {
1392                     bp->b_flags |= B_NEEDCOMMIT;
1393                     if (bp->b_dirtyoff == 0
1394                         && bp->b_dirtyend == bp->b_bcount)
1395                         bp->b_flags |= B_CLUSTEROK;
1396                 } else {
1397                     bp->b_flags &= ~(B_NEEDCOMMIT | B_CLUSTEROK);
1398                 }
1399
1400                 /*
1401                  * For an interrupted write, the buffer is still valid
1402                  * and the write hasn't been pushed to the server yet,
1403                  * so we can't set B_ERROR and report the interruption
1404                  * by setting B_EINTR. For the async case, B_EINTR
1405                  * is not relevant, so the rpc attempt is essentially
1406                  * a noop.  For the case of a V3 write rpc not being
1407                  * committed to stable storage, the block is still
1408                  * dirty and requires either a commit rpc or another
1409                  * write rpc with iomode == NFSV3WRITE_FILESYNC before
1410                  * the block is reused. This is indicated by setting
1411                  * the B_DELWRI and B_NEEDCOMMIT flags.
1412                  *
1413                  * If the buffer is marked B_PAGING, it does not reside on
1414                  * the vp's paging queues so we cannot call bdirty().  The
1415                  * bp in this case is not an NFS cache block so we should
1416                  * be safe. XXX
1417                  */
1418                 if (error == EINTR
1419                     || (!error && (bp->b_flags & B_NEEDCOMMIT))) {
1420                         crit_enter();
1421                         bp->b_flags &= ~(B_INVAL|B_NOCACHE);
1422                         if ((bp->b_flags & B_PAGING) == 0)
1423                             bdirty(bp);
1424                         if (error)
1425                             bp->b_flags |= B_EINTR;
1426                         crit_exit();
1427                 } else {
1428                     if (error) {
1429                         bp->b_flags |= B_ERROR;
1430                         bp->b_error = np->n_error = error;
1431                         np->n_flag |= NWRITEERR;
1432                     }
1433                     bp->b_dirtyoff = bp->b_dirtyend = 0;
1434                 }
1435             } else {
1436                 bp->b_resid = 0;
1437                 biodone(bio);
1438                 return (0);
1439             }
1440         }
1441         bp->b_resid = uiop->uio_resid;
1442         if (must_commit)
1443             nfs_clearcommit(vp->v_mount);
1444         biodone(bio);
1445         return (error);
1446 }
1447
1448 /*
1449  * Used to aid in handling ftruncate() operations on the NFS client side.
1450  * Truncation creates a number of special problems for NFS.  We have to
1451  * throw away VM pages and buffer cache buffers that are beyond EOF, and
1452  * we have to properly handle VM pages or (potentially dirty) buffers
1453  * that straddle the truncation point.
1454  */
1455
1456 int
1457 nfs_meta_setsize(struct vnode *vp, struct thread *td, u_quad_t nsize)
1458 {
1459         struct nfsnode *np = VTONFS(vp);
1460         u_quad_t tsize = np->n_size;
1461         int biosize = vp->v_mount->mnt_stat.f_iosize;
1462         int error = 0;
1463
1464         np->n_size = nsize;
1465
1466         if (np->n_size < tsize) {
1467                 struct buf *bp;
1468                 daddr_t lbn;
1469                 off_t loffset;
1470                 int bufsize;
1471
1472                 /*
1473                  * vtruncbuf() doesn't get the buffer overlapping the 
1474                  * truncation point.  We may have a B_DELWRI and/or B_CACHE
1475                  * buffer that now needs to be truncated.
1476                  */
1477                 error = vtruncbuf(vp, nsize, biosize);
1478                 lbn = nsize / biosize;
1479                 bufsize = nsize & (biosize - 1);
1480                 loffset = nsize - bufsize;
1481                 bp = nfs_getcacheblk(vp, loffset, bufsize, td);
1482                 if (bp->b_dirtyoff > bp->b_bcount)
1483                         bp->b_dirtyoff = bp->b_bcount;
1484                 if (bp->b_dirtyend > bp->b_bcount)
1485                         bp->b_dirtyend = bp->b_bcount;
1486                 bp->b_flags |= B_RELBUF;  /* don't leave garbage around */
1487                 brelse(bp);
1488         } else {
1489                 vnode_pager_setsize(vp, nsize);
1490         }
1491         return(error);
1492 }
1493
1494 /*
1495  * Synchronous completion for nfs_doio.  Call bpdone() with elseit=FALSE.
1496  * Caller is responsible for brelse()'ing the bp.
1497  */
1498 static void
1499 nfsiodone_sync(struct bio *bio)
1500 {
1501         bio->bio_flags = 0;
1502         bpdone(bio->bio_buf, 0);
1503 }