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