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