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