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