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