xref: /freebsd/sys/fs/nfsclient/nfs_clbio.c (revision 59c8e88e72633afbc47a4ace0d2170d00d51f7dc)
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 static bool
418 ncl_bioread_dora(struct vnode *vp)
419 {
420 	vm_object_t obj;
421 
422 	obj = vp->v_object;
423 	if (obj == NULL)
424 		return (true);
425 	return (!vm_object_mightbedirty(vp->v_object) &&
426 	    vp->v_object->un_pager.vnp.writemappings == 0);
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 	struct buf *bp, *rabp;
437 	struct thread *td;
438 	struct nfsmount *nmp = VFSTONFS(vp->v_mount);
439 	daddr_t lbn, rabn;
440 	int biosize, bcount, error, i, n, nra, on, save2, seqcount;
441 	off_t tmp_off;
442 
443 	KASSERT(uio->uio_rw == UIO_READ, ("ncl_read mode"));
444 	if (uio->uio_resid == 0)
445 		return (0);
446 	if (uio->uio_offset < 0)	/* XXX VDIR cookies can be negative */
447 		return (EINVAL);
448 	td = uio->uio_td;
449 
450 	mtx_lock(&nmp->nm_mtx);
451 	if ((nmp->nm_flag & NFSMNT_NFSV3) != 0 &&
452 	    (nmp->nm_state & NFSSTA_GOTFSINFO) == 0) {
453 		mtx_unlock(&nmp->nm_mtx);
454 		(void)ncl_fsinfo(nmp, vp, cred, td);
455 		mtx_lock(&nmp->nm_mtx);
456 	}
457 	if (nmp->nm_rsize == 0 || nmp->nm_readdirsize == 0)
458 		(void) newnfs_iosize(nmp);
459 
460 	tmp_off = uio->uio_offset + uio->uio_resid;
461 	if (vp->v_type != VDIR &&
462 	    (tmp_off > nmp->nm_maxfilesize || tmp_off < uio->uio_offset)) {
463 		mtx_unlock(&nmp->nm_mtx);
464 		return (EFBIG);
465 	}
466 	mtx_unlock(&nmp->nm_mtx);
467 
468 	if (newnfs_directio_enable && (ioflag & IO_DIRECT) && (vp->v_type == VREG))
469 		/* No caching/ no readaheads. Just read data into the user buffer */
470 		return ncl_readrpc(vp, uio, cred);
471 
472 	n = 0;
473 	on = 0;
474 	biosize = vp->v_bufobj.bo_bsize;
475 	seqcount = (int)((off_t)(ioflag >> IO_SEQSHIFT) * biosize / BKVASIZE);
476 
477 	error = nfs_bioread_check_cons(vp, td, cred);
478 	if (error)
479 		return error;
480 
481 	save2 = curthread_pflags2_set(TDP2_SBPAGES);
482 	do {
483 	    u_quad_t nsize;
484 
485 	    NFSLOCKNODE(np);
486 	    nsize = np->n_size;
487 	    NFSUNLOCKNODE(np);
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.  Do not do
497 		 * read-ahead if there are writeable mappings, since
498 		 * unlocked read by nfsiod could obliterate changes
499 		 * done by userspace.
500 		 */
501 		if (nmp->nm_readahead > 0 && ncl_bioread_dora(vp)) {
502 		    for (nra = 0; nra < nmp->nm_readahead && nra < seqcount &&
503 			(off_t)(lbn + 1 + nra) * biosize < nsize; nra++) {
504 			rabn = lbn + 1 + nra;
505 			if (incore(&vp->v_bufobj, rabn) == NULL) {
506 			    rabp = nfs_getcacheblk(vp, rabn, biosize, td);
507 			    if (!rabp) {
508 				error = newnfs_sigintr(nmp, td);
509 				if (error == 0)
510 					error = EINTR;
511 				goto out;
512 			    }
513 			    if ((rabp->b_flags & (B_CACHE|B_DELWRI)) == 0) {
514 				rabp->b_flags |= B_ASYNC;
515 				rabp->b_iocmd = BIO_READ;
516 				vfs_busy_pages(rabp, 0);
517 				if (ncl_asyncio(nmp, rabp, cred, td)) {
518 				    rabp->b_flags |= B_INVAL;
519 				    rabp->b_ioflags |= BIO_ERROR;
520 				    vfs_unbusy_pages(rabp);
521 				    brelse(rabp);
522 				    break;
523 				}
524 			    } else {
525 				brelse(rabp);
526 			    }
527 			}
528 		    }
529 		}
530 
531 		/* Note that bcount is *not* DEV_BSIZE aligned. */
532 		bcount = biosize;
533 		if ((off_t)lbn * biosize >= nsize) {
534 			bcount = 0;
535 		} else if ((off_t)(lbn + 1) * biosize > nsize) {
536 			bcount = nsize - (off_t)lbn * biosize;
537 		}
538 		bp = nfs_getcacheblk(vp, lbn, bcount, td);
539 
540 		if (!bp) {
541 			error = newnfs_sigintr(nmp, td);
542 			if (error == 0)
543 				error = EINTR;
544 			goto out;
545 		}
546 
547 		/*
548 		 * If B_CACHE is not set, we must issue the read.  If this
549 		 * fails, we return an error.
550 		 */
551 
552 		if ((bp->b_flags & B_CACHE) == 0) {
553 		    bp->b_iocmd = BIO_READ;
554 		    vfs_busy_pages(bp, 0);
555 		    error = ncl_doio(vp, bp, cred, td, 0);
556 		    if (error) {
557 			brelse(bp);
558 			goto out;
559 		    }
560 		}
561 
562 		/*
563 		 * on is the offset into the current bp.  Figure out how many
564 		 * bytes we can copy out of the bp.  Note that bcount is
565 		 * NOT DEV_BSIZE aligned.
566 		 *
567 		 * Then figure out how many bytes we can copy into the uio.
568 		 */
569 
570 		n = 0;
571 		if (on < bcount)
572 			n = MIN((unsigned)(bcount - on), uio->uio_resid);
573 		break;
574 	    case VLNK:
575 		NFSINCRGLOBAL(nfsstatsv1.biocache_readlinks);
576 		bp = nfs_getcacheblk(vp, (daddr_t)0, NFS_MAXPATHLEN, td);
577 		if (!bp) {
578 			error = newnfs_sigintr(nmp, td);
579 			if (error == 0)
580 				error = EINTR;
581 			goto out;
582 		}
583 		if ((bp->b_flags & B_CACHE) == 0) {
584 		    bp->b_iocmd = BIO_READ;
585 		    vfs_busy_pages(bp, 0);
586 		    error = ncl_doio(vp, bp, cred, td, 0);
587 		    if (error) {
588 			bp->b_ioflags |= BIO_ERROR;
589 			brelse(bp);
590 			goto out;
591 		    }
592 		}
593 		n = MIN(uio->uio_resid, NFS_MAXPATHLEN - bp->b_resid);
594 		on = 0;
595 		break;
596 	    case VDIR:
597 		NFSINCRGLOBAL(nfsstatsv1.biocache_readdirs);
598 		NFSLOCKNODE(np);
599 		if (np->n_direofoffset
600 		    && uio->uio_offset >= np->n_direofoffset) {
601 			NFSUNLOCKNODE(np);
602 			error = 0;
603 			goto out;
604 		}
605 		NFSUNLOCKNODE(np);
606 		lbn = (uoff_t)uio->uio_offset / NFS_DIRBLKSIZ;
607 		on = uio->uio_offset & (NFS_DIRBLKSIZ - 1);
608 		bp = nfs_getcacheblk(vp, lbn, NFS_DIRBLKSIZ, td);
609 		if (!bp) {
610 			error = newnfs_sigintr(nmp, td);
611 			if (error == 0)
612 				error = EINTR;
613 			goto out;
614 		}
615 		if ((bp->b_flags & B_CACHE) == 0) {
616 		    bp->b_iocmd = BIO_READ;
617 		    vfs_busy_pages(bp, 0);
618 		    error = ncl_doio(vp, bp, cred, td, 0);
619 		    if (error) {
620 			    brelse(bp);
621 		    }
622 		    while (error == NFSERR_BAD_COOKIE) {
623 			ncl_invaldir(vp);
624 			error = ncl_vinvalbuf(vp, 0, td, 1);
625 
626 			/*
627 			 * Yuck! The directory has been modified on the
628 			 * server. The only way to get the block is by
629 			 * reading from the beginning to get all the
630 			 * offset cookies.
631 			 *
632 			 * Leave the last bp intact unless there is an error.
633 			 * Loop back up to the while if the error is another
634 			 * NFSERR_BAD_COOKIE (double yuch!).
635 			 */
636 			for (i = 0; i <= lbn && !error; i++) {
637 			    NFSLOCKNODE(np);
638 			    if (np->n_direofoffset
639 				&& (i * NFS_DIRBLKSIZ) >= np->n_direofoffset) {
640 				    NFSUNLOCKNODE(np);
641 				    error = 0;
642 				    goto out;
643 			    }
644 			    NFSUNLOCKNODE(np);
645 			    bp = nfs_getcacheblk(vp, i, NFS_DIRBLKSIZ, td);
646 			    if (!bp) {
647 				error = newnfs_sigintr(nmp, td);
648 				if (error == 0)
649 					error = EINTR;
650 				goto out;
651 			    }
652 			    if ((bp->b_flags & B_CACHE) == 0) {
653 				    bp->b_iocmd = BIO_READ;
654 				    vfs_busy_pages(bp, 0);
655 				    error = ncl_doio(vp, bp, cred, td, 0);
656 				    /*
657 				     * no error + B_INVAL == directory EOF,
658 				     * use the block.
659 				     */
660 				    if (error == 0 && (bp->b_flags & B_INVAL))
661 					    break;
662 			    }
663 			    /*
664 			     * An error will throw away the block and the
665 			     * for loop will break out.  If no error and this
666 			     * is not the block we want, we throw away the
667 			     * block and go for the next one via the for loop.
668 			     */
669 			    if (error || i < lbn)
670 				    brelse(bp);
671 			}
672 		    }
673 		    /*
674 		     * The above while is repeated if we hit another cookie
675 		     * error.  If we hit an error and it wasn't a cookie error,
676 		     * we give up.
677 		     */
678 		    if (error)
679 			    goto out;
680 		}
681 
682 		/*
683 		 * If not eof and read aheads are enabled, start one.
684 		 * (You need the current block first, so that you have the
685 		 *  directory offset cookie of the next block.)
686 		 */
687 		NFSLOCKNODE(np);
688 		if (nmp->nm_readahead > 0 && ncl_bioread_dora(vp) &&
689 		    (bp->b_flags & B_INVAL) == 0 &&
690 		    (np->n_direofoffset == 0 ||
691 		    (lbn + 1) * NFS_DIRBLKSIZ < np->n_direofoffset) &&
692 		    incore(&vp->v_bufobj, lbn + 1) == NULL) {
693 			NFSUNLOCKNODE(np);
694 			rabp = nfs_getcacheblk(vp, lbn + 1, NFS_DIRBLKSIZ, td);
695 			if (rabp) {
696 			    if ((rabp->b_flags & (B_CACHE|B_DELWRI)) == 0) {
697 				rabp->b_flags |= B_ASYNC;
698 				rabp->b_iocmd = BIO_READ;
699 				vfs_busy_pages(rabp, 0);
700 				if (ncl_asyncio(nmp, rabp, cred, td)) {
701 				    rabp->b_flags |= B_INVAL;
702 				    rabp->b_ioflags |= BIO_ERROR;
703 				    vfs_unbusy_pages(rabp);
704 				    brelse(rabp);
705 				}
706 			    } else {
707 				brelse(rabp);
708 			    }
709 			}
710 			NFSLOCKNODE(np);
711 		}
712 		/*
713 		 * Unlike VREG files, whos buffer size ( bp->b_bcount ) is
714 		 * chopped for the EOF condition, we cannot tell how large
715 		 * NFS directories are going to be until we hit EOF.  So
716 		 * an NFS directory buffer is *not* chopped to its EOF.  Now,
717 		 * it just so happens that b_resid will effectively chop it
718 		 * to EOF.  *BUT* this information is lost if the buffer goes
719 		 * away and is reconstituted into a B_CACHE state ( due to
720 		 * being VMIO ) later.  So we keep track of the directory eof
721 		 * in np->n_direofoffset and chop it off as an extra step
722 		 * right here.
723 		 */
724 		n = lmin(uio->uio_resid, NFS_DIRBLKSIZ - bp->b_resid - on);
725 		if (np->n_direofoffset && n > np->n_direofoffset - uio->uio_offset)
726 			n = np->n_direofoffset - uio->uio_offset;
727 		NFSUNLOCKNODE(np);
728 		break;
729 	    default:
730 		printf(" ncl_bioread: type %x unexpected\n", vp->v_type);
731 		bp = NULL;
732 		break;
733 	    }
734 
735 	    if (n > 0) {
736 		    error = vn_io_fault_uiomove(bp->b_data + on, (int)n, uio);
737 	    }
738 	    if (vp->v_type == VLNK)
739 		n = 0;
740 	    if (bp != NULL)
741 		brelse(bp);
742 	} while (error == 0 && uio->uio_resid > 0 && n > 0);
743 out:
744 	curthread_pflags2_restore(save2);
745 	if ((curthread->td_pflags2 & TDP2_SBPAGES) == 0) {
746 		NFSLOCKNODE(np);
747 		ncl_pager_setsize(vp, NULL);
748 	}
749 	return (error);
750 }
751 
752 /*
753  * The NFS write path cannot handle iovecs with len > 1. So we need to
754  * break up iovecs accordingly (restricting them to wsize).
755  * For the SYNC case, we can do this with 1 copy (user buffer -> mbuf).
756  * For the ASYNC case, 2 copies are needed. The first a copy from the
757  * user buffer to a staging buffer and then a second copy from the staging
758  * buffer to mbufs. This can be optimized by copying from the user buffer
759  * directly into mbufs and passing the chain down, but that requires a
760  * fair amount of re-working of the relevant codepaths (and can be done
761  * later).
762  */
763 static int
764 nfs_directio_write(struct vnode *vp, struct uio *uiop, struct ucred *cred,
765     int ioflag)
766 {
767 	int error;
768 	struct nfsmount *nmp = VFSTONFS(vp->v_mount);
769 	struct thread *td = uiop->uio_td;
770 	int size;
771 	int wsize;
772 
773 	mtx_lock(&nmp->nm_mtx);
774 	wsize = nmp->nm_wsize;
775 	mtx_unlock(&nmp->nm_mtx);
776 	if (ioflag & IO_SYNC) {
777 		int iomode, must_commit;
778 		struct uio uio;
779 		struct iovec iov;
780 do_sync:
781 		while (uiop->uio_resid > 0) {
782 			size = MIN(uiop->uio_resid, wsize);
783 			size = MIN(uiop->uio_iov->iov_len, size);
784 			iov.iov_base = uiop->uio_iov->iov_base;
785 			iov.iov_len = size;
786 			uio.uio_iov = &iov;
787 			uio.uio_iovcnt = 1;
788 			uio.uio_offset = uiop->uio_offset;
789 			uio.uio_resid = size;
790 			uio.uio_segflg = uiop->uio_segflg;
791 			uio.uio_rw = UIO_WRITE;
792 			uio.uio_td = td;
793 			iomode = NFSWRITE_FILESYNC;
794 			/*
795 			 * When doing direct I/O we do not care if the
796 			 * server's write verifier has changed, but we
797 			 * do not want to update the verifier if it has
798 			 * changed, since that hides the change from
799 			 * writes being done through the buffer cache.
800 			 * By passing must_commit in set to two, the code
801 			 * in nfsrpc_writerpc() will not update the
802 			 * verifier on the mount point.
803 			 */
804 			must_commit = 2;
805 			error = ncl_writerpc(vp, &uio, cred, &iomode,
806 			    &must_commit, 0, ioflag);
807 			KASSERT((must_commit == 2),
808 			    ("ncl_directio_write: Updated write verifier"));
809 			if (error)
810 				return (error);
811 			if (iomode != NFSWRITE_FILESYNC)
812 				printf("nfs_directio_write: Broken server "
813 				    "did not reply FILE_SYNC\n");
814 			uiop->uio_offset += size;
815 			uiop->uio_resid -= size;
816 			if (uiop->uio_iov->iov_len <= size) {
817 				uiop->uio_iovcnt--;
818 				uiop->uio_iov++;
819 			} else {
820 				uiop->uio_iov->iov_base =
821 					(char *)uiop->uio_iov->iov_base + size;
822 				uiop->uio_iov->iov_len -= size;
823 			}
824 		}
825 	} else {
826 		struct uio *t_uio;
827 		struct iovec *t_iov;
828 		struct buf *bp;
829 
830 		/*
831 		 * Break up the write into blocksize chunks and hand these
832 		 * over to nfsiod's for write back.
833 		 * Unfortunately, this incurs a copy of the data. Since
834 		 * the user could modify the buffer before the write is
835 		 * initiated.
836 		 *
837 		 * The obvious optimization here is that one of the 2 copies
838 		 * in the async write path can be eliminated by copying the
839 		 * data here directly into mbufs and passing the mbuf chain
840 		 * down. But that will require a fair amount of re-working
841 		 * of the code and can be done if there's enough interest
842 		 * in NFS directio access.
843 		 */
844 		while (uiop->uio_resid > 0) {
845 			size = MIN(uiop->uio_resid, wsize);
846 			size = MIN(uiop->uio_iov->iov_len, size);
847 			bp = uma_zalloc(ncl_pbuf_zone, M_WAITOK);
848 			t_uio = malloc(sizeof(struct uio), M_NFSDIRECTIO, M_WAITOK);
849 			t_iov = malloc(sizeof(struct iovec), M_NFSDIRECTIO, M_WAITOK);
850 			t_iov->iov_base = malloc(size, M_NFSDIRECTIO, M_WAITOK);
851 			t_iov->iov_len = size;
852 			t_uio->uio_iov = t_iov;
853 			t_uio->uio_iovcnt = 1;
854 			t_uio->uio_offset = uiop->uio_offset;
855 			t_uio->uio_resid = size;
856 			t_uio->uio_segflg = UIO_SYSSPACE;
857 			t_uio->uio_rw = UIO_WRITE;
858 			t_uio->uio_td = td;
859 			KASSERT(uiop->uio_segflg == UIO_USERSPACE ||
860 			    uiop->uio_segflg == UIO_SYSSPACE,
861 			    ("nfs_directio_write: Bad uio_segflg"));
862 			if (uiop->uio_segflg == UIO_USERSPACE) {
863 				error = copyin(uiop->uio_iov->iov_base,
864 				    t_iov->iov_base, size);
865 				if (error != 0)
866 					goto err_free;
867 			} else
868 				/*
869 				 * UIO_SYSSPACE may never happen, but handle
870 				 * it just in case it does.
871 				 */
872 				bcopy(uiop->uio_iov->iov_base, t_iov->iov_base,
873 				    size);
874 			bp->b_flags |= B_DIRECT;
875 			bp->b_iocmd = BIO_WRITE;
876 			if (cred != NOCRED) {
877 				crhold(cred);
878 				bp->b_wcred = cred;
879 			} else
880 				bp->b_wcred = NOCRED;
881 			bp->b_caller1 = (void *)t_uio;
882 			bp->b_vp = vp;
883 			error = ncl_asyncio(nmp, bp, NOCRED, td);
884 err_free:
885 			if (error) {
886 				free(t_iov->iov_base, M_NFSDIRECTIO);
887 				free(t_iov, M_NFSDIRECTIO);
888 				free(t_uio, M_NFSDIRECTIO);
889 				bp->b_vp = NULL;
890 				uma_zfree(ncl_pbuf_zone, bp);
891 				if (error == EINTR)
892 					return (error);
893 				goto do_sync;
894 			}
895 			uiop->uio_offset += size;
896 			uiop->uio_resid -= size;
897 			if (uiop->uio_iov->iov_len <= size) {
898 				uiop->uio_iovcnt--;
899 				uiop->uio_iov++;
900 			} else {
901 				uiop->uio_iov->iov_base =
902 					(char *)uiop->uio_iov->iov_base + size;
903 				uiop->uio_iov->iov_len -= size;
904 			}
905 		}
906 	}
907 	return (0);
908 }
909 
910 /*
911  * Vnode op for write using bio
912  */
913 int
914 ncl_write(struct vop_write_args *ap)
915 {
916 	int biosize;
917 	struct uio *uio = ap->a_uio;
918 	struct thread *td = uio->uio_td;
919 	struct vnode *vp = ap->a_vp;
920 	struct nfsnode *np = VTONFS(vp);
921 	struct ucred *cred = ap->a_cred;
922 	int ioflag = ap->a_ioflag;
923 	struct buf *bp;
924 	struct vattr vattr;
925 	struct nfsmount *nmp = VFSTONFS(vp->v_mount);
926 	daddr_t lbn;
927 	int bcount, noncontig_write, obcount;
928 	int bp_cached, n, on, error = 0, error1, save2, wouldcommit;
929 	size_t orig_resid, local_resid;
930 	off_t orig_size, tmp_off;
931 	struct timespec ts;
932 
933 	KASSERT(uio->uio_rw == UIO_WRITE, ("ncl_write mode"));
934 	KASSERT(uio->uio_segflg != UIO_USERSPACE || uio->uio_td == curthread,
935 	    ("ncl_write proc"));
936 	if (vp->v_type != VREG)
937 		return (EIO);
938 	NFSLOCKNODE(np);
939 	if (np->n_flag & NWRITEERR) {
940 		np->n_flag &= ~NWRITEERR;
941 		NFSUNLOCKNODE(np);
942 		return (np->n_error);
943 	} else
944 		NFSUNLOCKNODE(np);
945 	mtx_lock(&nmp->nm_mtx);
946 	if ((nmp->nm_flag & NFSMNT_NFSV3) != 0 &&
947 	    (nmp->nm_state & NFSSTA_GOTFSINFO) == 0) {
948 		mtx_unlock(&nmp->nm_mtx);
949 		(void)ncl_fsinfo(nmp, vp, cred, td);
950 		mtx_lock(&nmp->nm_mtx);
951 	}
952 	if (nmp->nm_wsize == 0)
953 		(void) newnfs_iosize(nmp);
954 	mtx_unlock(&nmp->nm_mtx);
955 
956 	/*
957 	 * Synchronously flush pending buffers if we are in synchronous
958 	 * mode or if we are appending.
959 	 */
960 	if ((ioflag & IO_APPEND) || ((ioflag & IO_SYNC) && (np->n_flag &
961 	    NMODIFIED))) {
962 		/*
963 		 * For the case where IO_APPEND is being done using a
964 		 * direct output (to the NFS server) RPC and
965 		 * newnfs_directio_enable is 0, all buffer cache buffers,
966 		 * including ones not modified, must be invalidated.
967 		 * This ensures that stale data is not read out of the
968 		 * buffer cache.  The call also invalidates all mapped
969 		 * pages and, since the exclusive lock is held on the vnode,
970 		 * new pages cannot be faulted in.
971 		 *
972 		 * For the case where newnfs_directio_enable is set
973 		 * (which is not the default), it is not obvious that
974 		 * stale data should be left in the buffer cache, but
975 		 * the code has been this way for over a decade without
976 		 * complaints.  Note that, unlike doing IO_APPEND via
977 		 * a direct write RPC when newnfs_directio_enable is not set,
978 		 * when newnfs_directio_enable is set, reading is done via
979 		 * direct to NFS server RPCs as well.
980 		 */
981 		np->n_attrstamp = 0;
982 		KDTRACE_NFS_ATTRCACHE_FLUSH_DONE(vp);
983 		error = ncl_vinvalbuf(vp, V_SAVE | ((ioflag &
984 		    IO_VMIO) != 0 ? V_VMIO : 0), td, 1);
985 		if (error != 0)
986 			return (error);
987 	}
988 
989 	orig_resid = uio->uio_resid;
990 	NFSLOCKNODE(np);
991 	orig_size = np->n_size;
992 	NFSUNLOCKNODE(np);
993 
994 	/*
995 	 * If IO_APPEND then load uio_offset.  We restart here if we cannot
996 	 * get the append lock.
997 	 */
998 	if (ioflag & IO_APPEND) {
999 		/*
1000 		 * For NFSv4, the AppendWrite will Verify the size against
1001 		 * the file's size on the server.  If not the same, the
1002 		 * write will then be retried, using the file size returned
1003 		 * by the AppendWrite.  However, for NFSv2 and NFSv3, the
1004 		 * size must be acquired here via a Getattr RPC.
1005 		 * The AppendWrite is not done for a pNFS mount.
1006 		 */
1007 		if (!NFSHASNFSV4(nmp) || NFSHASPNFS(nmp)) {
1008 			np->n_attrstamp = 0;
1009 			KDTRACE_NFS_ATTRCACHE_FLUSH_DONE(vp);
1010 			error = VOP_GETATTR(vp, &vattr, cred);
1011 			if (error)
1012 				return (error);
1013 		}
1014 		NFSLOCKNODE(np);
1015 		uio->uio_offset = np->n_size;
1016 		NFSUNLOCKNODE(np);
1017 	}
1018 
1019 	if (uio->uio_offset < 0)
1020 		return (EINVAL);
1021 	tmp_off = uio->uio_offset + uio->uio_resid;
1022 	if (tmp_off > nmp->nm_maxfilesize || tmp_off < uio->uio_offset)
1023 		return (EFBIG);
1024 	if (uio->uio_resid == 0)
1025 		return (0);
1026 
1027 	/*
1028 	 * Do IO_APPEND writing via a synchronous direct write.
1029 	 * This can result in a significant performance improvement.
1030 	 */
1031 	if ((newnfs_directio_enable && (ioflag & IO_DIRECT)) ||
1032 	    (ioflag & IO_APPEND)) {
1033 		/*
1034 		 * Direct writes to the server must be done NFSWRITE_FILESYNC,
1035 		 * because the write data is not cached and, therefore, the
1036 		 * write cannot be redone after a server reboot.
1037 		 * Set IO_SYNC to make this happen.
1038 		 */
1039 		ioflag |= IO_SYNC;
1040 		return (nfs_directio_write(vp, uio, cred, ioflag));
1041 	}
1042 
1043 	/*
1044 	 * Maybe this should be above the vnode op call, but so long as
1045 	 * file servers have no limits, i don't think it matters
1046 	 */
1047 	error = vn_rlimit_fsize(vp, uio, td);
1048 	if (error != 0)
1049 		return (error);
1050 
1051 	save2 = curthread_pflags2_set(TDP2_SBPAGES);
1052 	biosize = vp->v_bufobj.bo_bsize;
1053 	/*
1054 	 * Find all of this file's B_NEEDCOMMIT buffers.  If our writes
1055 	 * would exceed the local maximum per-file write commit size when
1056 	 * combined with those, we must decide whether to flush,
1057 	 * go synchronous, or return error.  We don't bother checking
1058 	 * IO_UNIT -- we just make all writes atomic anyway, as there's
1059 	 * no point optimizing for something that really won't ever happen.
1060 	 */
1061 	wouldcommit = 0;
1062 	if (!(ioflag & IO_SYNC)) {
1063 		int nflag;
1064 
1065 		NFSLOCKNODE(np);
1066 		nflag = np->n_flag;
1067 		NFSUNLOCKNODE(np);
1068 		if (nflag & NMODIFIED) {
1069 			BO_LOCK(&vp->v_bufobj);
1070 			if (vp->v_bufobj.bo_dirty.bv_cnt != 0) {
1071 				TAILQ_FOREACH(bp, &vp->v_bufobj.bo_dirty.bv_hd,
1072 				    b_bobufs) {
1073 					if (bp->b_flags & B_NEEDCOMMIT)
1074 						wouldcommit += bp->b_bcount;
1075 				}
1076 			}
1077 			BO_UNLOCK(&vp->v_bufobj);
1078 		}
1079 	}
1080 
1081 	do {
1082 		if (!(ioflag & IO_SYNC)) {
1083 			wouldcommit += biosize;
1084 			if (wouldcommit > nmp->nm_wcommitsize) {
1085 				np->n_attrstamp = 0;
1086 				KDTRACE_NFS_ATTRCACHE_FLUSH_DONE(vp);
1087 				error = ncl_vinvalbuf(vp, V_SAVE | ((ioflag &
1088 				    IO_VMIO) != 0 ? V_VMIO : 0), td, 1);
1089 				if (error != 0)
1090 					goto out;
1091 				wouldcommit = biosize;
1092 			}
1093 		}
1094 
1095 		NFSINCRGLOBAL(nfsstatsv1.biocache_writes);
1096 		lbn = uio->uio_offset / biosize;
1097 		on = uio->uio_offset - (lbn * biosize);
1098 		n = MIN((unsigned)(biosize - on), uio->uio_resid);
1099 again:
1100 		/*
1101 		 * Handle direct append and file extension cases, calculate
1102 		 * unaligned buffer size.
1103 		 */
1104 		NFSLOCKNODE(np);
1105 		if ((np->n_flag & NHASBEENLOCKED) == 0 &&
1106 		    (nmp->nm_flag & NFSMNT_NONCONTIGWR) != 0)
1107 			noncontig_write = 1;
1108 		else
1109 			noncontig_write = 0;
1110 		if ((uio->uio_offset == np->n_size ||
1111 		    (noncontig_write != 0 &&
1112 		    lbn == (np->n_size / biosize) &&
1113 		    uio->uio_offset + n > np->n_size)) && n) {
1114 			NFSUNLOCKNODE(np);
1115 			/*
1116 			 * Get the buffer (in its pre-append state to maintain
1117 			 * B_CACHE if it was previously set).  Resize the
1118 			 * nfsnode after we have locked the buffer to prevent
1119 			 * readers from reading garbage.
1120 			 */
1121 			obcount = np->n_size - (lbn * biosize);
1122 			bp = nfs_getcacheblk(vp, lbn, obcount, td);
1123 
1124 			if (bp != NULL) {
1125 				long save;
1126 
1127 				NFSLOCKNODE(np);
1128 				np->n_size = uio->uio_offset + n;
1129 				np->n_flag |= NMODIFIED;
1130 				np->n_flag &= ~NVNSETSZSKIP;
1131 				vnode_pager_setsize(vp, np->n_size);
1132 				NFSUNLOCKNODE(np);
1133 
1134 				save = bp->b_flags & B_CACHE;
1135 				bcount = on + n;
1136 				allocbuf(bp, bcount);
1137 				bp->b_flags |= save;
1138 				if (noncontig_write != 0 && on > obcount)
1139 					vfs_bio_bzero_buf(bp, obcount, on -
1140 					    obcount);
1141 			}
1142 		} else {
1143 			/*
1144 			 * Obtain the locked cache block first, and then
1145 			 * adjust the file's size as appropriate.
1146 			 */
1147 			bcount = on + n;
1148 			if ((off_t)lbn * biosize + bcount < np->n_size) {
1149 				if ((off_t)(lbn + 1) * biosize < np->n_size)
1150 					bcount = biosize;
1151 				else
1152 					bcount = np->n_size - (off_t)lbn * biosize;
1153 			}
1154 			NFSUNLOCKNODE(np);
1155 			bp = nfs_getcacheblk(vp, lbn, bcount, td);
1156 			NFSLOCKNODE(np);
1157 			if (uio->uio_offset + n > np->n_size) {
1158 				np->n_size = uio->uio_offset + n;
1159 				np->n_flag |= NMODIFIED;
1160 				np->n_flag &= ~NVNSETSZSKIP;
1161 				vnode_pager_setsize(vp, np->n_size);
1162 			}
1163 			NFSUNLOCKNODE(np);
1164 		}
1165 
1166 		if (!bp) {
1167 			error = newnfs_sigintr(nmp, td);
1168 			if (!error)
1169 				error = EINTR;
1170 			break;
1171 		}
1172 
1173 		/*
1174 		 * Issue a READ if B_CACHE is not set.  In special-append
1175 		 * mode, B_CACHE is based on the buffer prior to the write
1176 		 * op and is typically set, avoiding the read.  If a read
1177 		 * is required in special append mode, the server will
1178 		 * probably send us a short-read since we extended the file
1179 		 * on our end, resulting in b_resid == 0 and, thusly,
1180 		 * B_CACHE getting set.
1181 		 *
1182 		 * We can also avoid issuing the read if the write covers
1183 		 * the entire buffer.  We have to make sure the buffer state
1184 		 * is reasonable in this case since we will not be initiating
1185 		 * I/O.  See the comments in kern/vfs_bio.c's getblk() for
1186 		 * more information.
1187 		 *
1188 		 * B_CACHE may also be set due to the buffer being cached
1189 		 * normally.
1190 		 */
1191 
1192 		bp_cached = 1;
1193 		if (on == 0 && n == bcount) {
1194 			if ((bp->b_flags & B_CACHE) == 0)
1195 				bp_cached = 0;
1196 			bp->b_flags |= B_CACHE;
1197 			bp->b_flags &= ~B_INVAL;
1198 			bp->b_ioflags &= ~BIO_ERROR;
1199 		}
1200 
1201 		if ((bp->b_flags & B_CACHE) == 0) {
1202 			bp->b_iocmd = BIO_READ;
1203 			vfs_busy_pages(bp, 0);
1204 			error = ncl_doio(vp, bp, cred, td, 0);
1205 			if (error) {
1206 				brelse(bp);
1207 				break;
1208 			}
1209 		}
1210 		if (bp->b_wcred == NOCRED)
1211 			bp->b_wcred = crhold(cred);
1212 		NFSLOCKNODE(np);
1213 		np->n_flag |= NMODIFIED;
1214 		NFSUNLOCKNODE(np);
1215 
1216 		/*
1217 		 * If dirtyend exceeds file size, chop it down.  This should
1218 		 * not normally occur but there is an append race where it
1219 		 * might occur XXX, so we log it.
1220 		 *
1221 		 * If the chopping creates a reverse-indexed or degenerate
1222 		 * situation with dirtyoff/end, we 0 both of them.
1223 		 */
1224 
1225 		if (bp->b_dirtyend > bcount) {
1226 			printf("NFS append race @%lx:%d\n",
1227 			    (long)bp->b_blkno * DEV_BSIZE,
1228 			    bp->b_dirtyend - bcount);
1229 			bp->b_dirtyend = bcount;
1230 		}
1231 
1232 		if (bp->b_dirtyoff >= bp->b_dirtyend)
1233 			bp->b_dirtyoff = bp->b_dirtyend = 0;
1234 
1235 		/*
1236 		 * If the new write will leave a contiguous dirty
1237 		 * area, just update the b_dirtyoff and b_dirtyend,
1238 		 * otherwise force a write rpc of the old dirty area.
1239 		 *
1240 		 * If there has been a file lock applied to this file
1241 		 * or vfs.nfs.old_noncontig_writing is set, do the following:
1242 		 * While it is possible to merge discontiguous writes due to
1243 		 * our having a B_CACHE buffer ( and thus valid read data
1244 		 * for the hole), we don't because it could lead to
1245 		 * significant cache coherency problems with multiple clients,
1246 		 * especially if locking is implemented later on.
1247 		 *
1248 		 * If vfs.nfs.old_noncontig_writing is not set and there has
1249 		 * not been file locking done on this file:
1250 		 * Relax coherency a bit for the sake of performance and
1251 		 * expand the current dirty region to contain the new
1252 		 * write even if it means we mark some non-dirty data as
1253 		 * dirty.
1254 		 */
1255 
1256 		if (noncontig_write == 0 && bp->b_dirtyend > 0 &&
1257 		    (on > bp->b_dirtyend || (on + n) < bp->b_dirtyoff)) {
1258 			if (bwrite(bp) == EINTR) {
1259 				error = EINTR;
1260 				break;
1261 			}
1262 			goto again;
1263 		}
1264 
1265 		local_resid = uio->uio_resid;
1266 		error = vn_io_fault_uiomove((char *)bp->b_data + on, n, uio);
1267 
1268 		if (error != 0 && !bp_cached) {
1269 			/*
1270 			 * This block has no other content then what
1271 			 * possibly was written by the faulty uiomove.
1272 			 * Release it, forgetting the data pages, to
1273 			 * prevent the leak of uninitialized data to
1274 			 * usermode.
1275 			 */
1276 			bp->b_ioflags |= BIO_ERROR;
1277 			brelse(bp);
1278 			uio->uio_offset -= local_resid - uio->uio_resid;
1279 			uio->uio_resid = local_resid;
1280 			break;
1281 		}
1282 
1283 		/*
1284 		 * Since this block is being modified, it must be written
1285 		 * again and not just committed.  Since write clustering does
1286 		 * not work for the stage 1 data write, only the stage 2
1287 		 * commit rpc, we have to clear B_CLUSTEROK as well.
1288 		 */
1289 		bp->b_flags &= ~(B_NEEDCOMMIT | B_CLUSTEROK);
1290 
1291 		/*
1292 		 * Get the partial update on the progress made from
1293 		 * uiomove, if an error occurred.
1294 		 */
1295 		if (error != 0)
1296 			n = local_resid - uio->uio_resid;
1297 
1298 		/*
1299 		 * Only update dirtyoff/dirtyend if not a degenerate
1300 		 * condition.
1301 		 */
1302 		if (n > 0) {
1303 			if (bp->b_dirtyend > 0) {
1304 				bp->b_dirtyoff = min(on, bp->b_dirtyoff);
1305 				bp->b_dirtyend = max((on + n), bp->b_dirtyend);
1306 			} else {
1307 				bp->b_dirtyoff = on;
1308 				bp->b_dirtyend = on + n;
1309 			}
1310 			vfs_bio_set_valid(bp, on, n);
1311 		}
1312 
1313 		/*
1314 		 * If IO_SYNC do bwrite().
1315 		 *
1316 		 * IO_INVAL appears to be unused.  The idea appears to be
1317 		 * to turn off caching in this case.  Very odd.  XXX
1318 		 */
1319 		if ((ioflag & IO_SYNC)) {
1320 			if (ioflag & IO_INVAL)
1321 				bp->b_flags |= B_NOCACHE;
1322 			error1 = bwrite(bp);
1323 			if (error1 != 0) {
1324 				if (error == 0)
1325 					error = error1;
1326 				break;
1327 			}
1328 		} else if ((n + on) == biosize || (ioflag & IO_ASYNC) != 0) {
1329 			bp->b_flags |= B_ASYNC;
1330 			(void) bwrite(bp);
1331 		} else {
1332 			bdwrite(bp);
1333 		}
1334 
1335 		if (error != 0)
1336 			break;
1337 	} while (uio->uio_resid > 0 && n > 0);
1338 
1339 	if (error == 0) {
1340 		nanouptime(&ts);
1341 		NFSLOCKNODE(np);
1342 		np->n_localmodtime = ts;
1343 		NFSUNLOCKNODE(np);
1344 	} else {
1345 		if (ioflag & IO_UNIT) {
1346 			VATTR_NULL(&vattr);
1347 			vattr.va_size = orig_size;
1348 			/* IO_SYNC is handled implicitely */
1349 			(void)VOP_SETATTR(vp, &vattr, cred);
1350 			uio->uio_offset -= orig_resid - uio->uio_resid;
1351 			uio->uio_resid = orig_resid;
1352 		}
1353 	}
1354 
1355 out:
1356 	curthread_pflags2_restore(save2);
1357 	return (error);
1358 }
1359 
1360 /*
1361  * Get an nfs cache block.
1362  *
1363  * Allocate a new one if the block isn't currently in the cache
1364  * and return the block marked busy. If the calling process is
1365  * interrupted by a signal for an interruptible mount point, return
1366  * NULL.
1367  *
1368  * The caller must carefully deal with the possible B_INVAL state of
1369  * the buffer.  ncl_doio() clears B_INVAL (and ncl_asyncio() clears it
1370  * indirectly), so synchronous reads can be issued without worrying about
1371  * the B_INVAL state.  We have to be a little more careful when dealing
1372  * with writes (see comments in nfs_write()) when extending a file past
1373  * its EOF.
1374  */
1375 static struct buf *
1376 nfs_getcacheblk(struct vnode *vp, daddr_t bn, int size, struct thread *td)
1377 {
1378 	struct buf *bp;
1379 	struct mount *mp;
1380 	struct nfsmount *nmp;
1381 
1382 	mp = vp->v_mount;
1383 	nmp = VFSTONFS(mp);
1384 
1385 	if (nmp->nm_flag & NFSMNT_INT) {
1386 		sigset_t oldset;
1387 
1388 		newnfs_set_sigmask(td, &oldset);
1389 		bp = getblk(vp, bn, size, PCATCH, 0, 0);
1390 		newnfs_restore_sigmask(td, &oldset);
1391 		while (bp == NULL) {
1392 			if (newnfs_sigintr(nmp, td))
1393 				return (NULL);
1394 			bp = getblk(vp, bn, size, 0, 2 * hz, 0);
1395 		}
1396 	} else {
1397 		bp = getblk(vp, bn, size, 0, 0, 0);
1398 	}
1399 
1400 	if (vp->v_type == VREG)
1401 		bp->b_blkno = bn * (vp->v_bufobj.bo_bsize / DEV_BSIZE);
1402 	return (bp);
1403 }
1404 
1405 /*
1406  * Flush and invalidate all dirty buffers. If another process is already
1407  * doing the flush, just wait for completion.
1408  */
1409 int
1410 ncl_vinvalbuf(struct vnode *vp, int flags, struct thread *td, int intrflg)
1411 {
1412 	struct nfsnode *np = VTONFS(vp);
1413 	struct nfsmount *nmp = VFSTONFS(vp->v_mount);
1414 	int error = 0, slpflag, slptimeo;
1415 	bool old_lock;
1416 	struct timespec ts;
1417 
1418 	ASSERT_VOP_LOCKED(vp, "ncl_vinvalbuf");
1419 
1420 	if ((nmp->nm_flag & NFSMNT_INT) == 0)
1421 		intrflg = 0;
1422 	if (NFSCL_FORCEDISM(nmp->nm_mountp))
1423 		intrflg = 1;
1424 	if (intrflg) {
1425 		slpflag = PCATCH;
1426 		slptimeo = 2 * hz;
1427 	} else {
1428 		slpflag = 0;
1429 		slptimeo = 0;
1430 	}
1431 
1432 	old_lock = ncl_excl_start(vp);
1433 	if (old_lock)
1434 		flags |= V_ALLOWCLEAN;
1435 
1436 	/*
1437 	 * Now, flush as required.
1438 	 */
1439 	if ((flags & (V_SAVE | V_VMIO)) == V_SAVE) {
1440 		vnode_pager_clean_sync(vp);
1441 
1442 		/*
1443 		 * If the page clean was interrupted, fail the invalidation.
1444 		 * Not doing so, we run the risk of losing dirty pages in the
1445 		 * vinvalbuf() call below.
1446 		 */
1447 		if (intrflg && (error = newnfs_sigintr(nmp, td)))
1448 			goto out;
1449 	}
1450 
1451 	error = vinvalbuf(vp, flags, slpflag, 0);
1452 	while (error) {
1453 		if (intrflg && (error = newnfs_sigintr(nmp, td)))
1454 			goto out;
1455 		error = vinvalbuf(vp, flags, 0, slptimeo);
1456 	}
1457 	if (NFSHASPNFS(nmp)) {
1458 		nfscl_layoutcommit(vp, td);
1459 		nanouptime(&ts);
1460 		/*
1461 		 * Invalidate the attribute cache, since writes to a DS
1462 		 * won't update the size attribute.
1463 		 */
1464 		NFSLOCKNODE(np);
1465 		np->n_attrstamp = 0;
1466 	} else {
1467 		nanouptime(&ts);
1468 		NFSLOCKNODE(np);
1469 	}
1470 	if (np->n_directio_asyncwr == 0 && (np->n_flag & NMODIFIED) != 0) {
1471 		np->n_localmodtime = ts;
1472 		np->n_flag &= ~NMODIFIED;
1473 	}
1474 	NFSUNLOCKNODE(np);
1475 out:
1476 	ncl_excl_finish(vp, old_lock);
1477 	return error;
1478 }
1479 
1480 /*
1481  * Initiate asynchronous I/O. Return an error if no nfsiods are available.
1482  * This is mainly to avoid queueing async I/O requests when the nfsiods
1483  * are all hung on a dead server.
1484  *
1485  * Note: ncl_asyncio() does not clear (BIO_ERROR|B_INVAL) but when the bp
1486  * is eventually dequeued by the async daemon, ncl_doio() *will*.
1487  */
1488 int
1489 ncl_asyncio(struct nfsmount *nmp, struct buf *bp, struct ucred *cred, struct thread *td)
1490 {
1491 	int iod;
1492 	int gotiod;
1493 	int slpflag = 0;
1494 	int slptimeo = 0;
1495 	int error, error2;
1496 
1497 	/*
1498 	 * Commits are usually short and sweet so lets save some cpu and
1499 	 * leave the async daemons for more important rpc's (such as reads
1500 	 * and writes).
1501 	 *
1502 	 * Readdirplus RPCs do vget()s to acquire the vnodes for entries
1503 	 * in the directory in order to update attributes. This can deadlock
1504 	 * with another thread that is waiting for async I/O to be done by
1505 	 * an nfsiod thread while holding a lock on one of these vnodes.
1506 	 * To avoid this deadlock, don't allow the async nfsiod threads to
1507 	 * perform Readdirplus RPCs.
1508 	 */
1509 	NFSLOCKIOD();
1510 	if ((bp->b_iocmd == BIO_WRITE && (bp->b_flags & B_NEEDCOMMIT) &&
1511 	     (nmp->nm_bufqiods > ncl_numasync / 2)) ||
1512 	    (bp->b_vp->v_type == VDIR && (nmp->nm_flag & NFSMNT_RDIRPLUS))) {
1513 		NFSUNLOCKIOD();
1514 		return(EIO);
1515 	}
1516 again:
1517 	if (nmp->nm_flag & NFSMNT_INT)
1518 		slpflag = PCATCH;
1519 	gotiod = FALSE;
1520 
1521 	/*
1522 	 * Find a free iod to process this request.
1523 	 */
1524 	for (iod = 0; iod < ncl_numasync; iod++)
1525 		if (ncl_iodwant[iod] == NFSIOD_AVAILABLE) {
1526 			gotiod = TRUE;
1527 			break;
1528 		}
1529 
1530 	/*
1531 	 * Try to create one if none are free.
1532 	 */
1533 	if (!gotiod)
1534 		ncl_nfsiodnew();
1535 	else {
1536 		/*
1537 		 * Found one, so wake it up and tell it which
1538 		 * mount to process.
1539 		 */
1540 		NFS_DPF(ASYNCIO, ("ncl_asyncio: waking iod %d for mount %p\n",
1541 		    iod, nmp));
1542 		ncl_iodwant[iod] = NFSIOD_NOT_AVAILABLE;
1543 		ncl_iodmount[iod] = nmp;
1544 		nmp->nm_bufqiods++;
1545 		wakeup(&ncl_iodwant[iod]);
1546 	}
1547 
1548 	/*
1549 	 * If none are free, we may already have an iod working on this mount
1550 	 * point.  If so, it will process our request.
1551 	 */
1552 	if (!gotiod) {
1553 		if (nmp->nm_bufqiods > 0) {
1554 			NFS_DPF(ASYNCIO,
1555 				("ncl_asyncio: %d iods are already processing mount %p\n",
1556 				 nmp->nm_bufqiods, nmp));
1557 			gotiod = TRUE;
1558 		}
1559 	}
1560 
1561 	/*
1562 	 * If we have an iod which can process the request, then queue
1563 	 * the buffer.
1564 	 */
1565 	if (gotiod) {
1566 		/*
1567 		 * Ensure that the queue never grows too large.  We still want
1568 		 * to asynchronize so we block rather then return EIO.
1569 		 */
1570 		while (nmp->nm_bufqlen >= 2*ncl_numasync) {
1571 			NFS_DPF(ASYNCIO,
1572 				("ncl_asyncio: waiting for mount %p queue to drain\n", nmp));
1573 			nmp->nm_bufqwant = TRUE;
1574 			error = newnfs_msleep(td, &nmp->nm_bufq,
1575 			    &ncl_iod_mutex, slpflag | PRIBIO, "nfsaio",
1576 			   slptimeo);
1577 			if (error) {
1578 				error2 = newnfs_sigintr(nmp, td);
1579 				if (error2) {
1580 					NFSUNLOCKIOD();
1581 					return (error2);
1582 				}
1583 				if (slpflag == PCATCH) {
1584 					slpflag = 0;
1585 					slptimeo = 2 * hz;
1586 				}
1587 			}
1588 			/*
1589 			 * We might have lost our iod while sleeping,
1590 			 * so check and loop if necessary.
1591 			 */
1592 			goto again;
1593 		}
1594 
1595 		/* We might have lost our nfsiod */
1596 		if (nmp->nm_bufqiods == 0) {
1597 			NFS_DPF(ASYNCIO,
1598 				("ncl_asyncio: no iods after mount %p queue was drained, looping\n", nmp));
1599 			goto again;
1600 		}
1601 
1602 		if (bp->b_iocmd == BIO_READ) {
1603 			if (bp->b_rcred == NOCRED && cred != NOCRED)
1604 				bp->b_rcred = crhold(cred);
1605 		} else {
1606 			if (bp->b_wcred == NOCRED && cred != NOCRED)
1607 				bp->b_wcred = crhold(cred);
1608 		}
1609 
1610 		if (bp->b_flags & B_REMFREE)
1611 			bremfreef(bp);
1612 		BUF_KERNPROC(bp);
1613 		TAILQ_INSERT_TAIL(&nmp->nm_bufq, bp, b_freelist);
1614 		nmp->nm_bufqlen++;
1615 		if ((bp->b_flags & B_DIRECT) && bp->b_iocmd == BIO_WRITE) {
1616 			NFSLOCKNODE(VTONFS(bp->b_vp));
1617 			VTONFS(bp->b_vp)->n_flag |= NMODIFIED;
1618 			VTONFS(bp->b_vp)->n_directio_asyncwr++;
1619 			NFSUNLOCKNODE(VTONFS(bp->b_vp));
1620 		}
1621 		NFSUNLOCKIOD();
1622 		return (0);
1623 	}
1624 
1625 	NFSUNLOCKIOD();
1626 
1627 	/*
1628 	 * All the iods are busy on other mounts, so return EIO to
1629 	 * force the caller to process the i/o synchronously.
1630 	 */
1631 	NFS_DPF(ASYNCIO, ("ncl_asyncio: no iods available, i/o is synchronous\n"));
1632 	return (EIO);
1633 }
1634 
1635 void
1636 ncl_doio_directwrite(struct buf *bp)
1637 {
1638 	int iomode, must_commit;
1639 	struct uio *uiop = (struct uio *)bp->b_caller1;
1640 	char *iov_base = uiop->uio_iov->iov_base;
1641 
1642 	iomode = NFSWRITE_FILESYNC;
1643 	uiop->uio_td = NULL; /* NULL since we're in nfsiod */
1644 	/*
1645 	 * When doing direct I/O we do not care if the
1646 	 * server's write verifier has changed, but we
1647 	 * do not want to update the verifier if it has
1648 	 * changed, since that hides the change from
1649 	 * writes being done through the buffer cache.
1650 	 * By passing must_commit in set to two, the code
1651 	 * in nfsrpc_writerpc() will not update the
1652 	 * verifier on the mount point.
1653 	 */
1654 	must_commit = 2;
1655 	ncl_writerpc(bp->b_vp, uiop, bp->b_wcred, &iomode, &must_commit, 0, 0);
1656 	KASSERT((must_commit == 2), ("ncl_doio_directwrite: Updated write"
1657 	    " verifier"));
1658 	if (iomode != NFSWRITE_FILESYNC)
1659 		printf("ncl_doio_directwrite: Broken server "
1660 		    "did not reply FILE_SYNC\n");
1661 	free(iov_base, M_NFSDIRECTIO);
1662 	free(uiop->uio_iov, M_NFSDIRECTIO);
1663 	free(uiop, M_NFSDIRECTIO);
1664 	if ((bp->b_flags & B_DIRECT) && bp->b_iocmd == BIO_WRITE) {
1665 		struct nfsnode *np = VTONFS(bp->b_vp);
1666 		NFSLOCKNODE(np);
1667 		if (NFSHASPNFS(VFSTONFS(bp->b_vp->v_mount))) {
1668 			/*
1669 			 * Invalidate the attribute cache, since writes to a DS
1670 			 * won't update the size attribute.
1671 			 */
1672 			np->n_attrstamp = 0;
1673 		}
1674 		np->n_directio_asyncwr--;
1675 		if (np->n_directio_asyncwr == 0) {
1676 			np->n_flag &= ~NMODIFIED;
1677 			if ((np->n_flag & NFSYNCWAIT)) {
1678 				np->n_flag &= ~NFSYNCWAIT;
1679 				wakeup((caddr_t)&np->n_directio_asyncwr);
1680 			}
1681 		}
1682 		NFSUNLOCKNODE(np);
1683 	}
1684 	bp->b_vp = NULL;
1685 	uma_zfree(ncl_pbuf_zone, bp);
1686 }
1687 
1688 /*
1689  * Do an I/O operation to/from a cache block. This may be called
1690  * synchronously or from an nfsiod.
1691  */
1692 int
1693 ncl_doio(struct vnode *vp, struct buf *bp, struct ucred *cr, struct thread *td,
1694     int called_from_strategy)
1695 {
1696 	struct uio *uiop;
1697 	struct nfsnode *np;
1698 	struct nfsmount *nmp;
1699 	int error = 0, iomode, must_commit = 0;
1700 	struct uio uio;
1701 	struct iovec io;
1702 	struct proc *p = td ? td->td_proc : NULL;
1703 	uint8_t	iocmd;
1704 
1705 	np = VTONFS(vp);
1706 	nmp = VFSTONFS(vp->v_mount);
1707 	uiop = &uio;
1708 	uiop->uio_iov = &io;
1709 	uiop->uio_iovcnt = 1;
1710 	uiop->uio_segflg = UIO_SYSSPACE;
1711 	uiop->uio_td = td;
1712 
1713 	/*
1714 	 * clear BIO_ERROR and B_INVAL state prior to initiating the I/O.  We
1715 	 * do this here so we do not have to do it in all the code that
1716 	 * calls us.
1717 	 */
1718 	bp->b_flags &= ~B_INVAL;
1719 	bp->b_ioflags &= ~BIO_ERROR;
1720 
1721 	KASSERT(!(bp->b_flags & B_DONE), ("ncl_doio: bp %p already marked done", bp));
1722 	iocmd = bp->b_iocmd;
1723 	if (iocmd == BIO_READ) {
1724 	    io.iov_len = uiop->uio_resid = bp->b_bcount;
1725 	    io.iov_base = bp->b_data;
1726 	    uiop->uio_rw = UIO_READ;
1727 
1728 	    switch (vp->v_type) {
1729 	    case VREG:
1730 		uiop->uio_offset = ((off_t)bp->b_blkno) * DEV_BSIZE;
1731 		NFSINCRGLOBAL(nfsstatsv1.read_bios);
1732 		error = ncl_readrpc(vp, uiop, cr);
1733 
1734 		if (!error) {
1735 		    if (uiop->uio_resid) {
1736 			/*
1737 			 * If we had a short read with no error, we must have
1738 			 * hit a file hole.  We should zero-fill the remainder.
1739 			 * This can also occur if the server hits the file EOF.
1740 			 *
1741 			 * Holes used to be able to occur due to pending
1742 			 * writes, but that is not possible any longer.
1743 			 */
1744 			int nread = bp->b_bcount - uiop->uio_resid;
1745 			ssize_t left = uiop->uio_resid;
1746 
1747 			if (left > 0)
1748 				bzero((char *)bp->b_data + nread, left);
1749 			uiop->uio_resid = 0;
1750 		    }
1751 		}
1752 		/* ASSERT_VOP_LOCKED(vp, "ncl_doio"); */
1753 		if (p && vp->v_writecount <= -1) {
1754 			NFSLOCKNODE(np);
1755 			if (NFS_TIMESPEC_COMPARE(&np->n_mtime, &np->n_vattr.na_mtime)) {
1756 				NFSUNLOCKNODE(np);
1757 				PROC_LOCK(p);
1758 				killproc(p, "text file modification");
1759 				PROC_UNLOCK(p);
1760 			} else
1761 				NFSUNLOCKNODE(np);
1762 		}
1763 		break;
1764 	    case VLNK:
1765 		uiop->uio_offset = (off_t)0;
1766 		NFSINCRGLOBAL(nfsstatsv1.readlink_bios);
1767 		error = ncl_readlinkrpc(vp, uiop, cr);
1768 		break;
1769 	    case VDIR:
1770 		NFSINCRGLOBAL(nfsstatsv1.readdir_bios);
1771 		uiop->uio_offset = ((u_quad_t)bp->b_lblkno) * NFS_DIRBLKSIZ;
1772 		if ((nmp->nm_flag & NFSMNT_RDIRPLUS) != 0) {
1773 			error = ncl_readdirplusrpc(vp, uiop, cr, td);
1774 			if (error == NFSERR_NOTSUPP)
1775 				nmp->nm_flag &= ~NFSMNT_RDIRPLUS;
1776 		}
1777 		if ((nmp->nm_flag & NFSMNT_RDIRPLUS) == 0)
1778 			error = ncl_readdirrpc(vp, uiop, cr, td);
1779 		/*
1780 		 * end-of-directory sets B_INVAL but does not generate an
1781 		 * error.
1782 		 */
1783 		if (error == 0 && uiop->uio_resid == bp->b_bcount)
1784 			bp->b_flags |= B_INVAL;
1785 		break;
1786 	    default:
1787 		printf("ncl_doio:  type %x unexpected\n", vp->v_type);
1788 		break;
1789 	    }
1790 	    if (error) {
1791 		bp->b_ioflags |= BIO_ERROR;
1792 		bp->b_error = error;
1793 	    }
1794 	} else {
1795 	    /*
1796 	     * If we only need to commit, try to commit
1797 	     */
1798 	    if (bp->b_flags & B_NEEDCOMMIT) {
1799 		    int retv;
1800 		    off_t off;
1801 
1802 		    off = ((u_quad_t)bp->b_blkno) * DEV_BSIZE + bp->b_dirtyoff;
1803 		    retv = ncl_commit(vp, off, bp->b_dirtyend-bp->b_dirtyoff,
1804 			bp->b_wcred, td);
1805 		    if (NFSCL_FORCEDISM(vp->v_mount) || retv == 0) {
1806 			    bp->b_dirtyoff = bp->b_dirtyend = 0;
1807 			    bp->b_flags &= ~(B_NEEDCOMMIT | B_CLUSTEROK);
1808 			    bp->b_resid = 0;
1809 			    bufdone(bp);
1810 			    return (0);
1811 		    }
1812 		    if (retv == NFSERR_STALEWRITEVERF) {
1813 			    ncl_clearcommit(vp->v_mount);
1814 		    }
1815 	    }
1816 
1817 	    /*
1818 	     * Setup for actual write
1819 	     */
1820 	    NFSLOCKNODE(np);
1821 	    if ((off_t)bp->b_blkno * DEV_BSIZE + bp->b_dirtyend > np->n_size)
1822 		bp->b_dirtyend = np->n_size - (off_t)bp->b_blkno * DEV_BSIZE;
1823 	    NFSUNLOCKNODE(np);
1824 
1825 	    if (bp->b_dirtyend > bp->b_dirtyoff) {
1826 		io.iov_len = uiop->uio_resid = bp->b_dirtyend
1827 		    - bp->b_dirtyoff;
1828 		uiop->uio_offset = (off_t)bp->b_blkno * DEV_BSIZE
1829 		    + bp->b_dirtyoff;
1830 		io.iov_base = (char *)bp->b_data + bp->b_dirtyoff;
1831 		uiop->uio_rw = UIO_WRITE;
1832 		NFSINCRGLOBAL(nfsstatsv1.write_bios);
1833 
1834 		if ((bp->b_flags & (B_ASYNC | B_NEEDCOMMIT | B_NOCACHE | B_CLUSTER)) == B_ASYNC)
1835 		    iomode = NFSWRITE_UNSTABLE;
1836 		else
1837 		    iomode = NFSWRITE_FILESYNC;
1838 
1839 		error = ncl_writerpc(vp, uiop, cr, &iomode, &must_commit,
1840 		    called_from_strategy, 0);
1841 
1842 		/*
1843 		 * When setting B_NEEDCOMMIT also set B_CLUSTEROK to try
1844 		 * to cluster the buffers needing commit.  This will allow
1845 		 * the system to submit a single commit rpc for the whole
1846 		 * cluster.  We can do this even if the buffer is not 100%
1847 		 * dirty (relative to the NFS blocksize), so we optimize the
1848 		 * append-to-file-case.
1849 		 *
1850 		 * (when clearing B_NEEDCOMMIT, B_CLUSTEROK must also be
1851 		 * cleared because write clustering only works for commit
1852 		 * rpc's, not for the data portion of the write).
1853 		 */
1854 
1855 		if (!error && iomode == NFSWRITE_UNSTABLE) {
1856 		    bp->b_flags |= B_NEEDCOMMIT;
1857 		    if (bp->b_dirtyoff == 0
1858 			&& bp->b_dirtyend == bp->b_bcount)
1859 			bp->b_flags |= B_CLUSTEROK;
1860 		} else {
1861 		    bp->b_flags &= ~(B_NEEDCOMMIT | B_CLUSTEROK);
1862 		}
1863 
1864 		/*
1865 		 * For an interrupted write, the buffer is still valid
1866 		 * and the write hasn't been pushed to the server yet,
1867 		 * so we can't set BIO_ERROR and report the interruption
1868 		 * by setting B_EINTR. For the B_ASYNC case, B_EINTR
1869 		 * is not relevant, so the rpc attempt is essentially
1870 		 * a noop.  For the case of a V3 write rpc not being
1871 		 * committed to stable storage, the block is still
1872 		 * dirty and requires either a commit rpc or another
1873 		 * write rpc with iomode == NFSV3WRITE_FILESYNC before
1874 		 * the block is reused. This is indicated by setting
1875 		 * the B_DELWRI and B_NEEDCOMMIT flags.
1876 		 *
1877 		 * EIO is returned by ncl_writerpc() to indicate a recoverable
1878 		 * write error and is handled as above, except that
1879 		 * B_EINTR isn't set. One cause of this is a stale stateid
1880 		 * error for the RPC that indicates recovery is required,
1881 		 * when called with called_from_strategy != 0.
1882 		 *
1883 		 * If the buffer is marked B_PAGING, it does not reside on
1884 		 * the vp's paging queues so we cannot call bdirty().  The
1885 		 * bp in this case is not an NFS cache block so we should
1886 		 * be safe. XXX
1887 		 *
1888 		 * The logic below breaks up errors into recoverable and
1889 		 * unrecoverable. For the former, we clear B_INVAL|B_NOCACHE
1890 		 * and keep the buffer around for potential write retries.
1891 		 * For the latter (eg ESTALE), we toss the buffer away (B_INVAL)
1892 		 * and save the error in the nfsnode. This is less than ideal
1893 		 * but necessary. Keeping such buffers around could potentially
1894 		 * cause buffer exhaustion eventually (they can never be written
1895 		 * out, so will get constantly be re-dirtied). It also causes
1896 		 * all sorts of vfs panics. For non-recoverable write errors,
1897 		 * also invalidate the attrcache, so we'll be forced to go over
1898 		 * the wire for this object, returning an error to user on next
1899 		 * call (most of the time).
1900 		 */
1901 		if (error == EINTR || error == EIO || error == ETIMEDOUT
1902 		    || (!error && (bp->b_flags & B_NEEDCOMMIT))) {
1903 			bp->b_flags &= ~(B_INVAL|B_NOCACHE);
1904 			if ((bp->b_flags & B_PAGING) == 0) {
1905 			    bdirty(bp);
1906 			    bp->b_flags &= ~B_DONE;
1907 			}
1908 			if ((error == EINTR || error == ETIMEDOUT) &&
1909 			    (bp->b_flags & B_ASYNC) == 0)
1910 			    bp->b_flags |= B_EINTR;
1911 		} else {
1912 		    if (error) {
1913 			bp->b_ioflags |= BIO_ERROR;
1914 			bp->b_flags |= B_INVAL;
1915 			bp->b_error = np->n_error = error;
1916 			NFSLOCKNODE(np);
1917 			np->n_flag |= NWRITEERR;
1918 			np->n_attrstamp = 0;
1919 			KDTRACE_NFS_ATTRCACHE_FLUSH_DONE(vp);
1920 			NFSUNLOCKNODE(np);
1921 		    }
1922 		    bp->b_dirtyoff = bp->b_dirtyend = 0;
1923 		}
1924 	    } else {
1925 		bp->b_resid = 0;
1926 		bufdone(bp);
1927 		return (0);
1928 	    }
1929 	}
1930 	bp->b_resid = uiop->uio_resid;
1931 	if (must_commit == 1)
1932 	    ncl_clearcommit(vp->v_mount);
1933 	bufdone(bp);
1934 	return (error);
1935 }
1936 
1937 /*
1938  * Used to aid in handling ftruncate() operations on the NFS client side.
1939  * Truncation creates a number of special problems for NFS.  We have to
1940  * throw away VM pages and buffer cache buffers that are beyond EOF, and
1941  * we have to properly handle VM pages or (potentially dirty) buffers
1942  * that straddle the truncation point.
1943  */
1944 
1945 int
1946 ncl_meta_setsize(struct vnode *vp, struct thread *td, u_quad_t nsize)
1947 {
1948 	struct nfsnode *np = VTONFS(vp);
1949 	u_quad_t tsize;
1950 	int biosize = vp->v_bufobj.bo_bsize;
1951 	int error = 0;
1952 
1953 	NFSLOCKNODE(np);
1954 	tsize = np->n_size;
1955 	np->n_size = nsize;
1956 	NFSUNLOCKNODE(np);
1957 
1958 	if (nsize < tsize) {
1959 		struct buf *bp;
1960 		daddr_t lbn;
1961 		int bufsize;
1962 
1963 		/*
1964 		 * vtruncbuf() doesn't get the buffer overlapping the
1965 		 * truncation point.  We may have a B_DELWRI and/or B_CACHE
1966 		 * buffer that now needs to be truncated.
1967 		 */
1968 		error = vtruncbuf(vp, nsize, biosize);
1969 		lbn = nsize / biosize;
1970 		bufsize = nsize - (lbn * biosize);
1971 		bp = nfs_getcacheblk(vp, lbn, bufsize, td);
1972 		if (!bp)
1973 			return EINTR;
1974 		if (bp->b_dirtyoff > bp->b_bcount)
1975 			bp->b_dirtyoff = bp->b_bcount;
1976 		if (bp->b_dirtyend > bp->b_bcount)
1977 			bp->b_dirtyend = bp->b_bcount;
1978 		bp->b_flags |= B_RELBUF;  /* don't leave garbage around */
1979 		brelse(bp);
1980 	} else {
1981 		vnode_pager_setsize(vp, nsize);
1982 	}
1983 	return(error);
1984 }
1985