]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/fs/nfsclient/nfs_clbio.c
Merge ACPICA 20170531.
[FreeBSD/FreeBSD.git] / sys / fs / nfsclient / nfs_clbio.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. Neither the name of the University nor the names of its contributors
17  *    may be used to endorse or promote products derived from this software
18  *    without specific prior written permission.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
21  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
24  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30  * SUCH DAMAGE.
31  *
32  *      @(#)nfs_bio.c   8.9 (Berkeley) 3/30/95
33  */
34
35 #include <sys/cdefs.h>
36 __FBSDID("$FreeBSD$");
37
38 #include <sys/param.h>
39 #include <sys/systm.h>
40 #include <sys/bio.h>
41 #include <sys/buf.h>
42 #include <sys/kernel.h>
43 #include <sys/mount.h>
44 #include <sys/rwlock.h>
45 #include <sys/vmmeter.h>
46 #include <sys/vnode.h>
47
48 #include <vm/vm.h>
49 #include <vm/vm_param.h>
50 #include <vm/vm_extern.h>
51 #include <vm/vm_page.h>
52 #include <vm/vm_object.h>
53 #include <vm/vm_pager.h>
54 #include <vm/vnode_pager.h>
55
56 #include <fs/nfs/nfsport.h>
57 #include <fs/nfsclient/nfsmount.h>
58 #include <fs/nfsclient/nfs.h>
59 #include <fs/nfsclient/nfsnode.h>
60 #include <fs/nfsclient/nfs_kdtrace.h>
61
62 extern int newnfs_directio_allow_mmap;
63 extern struct nfsstatsv1 nfsstatsv1;
64 extern struct mtx ncl_iod_mutex;
65 extern int ncl_numasync;
66 extern enum nfsiod_state ncl_iodwant[NFS_MAXASYNCDAEMON];
67 extern struct nfsmount *ncl_iodmount[NFS_MAXASYNCDAEMON];
68 extern int newnfs_directio_enable;
69 extern int nfs_keep_dirty_on_error;
70
71 int ncl_pbuf_freecnt = -1;      /* start out unlimited */
72
73 static struct buf *nfs_getcacheblk(struct vnode *vp, daddr_t bn, int size,
74     struct thread *td);
75 static int nfs_directio_write(struct vnode *vp, struct uio *uiop,
76     struct ucred *cred, int ioflag);
77
78 /*
79  * Vnode op for VM getpages.
80  */
81 SYSCTL_DECL(_vfs_nfs);
82 static int use_buf_pager = 1;
83 SYSCTL_INT(_vfs_nfs, OID_AUTO, use_buf_pager, CTLFLAG_RWTUN,
84     &use_buf_pager, 0,
85     "Use buffer pager instead of direct readrpc call");
86
87 static daddr_t
88 ncl_gbp_getblkno(struct vnode *vp, vm_ooffset_t off)
89 {
90
91         return (off / vp->v_bufobj.bo_bsize);
92 }
93
94 static int
95 ncl_gbp_getblksz(struct vnode *vp, daddr_t lbn)
96 {
97         struct nfsnode *np;
98         u_quad_t nsize;
99         int biosize, bcount;
100
101         np = VTONFS(vp);
102         mtx_lock(&np->n_mtx);
103         nsize = np->n_size;
104         mtx_unlock(&np->n_mtx);
105
106         biosize = vp->v_bufobj.bo_bsize;
107         bcount = biosize;
108         if ((off_t)lbn * biosize >= nsize)
109                 bcount = 0;
110         else if ((off_t)(lbn + 1) * biosize > nsize)
111                 bcount = nsize - (off_t)lbn * biosize;
112         return (bcount);
113 }
114
115 int
116 ncl_getpages(struct vop_getpages_args *ap)
117 {
118         int i, error, nextoff, size, toff, count, npages;
119         struct uio uio;
120         struct iovec iov;
121         vm_offset_t kva;
122         struct buf *bp;
123         struct vnode *vp;
124         struct thread *td;
125         struct ucred *cred;
126         struct nfsmount *nmp;
127         vm_object_t object;
128         vm_page_t *pages;
129         struct nfsnode *np;
130
131         vp = ap->a_vp;
132         np = VTONFS(vp);
133         td = curthread;
134         cred = curthread->td_ucred;
135         nmp = VFSTONFS(vp->v_mount);
136         pages = ap->a_m;
137         npages = ap->a_count;
138
139         if ((object = vp->v_object) == NULL) {
140                 printf("ncl_getpages: called with non-merged cache vnode\n");
141                 return (VM_PAGER_ERROR);
142         }
143
144         if (newnfs_directio_enable && !newnfs_directio_allow_mmap) {
145                 mtx_lock(&np->n_mtx);
146                 if ((np->n_flag & NNONCACHE) && (vp->v_type == VREG)) {
147                         mtx_unlock(&np->n_mtx);
148                         printf("ncl_getpages: called on non-cacheable vnode\n");
149                         return (VM_PAGER_ERROR);
150                 } else
151                         mtx_unlock(&np->n_mtx);
152         }
153
154         mtx_lock(&nmp->nm_mtx);
155         if ((nmp->nm_flag & NFSMNT_NFSV3) != 0 &&
156             (nmp->nm_state & NFSSTA_GOTFSINFO) == 0) {
157                 mtx_unlock(&nmp->nm_mtx);
158                 /* We'll never get here for v4, because we always have fsinfo */
159                 (void)ncl_fsinfo(nmp, vp, cred, td);
160         } else
161                 mtx_unlock(&nmp->nm_mtx);
162
163         if (use_buf_pager)
164                 return (vfs_bio_getpages(vp, pages, npages, ap->a_rbehind,
165                     ap->a_rahead, ncl_gbp_getblkno, ncl_gbp_getblksz));
166
167         /*
168          * If the requested page is partially valid, just return it and
169          * allow the pager to zero-out the blanks.  Partially valid pages
170          * can only occur at the file EOF.
171          *
172          * XXXGL: is that true for NFS, where short read can occur???
173          */
174         VM_OBJECT_WLOCK(object);
175         if (pages[npages - 1]->valid != 0 && --npages == 0)
176                 goto out;
177         VM_OBJECT_WUNLOCK(object);
178
179         /*
180          * We use only the kva address for the buffer, but this is extremely
181          * convenient and fast.
182          */
183         bp = getpbuf(&ncl_pbuf_freecnt);
184
185         kva = (vm_offset_t) bp->b_data;
186         pmap_qenter(kva, pages, npages);
187         VM_CNT_INC(v_vnodein);
188         VM_CNT_ADD(v_vnodepgsin, npages);
189
190         count = npages << PAGE_SHIFT;
191         iov.iov_base = (caddr_t) kva;
192         iov.iov_len = count;
193         uio.uio_iov = &iov;
194         uio.uio_iovcnt = 1;
195         uio.uio_offset = IDX_TO_OFF(pages[0]->pindex);
196         uio.uio_resid = count;
197         uio.uio_segflg = UIO_SYSSPACE;
198         uio.uio_rw = UIO_READ;
199         uio.uio_td = td;
200
201         error = ncl_readrpc(vp, &uio, cred);
202         pmap_qremove(kva, npages);
203
204         relpbuf(bp, &ncl_pbuf_freecnt);
205
206         if (error && (uio.uio_resid == count)) {
207                 printf("ncl_getpages: error %d\n", error);
208                 return (VM_PAGER_ERROR);
209         }
210
211         /*
212          * Calculate the number of bytes read and validate only that number
213          * of bytes.  Note that due to pending writes, size may be 0.  This
214          * does not mean that the remaining data is invalid!
215          */
216
217         size = count - uio.uio_resid;
218         VM_OBJECT_WLOCK(object);
219         for (i = 0, toff = 0; i < npages; i++, toff = nextoff) {
220                 vm_page_t m;
221                 nextoff = toff + PAGE_SIZE;
222                 m = pages[i];
223
224                 if (nextoff <= size) {
225                         /*
226                          * Read operation filled an entire page
227                          */
228                         m->valid = VM_PAGE_BITS_ALL;
229                         KASSERT(m->dirty == 0,
230                             ("nfs_getpages: page %p is dirty", m));
231                 } else if (size > toff) {
232                         /*
233                          * Read operation filled a partial page.
234                          */
235                         m->valid = 0;
236                         vm_page_set_valid_range(m, 0, size - toff);
237                         KASSERT(m->dirty == 0,
238                             ("nfs_getpages: page %p is dirty", m));
239                 } else {
240                         /*
241                          * Read operation was short.  If no error
242                          * occurred we may have hit a zero-fill
243                          * section.  We leave valid set to 0, and page
244                          * is freed by vm_page_readahead_finish() if
245                          * its index is not equal to requested, or
246                          * page is zeroed and set valid by
247                          * vm_pager_get_pages() for requested page.
248                          */
249                         ;
250                 }
251         }
252 out:
253         VM_OBJECT_WUNLOCK(object);
254         if (ap->a_rbehind)
255                 *ap->a_rbehind = 0;
256         if (ap->a_rahead)
257                 *ap->a_rahead = 0;
258         return (VM_PAGER_OK);
259 }
260
261 /*
262  * Vnode op for VM putpages.
263  */
264 int
265 ncl_putpages(struct vop_putpages_args *ap)
266 {
267         struct uio uio;
268         struct iovec iov;
269         int i, error, npages, count;
270         off_t offset;
271         int *rtvals;
272         struct vnode *vp;
273         struct thread *td;
274         struct ucred *cred;
275         struct nfsmount *nmp;
276         struct nfsnode *np;
277         vm_page_t *pages;
278
279         vp = ap->a_vp;
280         np = VTONFS(vp);
281         td = curthread;                         /* XXX */
282         /* Set the cred to n_writecred for the write rpcs. */
283         if (np->n_writecred != NULL)
284                 cred = crhold(np->n_writecred);
285         else
286                 cred = crhold(curthread->td_ucred);     /* XXX */
287         nmp = VFSTONFS(vp->v_mount);
288         pages = ap->a_m;
289         count = ap->a_count;
290         rtvals = ap->a_rtvals;
291         npages = btoc(count);
292         offset = IDX_TO_OFF(pages[0]->pindex);
293
294         mtx_lock(&nmp->nm_mtx);
295         if ((nmp->nm_flag & NFSMNT_NFSV3) != 0 &&
296             (nmp->nm_state & NFSSTA_GOTFSINFO) == 0) {
297                 mtx_unlock(&nmp->nm_mtx);
298                 (void)ncl_fsinfo(nmp, vp, cred, td);
299         } else
300                 mtx_unlock(&nmp->nm_mtx);
301
302         mtx_lock(&np->n_mtx);
303         if (newnfs_directio_enable && !newnfs_directio_allow_mmap &&
304             (np->n_flag & NNONCACHE) && (vp->v_type == VREG)) {
305                 mtx_unlock(&np->n_mtx);
306                 printf("ncl_putpages: called on noncache-able vnode\n");
307                 mtx_lock(&np->n_mtx);
308         }
309
310         for (i = 0; i < npages; i++)
311                 rtvals[i] = VM_PAGER_ERROR;
312
313         /*
314          * When putting pages, do not extend file past EOF.
315          */
316         if (offset + count > np->n_size) {
317                 count = np->n_size - offset;
318                 if (count < 0)
319                         count = 0;
320         }
321         mtx_unlock(&np->n_mtx);
322
323         VM_CNT_INC(v_vnodeout);
324         VM_CNT_ADD(v_vnodepgsout, count);
325
326         iov.iov_base = unmapped_buf;
327         iov.iov_len = count;
328         uio.uio_iov = &iov;
329         uio.uio_iovcnt = 1;
330         uio.uio_offset = offset;
331         uio.uio_resid = count;
332         uio.uio_segflg = UIO_NOCOPY;
333         uio.uio_rw = UIO_WRITE;
334         uio.uio_td = td;
335
336         error = VOP_WRITE(vp, &uio, vnode_pager_putpages_ioflags(ap->a_sync),
337             cred);
338         crfree(cred);
339
340         if (error == 0 || !nfs_keep_dirty_on_error)
341                 vnode_pager_undirty_pages(pages, rtvals, count - uio.uio_resid);
342         return (rtvals[0]);
343 }
344
345 /*
346  * For nfs, cache consistency can only be maintained approximately.
347  * Although RFC1094 does not specify the criteria, the following is
348  * believed to be compatible with the reference port.
349  * For nfs:
350  * If the file's modify time on the server has changed since the
351  * last read rpc or you have written to the file,
352  * you may have lost data cache consistency with the
353  * server, so flush all of the file's data out of the cache.
354  * Then force a getattr rpc to ensure that you have up to date
355  * attributes.
356  * NB: This implies that cache data can be read when up to
357  * NFS_ATTRTIMEO seconds out of date. If you find that you need current
358  * attributes this could be forced by setting n_attrstamp to 0 before
359  * the VOP_GETATTR() call.
360  */
361 static inline int
362 nfs_bioread_check_cons(struct vnode *vp, struct thread *td, struct ucred *cred)
363 {
364         int error = 0;
365         struct vattr vattr;
366         struct nfsnode *np = VTONFS(vp);
367         int old_lock;
368
369         /*
370          * Grab the exclusive lock before checking whether the cache is
371          * consistent.
372          * XXX - We can make this cheaper later (by acquiring cheaper locks).
373          * But for now, this suffices.
374          */
375         old_lock = ncl_upgrade_vnlock(vp);
376         if (vp->v_iflag & VI_DOOMED) {
377                 error = EBADF;
378                 goto out;
379         }
380
381         mtx_lock(&np->n_mtx);
382         if (np->n_flag & NMODIFIED) {
383                 mtx_unlock(&np->n_mtx);
384                 if (vp->v_type != VREG) {
385                         if (vp->v_type != VDIR)
386                                 panic("nfs: bioread, not dir");
387                         ncl_invaldir(vp);
388                         error = ncl_vinvalbuf(vp, V_SAVE, td, 1);
389                         if (error == 0 && (vp->v_iflag & VI_DOOMED) != 0)
390                                 error = EBADF;
391                         if (error != 0)
392                                 goto out;
393                 }
394                 np->n_attrstamp = 0;
395                 KDTRACE_NFS_ATTRCACHE_FLUSH_DONE(vp);
396                 error = VOP_GETATTR(vp, &vattr, cred);
397                 if (error)
398                         goto out;
399                 mtx_lock(&np->n_mtx);
400                 np->n_mtime = vattr.va_mtime;
401                 mtx_unlock(&np->n_mtx);
402         } else {
403                 mtx_unlock(&np->n_mtx);
404                 error = VOP_GETATTR(vp, &vattr, cred);
405                 if (error)
406                         return (error);
407                 mtx_lock(&np->n_mtx);
408                 if ((np->n_flag & NSIZECHANGED)
409                     || (NFS_TIMESPEC_COMPARE(&np->n_mtime, &vattr.va_mtime))) {
410                         mtx_unlock(&np->n_mtx);
411                         if (vp->v_type == VDIR)
412                                 ncl_invaldir(vp);
413                         error = ncl_vinvalbuf(vp, V_SAVE, td, 1);
414                         if (error == 0 && (vp->v_iflag & VI_DOOMED) != 0)
415                                 error = EBADF;
416                         if (error != 0)
417                                 goto out;
418                         mtx_lock(&np->n_mtx);
419                         np->n_mtime = vattr.va_mtime;
420                         np->n_flag &= ~NSIZECHANGED;
421                 }
422                 mtx_unlock(&np->n_mtx);
423         }
424 out:
425         ncl_downgrade_vnlock(vp, old_lock);
426         return (error);
427 }
428
429 /*
430  * Vnode op for read using bio
431  */
432 int
433 ncl_bioread(struct vnode *vp, struct uio *uio, int ioflag, struct ucred *cred)
434 {
435         struct nfsnode *np = VTONFS(vp);
436         int biosize, i;
437         struct buf *bp, *rabp;
438         struct thread *td;
439         struct nfsmount *nmp = VFSTONFS(vp->v_mount);
440         daddr_t lbn, rabn;
441         int bcount;
442         int seqcount;
443         int nra, error = 0, n = 0, on = 0;
444         off_t tmp_off;
445
446         KASSERT(uio->uio_rw == UIO_READ, ("ncl_read mode"));
447         if (uio->uio_resid == 0)
448                 return (0);
449         if (uio->uio_offset < 0)        /* XXX VDIR cookies can be negative */
450                 return (EINVAL);
451         td = uio->uio_td;
452
453         mtx_lock(&nmp->nm_mtx);
454         if ((nmp->nm_flag & NFSMNT_NFSV3) != 0 &&
455             (nmp->nm_state & NFSSTA_GOTFSINFO) == 0) {
456                 mtx_unlock(&nmp->nm_mtx);
457                 (void)ncl_fsinfo(nmp, vp, cred, td);
458                 mtx_lock(&nmp->nm_mtx);
459         }
460         if (nmp->nm_rsize == 0 || nmp->nm_readdirsize == 0)
461                 (void) newnfs_iosize(nmp);
462
463         tmp_off = uio->uio_offset + uio->uio_resid;
464         if (vp->v_type != VDIR &&
465             (tmp_off > nmp->nm_maxfilesize || tmp_off < uio->uio_offset)) {
466                 mtx_unlock(&nmp->nm_mtx);
467                 return (EFBIG);
468         }
469         mtx_unlock(&nmp->nm_mtx);
470
471         if (newnfs_directio_enable && (ioflag & IO_DIRECT) && (vp->v_type == VREG))
472                 /* No caching/ no readaheads. Just read data into the user buffer */
473                 return ncl_readrpc(vp, uio, cred);
474
475         biosize = vp->v_bufobj.bo_bsize;
476         seqcount = (int)((off_t)(ioflag >> IO_SEQSHIFT) * biosize / BKVASIZE);
477
478         error = nfs_bioread_check_cons(vp, td, cred);
479         if (error)
480                 return error;
481
482         do {
483             u_quad_t nsize;
484
485             mtx_lock(&np->n_mtx);
486             nsize = np->n_size;
487             mtx_unlock(&np->n_mtx);
488
489             switch (vp->v_type) {
490             case VREG:
491                 NFSINCRGLOBAL(nfsstatsv1.biocache_reads);
492                 lbn = uio->uio_offset / biosize;
493                 on = uio->uio_offset - (lbn * biosize);
494
495                 /*
496                  * Start the read ahead(s), as required.
497                  */
498                 if (nmp->nm_readahead > 0) {
499                     for (nra = 0; nra < nmp->nm_readahead && nra < seqcount &&
500                         (off_t)(lbn + 1 + nra) * biosize < nsize; nra++) {
501                         rabn = lbn + 1 + nra;
502                         if (incore(&vp->v_bufobj, rabn) == NULL) {
503                             rabp = nfs_getcacheblk(vp, rabn, biosize, td);
504                             if (!rabp) {
505                                 error = newnfs_sigintr(nmp, td);
506                                 return (error ? error : EINTR);
507                             }
508                             if ((rabp->b_flags & (B_CACHE|B_DELWRI)) == 0) {
509                                 rabp->b_flags |= B_ASYNC;
510                                 rabp->b_iocmd = BIO_READ;
511                                 vfs_busy_pages(rabp, 0);
512                                 if (ncl_asyncio(nmp, rabp, cred, td)) {
513                                     rabp->b_flags |= B_INVAL;
514                                     rabp->b_ioflags |= BIO_ERROR;
515                                     vfs_unbusy_pages(rabp);
516                                     brelse(rabp);
517                                     break;
518                                 }
519                             } else {
520                                 brelse(rabp);
521                             }
522                         }
523                     }
524                 }
525
526                 /* Note that bcount is *not* DEV_BSIZE aligned. */
527                 bcount = biosize;
528                 if ((off_t)lbn * biosize >= nsize) {
529                         bcount = 0;
530                 } else if ((off_t)(lbn + 1) * biosize > nsize) {
531                         bcount = nsize - (off_t)lbn * biosize;
532                 }
533                 bp = nfs_getcacheblk(vp, lbn, bcount, td);
534
535                 if (!bp) {
536                         error = newnfs_sigintr(nmp, td);
537                         return (error ? error : EINTR);
538                 }
539
540                 /*
541                  * If B_CACHE is not set, we must issue the read.  If this
542                  * fails, we return an error.
543                  */
544
545                 if ((bp->b_flags & B_CACHE) == 0) {
546                     bp->b_iocmd = BIO_READ;
547                     vfs_busy_pages(bp, 0);
548                     error = ncl_doio(vp, bp, cred, td, 0);
549                     if (error) {
550                         brelse(bp);
551                         return (error);
552                     }
553                 }
554
555                 /*
556                  * on is the offset into the current bp.  Figure out how many
557                  * bytes we can copy out of the bp.  Note that bcount is
558                  * NOT DEV_BSIZE aligned.
559                  *
560                  * Then figure out how many bytes we can copy into the uio.
561                  */
562
563                 n = 0;
564                 if (on < bcount)
565                         n = MIN((unsigned)(bcount - on), uio->uio_resid);
566                 break;
567             case VLNK:
568                 NFSINCRGLOBAL(nfsstatsv1.biocache_readlinks);
569                 bp = nfs_getcacheblk(vp, (daddr_t)0, NFS_MAXPATHLEN, td);
570                 if (!bp) {
571                         error = newnfs_sigintr(nmp, td);
572                         return (error ? error : EINTR);
573                 }
574                 if ((bp->b_flags & B_CACHE) == 0) {
575                     bp->b_iocmd = BIO_READ;
576                     vfs_busy_pages(bp, 0);
577                     error = ncl_doio(vp, bp, cred, td, 0);
578                     if (error) {
579                         bp->b_ioflags |= BIO_ERROR;
580                         brelse(bp);
581                         return (error);
582                     }
583                 }
584                 n = MIN(uio->uio_resid, NFS_MAXPATHLEN - bp->b_resid);
585                 on = 0;
586                 break;
587             case VDIR:
588                 NFSINCRGLOBAL(nfsstatsv1.biocache_readdirs);
589                 if (np->n_direofoffset
590                     && uio->uio_offset >= np->n_direofoffset) {
591                     return (0);
592                 }
593                 lbn = (uoff_t)uio->uio_offset / NFS_DIRBLKSIZ;
594                 on = uio->uio_offset & (NFS_DIRBLKSIZ - 1);
595                 bp = nfs_getcacheblk(vp, lbn, NFS_DIRBLKSIZ, td);
596                 if (!bp) {
597                     error = newnfs_sigintr(nmp, td);
598                     return (error ? error : EINTR);
599                 }
600                 if ((bp->b_flags & B_CACHE) == 0) {
601                     bp->b_iocmd = BIO_READ;
602                     vfs_busy_pages(bp, 0);
603                     error = ncl_doio(vp, bp, cred, td, 0);
604                     if (error) {
605                             brelse(bp);
606                     }
607                     while (error == NFSERR_BAD_COOKIE) {
608                         ncl_invaldir(vp);
609                         error = ncl_vinvalbuf(vp, 0, td, 1);
610                         if (error == 0 && (vp->v_iflag & VI_DOOMED) != 0)
611                                 return (EBADF);
612
613                         /*
614                          * Yuck! The directory has been modified on the
615                          * server. The only way to get the block is by
616                          * reading from the beginning to get all the
617                          * offset cookies.
618                          *
619                          * Leave the last bp intact unless there is an error.
620                          * Loop back up to the while if the error is another
621                          * NFSERR_BAD_COOKIE (double yuch!).
622                          */
623                         for (i = 0; i <= lbn && !error; i++) {
624                             if (np->n_direofoffset
625                                 && (i * NFS_DIRBLKSIZ) >= np->n_direofoffset)
626                                     return (0);
627                             bp = nfs_getcacheblk(vp, i, NFS_DIRBLKSIZ, td);
628                             if (!bp) {
629                                 error = newnfs_sigintr(nmp, td);
630                                 return (error ? error : EINTR);
631                             }
632                             if ((bp->b_flags & B_CACHE) == 0) {
633                                     bp->b_iocmd = BIO_READ;
634                                     vfs_busy_pages(bp, 0);
635                                     error = ncl_doio(vp, bp, cred, td, 0);
636                                     /*
637                                      * no error + B_INVAL == directory EOF,
638                                      * use the block.
639                                      */
640                                     if (error == 0 && (bp->b_flags & B_INVAL))
641                                             break;
642                             }
643                             /*
644                              * An error will throw away the block and the
645                              * for loop will break out.  If no error and this
646                              * is not the block we want, we throw away the
647                              * block and go for the next one via the for loop.
648                              */
649                             if (error || i < lbn)
650                                     brelse(bp);
651                         }
652                     }
653                     /*
654                      * The above while is repeated if we hit another cookie
655                      * error.  If we hit an error and it wasn't a cookie error,
656                      * we give up.
657                      */
658                     if (error)
659                             return (error);
660                 }
661
662                 /*
663                  * If not eof and read aheads are enabled, start one.
664                  * (You need the current block first, so that you have the
665                  *  directory offset cookie of the next block.)
666                  */
667                 if (nmp->nm_readahead > 0 &&
668                     (bp->b_flags & B_INVAL) == 0 &&
669                     (np->n_direofoffset == 0 ||
670                     (lbn + 1) * NFS_DIRBLKSIZ < np->n_direofoffset) &&
671                     incore(&vp->v_bufobj, lbn + 1) == NULL) {
672                         rabp = nfs_getcacheblk(vp, lbn + 1, NFS_DIRBLKSIZ, td);
673                         if (rabp) {
674                             if ((rabp->b_flags & (B_CACHE|B_DELWRI)) == 0) {
675                                 rabp->b_flags |= B_ASYNC;
676                                 rabp->b_iocmd = BIO_READ;
677                                 vfs_busy_pages(rabp, 0);
678                                 if (ncl_asyncio(nmp, rabp, cred, td)) {
679                                     rabp->b_flags |= B_INVAL;
680                                     rabp->b_ioflags |= BIO_ERROR;
681                                     vfs_unbusy_pages(rabp);
682                                     brelse(rabp);
683                                 }
684                             } else {
685                                 brelse(rabp);
686                             }
687                         }
688                 }
689                 /*
690                  * Unlike VREG files, whos buffer size ( bp->b_bcount ) is
691                  * chopped for the EOF condition, we cannot tell how large
692                  * NFS directories are going to be until we hit EOF.  So
693                  * an NFS directory buffer is *not* chopped to its EOF.  Now,
694                  * it just so happens that b_resid will effectively chop it
695                  * to EOF.  *BUT* this information is lost if the buffer goes
696                  * away and is reconstituted into a B_CACHE state ( due to
697                  * being VMIO ) later.  So we keep track of the directory eof
698                  * in np->n_direofoffset and chop it off as an extra step
699                  * right here.
700                  */
701                 n = lmin(uio->uio_resid, NFS_DIRBLKSIZ - bp->b_resid - on);
702                 if (np->n_direofoffset && n > np->n_direofoffset - uio->uio_offset)
703                         n = np->n_direofoffset - uio->uio_offset;
704                 break;
705             default:
706                 printf(" ncl_bioread: type %x unexpected\n", vp->v_type);
707                 bp = NULL;
708                 break;
709             }
710
711             if (n > 0) {
712                     error = vn_io_fault_uiomove(bp->b_data + on, (int)n, uio);
713             }
714             if (vp->v_type == VLNK)
715                 n = 0;
716             if (bp != NULL)
717                 brelse(bp);
718         } while (error == 0 && uio->uio_resid > 0 && n > 0);
719         return (error);
720 }
721
722 /*
723  * The NFS write path cannot handle iovecs with len > 1. So we need to
724  * break up iovecs accordingly (restricting them to wsize).
725  * For the SYNC case, we can do this with 1 copy (user buffer -> mbuf).
726  * For the ASYNC case, 2 copies are needed. The first a copy from the
727  * user buffer to a staging buffer and then a second copy from the staging
728  * buffer to mbufs. This can be optimized by copying from the user buffer
729  * directly into mbufs and passing the chain down, but that requires a
730  * fair amount of re-working of the relevant codepaths (and can be done
731  * later).
732  */
733 static int
734 nfs_directio_write(vp, uiop, cred, ioflag)
735         struct vnode *vp;
736         struct uio *uiop;
737         struct ucred *cred;
738         int ioflag;
739 {
740         int error;
741         struct nfsmount *nmp = VFSTONFS(vp->v_mount);
742         struct thread *td = uiop->uio_td;
743         int size;
744         int wsize;
745
746         mtx_lock(&nmp->nm_mtx);
747         wsize = nmp->nm_wsize;
748         mtx_unlock(&nmp->nm_mtx);
749         if (ioflag & IO_SYNC) {
750                 int iomode, must_commit;
751                 struct uio uio;
752                 struct iovec iov;
753 do_sync:
754                 while (uiop->uio_resid > 0) {
755                         size = MIN(uiop->uio_resid, wsize);
756                         size = MIN(uiop->uio_iov->iov_len, size);
757                         iov.iov_base = uiop->uio_iov->iov_base;
758                         iov.iov_len = size;
759                         uio.uio_iov = &iov;
760                         uio.uio_iovcnt = 1;
761                         uio.uio_offset = uiop->uio_offset;
762                         uio.uio_resid = size;
763                         uio.uio_segflg = UIO_USERSPACE;
764                         uio.uio_rw = UIO_WRITE;
765                         uio.uio_td = td;
766                         iomode = NFSWRITE_FILESYNC;
767                         error = ncl_writerpc(vp, &uio, cred, &iomode,
768                             &must_commit, 0);
769                         KASSERT((must_commit == 0),
770                                 ("ncl_directio_write: Did not commit write"));
771                         if (error)
772                                 return (error);
773                         uiop->uio_offset += size;
774                         uiop->uio_resid -= size;
775                         if (uiop->uio_iov->iov_len <= size) {
776                                 uiop->uio_iovcnt--;
777                                 uiop->uio_iov++;
778                         } else {
779                                 uiop->uio_iov->iov_base =
780                                         (char *)uiop->uio_iov->iov_base + size;
781                                 uiop->uio_iov->iov_len -= size;
782                         }
783                 }
784         } else {
785                 struct uio *t_uio;
786                 struct iovec *t_iov;
787                 struct buf *bp;
788
789                 /*
790                  * Break up the write into blocksize chunks and hand these
791                  * over to nfsiod's for write back.
792                  * Unfortunately, this incurs a copy of the data. Since
793                  * the user could modify the buffer before the write is
794                  * initiated.
795                  *
796                  * The obvious optimization here is that one of the 2 copies
797                  * in the async write path can be eliminated by copying the
798                  * data here directly into mbufs and passing the mbuf chain
799                  * down. But that will require a fair amount of re-working
800                  * of the code and can be done if there's enough interest
801                  * in NFS directio access.
802                  */
803                 while (uiop->uio_resid > 0) {
804                         size = MIN(uiop->uio_resid, wsize);
805                         size = MIN(uiop->uio_iov->iov_len, size);
806                         bp = getpbuf(&ncl_pbuf_freecnt);
807                         t_uio = malloc(sizeof(struct uio), M_NFSDIRECTIO, M_WAITOK);
808                         t_iov = malloc(sizeof(struct iovec), M_NFSDIRECTIO, M_WAITOK);
809                         t_iov->iov_base = malloc(size, M_NFSDIRECTIO, M_WAITOK);
810                         t_iov->iov_len = size;
811                         t_uio->uio_iov = t_iov;
812                         t_uio->uio_iovcnt = 1;
813                         t_uio->uio_offset = uiop->uio_offset;
814                         t_uio->uio_resid = size;
815                         t_uio->uio_segflg = UIO_SYSSPACE;
816                         t_uio->uio_rw = UIO_WRITE;
817                         t_uio->uio_td = td;
818                         KASSERT(uiop->uio_segflg == UIO_USERSPACE ||
819                             uiop->uio_segflg == UIO_SYSSPACE,
820                             ("nfs_directio_write: Bad uio_segflg"));
821                         if (uiop->uio_segflg == UIO_USERSPACE) {
822                                 error = copyin(uiop->uio_iov->iov_base,
823                                     t_iov->iov_base, size);
824                                 if (error != 0)
825                                         goto err_free;
826                         } else
827                                 /*
828                                  * UIO_SYSSPACE may never happen, but handle
829                                  * it just in case it does.
830                                  */
831                                 bcopy(uiop->uio_iov->iov_base, t_iov->iov_base,
832                                     size);
833                         bp->b_flags |= B_DIRECT;
834                         bp->b_iocmd = BIO_WRITE;
835                         if (cred != NOCRED) {
836                                 crhold(cred);
837                                 bp->b_wcred = cred;
838                         } else
839                                 bp->b_wcred = NOCRED;
840                         bp->b_caller1 = (void *)t_uio;
841                         bp->b_vp = vp;
842                         error = ncl_asyncio(nmp, bp, NOCRED, td);
843 err_free:
844                         if (error) {
845                                 free(t_iov->iov_base, M_NFSDIRECTIO);
846                                 free(t_iov, M_NFSDIRECTIO);
847                                 free(t_uio, M_NFSDIRECTIO);
848                                 bp->b_vp = NULL;
849                                 relpbuf(bp, &ncl_pbuf_freecnt);
850                                 if (error == EINTR)
851                                         return (error);
852                                 goto do_sync;
853                         }
854                         uiop->uio_offset += size;
855                         uiop->uio_resid -= size;
856                         if (uiop->uio_iov->iov_len <= size) {
857                                 uiop->uio_iovcnt--;
858                                 uiop->uio_iov++;
859                         } else {
860                                 uiop->uio_iov->iov_base =
861                                         (char *)uiop->uio_iov->iov_base + size;
862                                 uiop->uio_iov->iov_len -= size;
863                         }
864                 }
865         }
866         return (0);
867 }
868
869 /*
870  * Vnode op for write using bio
871  */
872 int
873 ncl_write(struct vop_write_args *ap)
874 {
875         int biosize;
876         struct uio *uio = ap->a_uio;
877         struct thread *td = uio->uio_td;
878         struct vnode *vp = ap->a_vp;
879         struct nfsnode *np = VTONFS(vp);
880         struct ucred *cred = ap->a_cred;
881         int ioflag = ap->a_ioflag;
882         struct buf *bp;
883         struct vattr vattr;
884         struct nfsmount *nmp = VFSTONFS(vp->v_mount);
885         daddr_t lbn;
886         int bcount, noncontig_write, obcount;
887         int bp_cached, n, on, error = 0, error1, wouldcommit;
888         size_t orig_resid, local_resid;
889         off_t orig_size, tmp_off;
890
891         KASSERT(uio->uio_rw == UIO_WRITE, ("ncl_write mode"));
892         KASSERT(uio->uio_segflg != UIO_USERSPACE || uio->uio_td == curthread,
893             ("ncl_write proc"));
894         if (vp->v_type != VREG)
895                 return (EIO);
896         mtx_lock(&np->n_mtx);
897         if (np->n_flag & NWRITEERR) {
898                 np->n_flag &= ~NWRITEERR;
899                 mtx_unlock(&np->n_mtx);
900                 return (np->n_error);
901         } else
902                 mtx_unlock(&np->n_mtx);
903         mtx_lock(&nmp->nm_mtx);
904         if ((nmp->nm_flag & NFSMNT_NFSV3) != 0 &&
905             (nmp->nm_state & NFSSTA_GOTFSINFO) == 0) {
906                 mtx_unlock(&nmp->nm_mtx);
907                 (void)ncl_fsinfo(nmp, vp, cred, td);
908                 mtx_lock(&nmp->nm_mtx);
909         }
910         if (nmp->nm_wsize == 0)
911                 (void) newnfs_iosize(nmp);
912         mtx_unlock(&nmp->nm_mtx);
913
914         /*
915          * Synchronously flush pending buffers if we are in synchronous
916          * mode or if we are appending.
917          */
918         if (ioflag & (IO_APPEND | IO_SYNC)) {
919                 mtx_lock(&np->n_mtx);
920                 if (np->n_flag & NMODIFIED) {
921                         mtx_unlock(&np->n_mtx);
922 #ifdef notyet /* Needs matching nonblock semantics elsewhere, too. */
923                         /*
924                          * Require non-blocking, synchronous writes to
925                          * dirty files to inform the program it needs
926                          * to fsync(2) explicitly.
927                          */
928                         if (ioflag & IO_NDELAY)
929                                 return (EAGAIN);
930 #endif
931                         np->n_attrstamp = 0;
932                         KDTRACE_NFS_ATTRCACHE_FLUSH_DONE(vp);
933                         error = ncl_vinvalbuf(vp, V_SAVE | ((ioflag &
934                             IO_VMIO) != 0 ? V_VMIO : 0), td, 1);
935                         if (error == 0 && (vp->v_iflag & VI_DOOMED) != 0)
936                                 error = EBADF;
937                         if (error != 0)
938                                 return (error);
939                 } else
940                         mtx_unlock(&np->n_mtx);
941         }
942
943         orig_resid = uio->uio_resid;
944         mtx_lock(&np->n_mtx);
945         orig_size = np->n_size;
946         mtx_unlock(&np->n_mtx);
947
948         /*
949          * If IO_APPEND then load uio_offset.  We restart here if we cannot
950          * get the append lock.
951          */
952         if (ioflag & IO_APPEND) {
953                 np->n_attrstamp = 0;
954                 KDTRACE_NFS_ATTRCACHE_FLUSH_DONE(vp);
955                 error = VOP_GETATTR(vp, &vattr, cred);
956                 if (error)
957                         return (error);
958                 mtx_lock(&np->n_mtx);
959                 uio->uio_offset = np->n_size;
960                 mtx_unlock(&np->n_mtx);
961         }
962
963         if (uio->uio_offset < 0)
964                 return (EINVAL);
965         tmp_off = uio->uio_offset + uio->uio_resid;
966         if (tmp_off > nmp->nm_maxfilesize || tmp_off < uio->uio_offset)
967                 return (EFBIG);
968         if (uio->uio_resid == 0)
969                 return (0);
970
971         if (newnfs_directio_enable && (ioflag & IO_DIRECT) && vp->v_type == VREG)
972                 return nfs_directio_write(vp, uio, cred, ioflag);
973
974         /*
975          * Maybe this should be above the vnode op call, but so long as
976          * file servers have no limits, i don't think it matters
977          */
978         if (vn_rlimit_fsize(vp, uio, td))
979                 return (EFBIG);
980
981         biosize = vp->v_bufobj.bo_bsize;
982         /*
983          * Find all of this file's B_NEEDCOMMIT buffers.  If our writes
984          * would exceed the local maximum per-file write commit size when
985          * combined with those, we must decide whether to flush,
986          * go synchronous, or return error.  We don't bother checking
987          * IO_UNIT -- we just make all writes atomic anyway, as there's
988          * no point optimizing for something that really won't ever happen.
989          */
990         wouldcommit = 0;
991         if (!(ioflag & IO_SYNC)) {
992                 int nflag;
993
994                 mtx_lock(&np->n_mtx);
995                 nflag = np->n_flag;
996                 mtx_unlock(&np->n_mtx);
997                 if (nflag & NMODIFIED) {
998                         BO_LOCK(&vp->v_bufobj);
999                         if (vp->v_bufobj.bo_dirty.bv_cnt != 0) {
1000                                 TAILQ_FOREACH(bp, &vp->v_bufobj.bo_dirty.bv_hd,
1001                                     b_bobufs) {
1002                                         if (bp->b_flags & B_NEEDCOMMIT)
1003                                                 wouldcommit += bp->b_bcount;
1004                                 }
1005                         }
1006                         BO_UNLOCK(&vp->v_bufobj);
1007                 }
1008         }
1009
1010         do {
1011                 if (!(ioflag & IO_SYNC)) {
1012                         wouldcommit += biosize;
1013                         if (wouldcommit > nmp->nm_wcommitsize) {
1014                                 np->n_attrstamp = 0;
1015                                 KDTRACE_NFS_ATTRCACHE_FLUSH_DONE(vp);
1016                                 error = ncl_vinvalbuf(vp, V_SAVE | ((ioflag &
1017                                     IO_VMIO) != 0 ? V_VMIO : 0), td, 1);
1018                                 if (error == 0 &&
1019                                     (vp->v_iflag & VI_DOOMED) != 0)
1020                                         error = EBADF;
1021                                 if (error != 0)
1022                                         return (error);
1023                                 wouldcommit = biosize;
1024                         }
1025                 }
1026
1027                 NFSINCRGLOBAL(nfsstatsv1.biocache_writes);
1028                 lbn = uio->uio_offset / biosize;
1029                 on = uio->uio_offset - (lbn * biosize);
1030                 n = MIN((unsigned)(biosize - on), uio->uio_resid);
1031 again:
1032                 /*
1033                  * Handle direct append and file extension cases, calculate
1034                  * unaligned buffer size.
1035                  */
1036                 mtx_lock(&np->n_mtx);
1037                 if ((np->n_flag & NHASBEENLOCKED) == 0 &&
1038                     (nmp->nm_flag & NFSMNT_NONCONTIGWR) != 0)
1039                         noncontig_write = 1;
1040                 else
1041                         noncontig_write = 0;
1042                 if ((uio->uio_offset == np->n_size ||
1043                     (noncontig_write != 0 &&
1044                     lbn == (np->n_size / biosize) &&
1045                     uio->uio_offset + n > np->n_size)) && n) {
1046                         mtx_unlock(&np->n_mtx);
1047                         /*
1048                          * Get the buffer (in its pre-append state to maintain
1049                          * B_CACHE if it was previously set).  Resize the
1050                          * nfsnode after we have locked the buffer to prevent
1051                          * readers from reading garbage.
1052                          */
1053                         obcount = np->n_size - (lbn * biosize);
1054                         bp = nfs_getcacheblk(vp, lbn, obcount, td);
1055
1056                         if (bp != NULL) {
1057                                 long save;
1058
1059                                 mtx_lock(&np->n_mtx);
1060                                 np->n_size = uio->uio_offset + n;
1061                                 np->n_flag |= NMODIFIED;
1062                                 vnode_pager_setsize(vp, np->n_size);
1063                                 mtx_unlock(&np->n_mtx);
1064
1065                                 save = bp->b_flags & B_CACHE;
1066                                 bcount = on + n;
1067                                 allocbuf(bp, bcount);
1068                                 bp->b_flags |= save;
1069                                 if (noncontig_write != 0 && on > obcount)
1070                                         vfs_bio_bzero_buf(bp, obcount, on -
1071                                             obcount);
1072                         }
1073                 } else {
1074                         /*
1075                          * Obtain the locked cache block first, and then
1076                          * adjust the file's size as appropriate.
1077                          */
1078                         bcount = on + n;
1079                         if ((off_t)lbn * biosize + bcount < np->n_size) {
1080                                 if ((off_t)(lbn + 1) * biosize < np->n_size)
1081                                         bcount = biosize;
1082                                 else
1083                                         bcount = np->n_size - (off_t)lbn * biosize;
1084                         }
1085                         mtx_unlock(&np->n_mtx);
1086                         bp = nfs_getcacheblk(vp, lbn, bcount, td);
1087                         mtx_lock(&np->n_mtx);
1088                         if (uio->uio_offset + n > np->n_size) {
1089                                 np->n_size = uio->uio_offset + n;
1090                                 np->n_flag |= NMODIFIED;
1091                                 vnode_pager_setsize(vp, np->n_size);
1092                         }
1093                         mtx_unlock(&np->n_mtx);
1094                 }
1095
1096                 if (!bp) {
1097                         error = newnfs_sigintr(nmp, td);
1098                         if (!error)
1099                                 error = EINTR;
1100                         break;
1101                 }
1102
1103                 /*
1104                  * Issue a READ if B_CACHE is not set.  In special-append
1105                  * mode, B_CACHE is based on the buffer prior to the write
1106                  * op and is typically set, avoiding the read.  If a read
1107                  * is required in special append mode, the server will
1108                  * probably send us a short-read since we extended the file
1109                  * on our end, resulting in b_resid == 0 and, thusly,
1110                  * B_CACHE getting set.
1111                  *
1112                  * We can also avoid issuing the read if the write covers
1113                  * the entire buffer.  We have to make sure the buffer state
1114                  * is reasonable in this case since we will not be initiating
1115                  * I/O.  See the comments in kern/vfs_bio.c's getblk() for
1116                  * more information.
1117                  *
1118                  * B_CACHE may also be set due to the buffer being cached
1119                  * normally.
1120                  */
1121
1122                 bp_cached = 1;
1123                 if (on == 0 && n == bcount) {
1124                         if ((bp->b_flags & B_CACHE) == 0)
1125                                 bp_cached = 0;
1126                         bp->b_flags |= B_CACHE;
1127                         bp->b_flags &= ~B_INVAL;
1128                         bp->b_ioflags &= ~BIO_ERROR;
1129                 }
1130
1131                 if ((bp->b_flags & B_CACHE) == 0) {
1132                         bp->b_iocmd = BIO_READ;
1133                         vfs_busy_pages(bp, 0);
1134                         error = ncl_doio(vp, bp, cred, td, 0);
1135                         if (error) {
1136                                 brelse(bp);
1137                                 break;
1138                         }
1139                 }
1140                 if (bp->b_wcred == NOCRED)
1141                         bp->b_wcred = crhold(cred);
1142                 mtx_lock(&np->n_mtx);
1143                 np->n_flag |= NMODIFIED;
1144                 mtx_unlock(&np->n_mtx);
1145
1146                 /*
1147                  * If dirtyend exceeds file size, chop it down.  This should
1148                  * not normally occur but there is an append race where it
1149                  * might occur XXX, so we log it.
1150                  *
1151                  * If the chopping creates a reverse-indexed or degenerate
1152                  * situation with dirtyoff/end, we 0 both of them.
1153                  */
1154
1155                 if (bp->b_dirtyend > bcount) {
1156                         printf("NFS append race @%lx:%d\n",
1157                             (long)bp->b_blkno * DEV_BSIZE,
1158                             bp->b_dirtyend - bcount);
1159                         bp->b_dirtyend = bcount;
1160                 }
1161
1162                 if (bp->b_dirtyoff >= bp->b_dirtyend)
1163                         bp->b_dirtyoff = bp->b_dirtyend = 0;
1164
1165                 /*
1166                  * If the new write will leave a contiguous dirty
1167                  * area, just update the b_dirtyoff and b_dirtyend,
1168                  * otherwise force a write rpc of the old dirty area.
1169                  *
1170                  * If there has been a file lock applied to this file
1171                  * or vfs.nfs.old_noncontig_writing is set, do the following:
1172                  * While it is possible to merge discontiguous writes due to
1173                  * our having a B_CACHE buffer ( and thus valid read data
1174                  * for the hole), we don't because it could lead to
1175                  * significant cache coherency problems with multiple clients,
1176                  * especially if locking is implemented later on.
1177                  *
1178                  * If vfs.nfs.old_noncontig_writing is not set and there has
1179                  * not been file locking done on this file:
1180                  * Relax coherency a bit for the sake of performance and
1181                  * expand the current dirty region to contain the new
1182                  * write even if it means we mark some non-dirty data as
1183                  * dirty.
1184                  */
1185
1186                 if (noncontig_write == 0 && bp->b_dirtyend > 0 &&
1187                     (on > bp->b_dirtyend || (on + n) < bp->b_dirtyoff)) {
1188                         if (bwrite(bp) == EINTR) {
1189                                 error = EINTR;
1190                                 break;
1191                         }
1192                         goto again;
1193                 }
1194
1195                 local_resid = uio->uio_resid;
1196                 error = vn_io_fault_uiomove((char *)bp->b_data + on, n, uio);
1197
1198                 if (error != 0 && !bp_cached) {
1199                         /*
1200                          * This block has no other content then what
1201                          * possibly was written by the faulty uiomove.
1202                          * Release it, forgetting the data pages, to
1203                          * prevent the leak of uninitialized data to
1204                          * usermode.
1205                          */
1206                         bp->b_ioflags |= BIO_ERROR;
1207                         brelse(bp);
1208                         uio->uio_offset -= local_resid - uio->uio_resid;
1209                         uio->uio_resid = local_resid;
1210                         break;
1211                 }
1212
1213                 /*
1214                  * Since this block is being modified, it must be written
1215                  * again and not just committed.  Since write clustering does
1216                  * not work for the stage 1 data write, only the stage 2
1217                  * commit rpc, we have to clear B_CLUSTEROK as well.
1218                  */
1219                 bp->b_flags &= ~(B_NEEDCOMMIT | B_CLUSTEROK);
1220
1221                 /*
1222                  * Get the partial update on the progress made from
1223                  * uiomove, if an error occurred.
1224                  */
1225                 if (error != 0)
1226                         n = local_resid - uio->uio_resid;
1227
1228                 /*
1229                  * Only update dirtyoff/dirtyend if not a degenerate
1230                  * condition.
1231                  */
1232                 if (n > 0) {
1233                         if (bp->b_dirtyend > 0) {
1234                                 bp->b_dirtyoff = min(on, bp->b_dirtyoff);
1235                                 bp->b_dirtyend = max((on + n), bp->b_dirtyend);
1236                         } else {
1237                                 bp->b_dirtyoff = on;
1238                                 bp->b_dirtyend = on + n;
1239                         }
1240                         vfs_bio_set_valid(bp, on, n);
1241                 }
1242
1243                 /*
1244                  * If IO_SYNC do bwrite().
1245                  *
1246                  * IO_INVAL appears to be unused.  The idea appears to be
1247                  * to turn off caching in this case.  Very odd.  XXX
1248                  */
1249                 if ((ioflag & IO_SYNC)) {
1250                         if (ioflag & IO_INVAL)
1251                                 bp->b_flags |= B_NOCACHE;
1252                         error1 = bwrite(bp);
1253                         if (error1 != 0) {
1254                                 if (error == 0)
1255                                         error = error1;
1256                                 break;
1257                         }
1258                 } else if ((n + on) == biosize || (ioflag & IO_ASYNC) != 0) {
1259                         bp->b_flags |= B_ASYNC;
1260                         (void) ncl_writebp(bp, 0, NULL);
1261                 } else {
1262                         bdwrite(bp);
1263                 }
1264
1265                 if (error != 0)
1266                         break;
1267         } while (uio->uio_resid > 0 && n > 0);
1268
1269         if (error != 0) {
1270                 if (ioflag & IO_UNIT) {
1271                         VATTR_NULL(&vattr);
1272                         vattr.va_size = orig_size;
1273                         /* IO_SYNC is handled implicitely */
1274                         (void)VOP_SETATTR(vp, &vattr, cred);
1275                         uio->uio_offset -= orig_resid - uio->uio_resid;
1276                         uio->uio_resid = orig_resid;
1277                 }
1278         }
1279
1280         return (error);
1281 }
1282
1283 /*
1284  * Get an nfs cache block.
1285  *
1286  * Allocate a new one if the block isn't currently in the cache
1287  * and return the block marked busy. If the calling process is
1288  * interrupted by a signal for an interruptible mount point, return
1289  * NULL.
1290  *
1291  * The caller must carefully deal with the possible B_INVAL state of
1292  * the buffer.  ncl_doio() clears B_INVAL (and ncl_asyncio() clears it
1293  * indirectly), so synchronous reads can be issued without worrying about
1294  * the B_INVAL state.  We have to be a little more careful when dealing
1295  * with writes (see comments in nfs_write()) when extending a file past
1296  * its EOF.
1297  */
1298 static struct buf *
1299 nfs_getcacheblk(struct vnode *vp, daddr_t bn, int size, struct thread *td)
1300 {
1301         struct buf *bp;
1302         struct mount *mp;
1303         struct nfsmount *nmp;
1304
1305         mp = vp->v_mount;
1306         nmp = VFSTONFS(mp);
1307
1308         if (nmp->nm_flag & NFSMNT_INT) {
1309                 sigset_t oldset;
1310
1311                 newnfs_set_sigmask(td, &oldset);
1312                 bp = getblk(vp, bn, size, PCATCH, 0, 0);
1313                 newnfs_restore_sigmask(td, &oldset);
1314                 while (bp == NULL) {
1315                         if (newnfs_sigintr(nmp, td))
1316                                 return (NULL);
1317                         bp = getblk(vp, bn, size, 0, 2 * hz, 0);
1318                 }
1319         } else {
1320                 bp = getblk(vp, bn, size, 0, 0, 0);
1321         }
1322
1323         if (vp->v_type == VREG)
1324                 bp->b_blkno = bn * (vp->v_bufobj.bo_bsize / DEV_BSIZE);
1325         return (bp);
1326 }
1327
1328 /*
1329  * Flush and invalidate all dirty buffers. If another process is already
1330  * doing the flush, just wait for completion.
1331  */
1332 int
1333 ncl_vinvalbuf(struct vnode *vp, int flags, struct thread *td, int intrflg)
1334 {
1335         struct nfsnode *np = VTONFS(vp);
1336         struct nfsmount *nmp = VFSTONFS(vp->v_mount);
1337         int error = 0, slpflag, slptimeo;
1338         int old_lock = 0;
1339
1340         ASSERT_VOP_LOCKED(vp, "ncl_vinvalbuf");
1341
1342         if ((nmp->nm_flag & NFSMNT_INT) == 0)
1343                 intrflg = 0;
1344         if ((nmp->nm_mountp->mnt_kern_flag & MNTK_UNMOUNTF))
1345                 intrflg = 1;
1346         if (intrflg) {
1347                 slpflag = PCATCH;
1348                 slptimeo = 2 * hz;
1349         } else {
1350                 slpflag = 0;
1351                 slptimeo = 0;
1352         }
1353
1354         old_lock = ncl_upgrade_vnlock(vp);
1355         if (vp->v_iflag & VI_DOOMED) {
1356                 /*
1357                  * Since vgonel() uses the generic vinvalbuf() to flush
1358                  * dirty buffers and it does not call this function, it
1359                  * is safe to just return OK when VI_DOOMED is set.
1360                  */
1361                 ncl_downgrade_vnlock(vp, old_lock);
1362                 return (0);
1363         }
1364
1365         /*
1366          * Now, flush as required.
1367          */
1368         if ((flags & (V_SAVE | V_VMIO)) == V_SAVE &&
1369              vp->v_bufobj.bo_object != NULL) {
1370                 VM_OBJECT_WLOCK(vp->v_bufobj.bo_object);
1371                 vm_object_page_clean(vp->v_bufobj.bo_object, 0, 0, OBJPC_SYNC);
1372                 VM_OBJECT_WUNLOCK(vp->v_bufobj.bo_object);
1373                 /*
1374                  * If the page clean was interrupted, fail the invalidation.
1375                  * Not doing so, we run the risk of losing dirty pages in the
1376                  * vinvalbuf() call below.
1377                  */
1378                 if (intrflg && (error = newnfs_sigintr(nmp, td)))
1379                         goto out;
1380         }
1381
1382         error = vinvalbuf(vp, flags, slpflag, 0);
1383         while (error) {
1384                 if (intrflg && (error = newnfs_sigintr(nmp, td)))
1385                         goto out;
1386                 error = vinvalbuf(vp, flags, 0, slptimeo);
1387         }
1388         if (NFSHASPNFS(nmp)) {
1389                 nfscl_layoutcommit(vp, td);
1390                 /*
1391                  * Invalidate the attribute cache, since writes to a DS
1392                  * won't update the size attribute.
1393                  */
1394                 mtx_lock(&np->n_mtx);
1395                 np->n_attrstamp = 0;
1396         } else
1397                 mtx_lock(&np->n_mtx);
1398         if (np->n_directio_asyncwr == 0)
1399                 np->n_flag &= ~NMODIFIED;
1400         mtx_unlock(&np->n_mtx);
1401 out:
1402         ncl_downgrade_vnlock(vp, old_lock);
1403         return error;
1404 }
1405
1406 /*
1407  * Initiate asynchronous I/O. Return an error if no nfsiods are available.
1408  * This is mainly to avoid queueing async I/O requests when the nfsiods
1409  * are all hung on a dead server.
1410  *
1411  * Note: ncl_asyncio() does not clear (BIO_ERROR|B_INVAL) but when the bp
1412  * is eventually dequeued by the async daemon, ncl_doio() *will*.
1413  */
1414 int
1415 ncl_asyncio(struct nfsmount *nmp, struct buf *bp, struct ucred *cred, struct thread *td)
1416 {
1417         int iod;
1418         int gotiod;
1419         int slpflag = 0;
1420         int slptimeo = 0;
1421         int error, error2;
1422
1423         /*
1424          * Commits are usually short and sweet so lets save some cpu and
1425          * leave the async daemons for more important rpc's (such as reads
1426          * and writes).
1427          *
1428          * Readdirplus RPCs do vget()s to acquire the vnodes for entries
1429          * in the directory in order to update attributes. This can deadlock
1430          * with another thread that is waiting for async I/O to be done by
1431          * an nfsiod thread while holding a lock on one of these vnodes.
1432          * To avoid this deadlock, don't allow the async nfsiod threads to
1433          * perform Readdirplus RPCs.
1434          */
1435         mtx_lock(&ncl_iod_mutex);
1436         if ((bp->b_iocmd == BIO_WRITE && (bp->b_flags & B_NEEDCOMMIT) &&
1437              (nmp->nm_bufqiods > ncl_numasync / 2)) ||
1438             (bp->b_vp->v_type == VDIR && (nmp->nm_flag & NFSMNT_RDIRPLUS))) {
1439                 mtx_unlock(&ncl_iod_mutex);
1440                 return(EIO);
1441         }
1442 again:
1443         if (nmp->nm_flag & NFSMNT_INT)
1444                 slpflag = PCATCH;
1445         gotiod = FALSE;
1446
1447         /*
1448          * Find a free iod to process this request.
1449          */
1450         for (iod = 0; iod < ncl_numasync; iod++)
1451                 if (ncl_iodwant[iod] == NFSIOD_AVAILABLE) {
1452                         gotiod = TRUE;
1453                         break;
1454                 }
1455
1456         /*
1457          * Try to create one if none are free.
1458          */
1459         if (!gotiod)
1460                 ncl_nfsiodnew();
1461         else {
1462                 /*
1463                  * Found one, so wake it up and tell it which
1464                  * mount to process.
1465                  */
1466                 NFS_DPF(ASYNCIO, ("ncl_asyncio: waking iod %d for mount %p\n",
1467                     iod, nmp));
1468                 ncl_iodwant[iod] = NFSIOD_NOT_AVAILABLE;
1469                 ncl_iodmount[iod] = nmp;
1470                 nmp->nm_bufqiods++;
1471                 wakeup(&ncl_iodwant[iod]);
1472         }
1473
1474         /*
1475          * If none are free, we may already have an iod working on this mount
1476          * point.  If so, it will process our request.
1477          */
1478         if (!gotiod) {
1479                 if (nmp->nm_bufqiods > 0) {
1480                         NFS_DPF(ASYNCIO,
1481                                 ("ncl_asyncio: %d iods are already processing mount %p\n",
1482                                  nmp->nm_bufqiods, nmp));
1483                         gotiod = TRUE;
1484                 }
1485         }
1486
1487         /*
1488          * If we have an iod which can process the request, then queue
1489          * the buffer.
1490          */
1491         if (gotiod) {
1492                 /*
1493                  * Ensure that the queue never grows too large.  We still want
1494                  * to asynchronize so we block rather then return EIO.
1495                  */
1496                 while (nmp->nm_bufqlen >= 2*ncl_numasync) {
1497                         NFS_DPF(ASYNCIO,
1498                                 ("ncl_asyncio: waiting for mount %p queue to drain\n", nmp));
1499                         nmp->nm_bufqwant = TRUE;
1500                         error = newnfs_msleep(td, &nmp->nm_bufq,
1501                             &ncl_iod_mutex, slpflag | PRIBIO, "nfsaio",
1502                            slptimeo);
1503                         if (error) {
1504                                 error2 = newnfs_sigintr(nmp, td);
1505                                 if (error2) {
1506                                         mtx_unlock(&ncl_iod_mutex);
1507                                         return (error2);
1508                                 }
1509                                 if (slpflag == PCATCH) {
1510                                         slpflag = 0;
1511                                         slptimeo = 2 * hz;
1512                                 }
1513                         }
1514                         /*
1515                          * We might have lost our iod while sleeping,
1516                          * so check and loop if necessary.
1517                          */
1518                         goto again;
1519                 }
1520
1521                 /* We might have lost our nfsiod */
1522                 if (nmp->nm_bufqiods == 0) {
1523                         NFS_DPF(ASYNCIO,
1524                                 ("ncl_asyncio: no iods after mount %p queue was drained, looping\n", nmp));
1525                         goto again;
1526                 }
1527
1528                 if (bp->b_iocmd == BIO_READ) {
1529                         if (bp->b_rcred == NOCRED && cred != NOCRED)
1530                                 bp->b_rcred = crhold(cred);
1531                 } else {
1532                         if (bp->b_wcred == NOCRED && cred != NOCRED)
1533                                 bp->b_wcred = crhold(cred);
1534                 }
1535
1536                 if (bp->b_flags & B_REMFREE)
1537                         bremfreef(bp);
1538                 BUF_KERNPROC(bp);
1539                 TAILQ_INSERT_TAIL(&nmp->nm_bufq, bp, b_freelist);
1540                 nmp->nm_bufqlen++;
1541                 if ((bp->b_flags & B_DIRECT) && bp->b_iocmd == BIO_WRITE) {
1542                         mtx_lock(&(VTONFS(bp->b_vp))->n_mtx);
1543                         VTONFS(bp->b_vp)->n_flag |= NMODIFIED;
1544                         VTONFS(bp->b_vp)->n_directio_asyncwr++;
1545                         mtx_unlock(&(VTONFS(bp->b_vp))->n_mtx);
1546                 }
1547                 mtx_unlock(&ncl_iod_mutex);
1548                 return (0);
1549         }
1550
1551         mtx_unlock(&ncl_iod_mutex);
1552
1553         /*
1554          * All the iods are busy on other mounts, so return EIO to
1555          * force the caller to process the i/o synchronously.
1556          */
1557         NFS_DPF(ASYNCIO, ("ncl_asyncio: no iods available, i/o is synchronous\n"));
1558         return (EIO);
1559 }
1560
1561 void
1562 ncl_doio_directwrite(struct buf *bp)
1563 {
1564         int iomode, must_commit;
1565         struct uio *uiop = (struct uio *)bp->b_caller1;
1566         char *iov_base = uiop->uio_iov->iov_base;
1567
1568         iomode = NFSWRITE_FILESYNC;
1569         uiop->uio_td = NULL; /* NULL since we're in nfsiod */
1570         ncl_writerpc(bp->b_vp, uiop, bp->b_wcred, &iomode, &must_commit, 0);
1571         KASSERT((must_commit == 0), ("ncl_doio_directwrite: Did not commit write"));
1572         free(iov_base, M_NFSDIRECTIO);
1573         free(uiop->uio_iov, M_NFSDIRECTIO);
1574         free(uiop, M_NFSDIRECTIO);
1575         if ((bp->b_flags & B_DIRECT) && bp->b_iocmd == BIO_WRITE) {
1576                 struct nfsnode *np = VTONFS(bp->b_vp);
1577                 mtx_lock(&np->n_mtx);
1578                 if (NFSHASPNFS(VFSTONFS(vnode_mount(bp->b_vp)))) {
1579                         /*
1580                          * Invalidate the attribute cache, since writes to a DS
1581                          * won't update the size attribute.
1582                          */
1583                         np->n_attrstamp = 0;
1584                 }
1585                 np->n_directio_asyncwr--;
1586                 if (np->n_directio_asyncwr == 0) {
1587                         np->n_flag &= ~NMODIFIED;
1588                         if ((np->n_flag & NFSYNCWAIT)) {
1589                                 np->n_flag &= ~NFSYNCWAIT;
1590                                 wakeup((caddr_t)&np->n_directio_asyncwr);
1591                         }
1592                 }
1593                 mtx_unlock(&np->n_mtx);
1594         }
1595         bp->b_vp = NULL;
1596         relpbuf(bp, &ncl_pbuf_freecnt);
1597 }
1598
1599 /*
1600  * Do an I/O operation to/from a cache block. This may be called
1601  * synchronously or from an nfsiod.
1602  */
1603 int
1604 ncl_doio(struct vnode *vp, struct buf *bp, struct ucred *cr, struct thread *td,
1605     int called_from_strategy)
1606 {
1607         struct uio *uiop;
1608         struct nfsnode *np;
1609         struct nfsmount *nmp;
1610         int error = 0, iomode, must_commit = 0;
1611         struct uio uio;
1612         struct iovec io;
1613         struct proc *p = td ? td->td_proc : NULL;
1614         uint8_t iocmd;
1615
1616         np = VTONFS(vp);
1617         nmp = VFSTONFS(vp->v_mount);
1618         uiop = &uio;
1619         uiop->uio_iov = &io;
1620         uiop->uio_iovcnt = 1;
1621         uiop->uio_segflg = UIO_SYSSPACE;
1622         uiop->uio_td = td;
1623
1624         /*
1625          * clear BIO_ERROR and B_INVAL state prior to initiating the I/O.  We
1626          * do this here so we do not have to do it in all the code that
1627          * calls us.
1628          */
1629         bp->b_flags &= ~B_INVAL;
1630         bp->b_ioflags &= ~BIO_ERROR;
1631
1632         KASSERT(!(bp->b_flags & B_DONE), ("ncl_doio: bp %p already marked done", bp));
1633         iocmd = bp->b_iocmd;
1634         if (iocmd == BIO_READ) {
1635             io.iov_len = uiop->uio_resid = bp->b_bcount;
1636             io.iov_base = bp->b_data;
1637             uiop->uio_rw = UIO_READ;
1638
1639             switch (vp->v_type) {
1640             case VREG:
1641                 uiop->uio_offset = ((off_t)bp->b_blkno) * DEV_BSIZE;
1642                 NFSINCRGLOBAL(nfsstatsv1.read_bios);
1643                 error = ncl_readrpc(vp, uiop, cr);
1644
1645                 if (!error) {
1646                     if (uiop->uio_resid) {
1647                         /*
1648                          * If we had a short read with no error, we must have
1649                          * hit a file hole.  We should zero-fill the remainder.
1650                          * This can also occur if the server hits the file EOF.
1651                          *
1652                          * Holes used to be able to occur due to pending
1653                          * writes, but that is not possible any longer.
1654                          */
1655                         int nread = bp->b_bcount - uiop->uio_resid;
1656                         ssize_t left = uiop->uio_resid;
1657
1658                         if (left > 0)
1659                                 bzero((char *)bp->b_data + nread, left);
1660                         uiop->uio_resid = 0;
1661                     }
1662                 }
1663                 /* ASSERT_VOP_LOCKED(vp, "ncl_doio"); */
1664                 if (p && (vp->v_vflag & VV_TEXT)) {
1665                         mtx_lock(&np->n_mtx);
1666                         if (NFS_TIMESPEC_COMPARE(&np->n_mtime, &np->n_vattr.na_mtime)) {
1667                                 mtx_unlock(&np->n_mtx);
1668                                 PROC_LOCK(p);
1669                                 killproc(p, "text file modification");
1670                                 PROC_UNLOCK(p);
1671                         } else
1672                                 mtx_unlock(&np->n_mtx);
1673                 }
1674                 break;
1675             case VLNK:
1676                 uiop->uio_offset = (off_t)0;
1677                 NFSINCRGLOBAL(nfsstatsv1.readlink_bios);
1678                 error = ncl_readlinkrpc(vp, uiop, cr);
1679                 break;
1680             case VDIR:
1681                 NFSINCRGLOBAL(nfsstatsv1.readdir_bios);
1682                 uiop->uio_offset = ((u_quad_t)bp->b_lblkno) * NFS_DIRBLKSIZ;
1683                 if ((nmp->nm_flag & NFSMNT_RDIRPLUS) != 0) {
1684                         error = ncl_readdirplusrpc(vp, uiop, cr, td);
1685                         if (error == NFSERR_NOTSUPP)
1686                                 nmp->nm_flag &= ~NFSMNT_RDIRPLUS;
1687                 }
1688                 if ((nmp->nm_flag & NFSMNT_RDIRPLUS) == 0)
1689                         error = ncl_readdirrpc(vp, uiop, cr, td);
1690                 /*
1691                  * end-of-directory sets B_INVAL but does not generate an
1692                  * error.
1693                  */
1694                 if (error == 0 && uiop->uio_resid == bp->b_bcount)
1695                         bp->b_flags |= B_INVAL;
1696                 break;
1697             default:
1698                 printf("ncl_doio:  type %x unexpected\n", vp->v_type);
1699                 break;
1700             }
1701             if (error) {
1702                 bp->b_ioflags |= BIO_ERROR;
1703                 bp->b_error = error;
1704             }
1705         } else {
1706             /*
1707              * If we only need to commit, try to commit
1708              */
1709             if (bp->b_flags & B_NEEDCOMMIT) {
1710                     int retv;
1711                     off_t off;
1712
1713                     off = ((u_quad_t)bp->b_blkno) * DEV_BSIZE + bp->b_dirtyoff;
1714                     retv = ncl_commit(vp, off, bp->b_dirtyend-bp->b_dirtyoff,
1715                         bp->b_wcred, td);
1716                     if (retv == 0) {
1717                             bp->b_dirtyoff = bp->b_dirtyend = 0;
1718                             bp->b_flags &= ~(B_NEEDCOMMIT | B_CLUSTEROK);
1719                             bp->b_resid = 0;
1720                             bufdone(bp);
1721                             return (0);
1722                     }
1723                     if (retv == NFSERR_STALEWRITEVERF) {
1724                             ncl_clearcommit(vp->v_mount);
1725                     }
1726             }
1727
1728             /*
1729              * Setup for actual write
1730              */
1731             mtx_lock(&np->n_mtx);
1732             if ((off_t)bp->b_blkno * DEV_BSIZE + bp->b_dirtyend > np->n_size)
1733                 bp->b_dirtyend = np->n_size - (off_t)bp->b_blkno * DEV_BSIZE;
1734             mtx_unlock(&np->n_mtx);
1735
1736             if (bp->b_dirtyend > bp->b_dirtyoff) {
1737                 io.iov_len = uiop->uio_resid = bp->b_dirtyend
1738                     - bp->b_dirtyoff;
1739                 uiop->uio_offset = (off_t)bp->b_blkno * DEV_BSIZE
1740                     + bp->b_dirtyoff;
1741                 io.iov_base = (char *)bp->b_data + bp->b_dirtyoff;
1742                 uiop->uio_rw = UIO_WRITE;
1743                 NFSINCRGLOBAL(nfsstatsv1.write_bios);
1744
1745                 if ((bp->b_flags & (B_ASYNC | B_NEEDCOMMIT | B_NOCACHE | B_CLUSTER)) == B_ASYNC)
1746                     iomode = NFSWRITE_UNSTABLE;
1747                 else
1748                     iomode = NFSWRITE_FILESYNC;
1749
1750                 error = ncl_writerpc(vp, uiop, cr, &iomode, &must_commit,
1751                     called_from_strategy);
1752
1753                 /*
1754                  * When setting B_NEEDCOMMIT also set B_CLUSTEROK to try
1755                  * to cluster the buffers needing commit.  This will allow
1756                  * the system to submit a single commit rpc for the whole
1757                  * cluster.  We can do this even if the buffer is not 100%
1758                  * dirty (relative to the NFS blocksize), so we optimize the
1759                  * append-to-file-case.
1760                  *
1761                  * (when clearing B_NEEDCOMMIT, B_CLUSTEROK must also be
1762                  * cleared because write clustering only works for commit
1763                  * rpc's, not for the data portion of the write).
1764                  */
1765
1766                 if (!error && iomode == NFSWRITE_UNSTABLE) {
1767                     bp->b_flags |= B_NEEDCOMMIT;
1768                     if (bp->b_dirtyoff == 0
1769                         && bp->b_dirtyend == bp->b_bcount)
1770                         bp->b_flags |= B_CLUSTEROK;
1771                 } else {
1772                     bp->b_flags &= ~(B_NEEDCOMMIT | B_CLUSTEROK);
1773                 }
1774
1775                 /*
1776                  * For an interrupted write, the buffer is still valid
1777                  * and the write hasn't been pushed to the server yet,
1778                  * so we can't set BIO_ERROR and report the interruption
1779                  * by setting B_EINTR. For the B_ASYNC case, B_EINTR
1780                  * is not relevant, so the rpc attempt is essentially
1781                  * a noop.  For the case of a V3 write rpc not being
1782                  * committed to stable storage, the block is still
1783                  * dirty and requires either a commit rpc or another
1784                  * write rpc with iomode == NFSV3WRITE_FILESYNC before
1785                  * the block is reused. This is indicated by setting
1786                  * the B_DELWRI and B_NEEDCOMMIT flags.
1787                  *
1788                  * EIO is returned by ncl_writerpc() to indicate a recoverable
1789                  * write error and is handled as above, except that
1790                  * B_EINTR isn't set. One cause of this is a stale stateid
1791                  * error for the RPC that indicates recovery is required,
1792                  * when called with called_from_strategy != 0.
1793                  *
1794                  * If the buffer is marked B_PAGING, it does not reside on
1795                  * the vp's paging queues so we cannot call bdirty().  The
1796                  * bp in this case is not an NFS cache block so we should
1797                  * be safe. XXX
1798                  *
1799                  * The logic below breaks up errors into recoverable and
1800                  * unrecoverable. For the former, we clear B_INVAL|B_NOCACHE
1801                  * and keep the buffer around for potential write retries.
1802                  * For the latter (eg ESTALE), we toss the buffer away (B_INVAL)
1803                  * and save the error in the nfsnode. This is less than ideal
1804                  * but necessary. Keeping such buffers around could potentially
1805                  * cause buffer exhaustion eventually (they can never be written
1806                  * out, so will get constantly be re-dirtied). It also causes
1807                  * all sorts of vfs panics. For non-recoverable write errors,
1808                  * also invalidate the attrcache, so we'll be forced to go over
1809                  * the wire for this object, returning an error to user on next
1810                  * call (most of the time).
1811                  */
1812                 if (error == EINTR || error == EIO || error == ETIMEDOUT
1813                     || (!error && (bp->b_flags & B_NEEDCOMMIT))) {
1814                         bp->b_flags &= ~(B_INVAL|B_NOCACHE);
1815                         if ((bp->b_flags & B_PAGING) == 0) {
1816                             bdirty(bp);
1817                             bp->b_flags &= ~B_DONE;
1818                         }
1819                         if ((error == EINTR || error == ETIMEDOUT) &&
1820                             (bp->b_flags & B_ASYNC) == 0)
1821                             bp->b_flags |= B_EINTR;
1822                 } else {
1823                     if (error) {
1824                         bp->b_ioflags |= BIO_ERROR;
1825                         bp->b_flags |= B_INVAL;
1826                         bp->b_error = np->n_error = error;
1827                         mtx_lock(&np->n_mtx);
1828                         np->n_flag |= NWRITEERR;
1829                         np->n_attrstamp = 0;
1830                         KDTRACE_NFS_ATTRCACHE_FLUSH_DONE(vp);
1831                         mtx_unlock(&np->n_mtx);
1832                     }
1833                     bp->b_dirtyoff = bp->b_dirtyend = 0;
1834                 }
1835             } else {
1836                 bp->b_resid = 0;
1837                 bufdone(bp);
1838                 return (0);
1839             }
1840         }
1841         bp->b_resid = uiop->uio_resid;
1842         if (must_commit)
1843             ncl_clearcommit(vp->v_mount);
1844         bufdone(bp);
1845         return (error);
1846 }
1847
1848 /*
1849  * Used to aid in handling ftruncate() operations on the NFS client side.
1850  * Truncation creates a number of special problems for NFS.  We have to
1851  * throw away VM pages and buffer cache buffers that are beyond EOF, and
1852  * we have to properly handle VM pages or (potentially dirty) buffers
1853  * that straddle the truncation point.
1854  */
1855
1856 int
1857 ncl_meta_setsize(struct vnode *vp, struct ucred *cred, struct thread *td, u_quad_t nsize)
1858 {
1859         struct nfsnode *np = VTONFS(vp);
1860         u_quad_t tsize;
1861         int biosize = vp->v_bufobj.bo_bsize;
1862         int error = 0;
1863
1864         mtx_lock(&np->n_mtx);
1865         tsize = np->n_size;
1866         np->n_size = nsize;
1867         mtx_unlock(&np->n_mtx);
1868
1869         if (nsize < tsize) {
1870                 struct buf *bp;
1871                 daddr_t lbn;
1872                 int bufsize;
1873
1874                 /*
1875                  * vtruncbuf() doesn't get the buffer overlapping the
1876                  * truncation point.  We may have a B_DELWRI and/or B_CACHE
1877                  * buffer that now needs to be truncated.
1878                  */
1879                 error = vtruncbuf(vp, cred, nsize, biosize);
1880                 lbn = nsize / biosize;
1881                 bufsize = nsize - (lbn * biosize);
1882                 bp = nfs_getcacheblk(vp, lbn, bufsize, td);
1883                 if (!bp)
1884                         return EINTR;
1885                 if (bp->b_dirtyoff > bp->b_bcount)
1886                         bp->b_dirtyoff = bp->b_bcount;
1887                 if (bp->b_dirtyend > bp->b_bcount)
1888                         bp->b_dirtyend = bp->b_bcount;
1889                 bp->b_flags |= B_RELBUF;  /* don't leave garbage around */
1890                 brelse(bp);
1891         } else {
1892                 vnode_pager_setsize(vp, nsize);
1893         }
1894         return(error);
1895 }
1896