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