xref: /dragonfly/sys/vfs/nfs/nfs_bio.c (revision aa8d5dcb)
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  * 3. All advertising materials mentioning features or use of this software
17  *    must display the following acknowledgement:
18  *	This product includes software developed by the University of
19  *	California, Berkeley and its contributors.
20  * 4. Neither the name of the University nor the names of its contributors
21  *    may be used to endorse or promote products derived from this software
22  *    without specific prior written permission.
23  *
24  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
25  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
28  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
29  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
30  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
31  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
33  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34  * SUCH DAMAGE.
35  *
36  *	@(#)nfs_bio.c	8.9 (Berkeley) 3/30/95
37  * $FreeBSD: src/sys/nfs/nfs_bio.c,v 1.83.2.4 2002/12/29 18:19:53 dillon Exp $
38  * $DragonFly: src/sys/vfs/nfs/nfs_bio.c,v 1.12 2004/02/13 18:52:35 dillon Exp $
39  */
40 
41 
42 #include <sys/param.h>
43 #include <sys/systm.h>
44 #include <sys/resourcevar.h>
45 #include <sys/signalvar.h>
46 #include <sys/proc.h>
47 #include <sys/buf.h>
48 #include <sys/vnode.h>
49 #include <sys/mount.h>
50 #include <sys/kernel.h>
51 
52 #include <vm/vm.h>
53 #include <vm/vm_extern.h>
54 #include <vm/vm_page.h>
55 #include <vm/vm_object.h>
56 #include <vm/vm_pager.h>
57 #include <vm/vnode_pager.h>
58 
59 #include <sys/buf2.h>
60 
61 #include "rpcv2.h"
62 #include "nfsproto.h"
63 #include "nfs.h"
64 #include "nfsmount.h"
65 #include "nqnfs.h"
66 #include "nfsnode.h"
67 
68 static struct buf *nfs_getcacheblk (struct vnode *vp, daddr_t bn, int size,
69 					struct thread *td);
70 
71 extern int nfs_numasync;
72 extern int nfs_pbuf_freecnt;
73 extern struct nfsstats nfsstats;
74 
75 /*
76  * Vnode op for VM getpages.
77  */
78 int
79 nfs_getpages(ap)
80 	struct vop_getpages_args /* {
81 		struct vnode *a_vp;
82 		vm_page_t *a_m;
83 		int a_count;
84 		int a_reqpage;
85 		vm_ooffset_t a_offset;
86 	} */ *ap;
87 {
88 	struct thread *td = curthread;		/* XXX */
89 	int i, error, nextoff, size, toff, count, npages;
90 	struct uio uio;
91 	struct iovec iov;
92 	vm_offset_t kva;
93 	struct buf *bp;
94 	struct vnode *vp;
95 	struct nfsmount *nmp;
96 	vm_page_t *pages;
97 
98 	vp = ap->a_vp;
99 	nmp = VFSTONFS(vp->v_mount);
100 	pages = ap->a_m;
101 	count = ap->a_count;
102 
103 	if (vp->v_object == NULL) {
104 		printf("nfs_getpages: called with non-merged cache vnode??\n");
105 		return VM_PAGER_ERROR;
106 	}
107 
108 	if ((nmp->nm_flag & NFSMNT_NFSV3) != 0 &&
109 	    (nmp->nm_state & NFSSTA_GOTFSINFO) == 0)
110 		(void)nfs_fsinfo(nmp, vp, td);
111 
112 	npages = btoc(count);
113 
114 	/*
115 	 * If the requested page is partially valid, just return it and
116 	 * allow the pager to zero-out the blanks.  Partially valid pages
117 	 * can only occur at the file EOF.
118 	 */
119 
120 	{
121 		vm_page_t m = pages[ap->a_reqpage];
122 
123 		if (m->valid != 0) {
124 			/* handled by vm_fault now	  */
125 			/* vm_page_zero_invalid(m, TRUE); */
126 			for (i = 0; i < npages; ++i) {
127 				if (i != ap->a_reqpage)
128 					vnode_pager_freepage(pages[i]);
129 			}
130 			return(0);
131 		}
132 	}
133 
134 	/*
135 	 * We use only the kva address for the buffer, but this is extremely
136 	 * convienient and fast.
137 	 */
138 	bp = getpbuf(&nfs_pbuf_freecnt);
139 
140 	kva = (vm_offset_t) bp->b_data;
141 	pmap_qenter(kva, pages, npages);
142 
143 	iov.iov_base = (caddr_t) kva;
144 	iov.iov_len = count;
145 	uio.uio_iov = &iov;
146 	uio.uio_iovcnt = 1;
147 	uio.uio_offset = IDX_TO_OFF(pages[0]->pindex);
148 	uio.uio_resid = count;
149 	uio.uio_segflg = UIO_SYSSPACE;
150 	uio.uio_rw = UIO_READ;
151 	uio.uio_td = td;
152 
153 	error = nfs_readrpc(vp, &uio);
154 	pmap_qremove(kva, npages);
155 
156 	relpbuf(bp, &nfs_pbuf_freecnt);
157 
158 	if (error && (uio.uio_resid == count)) {
159 		printf("nfs_getpages: error %d\n", error);
160 		for (i = 0; i < npages; ++i) {
161 			if (i != ap->a_reqpage)
162 				vnode_pager_freepage(pages[i]);
163 		}
164 		return VM_PAGER_ERROR;
165 	}
166 
167 	/*
168 	 * Calculate the number of bytes read and validate only that number
169 	 * of bytes.  Note that due to pending writes, size may be 0.  This
170 	 * does not mean that the remaining data is invalid!
171 	 */
172 
173 	size = count - uio.uio_resid;
174 
175 	for (i = 0, toff = 0; i < npages; i++, toff = nextoff) {
176 		vm_page_t m;
177 		nextoff = toff + PAGE_SIZE;
178 		m = pages[i];
179 
180 		m->flags &= ~PG_ZERO;
181 
182 		if (nextoff <= size) {
183 			/*
184 			 * Read operation filled an entire page
185 			 */
186 			m->valid = VM_PAGE_BITS_ALL;
187 			vm_page_undirty(m);
188 		} else if (size > toff) {
189 			/*
190 			 * Read operation filled a partial page.
191 			 */
192 			m->valid = 0;
193 			vm_page_set_validclean(m, 0, size - toff);
194 			/* handled by vm_fault now	  */
195 			/* vm_page_zero_invalid(m, TRUE); */
196 		} else {
197 			/*
198 			 * Read operation was short.  If no error occured
199 			 * we may have hit a zero-fill section.   We simply
200 			 * leave valid set to 0.
201 			 */
202 			;
203 		}
204 		if (i != ap->a_reqpage) {
205 			/*
206 			 * Whether or not to leave the page activated is up in
207 			 * the air, but we should put the page on a page queue
208 			 * somewhere (it already is in the object).  Result:
209 			 * It appears that emperical results show that
210 			 * deactivating pages is best.
211 			 */
212 
213 			/*
214 			 * Just in case someone was asking for this page we
215 			 * now tell them that it is ok to use.
216 			 */
217 			if (!error) {
218 				if (m->flags & PG_WANTED)
219 					vm_page_activate(m);
220 				else
221 					vm_page_deactivate(m);
222 				vm_page_wakeup(m);
223 			} else {
224 				vnode_pager_freepage(m);
225 			}
226 		}
227 	}
228 	return 0;
229 }
230 
231 /*
232  * Vnode op for VM putpages.
233  */
234 int
235 nfs_putpages(ap)
236 	struct vop_putpages_args /* {
237 		struct vnode *a_vp;
238 		vm_page_t *a_m;
239 		int a_count;
240 		int a_sync;
241 		int *a_rtvals;
242 		vm_ooffset_t a_offset;
243 	} */ *ap;
244 {
245 	struct thread *td = curthread;
246 	struct uio uio;
247 	struct iovec iov;
248 	vm_offset_t kva;
249 	struct buf *bp;
250 	int iomode, must_commit, i, error, npages, count;
251 	off_t offset;
252 	int *rtvals;
253 	struct vnode *vp;
254 	struct nfsmount *nmp;
255 	struct nfsnode *np;
256 	vm_page_t *pages;
257 
258 	vp = ap->a_vp;
259 	np = VTONFS(vp);
260 	nmp = VFSTONFS(vp->v_mount);
261 	pages = ap->a_m;
262 	count = ap->a_count;
263 	rtvals = ap->a_rtvals;
264 	npages = btoc(count);
265 	offset = IDX_TO_OFF(pages[0]->pindex);
266 
267 	if ((nmp->nm_flag & NFSMNT_NFSV3) != 0 &&
268 	    (nmp->nm_state & NFSSTA_GOTFSINFO) == 0)
269 		(void)nfs_fsinfo(nmp, vp, td);
270 
271 	for (i = 0; i < npages; i++) {
272 		rtvals[i] = VM_PAGER_AGAIN;
273 	}
274 
275 	/*
276 	 * When putting pages, do not extend file past EOF.
277 	 */
278 
279 	if (offset + count > np->n_size) {
280 		count = np->n_size - offset;
281 		if (count < 0)
282 			count = 0;
283 	}
284 
285 	/*
286 	 * We use only the kva address for the buffer, but this is extremely
287 	 * convienient and fast.
288 	 */
289 	bp = getpbuf(&nfs_pbuf_freecnt);
290 
291 	kva = (vm_offset_t) bp->b_data;
292 	pmap_qenter(kva, pages, npages);
293 
294 	iov.iov_base = (caddr_t) kva;
295 	iov.iov_len = count;
296 	uio.uio_iov = &iov;
297 	uio.uio_iovcnt = 1;
298 	uio.uio_offset = offset;
299 	uio.uio_resid = count;
300 	uio.uio_segflg = UIO_SYSSPACE;
301 	uio.uio_rw = UIO_WRITE;
302 	uio.uio_td = td;
303 
304 	if ((ap->a_sync & VM_PAGER_PUT_SYNC) == 0)
305 	    iomode = NFSV3WRITE_UNSTABLE;
306 	else
307 	    iomode = NFSV3WRITE_FILESYNC;
308 
309 	error = nfs_writerpc(vp, &uio, &iomode, &must_commit);
310 
311 	pmap_qremove(kva, npages);
312 	relpbuf(bp, &nfs_pbuf_freecnt);
313 
314 	if (!error) {
315 		int nwritten = round_page(count - uio.uio_resid) / PAGE_SIZE;
316 		for (i = 0; i < nwritten; i++) {
317 			rtvals[i] = VM_PAGER_OK;
318 			vm_page_undirty(pages[i]);
319 		}
320 		if (must_commit)
321 			nfs_clearcommit(vp->v_mount);
322 	}
323 	return rtvals[0];
324 }
325 
326 /*
327  * Vnode op for read using bio
328  */
329 int
330 nfs_bioread(struct vnode *vp, struct uio *uio, int ioflag)
331 {
332 	struct nfsnode *np = VTONFS(vp);
333 	int biosize, i;
334 	struct buf *bp = 0, *rabp;
335 	struct vattr vattr;
336 	struct thread *td;
337 	struct nfsmount *nmp = VFSTONFS(vp->v_mount);
338 	daddr_t lbn, rabn;
339 	int bcount;
340 	int seqcount;
341 	int nra, error = 0, n = 0, on = 0;
342 
343 #ifdef DIAGNOSTIC
344 	if (uio->uio_rw != UIO_READ)
345 		panic("nfs_read mode");
346 #endif
347 	if (uio->uio_resid == 0)
348 		return (0);
349 	if (uio->uio_offset < 0)	/* XXX VDIR cookies can be negative */
350 		return (EINVAL);
351 	td = uio->uio_td;
352 
353 	if ((nmp->nm_flag & NFSMNT_NFSV3) != 0 &&
354 	    (nmp->nm_state & NFSSTA_GOTFSINFO) == 0)
355 		(void)nfs_fsinfo(nmp, vp, td);
356 	if (vp->v_type != VDIR &&
357 	    (uio->uio_offset + uio->uio_resid) > nmp->nm_maxfilesize)
358 		return (EFBIG);
359 	biosize = vp->v_mount->mnt_stat.f_iosize;
360 	seqcount = (int)((off_t)(ioflag >> IO_SEQSHIFT) * biosize / BKVASIZE);
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 nqnfs, full cache consistency is maintained within the loop.
366 	 * For nfs:
367 	 * If the file's modify time on the server has changed since the
368 	 * last read rpc or you have written to the file,
369 	 * you may have lost data cache consistency with the
370 	 * server, so flush all of the file's data out of the cache.
371 	 * Then force a getattr rpc to ensure that you have up to date
372 	 * attributes.
373 	 * NB: This implies that cache data can be read when up to
374 	 * NFS_ATTRTIMEO seconds out of date. If you find that you need current
375 	 * attributes this could be forced by setting n_attrstamp to 0 before
376 	 * the VOP_GETATTR() call.
377 	 */
378 	if ((nmp->nm_flag & NFSMNT_NQNFS) == 0) {
379 		if (np->n_flag & NMODIFIED) {
380 			if (vp->v_type != VREG) {
381 				if (vp->v_type != VDIR)
382 					panic("nfs: bioread, not dir");
383 				nfs_invaldir(vp);
384 				error = nfs_vinvalbuf(vp, V_SAVE, td, 1);
385 				if (error)
386 					return (error);
387 			}
388 			np->n_attrstamp = 0;
389 			error = VOP_GETATTR(vp, &vattr, td);
390 			if (error)
391 				return (error);
392 			np->n_mtime = vattr.va_mtime.tv_sec;
393 		} else {
394 			error = VOP_GETATTR(vp, &vattr, td);
395 			if (error)
396 				return (error);
397 			if (np->n_mtime != vattr.va_mtime.tv_sec) {
398 				if (vp->v_type == VDIR)
399 					nfs_invaldir(vp);
400 				error = nfs_vinvalbuf(vp, V_SAVE, td, 1);
401 				if (error)
402 					return (error);
403 				np->n_mtime = vattr.va_mtime.tv_sec;
404 			}
405 		}
406 	}
407 	do {
408 
409 	    /*
410 	     * Get a valid lease. If cached data is stale, flush it.
411 	     */
412 	    if (nmp->nm_flag & NFSMNT_NQNFS) {
413 		if (NQNFS_CKINVALID(vp, np, ND_READ)) {
414 		    do {
415 			error = nqnfs_getlease(vp, ND_READ, td);
416 		    } while (error == NQNFS_EXPIRED);
417 		    if (error)
418 			return (error);
419 		    if (np->n_lrev != np->n_brev ||
420 			(np->n_flag & NQNFSNONCACHE) ||
421 			((np->n_flag & NMODIFIED) && vp->v_type == VDIR)) {
422 			if (vp->v_type == VDIR)
423 			    nfs_invaldir(vp);
424 			error = nfs_vinvalbuf(vp, V_SAVE, td, 1);
425 			if (error)
426 			    return (error);
427 			np->n_brev = np->n_lrev;
428 		    }
429 		} else if (vp->v_type == VDIR && (np->n_flag & NMODIFIED)) {
430 		    nfs_invaldir(vp);
431 		    error = nfs_vinvalbuf(vp, V_SAVE, td, 1);
432 		    if (error)
433 			return (error);
434 		}
435 	    }
436 	    if (np->n_flag & NQNFSNONCACHE) {
437 		switch (vp->v_type) {
438 		case VREG:
439 			return (nfs_readrpc(vp, uio));
440 		case VLNK:
441 			return (nfs_readlinkrpc(vp, uio));
442 		case VDIR:
443 			break;
444 		default:
445 			printf(" NQNFSNONCACHE: type %x unexpected\n",
446 				vp->v_type);
447 		};
448 	    }
449 	    switch (vp->v_type) {
450 	    case VREG:
451 		nfsstats.biocache_reads++;
452 		lbn = uio->uio_offset / biosize;
453 		on = uio->uio_offset & (biosize - 1);
454 
455 		/*
456 		 * Start the read ahead(s), as required.
457 		 */
458 		if (nfs_numasync > 0 && nmp->nm_readahead > 0) {
459 		    for (nra = 0; nra < nmp->nm_readahead && nra < seqcount &&
460 			(off_t)(lbn + 1 + nra) * biosize < np->n_size; nra++) {
461 			rabn = lbn + 1 + nra;
462 			if (!incore(vp, rabn)) {
463 			    rabp = nfs_getcacheblk(vp, rabn, biosize, td);
464 			    if (!rabp)
465 				return (EINTR);
466 			    if ((rabp->b_flags & (B_CACHE|B_DELWRI)) == 0) {
467 				rabp->b_flags |= (B_READ | B_ASYNC);
468 				vfs_busy_pages(rabp, 0);
469 				if (nfs_asyncio(rabp, td)) {
470 				    rabp->b_flags |= B_INVAL|B_ERROR;
471 				    vfs_unbusy_pages(rabp);
472 				    brelse(rabp);
473 				    break;
474 				}
475 			    } else {
476 				brelse(rabp);
477 			    }
478 			}
479 		    }
480 		}
481 
482 		/*
483 		 * Obtain the buffer cache block.  Figure out the buffer size
484 		 * when we are at EOF.  If we are modifying the size of the
485 		 * buffer based on an EOF condition we need to hold
486 		 * nfs_rslock() through obtaining the buffer to prevent
487 		 * a potential writer-appender from messing with n_size.
488 		 * Otherwise we may accidently truncate the buffer and
489 		 * lose dirty data.
490 		 *
491 		 * Note that bcount is *not* DEV_BSIZE aligned.
492 		 */
493 
494 again:
495 		bcount = biosize;
496 		if ((off_t)lbn * biosize >= np->n_size) {
497 			bcount = 0;
498 		} else if ((off_t)(lbn + 1) * biosize > np->n_size) {
499 			bcount = np->n_size - (off_t)lbn * biosize;
500 		}
501 		if (bcount != biosize) {
502 			switch(nfs_rslock(np, td)) {
503 			case ENOLCK:
504 				goto again;
505 				/* not reached */
506 			case EINTR:
507 			case ERESTART:
508 				return(EINTR);
509 				/* not reached */
510 			default:
511 				break;
512 			}
513 		}
514 
515 		bp = nfs_getcacheblk(vp, lbn, bcount, td);
516 
517 		if (bcount != biosize)
518 			nfs_rsunlock(np, td);
519 		if (!bp)
520 			return (EINTR);
521 
522 		/*
523 		 * If B_CACHE is not set, we must issue the read.  If this
524 		 * fails, we return an error.
525 		 */
526 
527 		if ((bp->b_flags & B_CACHE) == 0) {
528 		    bp->b_flags |= B_READ;
529 		    vfs_busy_pages(bp, 0);
530 		    error = nfs_doio(bp, td);
531 		    if (error) {
532 			brelse(bp);
533 			return (error);
534 		    }
535 		}
536 
537 		/*
538 		 * on is the offset into the current bp.  Figure out how many
539 		 * bytes we can copy out of the bp.  Note that bcount is
540 		 * NOT DEV_BSIZE aligned.
541 		 *
542 		 * Then figure out how many bytes we can copy into the uio.
543 		 */
544 
545 		n = 0;
546 		if (on < bcount)
547 			n = min((unsigned)(bcount - on), uio->uio_resid);
548 		break;
549 	    case VLNK:
550 		nfsstats.biocache_readlinks++;
551 		bp = nfs_getcacheblk(vp, (daddr_t)0, NFS_MAXPATHLEN, td);
552 		if (!bp)
553 			return (EINTR);
554 		if ((bp->b_flags & B_CACHE) == 0) {
555 		    bp->b_flags |= B_READ;
556 		    vfs_busy_pages(bp, 0);
557 		    error = nfs_doio(bp, td);
558 		    if (error) {
559 			bp->b_flags |= B_ERROR;
560 			brelse(bp);
561 			return (error);
562 		    }
563 		}
564 		n = min(uio->uio_resid, NFS_MAXPATHLEN - bp->b_resid);
565 		on = 0;
566 		break;
567 	    case VDIR:
568 		nfsstats.biocache_readdirs++;
569 		if (np->n_direofoffset
570 		    && uio->uio_offset >= np->n_direofoffset) {
571 		    return (0);
572 		}
573 		lbn = (uoff_t)uio->uio_offset / NFS_DIRBLKSIZ;
574 		on = uio->uio_offset & (NFS_DIRBLKSIZ - 1);
575 		bp = nfs_getcacheblk(vp, lbn, NFS_DIRBLKSIZ, td);
576 		if (!bp)
577 		    return (EINTR);
578 		if ((bp->b_flags & B_CACHE) == 0) {
579 		    bp->b_flags |= B_READ;
580 		    vfs_busy_pages(bp, 0);
581 		    error = nfs_doio(bp, td);
582 		    if (error) {
583 			    brelse(bp);
584 		    }
585 		    while (error == NFSERR_BAD_COOKIE) {
586 			printf("got bad cookie vp %p bp %p\n", vp, bp);
587 			nfs_invaldir(vp);
588 			error = nfs_vinvalbuf(vp, 0, td, 1);
589 			/*
590 			 * Yuck! The directory has been modified on the
591 			 * server. The only way to get the block is by
592 			 * reading from the beginning to get all the
593 			 * offset cookies.
594 			 *
595 			 * Leave the last bp intact unless there is an error.
596 			 * Loop back up to the while if the error is another
597 			 * NFSERR_BAD_COOKIE (double yuch!).
598 			 */
599 			for (i = 0; i <= lbn && !error; i++) {
600 			    if (np->n_direofoffset
601 				&& (i * NFS_DIRBLKSIZ) >= np->n_direofoffset)
602 				    return (0);
603 			    bp = nfs_getcacheblk(vp, i, NFS_DIRBLKSIZ, td);
604 			    if (!bp)
605 				return (EINTR);
606 			    if ((bp->b_flags & B_CACHE) == 0) {
607 				    bp->b_flags |= B_READ;
608 				    vfs_busy_pages(bp, 0);
609 				    error = nfs_doio(bp, td);
610 				    /*
611 				     * no error + B_INVAL == directory EOF,
612 				     * use the block.
613 				     */
614 				    if (error == 0 && (bp->b_flags & B_INVAL))
615 					    break;
616 			    }
617 			    /*
618 			     * An error will throw away the block and the
619 			     * for loop will break out.  If no error and this
620 			     * is not the block we want, we throw away the
621 			     * block and go for the next one via the for loop.
622 			     */
623 			    if (error || i < lbn)
624 				    brelse(bp);
625 			}
626 		    }
627 		    /*
628 		     * The above while is repeated if we hit another cookie
629 		     * error.  If we hit an error and it wasn't a cookie error,
630 		     * we give up.
631 		     */
632 		    if (error)
633 			    return (error);
634 		}
635 
636 		/*
637 		 * If not eof and read aheads are enabled, start one.
638 		 * (You need the current block first, so that you have the
639 		 *  directory offset cookie of the next block.)
640 		 */
641 		if (nfs_numasync > 0 && nmp->nm_readahead > 0 &&
642 		    (bp->b_flags & B_INVAL) == 0 &&
643 		    (np->n_direofoffset == 0 ||
644 		    (lbn + 1) * NFS_DIRBLKSIZ < np->n_direofoffset) &&
645 		    !(np->n_flag & NQNFSNONCACHE) &&
646 		    !incore(vp, lbn + 1)) {
647 			rabp = nfs_getcacheblk(vp, lbn + 1, NFS_DIRBLKSIZ, td);
648 			if (rabp) {
649 			    if ((rabp->b_flags & (B_CACHE|B_DELWRI)) == 0) {
650 				rabp->b_flags |= (B_READ | B_ASYNC);
651 				vfs_busy_pages(rabp, 0);
652 				if (nfs_asyncio(rabp, td)) {
653 				    rabp->b_flags |= B_INVAL|B_ERROR;
654 				    vfs_unbusy_pages(rabp);
655 				    brelse(rabp);
656 				}
657 			    } else {
658 				brelse(rabp);
659 			    }
660 			}
661 		}
662 		/*
663 		 * Unlike VREG files, whos buffer size ( bp->b_bcount ) is
664 		 * chopped for the EOF condition, we cannot tell how large
665 		 * NFS directories are going to be until we hit EOF.  So
666 		 * an NFS directory buffer is *not* chopped to its EOF.  Now,
667 		 * it just so happens that b_resid will effectively chop it
668 		 * to EOF.  *BUT* this information is lost if the buffer goes
669 		 * away and is reconstituted into a B_CACHE state ( due to
670 		 * being VMIO ) later.  So we keep track of the directory eof
671 		 * in np->n_direofoffset and chop it off as an extra step
672 		 * right here.
673 		 */
674 		n = lmin(uio->uio_resid, NFS_DIRBLKSIZ - bp->b_resid - on);
675 		if (np->n_direofoffset && n > np->n_direofoffset - uio->uio_offset)
676 			n = np->n_direofoffset - uio->uio_offset;
677 		break;
678 	    default:
679 		printf(" nfs_bioread: type %x unexpected\n",vp->v_type);
680 		break;
681 	    };
682 
683 	    if (n > 0) {
684 		    error = uiomove(bp->b_data + on, (int)n, uio);
685 	    }
686 	    switch (vp->v_type) {
687 	    case VREG:
688 		break;
689 	    case VLNK:
690 		n = 0;
691 		break;
692 	    case VDIR:
693 		/*
694 		 * Invalidate buffer if caching is disabled, forcing a
695 		 * re-read from the remote later.
696 		 */
697 		if (np->n_flag & NQNFSNONCACHE)
698 			bp->b_flags |= B_INVAL;
699 		break;
700 	    default:
701 		printf(" nfs_bioread: type %x unexpected\n",vp->v_type);
702 	    }
703 	    brelse(bp);
704 	} while (error == 0 && uio->uio_resid > 0 && n > 0);
705 	return (error);
706 }
707 
708 /*
709  * Vnode op for write using bio
710  */
711 int
712 nfs_write(ap)
713 	struct vop_write_args /* {
714 		struct vnode *a_vp;
715 		struct uio *a_uio;
716 		int  a_ioflag;
717 		struct ucred *a_cred;
718 	} */ *ap;
719 {
720 	int biosize;
721 	struct uio *uio = ap->a_uio;
722 	struct thread *td = uio->uio_td;
723 	struct vnode *vp = ap->a_vp;
724 	struct nfsnode *np = VTONFS(vp);
725 	int ioflag = ap->a_ioflag;
726 	struct buf *bp;
727 	struct vattr vattr;
728 	struct nfsmount *nmp = VFSTONFS(vp->v_mount);
729 	daddr_t lbn;
730 	int bcount;
731 	int n, on, error = 0, iomode, must_commit;
732 	int haverslock = 0;
733 
734 #ifdef DIAGNOSTIC
735 	if (uio->uio_rw != UIO_WRITE)
736 		panic("nfs_write mode");
737 	if (uio->uio_segflg == UIO_USERSPACE && uio->uio_td != curthread)
738 		panic("nfs_write proc");
739 #endif
740 	if (vp->v_type != VREG)
741 		return (EIO);
742 	if (np->n_flag & NWRITEERR) {
743 		np->n_flag &= ~NWRITEERR;
744 		return (np->n_error);
745 	}
746 	if ((nmp->nm_flag & NFSMNT_NFSV3) != 0 &&
747 	    (nmp->nm_state & NFSSTA_GOTFSINFO) == 0)
748 		(void)nfs_fsinfo(nmp, vp, td);
749 
750 	/*
751 	 * Synchronously flush pending buffers if we are in synchronous
752 	 * mode or if we are appending.
753 	 */
754 	if (ioflag & (IO_APPEND | IO_SYNC)) {
755 		if (np->n_flag & NMODIFIED) {
756 			np->n_attrstamp = 0;
757 			error = nfs_vinvalbuf(vp, V_SAVE, td, 1);
758 			if (error)
759 				return (error);
760 		}
761 	}
762 
763 	/*
764 	 * If IO_APPEND then load uio_offset.  We restart here if we cannot
765 	 * get the append lock.
766 	 */
767 restart:
768 	if (ioflag & IO_APPEND) {
769 		np->n_attrstamp = 0;
770 		error = VOP_GETATTR(vp, &vattr, td);
771 		if (error)
772 			return (error);
773 		uio->uio_offset = np->n_size;
774 	}
775 
776 	if (uio->uio_offset < 0)
777 		return (EINVAL);
778 	if ((uio->uio_offset + uio->uio_resid) > nmp->nm_maxfilesize)
779 		return (EFBIG);
780 	if (uio->uio_resid == 0)
781 		return (0);
782 
783 	/*
784 	 * We need to obtain the rslock if we intend to modify np->n_size
785 	 * in order to guarentee the append point with multiple contending
786 	 * writers, to guarentee that no other appenders modify n_size
787 	 * while we are trying to obtain a truncated buffer (i.e. to avoid
788 	 * accidently truncating data written by another appender due to
789 	 * the race), and to ensure that the buffer is populated prior to
790 	 * our extending of the file.  We hold rslock through the entire
791 	 * operation.
792 	 *
793 	 * Note that we do not synchronize the case where someone truncates
794 	 * the file while we are appending to it because attempting to lock
795 	 * this case may deadlock other parts of the system unexpectedly.
796 	 */
797 	if ((ioflag & IO_APPEND) ||
798 	    uio->uio_offset + uio->uio_resid > np->n_size) {
799 		switch(nfs_rslock(np, td)) {
800 		case ENOLCK:
801 			goto restart;
802 			/* not reached */
803 		case EINTR:
804 		case ERESTART:
805 			return(EINTR);
806 			/* not reached */
807 		default:
808 			break;
809 		}
810 		haverslock = 1;
811 	}
812 
813 	/*
814 	 * Maybe this should be above the vnode op call, but so long as
815 	 * file servers have no limits, i don't think it matters
816 	 */
817 	if (td->td_proc && uio->uio_offset + uio->uio_resid >
818 	      td->td_proc->p_rlimit[RLIMIT_FSIZE].rlim_cur) {
819 		psignal(td->td_proc, SIGXFSZ);
820 		if (haverslock)
821 			nfs_rsunlock(np, td);
822 		return (EFBIG);
823 	}
824 
825 	biosize = vp->v_mount->mnt_stat.f_iosize;
826 
827 	do {
828 		/*
829 		 * Check for a valid write lease.
830 		 */
831 		if ((nmp->nm_flag & NFSMNT_NQNFS) &&
832 		    NQNFS_CKINVALID(vp, np, ND_WRITE)) {
833 			do {
834 				error = nqnfs_getlease(vp, ND_WRITE, td);
835 			} while (error == NQNFS_EXPIRED);
836 			if (error)
837 				break;
838 			if (np->n_lrev != np->n_brev ||
839 			    (np->n_flag & NQNFSNONCACHE)) {
840 				error = nfs_vinvalbuf(vp, V_SAVE, td, 1);
841 				if (error)
842 					break;
843 				np->n_brev = np->n_lrev;
844 			}
845 		}
846 		if ((np->n_flag & NQNFSNONCACHE) && uio->uio_iovcnt == 1) {
847 		    iomode = NFSV3WRITE_FILESYNC;
848 		    error = nfs_writerpc(vp, uio, &iomode, &must_commit);
849 		    if (must_commit)
850 			    nfs_clearcommit(vp->v_mount);
851 		    break;
852 		}
853 		nfsstats.biocache_writes++;
854 		lbn = uio->uio_offset / biosize;
855 		on = uio->uio_offset & (biosize-1);
856 		n = min((unsigned)(biosize - on), uio->uio_resid);
857 again:
858 		/*
859 		 * Handle direct append and file extension cases, calculate
860 		 * unaligned buffer size.
861 		 */
862 
863 		if (uio->uio_offset == np->n_size && n) {
864 			/*
865 			 * Get the buffer (in its pre-append state to maintain
866 			 * B_CACHE if it was previously set).  Resize the
867 			 * nfsnode after we have locked the buffer to prevent
868 			 * readers from reading garbage.
869 			 */
870 			bcount = on;
871 			bp = nfs_getcacheblk(vp, lbn, bcount, td);
872 
873 			if (bp != NULL) {
874 				long save;
875 
876 				np->n_size = uio->uio_offset + n;
877 				np->n_flag |= NMODIFIED;
878 				vnode_pager_setsize(vp, np->n_size);
879 
880 				save = bp->b_flags & B_CACHE;
881 				bcount += n;
882 				allocbuf(bp, bcount);
883 				bp->b_flags |= save;
884 			}
885 		} else {
886 			/*
887 			 * Obtain the locked cache block first, and then
888 			 * adjust the file's size as appropriate.
889 			 */
890 			bcount = on + n;
891 			if ((off_t)lbn * biosize + bcount < np->n_size) {
892 				if ((off_t)(lbn + 1) * biosize < np->n_size)
893 					bcount = biosize;
894 				else
895 					bcount = np->n_size - (off_t)lbn * biosize;
896 			}
897 			bp = nfs_getcacheblk(vp, lbn, bcount, td);
898 			if (uio->uio_offset + n > np->n_size) {
899 				np->n_size = uio->uio_offset + n;
900 				np->n_flag |= NMODIFIED;
901 				vnode_pager_setsize(vp, np->n_size);
902 			}
903 		}
904 
905 		if (!bp) {
906 			error = EINTR;
907 			break;
908 		}
909 
910 		/*
911 		 * Issue a READ if B_CACHE is not set.  In special-append
912 		 * mode, B_CACHE is based on the buffer prior to the write
913 		 * op and is typically set, avoiding the read.  If a read
914 		 * is required in special append mode, the server will
915 		 * probably send us a short-read since we extended the file
916 		 * on our end, resulting in b_resid == 0 and, thusly,
917 		 * B_CACHE getting set.
918 		 *
919 		 * We can also avoid issuing the read if the write covers
920 		 * the entire buffer.  We have to make sure the buffer state
921 		 * is reasonable in this case since we will not be initiating
922 		 * I/O.  See the comments in kern/vfs_bio.c's getblk() for
923 		 * more information.
924 		 *
925 		 * B_CACHE may also be set due to the buffer being cached
926 		 * normally.
927 		 */
928 
929 		if (on == 0 && n == bcount) {
930 			bp->b_flags |= B_CACHE;
931 			bp->b_flags &= ~(B_ERROR | B_INVAL);
932 		}
933 
934 		if ((bp->b_flags & B_CACHE) == 0) {
935 			bp->b_flags |= B_READ;
936 			vfs_busy_pages(bp, 0);
937 			error = nfs_doio(bp, td);
938 			if (error) {
939 				brelse(bp);
940 				break;
941 			}
942 		}
943 		if (!bp) {
944 			error = EINTR;
945 			break;
946 		}
947 		np->n_flag |= NMODIFIED;
948 
949 		/*
950 		 * If dirtyend exceeds file size, chop it down.  This should
951 		 * not normally occur but there is an append race where it
952 		 * might occur XXX, so we log it.
953 		 *
954 		 * If the chopping creates a reverse-indexed or degenerate
955 		 * situation with dirtyoff/end, we 0 both of them.
956 		 */
957 
958 		if (bp->b_dirtyend > bcount) {
959 			printf("NFS append race @%lx:%d\n",
960 			    (long)bp->b_blkno * DEV_BSIZE,
961 			    bp->b_dirtyend - bcount);
962 			bp->b_dirtyend = bcount;
963 		}
964 
965 		if (bp->b_dirtyoff >= bp->b_dirtyend)
966 			bp->b_dirtyoff = bp->b_dirtyend = 0;
967 
968 		/*
969 		 * If the new write will leave a contiguous dirty
970 		 * area, just update the b_dirtyoff and b_dirtyend,
971 		 * otherwise force a write rpc of the old dirty area.
972 		 *
973 		 * While it is possible to merge discontiguous writes due to
974 		 * our having a B_CACHE buffer ( and thus valid read data
975 		 * for the hole), we don't because it could lead to
976 		 * significant cache coherency problems with multiple clients,
977 		 * especially if locking is implemented later on.
978 		 *
979 		 * as an optimization we could theoretically maintain
980 		 * a linked list of discontinuous areas, but we would still
981 		 * have to commit them separately so there isn't much
982 		 * advantage to it except perhaps a bit of asynchronization.
983 		 */
984 
985 		if (bp->b_dirtyend > 0 &&
986 		    (on > bp->b_dirtyend || (on + n) < bp->b_dirtyoff)) {
987 			if (VOP_BWRITE(bp->b_vp, bp) == EINTR) {
988 				error = EINTR;
989 				break;
990 			}
991 			goto again;
992 		}
993 
994 		/*
995 		 * Check for valid write lease and get one as required.
996 		 * In case getblk() and/or bwrite() delayed us.
997 		 */
998 		if ((nmp->nm_flag & NFSMNT_NQNFS) &&
999 		    NQNFS_CKINVALID(vp, np, ND_WRITE)) {
1000 			do {
1001 				error = nqnfs_getlease(vp, ND_WRITE, td);
1002 			} while (error == NQNFS_EXPIRED);
1003 			if (error) {
1004 				brelse(bp);
1005 				break;
1006 			}
1007 			if (np->n_lrev != np->n_brev ||
1008 			    (np->n_flag & NQNFSNONCACHE)) {
1009 				brelse(bp);
1010 				error = nfs_vinvalbuf(vp, V_SAVE, td, 1);
1011 				if (error)
1012 					break;
1013 				np->n_brev = np->n_lrev;
1014 				goto again;
1015 			}
1016 		}
1017 
1018 		error = uiomove((char *)bp->b_data + on, n, uio);
1019 
1020 		/*
1021 		 * Since this block is being modified, it must be written
1022 		 * again and not just committed.  Since write clustering does
1023 		 * not work for the stage 1 data write, only the stage 2
1024 		 * commit rpc, we have to clear B_CLUSTEROK as well.
1025 		 */
1026 		bp->b_flags &= ~(B_NEEDCOMMIT | B_CLUSTEROK);
1027 
1028 		if (error) {
1029 			bp->b_flags |= B_ERROR;
1030 			brelse(bp);
1031 			break;
1032 		}
1033 
1034 		/*
1035 		 * Only update dirtyoff/dirtyend if not a degenerate
1036 		 * condition.
1037 		 */
1038 		if (n) {
1039 			if (bp->b_dirtyend > 0) {
1040 				bp->b_dirtyoff = min(on, bp->b_dirtyoff);
1041 				bp->b_dirtyend = max((on + n), bp->b_dirtyend);
1042 			} else {
1043 				bp->b_dirtyoff = on;
1044 				bp->b_dirtyend = on + n;
1045 			}
1046 			vfs_bio_set_validclean(bp, on, n);
1047 		}
1048 		/*
1049 		 * If IO_NOWDRAIN then set B_NOWDRAIN (e.g. nfs-backed VN
1050 		 * filesystem).  XXX also use for loopback NFS mounts.
1051 		 */
1052 		if (ioflag & IO_NOWDRAIN)
1053 			bp->b_flags |= B_NOWDRAIN;
1054 
1055 		/*
1056 		 * If the lease is non-cachable or IO_SYNC do bwrite().
1057 		 *
1058 		 * IO_INVAL appears to be unused.  The idea appears to be
1059 		 * to turn off caching in this case.  Very odd.  XXX
1060 		 */
1061 		if ((np->n_flag & NQNFSNONCACHE) || (ioflag & IO_SYNC)) {
1062 			if (ioflag & IO_INVAL)
1063 				bp->b_flags |= B_NOCACHE;
1064 			error = VOP_BWRITE(bp->b_vp, bp);
1065 			if (error)
1066 				break;
1067 			if (np->n_flag & NQNFSNONCACHE) {
1068 				error = nfs_vinvalbuf(vp, V_SAVE, td, 1);
1069 				if (error)
1070 					break;
1071 			}
1072 		} else if ((n + on) == biosize &&
1073 			(nmp->nm_flag & NFSMNT_NQNFS) == 0) {
1074 			bp->b_flags |= B_ASYNC;
1075 			(void)nfs_writebp(bp, 0, 0);
1076 		} else {
1077 			bdwrite(bp);
1078 		}
1079 	} while (uio->uio_resid > 0 && n > 0);
1080 
1081 	if (haverslock)
1082 		nfs_rsunlock(np, td);
1083 
1084 	return (error);
1085 }
1086 
1087 /*
1088  * Get an nfs cache block.
1089  *
1090  * Allocate a new one if the block isn't currently in the cache
1091  * and return the block marked busy. If the calling process is
1092  * interrupted by a signal for an interruptible mount point, return
1093  * NULL.
1094  *
1095  * The caller must carefully deal with the possible B_INVAL state of
1096  * the buffer.  nfs_doio() clears B_INVAL (and nfs_asyncio() clears it
1097  * indirectly), so synchronous reads can be issued without worrying about
1098  * the B_INVAL state.  We have to be a little more careful when dealing
1099  * with writes (see comments in nfs_write()) when extending a file past
1100  * its EOF.
1101  */
1102 static struct buf *
1103 nfs_getcacheblk(struct vnode *vp, daddr_t bn, int size, struct thread *td)
1104 {
1105 	struct buf *bp;
1106 	struct mount *mp;
1107 	struct nfsmount *nmp;
1108 
1109 	mp = vp->v_mount;
1110 	nmp = VFSTONFS(mp);
1111 
1112 	if (nmp->nm_flag & NFSMNT_INT) {
1113 		bp = getblk(vp, bn, size, PCATCH, 0);
1114 		while (bp == (struct buf *)0) {
1115 			if (nfs_sigintr(nmp, (struct nfsreq *)0, td))
1116 				return ((struct buf *)0);
1117 			bp = getblk(vp, bn, size, 0, 2 * hz);
1118 		}
1119 	} else {
1120 		bp = getblk(vp, bn, size, 0, 0);
1121 	}
1122 
1123 	if (vp->v_type == VREG) {
1124 		int biosize;
1125 
1126 		biosize = mp->mnt_stat.f_iosize;
1127 		bp->b_blkno = bn * (biosize / DEV_BSIZE);
1128 	}
1129 	return (bp);
1130 }
1131 
1132 /*
1133  * Flush and invalidate all dirty buffers. If another process is already
1134  * doing the flush, just wait for completion.
1135  */
1136 int
1137 nfs_vinvalbuf(struct vnode *vp, int flags,
1138 	struct thread *td, int intrflg)
1139 {
1140 	struct nfsnode *np = VTONFS(vp);
1141 	struct nfsmount *nmp = VFSTONFS(vp->v_mount);
1142 	int error = 0, slpflag, slptimeo;
1143 
1144 	if (vp->v_flag & VXLOCK) {
1145 		return (0);
1146 	}
1147 
1148 	if ((nmp->nm_flag & NFSMNT_INT) == 0)
1149 		intrflg = 0;
1150 	if (intrflg) {
1151 		slpflag = PCATCH;
1152 		slptimeo = 2 * hz;
1153 	} else {
1154 		slpflag = 0;
1155 		slptimeo = 0;
1156 	}
1157 	/*
1158 	 * First wait for any other process doing a flush to complete.
1159 	 */
1160 	while (np->n_flag & NFLUSHINPROG) {
1161 		np->n_flag |= NFLUSHWANT;
1162 		error = tsleep((caddr_t)&np->n_flag, 0, "nfsvinval", slptimeo);
1163 		if (error && intrflg && nfs_sigintr(nmp, (struct nfsreq *)0, td))
1164 			return (EINTR);
1165 	}
1166 
1167 	/*
1168 	 * Now, flush as required.
1169 	 */
1170 	np->n_flag |= NFLUSHINPROG;
1171 	error = vinvalbuf(vp, flags, td, slpflag, 0);
1172 	while (error) {
1173 		if (intrflg && nfs_sigintr(nmp, (struct nfsreq *)0, td)) {
1174 			np->n_flag &= ~NFLUSHINPROG;
1175 			if (np->n_flag & NFLUSHWANT) {
1176 				np->n_flag &= ~NFLUSHWANT;
1177 				wakeup((caddr_t)&np->n_flag);
1178 			}
1179 			return (EINTR);
1180 		}
1181 		error = vinvalbuf(vp, flags, td, 0, slptimeo);
1182 	}
1183 	np->n_flag &= ~(NMODIFIED | NFLUSHINPROG);
1184 	if (np->n_flag & NFLUSHWANT) {
1185 		np->n_flag &= ~NFLUSHWANT;
1186 		wakeup((caddr_t)&np->n_flag);
1187 	}
1188 	return (0);
1189 }
1190 
1191 /*
1192  * Initiate asynchronous I/O. Return an error if no nfsiods are available.
1193  * This is mainly to avoid queueing async I/O requests when the nfsiods
1194  * are all hung on a dead server.
1195  *
1196  * Note: nfs_asyncio() does not clear (B_ERROR|B_INVAL) but when the bp
1197  * is eventually dequeued by the async daemon, nfs_doio() *will*.
1198  */
1199 int
1200 nfs_asyncio(struct buf *bp, struct thread *td)
1201 {
1202 	struct nfsmount *nmp;
1203 	int i;
1204 	int gotiod;
1205 	int slpflag = 0;
1206 	int slptimeo = 0;
1207 	int error;
1208 
1209 	/*
1210 	 * If no async daemons then return EIO to force caller to run the rpc
1211 	 * synchronously.
1212 	 */
1213 	if (nfs_numasync == 0)
1214 		return (EIO);
1215 
1216 	nmp = VFSTONFS(bp->b_vp->v_mount);
1217 
1218 	/*
1219 	 * Commits are usually short and sweet so lets save some cpu and
1220 	 * leave the async daemons for more important rpc's (such as reads
1221 	 * and writes).
1222 	 */
1223 	if ((bp->b_flags & (B_READ|B_NEEDCOMMIT)) == B_NEEDCOMMIT &&
1224 	    (nmp->nm_bufqiods > nfs_numasync / 2)) {
1225 		return(EIO);
1226 	}
1227 
1228 again:
1229 	if (nmp->nm_flag & NFSMNT_INT)
1230 		slpflag = PCATCH;
1231 	gotiod = FALSE;
1232 
1233 	/*
1234 	 * Find a free iod to process this request.
1235 	 */
1236 	for (i = 0; i < NFS_MAXASYNCDAEMON; i++)
1237 		if (nfs_iodwant[i]) {
1238 			/*
1239 			 * Found one, so wake it up and tell it which
1240 			 * mount to process.
1241 			 */
1242 			NFS_DPF(ASYNCIO,
1243 				("nfs_asyncio: waking iod %d for mount %p\n",
1244 				 i, nmp));
1245 			nfs_iodwant[i] = NULL;
1246 			nfs_iodmount[i] = nmp;
1247 			nmp->nm_bufqiods++;
1248 			wakeup((caddr_t)&nfs_iodwant[i]);
1249 			gotiod = TRUE;
1250 			break;
1251 		}
1252 
1253 	/*
1254 	 * If none are free, we may already have an iod working on this mount
1255 	 * point.  If so, it will process our request.
1256 	 */
1257 	if (!gotiod) {
1258 		if (nmp->nm_bufqiods > 0) {
1259 			NFS_DPF(ASYNCIO,
1260 				("nfs_asyncio: %d iods are already processing mount %p\n",
1261 				 nmp->nm_bufqiods, nmp));
1262 			gotiod = TRUE;
1263 		}
1264 	}
1265 
1266 	/*
1267 	 * If we have an iod which can process the request, then queue
1268 	 * the buffer.
1269 	 */
1270 	if (gotiod) {
1271 		/*
1272 		 * Ensure that the queue never grows too large.  We still want
1273 		 * to asynchronize so we block rather then return EIO.
1274 		 */
1275 		while (nmp->nm_bufqlen >= 2*nfs_numasync) {
1276 			NFS_DPF(ASYNCIO,
1277 				("nfs_asyncio: waiting for mount %p queue to drain\n", nmp));
1278 			nmp->nm_bufqwant = TRUE;
1279 			error = tsleep(&nmp->nm_bufq, slpflag,
1280 				       "nfsaio", slptimeo);
1281 			if (error) {
1282 				if (nfs_sigintr(nmp, NULL, td))
1283 					return (EINTR);
1284 				if (slpflag == PCATCH) {
1285 					slpflag = 0;
1286 					slptimeo = 2 * hz;
1287 				}
1288 			}
1289 			/*
1290 			 * We might have lost our iod while sleeping,
1291 			 * so check and loop if nescessary.
1292 			 */
1293 			if (nmp->nm_bufqiods == 0) {
1294 				NFS_DPF(ASYNCIO,
1295 					("nfs_asyncio: no iods after mount %p queue was drained, looping\n", nmp));
1296 				goto again;
1297 			}
1298 		}
1299 
1300 		if ((bp->b_flags & B_READ) == 0)
1301 			bp->b_flags |= B_WRITEINPROG;
1302 
1303 		BUF_KERNPROC(bp);
1304 		TAILQ_INSERT_TAIL(&nmp->nm_bufq, bp, b_freelist);
1305 		nmp->nm_bufqlen++;
1306 		return (0);
1307 	}
1308 
1309 	/*
1310 	 * All the iods are busy on other mounts, so return EIO to
1311 	 * force the caller to process the i/o synchronously.
1312 	 */
1313 	NFS_DPF(ASYNCIO, ("nfs_asyncio: no iods available, i/o is synchronous\n"));
1314 	return (EIO);
1315 }
1316 
1317 /*
1318  * Do an I/O operation to/from a cache block. This may be called
1319  * synchronously or from an nfsiod.
1320  *
1321  * NOTE! TD MIGHT BE NULL
1322  */
1323 int
1324 nfs_doio(struct buf *bp, struct thread *td)
1325 {
1326 	struct uio *uiop;
1327 	struct vnode *vp;
1328 	struct nfsnode *np;
1329 	struct nfsmount *nmp;
1330 	int error = 0, iomode, must_commit = 0;
1331 	struct uio uio;
1332 	struct iovec io;
1333 
1334 	vp = bp->b_vp;
1335 	np = VTONFS(vp);
1336 	nmp = VFSTONFS(vp->v_mount);
1337 	uiop = &uio;
1338 	uiop->uio_iov = &io;
1339 	uiop->uio_iovcnt = 1;
1340 	uiop->uio_segflg = UIO_SYSSPACE;
1341 	uiop->uio_td = td;
1342 
1343 	/*
1344 	 * clear B_ERROR and B_INVAL state prior to initiating the I/O.  We
1345 	 * do this here so we do not have to do it in all the code that
1346 	 * calls us.
1347 	 */
1348 	bp->b_flags &= ~(B_ERROR | B_INVAL);
1349 
1350 	KASSERT(!(bp->b_flags & B_DONE), ("nfs_doio: bp %p already marked done", bp));
1351 
1352 	/*
1353 	 * Historically, paging was done with physio, but no more.
1354 	 */
1355 	if (bp->b_flags & B_PHYS) {
1356 	    /*
1357 	     * ...though reading /dev/drum still gets us here.
1358 	     */
1359 	    io.iov_len = uiop->uio_resid = bp->b_bcount;
1360 	    /* mapping was done by vmapbuf() */
1361 	    io.iov_base = bp->b_data;
1362 	    uiop->uio_offset = ((off_t)bp->b_blkno) * DEV_BSIZE;
1363 	    if (bp->b_flags & B_READ) {
1364 		uiop->uio_rw = UIO_READ;
1365 		nfsstats.read_physios++;
1366 		error = nfs_readrpc(vp, uiop);
1367 	    } else {
1368 		int com;
1369 
1370 		iomode = NFSV3WRITE_DATASYNC;
1371 		uiop->uio_rw = UIO_WRITE;
1372 		nfsstats.write_physios++;
1373 		error = nfs_writerpc(vp, uiop, &iomode, &com);
1374 	    }
1375 	    if (error) {
1376 		bp->b_flags |= B_ERROR;
1377 		bp->b_error = error;
1378 	    }
1379 	} else if (bp->b_flags & B_READ) {
1380 	    io.iov_len = uiop->uio_resid = bp->b_bcount;
1381 	    io.iov_base = bp->b_data;
1382 	    uiop->uio_rw = UIO_READ;
1383 
1384 	    switch (vp->v_type) {
1385 	    case VREG:
1386 		uiop->uio_offset = ((off_t)bp->b_blkno) * DEV_BSIZE;
1387 		nfsstats.read_bios++;
1388 		error = nfs_readrpc(vp, uiop);
1389 
1390 		if (!error) {
1391 		    if (uiop->uio_resid) {
1392 			/*
1393 			 * If we had a short read with no error, we must have
1394 			 * hit a file hole.  We should zero-fill the remainder.
1395 			 * This can also occur if the server hits the file EOF.
1396 			 *
1397 			 * Holes used to be able to occur due to pending
1398 			 * writes, but that is not possible any longer.
1399 			 */
1400 			int nread = bp->b_bcount - uiop->uio_resid;
1401 			int left  = uiop->uio_resid;
1402 
1403 			if (left > 0)
1404 				bzero((char *)bp->b_data + nread, left);
1405 			uiop->uio_resid = 0;
1406 		    }
1407 		}
1408 		if (td && td->td_proc && (vp->v_flag & VTEXT) &&
1409 			(((nmp->nm_flag & NFSMNT_NQNFS) &&
1410 			  NQNFS_CKINVALID(vp, np, ND_READ) &&
1411 			  np->n_lrev != np->n_brev) ||
1412 			 (!(nmp->nm_flag & NFSMNT_NQNFS) &&
1413 			  np->n_mtime != np->n_vattr.va_mtime.tv_sec))) {
1414 			uprintf("Process killed due to text file modification\n");
1415 			psignal(td->td_proc, SIGKILL);
1416 			PHOLD(td->td_proc);
1417 		}
1418 		break;
1419 	    case VLNK:
1420 		uiop->uio_offset = (off_t)0;
1421 		nfsstats.readlink_bios++;
1422 		error = nfs_readlinkrpc(vp, uiop);
1423 		break;
1424 	    case VDIR:
1425 		nfsstats.readdir_bios++;
1426 		uiop->uio_offset = ((u_quad_t)bp->b_lblkno) * NFS_DIRBLKSIZ;
1427 		if (nmp->nm_flag & NFSMNT_RDIRPLUS) {
1428 			error = nfs_readdirplusrpc(vp, uiop);
1429 			if (error == NFSERR_NOTSUPP)
1430 				nmp->nm_flag &= ~NFSMNT_RDIRPLUS;
1431 		}
1432 		if ((nmp->nm_flag & NFSMNT_RDIRPLUS) == 0)
1433 			error = nfs_readdirrpc(vp, uiop);
1434 		/*
1435 		 * end-of-directory sets B_INVAL but does not generate an
1436 		 * error.
1437 		 */
1438 		if (error == 0 && uiop->uio_resid == bp->b_bcount)
1439 			bp->b_flags |= B_INVAL;
1440 		break;
1441 	    default:
1442 		printf("nfs_doio:  type %x unexpected\n",vp->v_type);
1443 		break;
1444 	    };
1445 	    if (error) {
1446 		bp->b_flags |= B_ERROR;
1447 		bp->b_error = error;
1448 	    }
1449 	} else {
1450 	    /*
1451 	     * If we only need to commit, try to commit
1452 	     */
1453 	    if (bp->b_flags & B_NEEDCOMMIT) {
1454 		    int retv;
1455 		    off_t off;
1456 
1457 		    off = ((u_quad_t)bp->b_blkno) * DEV_BSIZE + bp->b_dirtyoff;
1458 		    bp->b_flags |= B_WRITEINPROG;
1459 		    retv = nfs_commit(bp->b_vp, off,
1460 				bp->b_dirtyend - bp->b_dirtyoff, td);
1461 		    bp->b_flags &= ~B_WRITEINPROG;
1462 		    if (retv == 0) {
1463 			    bp->b_dirtyoff = bp->b_dirtyend = 0;
1464 			    bp->b_flags &= ~(B_NEEDCOMMIT | B_CLUSTEROK);
1465 			    bp->b_resid = 0;
1466 			    biodone(bp);
1467 			    return (0);
1468 		    }
1469 		    if (retv == NFSERR_STALEWRITEVERF) {
1470 			    nfs_clearcommit(bp->b_vp->v_mount);
1471 		    }
1472 	    }
1473 
1474 	    /*
1475 	     * Setup for actual write
1476 	     */
1477 
1478 	    if ((off_t)bp->b_blkno * DEV_BSIZE + bp->b_dirtyend > np->n_size)
1479 		bp->b_dirtyend = np->n_size - (off_t)bp->b_blkno * DEV_BSIZE;
1480 
1481 	    if (bp->b_dirtyend > bp->b_dirtyoff) {
1482 		io.iov_len = uiop->uio_resid = bp->b_dirtyend
1483 		    - bp->b_dirtyoff;
1484 		uiop->uio_offset = (off_t)bp->b_blkno * DEV_BSIZE
1485 		    + bp->b_dirtyoff;
1486 		io.iov_base = (char *)bp->b_data + bp->b_dirtyoff;
1487 		uiop->uio_rw = UIO_WRITE;
1488 		nfsstats.write_bios++;
1489 
1490 		if ((bp->b_flags & (B_ASYNC | B_NEEDCOMMIT | B_NOCACHE | B_CLUSTER)) == B_ASYNC)
1491 		    iomode = NFSV3WRITE_UNSTABLE;
1492 		else
1493 		    iomode = NFSV3WRITE_FILESYNC;
1494 
1495 		bp->b_flags |= B_WRITEINPROG;
1496 		error = nfs_writerpc(vp, uiop, &iomode, &must_commit);
1497 
1498 		/*
1499 		 * When setting B_NEEDCOMMIT also set B_CLUSTEROK to try
1500 		 * to cluster the buffers needing commit.  This will allow
1501 		 * the system to submit a single commit rpc for the whole
1502 		 * cluster.  We can do this even if the buffer is not 100%
1503 		 * dirty (relative to the NFS blocksize), so we optimize the
1504 		 * append-to-file-case.
1505 		 *
1506 		 * (when clearing B_NEEDCOMMIT, B_CLUSTEROK must also be
1507 		 * cleared because write clustering only works for commit
1508 		 * rpc's, not for the data portion of the write).
1509 		 */
1510 
1511 		if (!error && iomode == NFSV3WRITE_UNSTABLE) {
1512 		    bp->b_flags |= B_NEEDCOMMIT;
1513 		    if (bp->b_dirtyoff == 0
1514 			&& bp->b_dirtyend == bp->b_bcount)
1515 			bp->b_flags |= B_CLUSTEROK;
1516 		} else {
1517 		    bp->b_flags &= ~(B_NEEDCOMMIT | B_CLUSTEROK);
1518 		}
1519 		bp->b_flags &= ~B_WRITEINPROG;
1520 
1521 		/*
1522 		 * For an interrupted write, the buffer is still valid
1523 		 * and the write hasn't been pushed to the server yet,
1524 		 * so we can't set B_ERROR and report the interruption
1525 		 * by setting B_EINTR. For the B_ASYNC case, B_EINTR
1526 		 * is not relevant, so the rpc attempt is essentially
1527 		 * a noop.  For the case of a V3 write rpc not being
1528 		 * committed to stable storage, the block is still
1529 		 * dirty and requires either a commit rpc or another
1530 		 * write rpc with iomode == NFSV3WRITE_FILESYNC before
1531 		 * the block is reused. This is indicated by setting
1532 		 * the B_DELWRI and B_NEEDCOMMIT flags.
1533 		 *
1534 		 * If the buffer is marked B_PAGING, it does not reside on
1535 		 * the vp's paging queues so we cannot call bdirty().  The
1536 		 * bp in this case is not an NFS cache block so we should
1537 		 * be safe. XXX
1538 		 */
1539     		if (error == EINTR
1540 		    || (!error && (bp->b_flags & B_NEEDCOMMIT))) {
1541 			int s;
1542 
1543 			s = splbio();
1544 			bp->b_flags &= ~(B_INVAL|B_NOCACHE);
1545 			if ((bp->b_flags & B_PAGING) == 0) {
1546 			    bdirty(bp);
1547 			    bp->b_flags &= ~B_DONE;
1548 			}
1549 			if (error && (bp->b_flags & B_ASYNC) == 0)
1550 			    bp->b_flags |= B_EINTR;
1551 			splx(s);
1552 	    	} else {
1553 		    if (error) {
1554 			bp->b_flags |= B_ERROR;
1555 			bp->b_error = np->n_error = error;
1556 			np->n_flag |= NWRITEERR;
1557 		    }
1558 		    bp->b_dirtyoff = bp->b_dirtyend = 0;
1559 		}
1560 	    } else {
1561 		bp->b_resid = 0;
1562 		biodone(bp);
1563 		return (0);
1564 	    }
1565 	}
1566 	bp->b_resid = uiop->uio_resid;
1567 	if (must_commit)
1568 	    nfs_clearcommit(vp->v_mount);
1569 	biodone(bp);
1570 	return (error);
1571 }
1572 
1573 /*
1574  * Used to aid in handling ftruncate() operations on the NFS client side.
1575  * Truncation creates a number of special problems for NFS.  We have to
1576  * throw away VM pages and buffer cache buffers that are beyond EOF, and
1577  * we have to properly handle VM pages or (potentially dirty) buffers
1578  * that straddle the truncation point.
1579  */
1580 
1581 int
1582 nfs_meta_setsize(struct vnode *vp, struct thread *td, u_quad_t nsize)
1583 {
1584 	struct nfsnode *np = VTONFS(vp);
1585 	u_quad_t tsize = np->n_size;
1586 	int biosize = vp->v_mount->mnt_stat.f_iosize;
1587 	int error = 0;
1588 
1589 	np->n_size = nsize;
1590 
1591 	if (np->n_size < tsize) {
1592 		struct buf *bp;
1593 		daddr_t lbn;
1594 		int bufsize;
1595 
1596 		/*
1597 		 * vtruncbuf() doesn't get the buffer overlapping the
1598 		 * truncation point.  We may have a B_DELWRI and/or B_CACHE
1599 		 * buffer that now needs to be truncated.
1600 		 */
1601 		error = vtruncbuf(vp, td, nsize, biosize);
1602 		lbn = nsize / biosize;
1603 		bufsize = nsize & (biosize - 1);
1604 		bp = nfs_getcacheblk(vp, lbn, bufsize, td);
1605 		if (bp->b_dirtyoff > bp->b_bcount)
1606 			bp->b_dirtyoff = bp->b_bcount;
1607 		if (bp->b_dirtyend > bp->b_bcount)
1608 			bp->b_dirtyend = bp->b_bcount;
1609 		bp->b_flags |= B_RELBUF;  /* don't leave garbage around */
1610 		brelse(bp);
1611 	} else {
1612 		vnode_pager_setsize(vp, nsize);
1613 	}
1614 	return(error);
1615 }
1616 
1617