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