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