xref: /dflybsd-src/sys/vfs/nfs/nfs_bio.c (revision cd29885abfb8f68adb0c082e313b891156d66964)
1 /*
2  * Copyright (c) 1989, 1993
3  *	The Regents of the University of California.  All rights reserved.
4  *
5  * This code is derived from software contributed to Berkeley by
6  * Rick Macklem at The University of Guelph.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  * 3. All advertising materials mentioning features or use of this software
17  *    must display the following acknowledgement:
18  *	This product includes software developed by the University of
19  *	California, Berkeley and its contributors.
20  * 4. Neither the name of the University nor the names of its contributors
21  *    may be used to endorse or promote products derived from this software
22  *    without specific prior written permission.
23  *
24  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
25  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
28  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
29  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
30  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
31  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
33  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34  * SUCH DAMAGE.
35  *
36  *	@(#)nfs_bio.c	8.9 (Berkeley) 3/30/95
37  * $FreeBSD: /repoman/r/ncvs/src/sys/nfsclient/nfs_bio.c,v 1.130 2004/04/14 23:23:55 peadar Exp $
38  * $DragonFly: src/sys/vfs/nfs/nfs_bio.c,v 1.45 2008/07/18 00:09:39 dillon Exp $
39  */
40 
41 
42 #include <sys/param.h>
43 #include <sys/systm.h>
44 #include <sys/resourcevar.h>
45 #include <sys/signalvar.h>
46 #include <sys/proc.h>
47 #include <sys/buf.h>
48 #include <sys/vnode.h>
49 #include <sys/mount.h>
50 #include <sys/kernel.h>
51 #include <sys/mbuf.h>
52 #include <sys/msfbuf.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 <sys/buf2.h>
62 #include <sys/thread2.h>
63 
64 #include "rpcv2.h"
65 #include "nfsproto.h"
66 #include "nfs.h"
67 #include "nfsmount.h"
68 #include "nfsnode.h"
69 #include "xdr_subs.h"
70 #include "nfsm_subs.h"
71 
72 
73 static struct buf *nfs_getcacheblk(struct vnode *vp, off_t loffset,
74 				   int size, struct thread *td);
75 static int nfs_check_dirent(struct nfs_dirent *dp, int maxlen);
76 static void nfsiodone_sync(struct bio *bio);
77 static void nfs_readrpc_bio_done(nfsm_info_t info);
78 static void nfs_writerpc_bio_done(nfsm_info_t info);
79 static void nfs_commitrpc_bio_done(nfsm_info_t info);
80 
81 /*
82  * Vnode op for VM getpages.
83  *
84  * nfs_getpages(struct vnode *a_vp, vm_page_t *a_m, int a_count,
85  *		int a_reqpage, vm_ooffset_t a_offset)
86  */
87 int
88 nfs_getpages(struct vop_getpages_args *ap)
89 {
90 	struct thread *td = curthread;		/* XXX */
91 	int i, error, nextoff, size, toff, count, npages;
92 	struct uio uio;
93 	struct iovec iov;
94 	char *kva;
95 	struct vnode *vp;
96 	struct nfsmount *nmp;
97 	vm_page_t *pages;
98 	vm_page_t m;
99 	struct msf_buf *msf;
100 
101 	vp = ap->a_vp;
102 	nmp = VFSTONFS(vp->v_mount);
103 	pages = ap->a_m;
104 	count = ap->a_count;
105 
106 	if (vp->v_object == NULL) {
107 		kprintf("nfs_getpages: called with non-merged cache vnode??\n");
108 		return VM_PAGER_ERROR;
109 	}
110 
111 	if ((nmp->nm_flag & NFSMNT_NFSV3) != 0 &&
112 	    (nmp->nm_state & NFSSTA_GOTFSINFO) == 0)
113 		(void)nfs_fsinfo(nmp, vp, td);
114 
115 	npages = btoc(count);
116 
117 	/*
118 	 * NOTE that partially valid pages may occur in cases other
119 	 * then file EOF, such as when a file is partially written and
120 	 * ftruncate()-extended to a larger size.   It is also possible
121 	 * for the valid bits to be set on garbage beyond the file EOF and
122 	 * clear in the area before EOF (e.g. m->valid == 0xfc), which can
123 	 * occur due to vtruncbuf() and the buffer cache's handling of
124 	 * pages which 'straddle' buffers or when b_bufsize is not a
125 	 * multiple of PAGE_SIZE.... the buffer cache cannot normally
126 	 * clear the extra bits.  This kind of situation occurs when you
127 	 * make a small write() (m->valid == 0x03) and then mmap() and
128 	 * fault in the buffer(m->valid = 0xFF).  When NFS flushes the
129 	 * buffer (vinvalbuf() m->valid = 0xFC) we are left with a mess.
130 	 *
131 	 * This is combined with the possibility that the pages are partially
132 	 * dirty or that there is a buffer backing the pages that is dirty
133 	 * (even if m->dirty is 0).
134 	 *
135 	 * To solve this problem several hacks have been made:  (1) NFS
136 	 * guarentees that the IO block size is a multiple of PAGE_SIZE and
137 	 * (2) The buffer cache, when invalidating an NFS buffer, will
138 	 * disregard the buffer's fragmentory b_bufsize and invalidate
139 	 * the whole page rather then just the piece the buffer owns.
140 	 *
141 	 * This allows us to assume that a partially valid page found here
142 	 * is fully valid (vm_fault will zero'd out areas of the page not
143 	 * marked as valid).
144 	 */
145 	m = pages[ap->a_reqpage];
146 	if (m->valid != 0) {
147 		for (i = 0; i < npages; ++i) {
148 			if (i != ap->a_reqpage)
149 				vnode_pager_freepage(pages[i]);
150 		}
151 		return(0);
152 	}
153 
154 	/*
155 	 * Use an MSF_BUF as a medium to retrieve data from the pages.
156 	 */
157 	msf_map_pagelist(&msf, pages, npages, 0);
158 	KKASSERT(msf);
159 	kva = msf_buf_kva(msf);
160 
161 	iov.iov_base = 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 = nfs_readrpc_uio(vp, &uio);
172 	msf_buf_free(msf);
173 
174 	if (error && (uio.uio_resid == count)) {
175 		kprintf("nfs_getpages: error %d\n", error);
176 		for (i = 0; i < npages; ++i) {
177 			if (i != ap->a_reqpage)
178 				vnode_pager_freepage(pages[i]);
179 		}
180 		return VM_PAGER_ERROR;
181 	}
182 
183 	/*
184 	 * Calculate the number of bytes read and validate only that number
185 	 * of bytes.  Note that due to pending writes, size may be 0.  This
186 	 * does not mean that the remaining data is invalid!
187 	 */
188 
189 	size = count - uio.uio_resid;
190 
191 	for (i = 0, toff = 0; i < npages; i++, toff = nextoff) {
192 		nextoff = toff + PAGE_SIZE;
193 		m = pages[i];
194 
195 		m->flags &= ~PG_ZERO;
196 
197 		if (nextoff <= size) {
198 			/*
199 			 * Read operation filled an entire page
200 			 */
201 			m->valid = VM_PAGE_BITS_ALL;
202 			vm_page_undirty(m);
203 		} else if (size > toff) {
204 			/*
205 			 * Read operation filled a partial page.
206 			 */
207 			m->valid = 0;
208 			vm_page_set_validclean(m, 0, size - toff);
209 			/* handled by vm_fault now	  */
210 			/* vm_page_zero_invalid(m, TRUE); */
211 		} else {
212 			/*
213 			 * Read operation was short.  If no error occured
214 			 * we may have hit a zero-fill section.   We simply
215 			 * leave valid set to 0.
216 			 */
217 			;
218 		}
219 		if (i != ap->a_reqpage) {
220 			/*
221 			 * Whether or not to leave the page activated is up in
222 			 * the air, but we should put the page on a page queue
223 			 * somewhere (it already is in the object).  Result:
224 			 * It appears that emperical results show that
225 			 * deactivating pages is best.
226 			 */
227 
228 			/*
229 			 * Just in case someone was asking for this page we
230 			 * now tell them that it is ok to use.
231 			 */
232 			if (!error) {
233 				if (m->flags & PG_WANTED)
234 					vm_page_activate(m);
235 				else
236 					vm_page_deactivate(m);
237 				vm_page_wakeup(m);
238 			} else {
239 				vnode_pager_freepage(m);
240 			}
241 		}
242 	}
243 	return 0;
244 }
245 
246 /*
247  * Vnode op for VM putpages.
248  *
249  * nfs_putpages(struct vnode *a_vp, vm_page_t *a_m, int a_count, int a_sync,
250  *		int *a_rtvals, vm_ooffset_t a_offset)
251  */
252 int
253 nfs_putpages(struct vop_putpages_args *ap)
254 {
255 	struct thread *td = curthread;
256 	struct uio uio;
257 	struct iovec iov;
258 	char *kva;
259 	int iomode, must_commit, i, error, npages, count;
260 	off_t offset;
261 	int *rtvals;
262 	struct vnode *vp;
263 	struct nfsmount *nmp;
264 	struct nfsnode *np;
265 	vm_page_t *pages;
266 	struct msf_buf *msf;
267 
268 	vp = ap->a_vp;
269 	np = VTONFS(vp);
270 	nmp = VFSTONFS(vp->v_mount);
271 	pages = ap->a_m;
272 	count = ap->a_count;
273 	rtvals = ap->a_rtvals;
274 	npages = btoc(count);
275 	offset = IDX_TO_OFF(pages[0]->pindex);
276 
277 	if ((nmp->nm_flag & NFSMNT_NFSV3) != 0 &&
278 	    (nmp->nm_state & NFSSTA_GOTFSINFO) == 0)
279 		(void)nfs_fsinfo(nmp, vp, td);
280 
281 	for (i = 0; i < npages; i++) {
282 		rtvals[i] = VM_PAGER_AGAIN;
283 	}
284 
285 	/*
286 	 * When putting pages, do not extend file past EOF.
287 	 */
288 
289 	if (offset + count > np->n_size) {
290 		count = np->n_size - offset;
291 		if (count < 0)
292 			count = 0;
293 	}
294 
295 	/*
296 	 * Use an MSF_BUF as a medium to retrieve data from the pages.
297 	 */
298 	msf_map_pagelist(&msf, pages, npages, 0);
299 	KKASSERT(msf);
300 	kva = msf_buf_kva(msf);
301 
302 	iov.iov_base = kva;
303 	iov.iov_len = count;
304 	uio.uio_iov = &iov;
305 	uio.uio_iovcnt = 1;
306 	uio.uio_offset = offset;
307 	uio.uio_resid = count;
308 	uio.uio_segflg = UIO_SYSSPACE;
309 	uio.uio_rw = UIO_WRITE;
310 	uio.uio_td = td;
311 
312 	if ((ap->a_sync & VM_PAGER_PUT_SYNC) == 0)
313 	    iomode = NFSV3WRITE_UNSTABLE;
314 	else
315 	    iomode = NFSV3WRITE_FILESYNC;
316 
317 	error = nfs_writerpc_uio(vp, &uio, &iomode, &must_commit);
318 
319 	msf_buf_free(msf);
320 
321 	if (!error) {
322 		int nwritten = round_page(count - uio.uio_resid) / PAGE_SIZE;
323 		for (i = 0; i < nwritten; i++) {
324 			rtvals[i] = VM_PAGER_OK;
325 			vm_page_undirty(pages[i]);
326 		}
327 		if (must_commit)
328 			nfs_clearcommit(vp->v_mount);
329 	}
330 	return rtvals[0];
331 }
332 
333 /*
334  * Vnode op for read using bio
335  */
336 int
337 nfs_bioread(struct vnode *vp, struct uio *uio, int ioflag)
338 {
339 	struct nfsnode *np = VTONFS(vp);
340 	int biosize, i;
341 	struct buf *bp = 0, *rabp;
342 	struct vattr vattr;
343 	struct thread *td;
344 	struct nfsmount *nmp = VFSTONFS(vp->v_mount);
345 	daddr_t lbn, rabn;
346 	off_t raoffset;
347 	off_t loffset;
348 	int bcount;
349 	int seqcount;
350 	int nra, error = 0, n = 0, on = 0;
351 
352 #ifdef DIAGNOSTIC
353 	if (uio->uio_rw != UIO_READ)
354 		panic("nfs_read mode");
355 #endif
356 	if (uio->uio_resid == 0)
357 		return (0);
358 	if (uio->uio_offset < 0)	/* XXX VDIR cookies can be negative */
359 		return (EINVAL);
360 	td = uio->uio_td;
361 
362 	if ((nmp->nm_flag & NFSMNT_NFSV3) != 0 &&
363 	    (nmp->nm_state & NFSSTA_GOTFSINFO) == 0)
364 		(void)nfs_fsinfo(nmp, vp, td);
365 	if (vp->v_type != VDIR &&
366 	    (uio->uio_offset + uio->uio_resid) > nmp->nm_maxfilesize)
367 		return (EFBIG);
368 	biosize = vp->v_mount->mnt_stat.f_iosize;
369 	seqcount = (int)((off_t)(ioflag >> IO_SEQSHIFT) * biosize / BKVASIZE);
370 
371 	/*
372 	 * For nfs, cache consistency can only be maintained approximately.
373 	 * Although RFC1094 does not specify the criteria, the following is
374 	 * believed to be compatible with the reference port.
375 	 *
376 	 * NFS:		If local changes have been made and this is a
377 	 *		directory, the directory must be invalidated and
378 	 *		the attribute cache must be cleared.
379 	 *
380 	 *		GETATTR is called to synchronize the file size.
381 	 *
382 	 *		If remote changes are detected local data is flushed
383 	 *		and the cache is invalidated.
384 	 *
385 	 *		NOTE: In the normal case the attribute cache is not
386 	 *		cleared which means GETATTR may use cached data and
387 	 *		not immediately detect changes made on the server.
388 	 */
389 	if ((np->n_flag & NLMODIFIED) && vp->v_type == VDIR) {
390 		nfs_invaldir(vp);
391 		error = nfs_vinvalbuf(vp, V_SAVE, 1);
392 		if (error)
393 			return (error);
394 		np->n_attrstamp = 0;
395 	}
396 	error = VOP_GETATTR(vp, &vattr);
397 	if (error)
398 		return (error);
399 	if (np->n_flag & NRMODIFIED) {
400 		if (vp->v_type == VDIR)
401 			nfs_invaldir(vp);
402 		error = nfs_vinvalbuf(vp, V_SAVE, 1);
403 		if (error)
404 			return (error);
405 		np->n_flag &= ~NRMODIFIED;
406 	}
407 	do {
408 	    if (np->n_flag & NDONTCACHE) {
409 		switch (vp->v_type) {
410 		case VREG:
411 			return (nfs_readrpc_uio(vp, uio));
412 		case VLNK:
413 			return (nfs_readlinkrpc_uio(vp, uio));
414 		case VDIR:
415 			break;
416 		default:
417 			kprintf(" NDONTCACHE: type %x unexpected\n", vp->v_type);
418 			break;
419 		};
420 	    }
421 	    switch (vp->v_type) {
422 	    case VREG:
423 		nfsstats.biocache_reads++;
424 		lbn = uio->uio_offset / biosize;
425 		on = uio->uio_offset & (biosize - 1);
426 		loffset = (off_t)lbn * biosize;
427 
428 		/*
429 		 * Start the read ahead(s), as required.
430 		 */
431 		if (nmp->nm_readahead > 0 && nfs_asyncok(nmp)) {
432 		    for (nra = 0; nra < nmp->nm_readahead && nra < seqcount &&
433 			(off_t)(lbn + 1 + nra) * biosize < np->n_size; nra++) {
434 			rabn = lbn + 1 + nra;
435 			raoffset = (off_t)rabn * biosize;
436 			if (findblk(vp, raoffset, FINDBLK_TEST) == NULL) {
437 			    rabp = nfs_getcacheblk(vp, raoffset, biosize, td);
438 			    if (!rabp)
439 				return (EINTR);
440 			    if ((rabp->b_flags & (B_CACHE|B_DELWRI)) == 0) {
441 				rabp->b_cmd = BUF_CMD_READ;
442 				vfs_busy_pages(vp, rabp);
443 				nfs_asyncio(vp, &rabp->b_bio2);
444 			    } else {
445 				brelse(rabp);
446 			    }
447 			}
448 		    }
449 		}
450 
451 		/*
452 		 * Obtain the buffer cache block.  Figure out the buffer size
453 		 * when we are at EOF.  If we are modifying the size of the
454 		 * buffer based on an EOF condition we need to hold
455 		 * nfs_rslock() through obtaining the buffer to prevent
456 		 * a potential writer-appender from messing with n_size.
457 		 * Otherwise we may accidently truncate the buffer and
458 		 * lose dirty data.
459 		 *
460 		 * Note that bcount is *not* DEV_BSIZE aligned.
461 		 */
462 
463 again:
464 		bcount = biosize;
465 		if (loffset >= np->n_size) {
466 			bcount = 0;
467 		} else if (loffset + biosize > np->n_size) {
468 			bcount = np->n_size - loffset;
469 		}
470 		if (bcount != biosize) {
471 			switch(nfs_rslock(np)) {
472 			case ENOLCK:
473 				goto again;
474 				/* not reached */
475 			case EINTR:
476 			case ERESTART:
477 				return(EINTR);
478 				/* not reached */
479 			default:
480 				break;
481 			}
482 		}
483 
484 		bp = nfs_getcacheblk(vp, loffset, bcount, td);
485 
486 		if (bcount != biosize)
487 			nfs_rsunlock(np);
488 		if (!bp)
489 			return (EINTR);
490 
491 		/*
492 		 * If B_CACHE is not set, we must issue the read.  If this
493 		 * fails, we return an error.
494 		 */
495 
496 		if ((bp->b_flags & B_CACHE) == 0) {
497 		    bp->b_cmd = BUF_CMD_READ;
498 		    bp->b_bio2.bio_done = nfsiodone_sync;
499 		    bp->b_bio2.bio_flags |= BIO_SYNC;
500 		    vfs_busy_pages(vp, bp);
501 		    error = nfs_doio(vp, &bp->b_bio2, td);
502 		    if (error) {
503 			brelse(bp);
504 			return (error);
505 		    }
506 		}
507 
508 		/*
509 		 * on is the offset into the current bp.  Figure out how many
510 		 * bytes we can copy out of the bp.  Note that bcount is
511 		 * NOT DEV_BSIZE aligned.
512 		 *
513 		 * Then figure out how many bytes we can copy into the uio.
514 		 */
515 
516 		n = 0;
517 		if (on < bcount)
518 			n = min((unsigned)(bcount - on), uio->uio_resid);
519 		break;
520 	    case VLNK:
521 		biosize = min(NFS_MAXPATHLEN, np->n_size);
522 		nfsstats.biocache_readlinks++;
523 		bp = nfs_getcacheblk(vp, (off_t)0, biosize, td);
524 		if (bp == NULL)
525 			return (EINTR);
526 		if ((bp->b_flags & B_CACHE) == 0) {
527 		    bp->b_cmd = BUF_CMD_READ;
528 		    bp->b_bio2.bio_done = nfsiodone_sync;
529 		    bp->b_bio2.bio_flags |= BIO_SYNC;
530 		    vfs_busy_pages(vp, bp);
531 		    error = nfs_doio(vp, &bp->b_bio2, td);
532 		    if (error) {
533 			bp->b_flags |= B_ERROR | B_INVAL;
534 			brelse(bp);
535 			return (error);
536 		    }
537 		}
538 		n = min(uio->uio_resid, bp->b_bcount - bp->b_resid);
539 		on = 0;
540 		break;
541 	    case VDIR:
542 		nfsstats.biocache_readdirs++;
543 		if (np->n_direofoffset
544 		    && uio->uio_offset >= np->n_direofoffset) {
545 		    return (0);
546 		}
547 		lbn = (uoff_t)uio->uio_offset / NFS_DIRBLKSIZ;
548 		on = uio->uio_offset & (NFS_DIRBLKSIZ - 1);
549 		loffset = uio->uio_offset - on;
550 		bp = nfs_getcacheblk(vp, loffset, NFS_DIRBLKSIZ, td);
551 		if (bp == NULL)
552 		    return (EINTR);
553 
554 		if ((bp->b_flags & B_CACHE) == 0) {
555 		    bp->b_cmd = BUF_CMD_READ;
556 		    bp->b_bio2.bio_done = nfsiodone_sync;
557 		    bp->b_bio2.bio_flags |= BIO_SYNC;
558 		    vfs_busy_pages(vp, bp);
559 		    error = nfs_doio(vp, &bp->b_bio2, td);
560 		    if (error)
561 			    brelse(bp);
562 		    while (error == NFSERR_BAD_COOKIE) {
563 			kprintf("got bad cookie vp %p bp %p\n", vp, bp);
564 			nfs_invaldir(vp);
565 			error = nfs_vinvalbuf(vp, 0, 1);
566 			/*
567 			 * Yuck! The directory has been modified on the
568 			 * server. The only way to get the block is by
569 			 * reading from the beginning to get all the
570 			 * offset cookies.
571 			 *
572 			 * Leave the last bp intact unless there is an error.
573 			 * Loop back up to the while if the error is another
574 			 * NFSERR_BAD_COOKIE (double yuch!).
575 			 */
576 			for (i = 0; i <= lbn && !error; i++) {
577 			    if (np->n_direofoffset
578 				&& (i * NFS_DIRBLKSIZ) >= np->n_direofoffset)
579 				    return (0);
580 			    bp = nfs_getcacheblk(vp, (off_t)i * NFS_DIRBLKSIZ,
581 						 NFS_DIRBLKSIZ, td);
582 			    if (!bp)
583 				return (EINTR);
584 			    if ((bp->b_flags & B_CACHE) == 0) {
585 				    bp->b_cmd = BUF_CMD_READ;
586 				    bp->b_bio2.bio_done = nfsiodone_sync;
587 				    bp->b_bio2.bio_flags |= BIO_SYNC;
588 				    vfs_busy_pages(vp, bp);
589 				    error = nfs_doio(vp, &bp->b_bio2, td);
590 				    /*
591 				     * no error + B_INVAL == directory EOF,
592 				     * use the block.
593 				     */
594 				    if (error == 0 && (bp->b_flags & B_INVAL))
595 					    break;
596 			    }
597 			    /*
598 			     * An error will throw away the block and the
599 			     * for loop will break out.  If no error and this
600 			     * is not the block we want, we throw away the
601 			     * block and go for the next one via the for loop.
602 			     */
603 			    if (error || i < lbn)
604 				    brelse(bp);
605 			}
606 		    }
607 		    /*
608 		     * The above while is repeated if we hit another cookie
609 		     * error.  If we hit an error and it wasn't a cookie error,
610 		     * we give up.
611 		     */
612 		    if (error)
613 			    return (error);
614 		}
615 
616 		/*
617 		 * If not eof and read aheads are enabled, start one.
618 		 * (You need the current block first, so that you have the
619 		 *  directory offset cookie of the next block.)
620 		 */
621 		if (nmp->nm_readahead > 0 && nfs_asyncok(nmp) &&
622 		    (bp->b_flags & B_INVAL) == 0 &&
623 		    (np->n_direofoffset == 0 ||
624 		    loffset + NFS_DIRBLKSIZ < np->n_direofoffset) &&
625 		    (np->n_flag & NDONTCACHE) == 0 &&
626 		    findblk(vp, loffset + NFS_DIRBLKSIZ, FINDBLK_TEST) == NULL
627 		) {
628 			rabp = nfs_getcacheblk(vp, loffset + NFS_DIRBLKSIZ,
629 					       NFS_DIRBLKSIZ, td);
630 			if (rabp) {
631 			    if ((rabp->b_flags & (B_CACHE|B_DELWRI)) == 0) {
632 				rabp->b_cmd = BUF_CMD_READ;
633 				vfs_busy_pages(vp, rabp);
634 				nfs_asyncio(vp, &rabp->b_bio2);
635 			    } else {
636 				brelse(rabp);
637 			    }
638 			}
639 		}
640 		/*
641 		 * Unlike VREG files, whos buffer size ( bp->b_bcount ) is
642 		 * chopped for the EOF condition, we cannot tell how large
643 		 * NFS directories are going to be until we hit EOF.  So
644 		 * an NFS directory buffer is *not* chopped to its EOF.  Now,
645 		 * it just so happens that b_resid will effectively chop it
646 		 * to EOF.  *BUT* this information is lost if the buffer goes
647 		 * away and is reconstituted into a B_CACHE state ( due to
648 		 * being VMIO ) later.  So we keep track of the directory eof
649 		 * in np->n_direofoffset and chop it off as an extra step
650 		 * right here.
651 		 */
652 		n = lmin(uio->uio_resid, NFS_DIRBLKSIZ - bp->b_resid - on);
653 		if (np->n_direofoffset && n > np->n_direofoffset - uio->uio_offset)
654 			n = np->n_direofoffset - uio->uio_offset;
655 		break;
656 	    default:
657 		kprintf(" nfs_bioread: type %x unexpected\n",vp->v_type);
658 		break;
659 	    };
660 
661 	    switch (vp->v_type) {
662 	    case VREG:
663 		if (n > 0)
664 		    error = uiomove(bp->b_data + on, (int)n, uio);
665 		break;
666 	    case VLNK:
667 		if (n > 0)
668 		    error = uiomove(bp->b_data + on, (int)n, uio);
669 		n = 0;
670 		break;
671 	    case VDIR:
672 		if (n > 0) {
673 		    off_t old_off = uio->uio_offset;
674 		    caddr_t cpos, epos;
675 		    struct nfs_dirent *dp;
676 
677 		    /*
678 		     * We are casting cpos to nfs_dirent, it must be
679 		     * int-aligned.
680 		     */
681 		    if (on & 3) {
682 			error = EINVAL;
683 			break;
684 		    }
685 
686 		    cpos = bp->b_data + on;
687 		    epos = bp->b_data + on + n;
688 		    while (cpos < epos && error == 0 && uio->uio_resid > 0) {
689 			    dp = (struct nfs_dirent *)cpos;
690 			    error = nfs_check_dirent(dp, (int)(epos - cpos));
691 			    if (error)
692 				    break;
693 			    if (vop_write_dirent(&error, uio, dp->nfs_ino,
694 				dp->nfs_type, dp->nfs_namlen, dp->nfs_name)) {
695 				    break;
696 			    }
697 			    cpos += dp->nfs_reclen;
698 		    }
699 		    n = 0;
700 		    if (error == 0)
701 			    uio->uio_offset = old_off + cpos - bp->b_data - on;
702 		}
703 		/*
704 		 * Invalidate buffer if caching is disabled, forcing a
705 		 * re-read from the remote later.
706 		 */
707 		if (np->n_flag & NDONTCACHE)
708 			bp->b_flags |= B_INVAL;
709 		break;
710 	    default:
711 		kprintf(" nfs_bioread: type %x unexpected\n",vp->v_type);
712 	    }
713 	    brelse(bp);
714 	} while (error == 0 && uio->uio_resid > 0 && n > 0);
715 	return (error);
716 }
717 
718 /*
719  * Userland can supply any 'seek' offset when reading a NFS directory.
720  * Validate the structure so we don't panic the kernel.  Note that
721  * the element name is nul terminated and the nul is not included
722  * in nfs_namlen.
723  */
724 static
725 int
726 nfs_check_dirent(struct nfs_dirent *dp, int maxlen)
727 {
728 	int nfs_name_off = offsetof(struct nfs_dirent, nfs_name[0]);
729 
730 	if (nfs_name_off >= maxlen)
731 		return (EINVAL);
732 	if (dp->nfs_reclen < nfs_name_off || dp->nfs_reclen > maxlen)
733 		return (EINVAL);
734 	if (nfs_name_off + dp->nfs_namlen >= dp->nfs_reclen)
735 		return (EINVAL);
736 	if (dp->nfs_reclen & 3)
737 		return (EINVAL);
738 	return (0);
739 }
740 
741 /*
742  * Vnode op for write using bio
743  *
744  * nfs_write(struct vnode *a_vp, struct uio *a_uio, int a_ioflag,
745  *	     struct ucred *a_cred)
746  */
747 int
748 nfs_write(struct vop_write_args *ap)
749 {
750 	struct uio *uio = ap->a_uio;
751 	struct thread *td = uio->uio_td;
752 	struct vnode *vp = ap->a_vp;
753 	struct nfsnode *np = VTONFS(vp);
754 	int ioflag = ap->a_ioflag;
755 	struct buf *bp;
756 	struct vattr vattr;
757 	struct nfsmount *nmp = VFSTONFS(vp->v_mount);
758 	daddr_t lbn;
759 	off_t loffset;
760 	int n, on, error = 0, iomode, must_commit;
761 	int haverslock = 0;
762 	int bcount;
763 	int biosize;
764 
765 #ifdef DIAGNOSTIC
766 	if (uio->uio_rw != UIO_WRITE)
767 		panic("nfs_write mode");
768 	if (uio->uio_segflg == UIO_USERSPACE && uio->uio_td != curthread)
769 		panic("nfs_write proc");
770 #endif
771 	if (vp->v_type != VREG)
772 		return (EIO);
773 	if (np->n_flag & NWRITEERR) {
774 		np->n_flag &= ~NWRITEERR;
775 		return (np->n_error);
776 	}
777 	if ((nmp->nm_flag & NFSMNT_NFSV3) != 0 &&
778 	    (nmp->nm_state & NFSSTA_GOTFSINFO) == 0)
779 		(void)nfs_fsinfo(nmp, vp, td);
780 
781 	/*
782 	 * Synchronously flush pending buffers if we are in synchronous
783 	 * mode or if we are appending.
784 	 */
785 	if (ioflag & (IO_APPEND | IO_SYNC)) {
786 		if (np->n_flag & NLMODIFIED) {
787 			np->n_attrstamp = 0;
788 			error = nfs_flush(vp, MNT_WAIT, td, 0);
789 			/* error = nfs_vinvalbuf(vp, V_SAVE, 1); */
790 			if (error)
791 				return (error);
792 		}
793 	}
794 
795 	/*
796 	 * If IO_APPEND then load uio_offset.  We restart here if we cannot
797 	 * get the append lock.
798 	 */
799 restart:
800 	if (ioflag & IO_APPEND) {
801 		np->n_attrstamp = 0;
802 		error = VOP_GETATTR(vp, &vattr);
803 		if (error)
804 			return (error);
805 		uio->uio_offset = np->n_size;
806 	}
807 
808 	if (uio->uio_offset < 0)
809 		return (EINVAL);
810 	if ((uio->uio_offset + uio->uio_resid) > nmp->nm_maxfilesize)
811 		return (EFBIG);
812 	if (uio->uio_resid == 0)
813 		return (0);
814 
815 	/*
816 	 * We need to obtain the rslock if we intend to modify np->n_size
817 	 * in order to guarentee the append point with multiple contending
818 	 * writers, to guarentee that no other appenders modify n_size
819 	 * while we are trying to obtain a truncated buffer (i.e. to avoid
820 	 * accidently truncating data written by another appender due to
821 	 * the race), and to ensure that the buffer is populated prior to
822 	 * our extending of the file.  We hold rslock through the entire
823 	 * operation.
824 	 *
825 	 * Note that we do not synchronize the case where someone truncates
826 	 * the file while we are appending to it because attempting to lock
827 	 * this case may deadlock other parts of the system unexpectedly.
828 	 */
829 	if ((ioflag & IO_APPEND) ||
830 	    uio->uio_offset + uio->uio_resid > np->n_size) {
831 		switch(nfs_rslock(np)) {
832 		case ENOLCK:
833 			goto restart;
834 			/* not reached */
835 		case EINTR:
836 		case ERESTART:
837 			return(EINTR);
838 			/* not reached */
839 		default:
840 			break;
841 		}
842 		haverslock = 1;
843 	}
844 
845 	/*
846 	 * Maybe this should be above the vnode op call, but so long as
847 	 * file servers have no limits, i don't think it matters
848 	 */
849 	if (td->td_proc && uio->uio_offset + uio->uio_resid >
850 	      td->td_proc->p_rlimit[RLIMIT_FSIZE].rlim_cur) {
851 		lwpsignal(td->td_proc, td->td_lwp, SIGXFSZ);
852 		if (haverslock)
853 			nfs_rsunlock(np);
854 		return (EFBIG);
855 	}
856 
857 	biosize = vp->v_mount->mnt_stat.f_iosize;
858 
859 	do {
860 		if ((np->n_flag & NDONTCACHE) && uio->uio_iovcnt == 1) {
861 		    iomode = NFSV3WRITE_FILESYNC;
862 		    error = nfs_writerpc_uio(vp, uio, &iomode, &must_commit);
863 		    if (must_commit)
864 			    nfs_clearcommit(vp->v_mount);
865 		    break;
866 		}
867 		nfsstats.biocache_writes++;
868 		lbn = uio->uio_offset / biosize;
869 		on = uio->uio_offset & (biosize-1);
870 		loffset = uio->uio_offset - on;
871 		n = min((unsigned)(biosize - on), uio->uio_resid);
872 again:
873 		/*
874 		 * Handle direct append and file extension cases, calculate
875 		 * unaligned buffer size.
876 		 */
877 
878 		if (uio->uio_offset == np->n_size && n) {
879 			/*
880 			 * Get the buffer (in its pre-append state to maintain
881 			 * B_CACHE if it was previously set).  Resize the
882 			 * nfsnode after we have locked the buffer to prevent
883 			 * readers from reading garbage.
884 			 */
885 			bcount = on;
886 			bp = nfs_getcacheblk(vp, loffset, bcount, td);
887 
888 			if (bp != NULL) {
889 				long save;
890 
891 				np->n_size = uio->uio_offset + n;
892 				np->n_flag |= NLMODIFIED;
893 				vnode_pager_setsize(vp, np->n_size);
894 
895 				save = bp->b_flags & B_CACHE;
896 				bcount += n;
897 				allocbuf(bp, bcount);
898 				bp->b_flags |= save;
899 			}
900 		} else {
901 			/*
902 			 * Obtain the locked cache block first, and then
903 			 * adjust the file's size as appropriate.
904 			 */
905 			bcount = on + n;
906 			if (loffset + bcount < np->n_size) {
907 				if (loffset + biosize < np->n_size)
908 					bcount = biosize;
909 				else
910 					bcount = np->n_size - loffset;
911 			}
912 			bp = nfs_getcacheblk(vp, loffset, bcount, td);
913 			if (uio->uio_offset + n > np->n_size) {
914 				np->n_size = uio->uio_offset + n;
915 				np->n_flag |= NLMODIFIED;
916 				vnode_pager_setsize(vp, np->n_size);
917 			}
918 		}
919 
920 		if (bp == NULL) {
921 			error = EINTR;
922 			break;
923 		}
924 
925 		/*
926 		 * Issue a READ if B_CACHE is not set.  In special-append
927 		 * mode, B_CACHE is based on the buffer prior to the write
928 		 * op and is typically set, avoiding the read.  If a read
929 		 * is required in special append mode, the server will
930 		 * probably send us a short-read since we extended the file
931 		 * on our end, resulting in b_resid == 0 and, thusly,
932 		 * B_CACHE getting set.
933 		 *
934 		 * We can also avoid issuing the read if the write covers
935 		 * the entire buffer.  We have to make sure the buffer state
936 		 * is reasonable in this case since we will not be initiating
937 		 * I/O.  See the comments in kern/vfs_bio.c's getblk() for
938 		 * more information.
939 		 *
940 		 * B_CACHE may also be set due to the buffer being cached
941 		 * normally.
942 		 *
943 		 * When doing a UIO_NOCOPY write the buffer is not
944 		 * overwritten and we cannot just set B_CACHE unconditionally
945 		 * for full-block writes.
946 		 */
947 
948 		if (on == 0 && n == bcount && uio->uio_segflg != UIO_NOCOPY) {
949 			bp->b_flags |= B_CACHE;
950 			bp->b_flags &= ~(B_ERROR | B_INVAL);
951 		}
952 
953 		if ((bp->b_flags & B_CACHE) == 0) {
954 			bp->b_cmd = BUF_CMD_READ;
955 			bp->b_bio2.bio_done = nfsiodone_sync;
956 			bp->b_bio2.bio_flags |= BIO_SYNC;
957 			vfs_busy_pages(vp, bp);
958 			error = nfs_doio(vp, &bp->b_bio2, td);
959 			if (error) {
960 				brelse(bp);
961 				break;
962 			}
963 		}
964 		if (!bp) {
965 			error = EINTR;
966 			break;
967 		}
968 		np->n_flag |= NLMODIFIED;
969 
970 		/*
971 		 * If dirtyend exceeds file size, chop it down.  This should
972 		 * not normally occur but there is an append race where it
973 		 * might occur XXX, so we log it.
974 		 *
975 		 * If the chopping creates a reverse-indexed or degenerate
976 		 * situation with dirtyoff/end, we 0 both of them.
977 		 */
978 
979 		if (bp->b_dirtyend > bcount) {
980 			kprintf("NFS append race @%08llx:%d\n",
981 			    (long long)bp->b_bio2.bio_offset,
982 			    bp->b_dirtyend - bcount);
983 			bp->b_dirtyend = bcount;
984 		}
985 
986 		if (bp->b_dirtyoff >= bp->b_dirtyend)
987 			bp->b_dirtyoff = bp->b_dirtyend = 0;
988 
989 		/*
990 		 * If the new write will leave a contiguous dirty
991 		 * area, just update the b_dirtyoff and b_dirtyend,
992 		 * otherwise force a write rpc of the old dirty area.
993 		 *
994 		 * While it is possible to merge discontiguous writes due to
995 		 * our having a B_CACHE buffer ( and thus valid read data
996 		 * for the hole), we don't because it could lead to
997 		 * significant cache coherency problems with multiple clients,
998 		 * especially if locking is implemented later on.
999 		 *
1000 		 * as an optimization we could theoretically maintain
1001 		 * a linked list of discontinuous areas, but we would still
1002 		 * have to commit them separately so there isn't much
1003 		 * advantage to it except perhaps a bit of asynchronization.
1004 		 */
1005 
1006 		if (bp->b_dirtyend > 0 &&
1007 		    (on > bp->b_dirtyend || (on + n) < bp->b_dirtyoff)) {
1008 			if (bwrite(bp) == EINTR) {
1009 				error = EINTR;
1010 				break;
1011 			}
1012 			goto again;
1013 		}
1014 
1015 		error = uiomove((char *)bp->b_data + on, n, uio);
1016 
1017 		/*
1018 		 * Since this block is being modified, it must be written
1019 		 * again and not just committed.  Since write clustering does
1020 		 * not work for the stage 1 data write, only the stage 2
1021 		 * commit rpc, we have to clear B_CLUSTEROK as well.
1022 		 */
1023 		bp->b_flags &= ~(B_NEEDCOMMIT | B_CLUSTEROK);
1024 
1025 		if (error) {
1026 			bp->b_flags |= B_ERROR;
1027 			brelse(bp);
1028 			break;
1029 		}
1030 
1031 		/*
1032 		 * Only update dirtyoff/dirtyend if not a degenerate
1033 		 * condition.
1034 		 */
1035 		if (n) {
1036 			if (bp->b_dirtyend > 0) {
1037 				bp->b_dirtyoff = min(on, bp->b_dirtyoff);
1038 				bp->b_dirtyend = max((on + n), bp->b_dirtyend);
1039 			} else {
1040 				bp->b_dirtyoff = on;
1041 				bp->b_dirtyend = on + n;
1042 			}
1043 			vfs_bio_set_validclean(bp, on, n);
1044 		}
1045 
1046 		/*
1047 		 * If the lease is non-cachable or IO_SYNC do bwrite().
1048 		 *
1049 		 * IO_INVAL appears to be unused.  The idea appears to be
1050 		 * to turn off caching in this case.  Very odd.  XXX
1051 		 *
1052 		 * If nfs_async is set bawrite() will use an unstable write
1053 		 * (build dirty bufs on the server), so we might as well
1054 		 * push it out with bawrite().  If nfs_async is not set we
1055 		 * use bdwrite() to cache dirty bufs on the client.
1056 		 */
1057 		if ((np->n_flag & NDONTCACHE) || (ioflag & IO_SYNC)) {
1058 			if (ioflag & IO_INVAL)
1059 				bp->b_flags |= B_NOCACHE;
1060 			error = bwrite(bp);
1061 			if (error)
1062 				break;
1063 			if (np->n_flag & NDONTCACHE) {
1064 				error = nfs_vinvalbuf(vp, V_SAVE, 1);
1065 				if (error)
1066 					break;
1067 			}
1068 		} else if ((n + on) == biosize && nfs_async) {
1069 			bawrite(bp);
1070 		} else {
1071 			bdwrite(bp);
1072 		}
1073 	} while (uio->uio_resid > 0 && n > 0);
1074 
1075 	if (haverslock)
1076 		nfs_rsunlock(np);
1077 
1078 	return (error);
1079 }
1080 
1081 /*
1082  * Get an nfs cache block.
1083  *
1084  * Allocate a new one if the block isn't currently in the cache
1085  * and return the block marked busy. If the calling process is
1086  * interrupted by a signal for an interruptible mount point, return
1087  * NULL.
1088  *
1089  * The caller must carefully deal with the possible B_INVAL state of
1090  * the buffer.  nfs_startio() clears B_INVAL (and nfs_asyncio() clears it
1091  * indirectly), so synchronous reads can be issued without worrying about
1092  * the B_INVAL state.  We have to be a little more careful when dealing
1093  * with writes (see comments in nfs_write()) when extending a file past
1094  * its EOF.
1095  */
1096 static struct buf *
1097 nfs_getcacheblk(struct vnode *vp, off_t loffset, int size, struct thread *td)
1098 {
1099 	struct buf *bp;
1100 	struct mount *mp;
1101 	struct nfsmount *nmp;
1102 
1103 	mp = vp->v_mount;
1104 	nmp = VFSTONFS(mp);
1105 
1106 	if (nmp->nm_flag & NFSMNT_INT) {
1107 		bp = getblk(vp, loffset, size, GETBLK_PCATCH, 0);
1108 		while (bp == NULL) {
1109 			if (nfs_sigintr(nmp, NULL, td))
1110 				return (NULL);
1111 			bp = getblk(vp, loffset, size, 0, 2 * hz);
1112 		}
1113 	} else {
1114 		bp = getblk(vp, loffset, size, 0, 0);
1115 	}
1116 
1117 	/*
1118 	 * bio2, the 'device' layer.  Since BIOs use 64 bit byte offsets
1119 	 * now, no translation is necessary.
1120 	 */
1121 	bp->b_bio2.bio_offset = loffset;
1122 	return (bp);
1123 }
1124 
1125 /*
1126  * Flush and invalidate all dirty buffers. If another process is already
1127  * doing the flush, just wait for completion.
1128  */
1129 int
1130 nfs_vinvalbuf(struct vnode *vp, int flags, int intrflg)
1131 {
1132 	struct nfsnode *np = VTONFS(vp);
1133 	struct nfsmount *nmp = VFSTONFS(vp->v_mount);
1134 	int error = 0, slpflag, slptimeo;
1135 	thread_t td = curthread;
1136 
1137 	if (vp->v_flag & VRECLAIMED)
1138 		return (0);
1139 
1140 	if ((nmp->nm_flag & NFSMNT_INT) == 0)
1141 		intrflg = 0;
1142 	if (intrflg) {
1143 		slpflag = PCATCH;
1144 		slptimeo = 2 * hz;
1145 	} else {
1146 		slpflag = 0;
1147 		slptimeo = 0;
1148 	}
1149 	/*
1150 	 * First wait for any other process doing a flush to complete.
1151 	 */
1152 	while (np->n_flag & NFLUSHINPROG) {
1153 		np->n_flag |= NFLUSHWANT;
1154 		error = tsleep((caddr_t)&np->n_flag, 0, "nfsvinval", slptimeo);
1155 		if (error && intrflg && nfs_sigintr(nmp, NULL, td))
1156 			return (EINTR);
1157 	}
1158 
1159 	/*
1160 	 * Now, flush as required.
1161 	 */
1162 	np->n_flag |= NFLUSHINPROG;
1163 	error = vinvalbuf(vp, flags, slpflag, 0);
1164 	while (error) {
1165 		if (intrflg && nfs_sigintr(nmp, NULL, td)) {
1166 			np->n_flag &= ~NFLUSHINPROG;
1167 			if (np->n_flag & NFLUSHWANT) {
1168 				np->n_flag &= ~NFLUSHWANT;
1169 				wakeup((caddr_t)&np->n_flag);
1170 			}
1171 			return (EINTR);
1172 		}
1173 		error = vinvalbuf(vp, flags, 0, slptimeo);
1174 	}
1175 	np->n_flag &= ~(NLMODIFIED | NFLUSHINPROG);
1176 	if (np->n_flag & NFLUSHWANT) {
1177 		np->n_flag &= ~NFLUSHWANT;
1178 		wakeup((caddr_t)&np->n_flag);
1179 	}
1180 	return (0);
1181 }
1182 
1183 /*
1184  * Return true (non-zero) if the txthread and rxthread are operational
1185  * and we do not already have too many not-yet-started BIO's built up.
1186  */
1187 int
1188 nfs_asyncok(struct nfsmount *nmp)
1189 {
1190 	return (nmp->nm_bioqlen < nfs_maxasyncbio &&
1191 		nmp->nm_bioqlen < nmp->nm_maxasync_scaled / NFS_ASYSCALE &&
1192 		nmp->nm_rxstate <= NFSSVC_PENDING &&
1193 		nmp->nm_txstate <= NFSSVC_PENDING);
1194 }
1195 
1196 /*
1197  * The read-ahead code calls this to queue a bio to the txthread.
1198  *
1199  * We don't touch the bio otherwise... that is, we do not even
1200  * construct or send the initial rpc.  The txthread will do it
1201  * for us.
1202  *
1203  * NOTE!  nm_bioqlen is not decremented until the request completes,
1204  *	  so it does not reflect the number of bio's on bioq.
1205  */
1206 void
1207 nfs_asyncio(struct vnode *vp, struct bio *bio)
1208 {
1209 	struct buf *bp = bio->bio_buf;
1210 	struct nfsmount *nmp = VFSTONFS(vp->v_mount);
1211 
1212 	KKASSERT(vp->v_tag == VT_NFS);
1213 	BUF_KERNPROC(bp);
1214 	bio->bio_driver_info = vp;
1215 	crit_enter();
1216 	TAILQ_INSERT_TAIL(&nmp->nm_bioq, bio, bio_act);
1217 	atomic_add_int(&nmp->nm_bioqlen, 1);
1218 	crit_exit();
1219 	nfssvc_iod_writer_wakeup(nmp);
1220 }
1221 
1222 /*
1223  * nfs_dio()	- Execute a BIO operation synchronously.  The BIO will be
1224  *		  completed and its error returned.  The caller is responsible
1225  *		  for brelse()ing it.  ONLY USE FOR BIO_SYNC IOs!  Otherwise
1226  *		  our error probe will be against an invalid pointer.
1227  *
1228  * nfs_startio()- Execute a BIO operation assynchronously.
1229  *
1230  * NOTE: nfs_asyncio() is used to initiate an asynchronous BIO operation,
1231  *	 which basically just queues it to the txthread.  nfs_startio()
1232  *	 actually initiates the I/O AFTER it has gotten to the txthread.
1233  *
1234  * NOTE: td might be NULL.
1235  */
1236 void
1237 nfs_startio(struct vnode *vp, struct bio *bio, struct thread *td)
1238 {
1239 	struct buf *bp = bio->bio_buf;
1240 	struct nfsnode *np;
1241 	struct nfsmount *nmp;
1242 
1243 	KKASSERT(vp->v_tag == VT_NFS);
1244 	np = VTONFS(vp);
1245 	nmp = VFSTONFS(vp->v_mount);
1246 
1247 	/*
1248 	 * clear B_ERROR and B_INVAL state prior to initiating the I/O.  We
1249 	 * do this here so we do not have to do it in all the code that
1250 	 * calls us.
1251 	 */
1252 	bp->b_flags &= ~(B_ERROR | B_INVAL);
1253 
1254 	KASSERT(bp->b_cmd != BUF_CMD_DONE,
1255 		("nfs_doio: bp %p already marked done!", bp));
1256 
1257 	if (bp->b_cmd == BUF_CMD_READ) {
1258 	    switch (vp->v_type) {
1259 	    case VREG:
1260 		nfsstats.read_bios++;
1261 		nfs_readrpc_bio(vp, bio);
1262 		break;
1263 	    case VLNK:
1264 #if 0
1265 		bio->bio_offset = 0;
1266 		nfsstats.readlink_bios++;
1267 		nfs_readlinkrpc_bio(vp, bio);
1268 #else
1269 		nfs_doio(vp, bio, td);
1270 #endif
1271 		break;
1272 	    case VDIR:
1273 		/*
1274 		 * NOTE: If nfs_readdirplusrpc_bio() is requested but
1275 		 *	 not supported, it will chain to
1276 		 *	 nfs_readdirrpc_bio().
1277 		 */
1278 #if 0
1279 		nfsstats.readdir_bios++;
1280 		uiop->uio_offset = bio->bio_offset;
1281 		if (nmp->nm_flag & NFSMNT_RDIRPLUS)
1282 			nfs_readdirplusrpc_bio(vp, bio);
1283 		else
1284 			nfs_readdirrpc_bio(vp, bio);
1285 #else
1286 		nfs_doio(vp, bio, td);
1287 #endif
1288 		break;
1289 	    default:
1290 		kprintf("nfs_doio:  type %x unexpected\n",vp->v_type);
1291 		bp->b_flags |= B_ERROR;
1292 		bp->b_error = EINVAL;
1293 		biodone(bio);
1294 		break;
1295 	    }
1296 	} else {
1297 	    /*
1298 	     * If we only need to commit, try to commit.  If this fails
1299 	     * it will chain through to the write.  Basically all the logic
1300 	     * in nfs_doio() is replicated.
1301 	     */
1302 	    KKASSERT(bp->b_cmd == BUF_CMD_WRITE);
1303 	    if (bp->b_flags & B_NEEDCOMMIT)
1304 		nfs_commitrpc_bio(vp, bio);
1305 	    else
1306 		nfs_writerpc_bio(vp, bio);
1307 	}
1308 }
1309 
1310 int
1311 nfs_doio(struct vnode *vp, struct bio *bio, struct thread *td)
1312 {
1313 	struct buf *bp = bio->bio_buf;
1314 	struct uio *uiop;
1315 	struct nfsnode *np;
1316 	struct nfsmount *nmp;
1317 	int error = 0;
1318 	int iomode, must_commit;
1319 	struct uio uio;
1320 	struct iovec io;
1321 
1322 	KKASSERT(vp->v_tag == VT_NFS);
1323 	np = VTONFS(vp);
1324 	nmp = VFSTONFS(vp->v_mount);
1325 	uiop = &uio;
1326 	uiop->uio_iov = &io;
1327 	uiop->uio_iovcnt = 1;
1328 	uiop->uio_segflg = UIO_SYSSPACE;
1329 	uiop->uio_td = td;
1330 
1331 	/*
1332 	 * clear B_ERROR and B_INVAL state prior to initiating the I/O.  We
1333 	 * do this here so we do not have to do it in all the code that
1334 	 * calls us.
1335 	 */
1336 	bp->b_flags &= ~(B_ERROR | B_INVAL);
1337 
1338 	KASSERT(bp->b_cmd != BUF_CMD_DONE,
1339 		("nfs_doio: bp %p already marked done!", bp));
1340 
1341 	if (bp->b_cmd == BUF_CMD_READ) {
1342 	    io.iov_len = uiop->uio_resid = bp->b_bcount;
1343 	    io.iov_base = bp->b_data;
1344 	    uiop->uio_rw = UIO_READ;
1345 
1346 	    switch (vp->v_type) {
1347 	    case VREG:
1348 		nfsstats.read_bios++;
1349 		uiop->uio_offset = bio->bio_offset;
1350 		error = nfs_readrpc_uio(vp, uiop);
1351 		if (error == 0) {
1352 		    if (uiop->uio_resid) {
1353 			/*
1354 			 * If we had a short read with no error, we must have
1355 			 * hit a file hole.  We should zero-fill the remainder.
1356 			 * This can also occur if the server hits the file EOF.
1357 			 *
1358 			 * Holes used to be able to occur due to pending
1359 			 * writes, but that is not possible any longer.
1360 			 */
1361 			int nread = bp->b_bcount - bp->b_resid;
1362 			int left  = bp->b_resid;
1363 
1364 			if (left > 0)
1365 				bzero((char *)bp->b_data + nread, left);
1366 			bp->b_resid = 0;
1367 		    }
1368 		}
1369 		if (td && td->td_proc && (vp->v_flag & VTEXT) &&
1370 		    np->n_mtime != np->n_vattr.va_mtime.tv_sec) {
1371 			uprintf("Process killed due to text file modification\n");
1372 			ksignal(td->td_proc, SIGKILL);
1373 		}
1374 		break;
1375 	    case VLNK:
1376 		uiop->uio_offset = 0;
1377 		nfsstats.readlink_bios++;
1378 		error = nfs_readlinkrpc_uio(vp, uiop);
1379 		break;
1380 	    case VDIR:
1381 		nfsstats.readdir_bios++;
1382 		uiop->uio_offset = bio->bio_offset;
1383 		if (nmp->nm_flag & NFSMNT_RDIRPLUS) {
1384 			error = nfs_readdirplusrpc_uio(vp, uiop);
1385 			if (error == NFSERR_NOTSUPP)
1386 				nmp->nm_flag &= ~NFSMNT_RDIRPLUS;
1387 		}
1388 		if ((nmp->nm_flag & NFSMNT_RDIRPLUS) == 0)
1389 			error = nfs_readdirrpc_uio(vp, uiop);
1390 		/*
1391 		 * end-of-directory sets B_INVAL but does not generate an
1392 		 * error.
1393 		 */
1394 		if (error == 0 && uiop->uio_resid == bp->b_bcount)
1395 			bp->b_flags |= B_INVAL;
1396 		break;
1397 	    default:
1398 		kprintf("nfs_doio:  type %x unexpected\n",vp->v_type);
1399 		break;
1400 	    };
1401 	    if (error) {
1402 		bp->b_flags |= B_ERROR;
1403 		bp->b_error = error;
1404 	    }
1405 	    bp->b_resid = uiop->uio_resid;
1406 	} else {
1407 	    /*
1408 	     * If we only need to commit, try to commit
1409 	     */
1410 	    KKASSERT(bp->b_cmd == BUF_CMD_WRITE);
1411 	    if (bp->b_flags & B_NEEDCOMMIT) {
1412 		    int retv;
1413 		    off_t off;
1414 
1415 		    off = bio->bio_offset + bp->b_dirtyoff;
1416 		    retv = nfs_commitrpc_uio(vp, off,
1417 					     bp->b_dirtyend - bp->b_dirtyoff,
1418 					     td);
1419 		    if (retv == 0) {
1420 			    bp->b_dirtyoff = bp->b_dirtyend = 0;
1421 			    bp->b_flags &= ~(B_NEEDCOMMIT | B_CLUSTEROK);
1422 			    bp->b_resid = 0;
1423 			    biodone(bio);
1424 			    return(0);
1425 		    }
1426 		    if (retv == NFSERR_STALEWRITEVERF) {
1427 			    nfs_clearcommit(vp->v_mount);
1428 		    }
1429 	    }
1430 
1431 	    /*
1432 	     * Setup for actual write
1433 	     */
1434 	    if (bio->bio_offset + bp->b_dirtyend > np->n_size)
1435 		bp->b_dirtyend = np->n_size - bio->bio_offset;
1436 
1437 	    if (bp->b_dirtyend > bp->b_dirtyoff) {
1438 		io.iov_len = uiop->uio_resid = bp->b_dirtyend
1439 		    - bp->b_dirtyoff;
1440 		uiop->uio_offset = bio->bio_offset + bp->b_dirtyoff;
1441 		io.iov_base = (char *)bp->b_data + bp->b_dirtyoff;
1442 		uiop->uio_rw = UIO_WRITE;
1443 		nfsstats.write_bios++;
1444 
1445 		if ((bp->b_flags & (B_NEEDCOMMIT | B_NOCACHE | B_CLUSTER)) == 0)
1446 		    iomode = NFSV3WRITE_UNSTABLE;
1447 		else
1448 		    iomode = NFSV3WRITE_FILESYNC;
1449 
1450 		must_commit = 0;
1451 		error = nfs_writerpc_uio(vp, uiop, &iomode, &must_commit);
1452 
1453 		/*
1454 		 * When setting B_NEEDCOMMIT also set B_CLUSTEROK to try
1455 		 * to cluster the buffers needing commit.  This will allow
1456 		 * the system to submit a single commit rpc for the whole
1457 		 * cluster.  We can do this even if the buffer is not 100%
1458 		 * dirty (relative to the NFS blocksize), so we optimize the
1459 		 * append-to-file-case.
1460 		 *
1461 		 * (when clearing B_NEEDCOMMIT, B_CLUSTEROK must also be
1462 		 * cleared because write clustering only works for commit
1463 		 * rpc's, not for the data portion of the write).
1464 		 */
1465 
1466 		if (!error && iomode == NFSV3WRITE_UNSTABLE) {
1467 		    bp->b_flags |= B_NEEDCOMMIT;
1468 		    if (bp->b_dirtyoff == 0
1469 			&& bp->b_dirtyend == bp->b_bcount)
1470 			bp->b_flags |= B_CLUSTEROK;
1471 		} else {
1472 		    bp->b_flags &= ~(B_NEEDCOMMIT | B_CLUSTEROK);
1473 		}
1474 
1475 		/*
1476 		 * For an interrupted write, the buffer is still valid
1477 		 * and the write hasn't been pushed to the server yet,
1478 		 * so we can't set B_ERROR and report the interruption
1479 		 * by setting B_EINTR. For the async case, B_EINTR
1480 		 * is not relevant, so the rpc attempt is essentially
1481 		 * a noop.  For the case of a V3 write rpc not being
1482 		 * committed to stable storage, the block is still
1483 		 * dirty and requires either a commit rpc or another
1484 		 * write rpc with iomode == NFSV3WRITE_FILESYNC before
1485 		 * the block is reused. This is indicated by setting
1486 		 * the B_DELWRI and B_NEEDCOMMIT flags.
1487 		 *
1488 		 * If the buffer is marked B_PAGING, it does not reside on
1489 		 * the vp's paging queues so we cannot call bdirty().  The
1490 		 * bp in this case is not an NFS cache block so we should
1491 		 * be safe. XXX
1492 		 */
1493     		if (error == EINTR
1494 		    || (!error && (bp->b_flags & B_NEEDCOMMIT))) {
1495 			crit_enter();
1496 			bp->b_flags &= ~(B_INVAL|B_NOCACHE);
1497 			if ((bp->b_flags & B_PAGING) == 0)
1498 			    bdirty(bp);
1499 			if (error)
1500 			    bp->b_flags |= B_EINTR;
1501 			crit_exit();
1502 	    	} else {
1503 		    if (error) {
1504 			bp->b_flags |= B_ERROR;
1505 			bp->b_error = np->n_error = error;
1506 			np->n_flag |= NWRITEERR;
1507 		    }
1508 		    bp->b_dirtyoff = bp->b_dirtyend = 0;
1509 		}
1510 		if (must_commit)
1511 		    nfs_clearcommit(vp->v_mount);
1512 		bp->b_resid = uiop->uio_resid;
1513 	    } else {
1514 		bp->b_resid = 0;
1515 	    }
1516 	}
1517 
1518 	/*
1519 	 * I/O was run synchronously, biodone() it and calculate the
1520 	 * error to return.
1521 	 */
1522 	biodone(bio);
1523 	KKASSERT(bp->b_cmd == BUF_CMD_DONE);
1524 	if (bp->b_flags & B_EINTR)
1525 		return (EINTR);
1526 	if (bp->b_flags & B_ERROR)
1527 		return (bp->b_error ? bp->b_error : EIO);
1528 	return (0);
1529 }
1530 
1531 /*
1532  * Used to aid in handling ftruncate() operations on the NFS client side.
1533  * Truncation creates a number of special problems for NFS.  We have to
1534  * throw away VM pages and buffer cache buffers that are beyond EOF, and
1535  * we have to properly handle VM pages or (potentially dirty) buffers
1536  * that straddle the truncation point.
1537  */
1538 
1539 int
1540 nfs_meta_setsize(struct vnode *vp, struct thread *td, u_quad_t nsize)
1541 {
1542 	struct nfsnode *np = VTONFS(vp);
1543 	u_quad_t tsize = np->n_size;
1544 	int biosize = vp->v_mount->mnt_stat.f_iosize;
1545 	int error = 0;
1546 
1547 	np->n_size = nsize;
1548 
1549 	if (np->n_size < tsize) {
1550 		struct buf *bp;
1551 		daddr_t lbn;
1552 		off_t loffset;
1553 		int bufsize;
1554 
1555 		/*
1556 		 * vtruncbuf() doesn't get the buffer overlapping the
1557 		 * truncation point.  We may have a B_DELWRI and/or B_CACHE
1558 		 * buffer that now needs to be truncated.
1559 		 */
1560 		error = vtruncbuf(vp, nsize, biosize);
1561 		lbn = nsize / biosize;
1562 		bufsize = nsize & (biosize - 1);
1563 		loffset = nsize - bufsize;
1564 		bp = nfs_getcacheblk(vp, loffset, bufsize, td);
1565 		if (bp->b_dirtyoff > bp->b_bcount)
1566 			bp->b_dirtyoff = bp->b_bcount;
1567 		if (bp->b_dirtyend > bp->b_bcount)
1568 			bp->b_dirtyend = bp->b_bcount;
1569 		bp->b_flags |= B_RELBUF;  /* don't leave garbage around */
1570 		brelse(bp);
1571 	} else {
1572 		vnode_pager_setsize(vp, nsize);
1573 	}
1574 	return(error);
1575 }
1576 
1577 /*
1578  * Synchronous completion for nfs_doio.  Call bpdone() with elseit=FALSE.
1579  * Caller is responsible for brelse()'ing the bp.
1580  */
1581 static void
1582 nfsiodone_sync(struct bio *bio)
1583 {
1584 	bio->bio_flags = 0;
1585 	bpdone(bio->bio_buf, 0);
1586 }
1587 
1588 /*
1589  * nfs read rpc - BIO version
1590  */
1591 void
1592 nfs_readrpc_bio(struct vnode *vp, struct bio *bio)
1593 {
1594 	struct buf *bp = bio->bio_buf;
1595 	u_int32_t *tl;
1596 	struct nfsmount *nmp;
1597 	int error = 0, len, tsiz;
1598 	struct nfsm_info *info;
1599 
1600 	info = kmalloc(sizeof(*info), M_NFSREQ, M_WAITOK);
1601 	info->mrep = NULL;
1602 	info->v3 = NFS_ISV3(vp);
1603 
1604 	nmp = VFSTONFS(vp->v_mount);
1605 	tsiz = bp->b_bcount;
1606 	KKASSERT(tsiz <= nmp->nm_rsize);
1607 	if (bio->bio_offset + tsiz > nmp->nm_maxfilesize) {
1608 		error = EFBIG;
1609 		goto nfsmout;
1610 	}
1611 	nfsstats.rpccnt[NFSPROC_READ]++;
1612 	len = tsiz;
1613 	nfsm_reqhead(info, vp, NFSPROC_READ,
1614 		     NFSX_FH(info->v3) + NFSX_UNSIGNED * 3);
1615 	ERROROUT(nfsm_fhtom(info, vp));
1616 	tl = nfsm_build(info, NFSX_UNSIGNED * 3);
1617 	if (info->v3) {
1618 		txdr_hyper(bio->bio_offset, tl);
1619 		*(tl + 2) = txdr_unsigned(len);
1620 	} else {
1621 		*tl++ = txdr_unsigned(bio->bio_offset);
1622 		*tl++ = txdr_unsigned(len);
1623 		*tl = 0;
1624 	}
1625 	info->bio = bio;
1626 	info->done = nfs_readrpc_bio_done;
1627 	nfsm_request_bio(info, vp, NFSPROC_READ, NULL,
1628 			 nfs_vpcred(vp, ND_READ));
1629 	return;
1630 nfsmout:
1631 	kfree(info, M_NFSREQ);
1632 	bp->b_error = error;
1633 	bp->b_flags |= B_ERROR;
1634 	biodone(bio);
1635 }
1636 
1637 static void
1638 nfs_readrpc_bio_done(nfsm_info_t info)
1639 {
1640 	struct nfsmount *nmp = VFSTONFS(info->vp->v_mount);
1641 	struct bio *bio = info->bio;
1642 	struct buf *bp = bio->bio_buf;
1643 	u_int32_t *tl;
1644 	int attrflag;
1645 	int retlen;
1646 	int eof;
1647 	int error = 0;
1648 
1649 	KKASSERT(info->state == NFSM_STATE_DONE);
1650 
1651 	if (info->v3) {
1652 		ERROROUT(nfsm_postop_attr(info, info->vp, &attrflag,
1653 					 NFS_LATTR_NOSHRINK));
1654 		NULLOUT(tl = nfsm_dissect(info, 2 * NFSX_UNSIGNED));
1655 		eof = fxdr_unsigned(int, *(tl + 1));
1656 	} else {
1657 		ERROROUT(nfsm_loadattr(info, info->vp, NULL));
1658 		eof = 0;
1659 	}
1660 	NEGATIVEOUT(retlen = nfsm_strsiz(info, nmp->nm_rsize));
1661 	ERROROUT(nfsm_mtobio(info, bio, retlen));
1662 	m_freem(info->mrep);
1663 	info->mrep = NULL;
1664 
1665 	/*
1666 	 * No error occured, fill the hole if any
1667 	 */
1668 	if (retlen < bp->b_bcount) {
1669 		bzero(bp->b_data + retlen, bp->b_bcount - retlen);
1670 	}
1671 	bp->b_resid = bp->b_bcount - retlen;
1672 #if 0
1673 	/* retlen */
1674 	tsiz -= retlen;
1675 	if (info.v3) {
1676 		if (eof || retlen == 0) {
1677 			tsiz = 0;
1678 		}
1679 	} else if (retlen < len) {
1680 		tsiz = 0;
1681 	}
1682 #endif
1683 nfsmout:
1684 	kfree(info, M_NFSREQ);
1685 	if (error) {
1686 		bp->b_error = error;
1687 		bp->b_flags |= B_ERROR;
1688 	}
1689 	biodone(bio);
1690 }
1691 
1692 /*
1693  * nfs write call - BIO version
1694  */
1695 void
1696 nfs_writerpc_bio(struct vnode *vp, struct bio *bio)
1697 {
1698 	struct nfsmount *nmp = VFSTONFS(vp->v_mount);
1699 	struct nfsnode *np = VTONFS(vp);
1700 	struct buf *bp = bio->bio_buf;
1701 	u_int32_t *tl;
1702 	int len;
1703 	int iomode;
1704 	int error = 0;
1705 	struct nfsm_info *info;
1706 	off_t offset;
1707 
1708 	/*
1709 	 * Setup for actual write.  Just clean up the bio if there
1710 	 * is nothing to do.
1711 	 */
1712 	if (bio->bio_offset + bp->b_dirtyend > np->n_size)
1713 		bp->b_dirtyend = np->n_size - bio->bio_offset;
1714 
1715 	if (bp->b_dirtyend <= bp->b_dirtyoff) {
1716 		bp->b_resid = 0;
1717 		biodone(bio);
1718 		return;
1719 	}
1720 	len = bp->b_dirtyend - bp->b_dirtyoff;
1721 	offset = bio->bio_offset + bp->b_dirtyoff;
1722 	if (offset + len > nmp->nm_maxfilesize) {
1723 		bp->b_flags |= B_ERROR;
1724 		bp->b_error = EFBIG;
1725 		biodone(bio);
1726 		return;
1727 	}
1728 	bp->b_resid = len;
1729 	nfsstats.write_bios++;
1730 
1731 	info = kmalloc(sizeof(*info), M_NFSREQ, M_WAITOK);
1732 	info->mrep = NULL;
1733 	info->v3 = NFS_ISV3(vp);
1734 	info->info_writerpc.must_commit = 0;
1735 	if ((bp->b_flags & (B_NEEDCOMMIT | B_NOCACHE | B_CLUSTER)) == 0)
1736 		iomode = NFSV3WRITE_UNSTABLE;
1737 	else
1738 		iomode = NFSV3WRITE_FILESYNC;
1739 
1740 	KKASSERT(len <= nmp->nm_wsize);
1741 
1742 	nfsstats.rpccnt[NFSPROC_WRITE]++;
1743 	nfsm_reqhead(info, vp, NFSPROC_WRITE,
1744 		     NFSX_FH(info->v3) + 5 * NFSX_UNSIGNED + nfsm_rndup(len));
1745 	ERROROUT(nfsm_fhtom(info, vp));
1746 	if (info->v3) {
1747 		tl = nfsm_build(info, 5 * NFSX_UNSIGNED);
1748 		txdr_hyper(offset, tl);
1749 		tl += 2;
1750 		*tl++ = txdr_unsigned(len);
1751 		*tl++ = txdr_unsigned(iomode);
1752 		*tl = txdr_unsigned(len);
1753 	} else {
1754 		u_int32_t x;
1755 
1756 		tl = nfsm_build(info, 4 * NFSX_UNSIGNED);
1757 		/* Set both "begin" and "current" to non-garbage. */
1758 		x = txdr_unsigned((u_int32_t)offset);
1759 		*tl++ = x;	/* "begin offset" */
1760 		*tl++ = x;	/* "current offset" */
1761 		x = txdr_unsigned(len);
1762 		*tl++ = x;	/* total to this offset */
1763 		*tl = x;	/* size of this write */
1764 	}
1765 	ERROROUT(nfsm_biotom(info, bio, bp->b_dirtyoff, len));
1766 	info->bio = bio;
1767 	info->done = nfs_writerpc_bio_done;
1768 	nfsm_request_bio(info, vp, NFSPROC_WRITE, NULL,
1769 			 nfs_vpcred(vp, ND_WRITE));
1770 	return;
1771 nfsmout:
1772 	kfree(info, M_NFSREQ);
1773 	bp->b_error = error;
1774 	bp->b_flags |= B_ERROR;
1775 	biodone(bio);
1776 }
1777 
1778 static void
1779 nfs_writerpc_bio_done(nfsm_info_t info)
1780 {
1781 	struct nfsmount *nmp = VFSTONFS(info->vp->v_mount);
1782 	struct nfsnode *np = VTONFS(info->vp);
1783 	struct bio *bio = info->bio;
1784 	struct buf *bp = bio->bio_buf;
1785 	int wccflag = NFSV3_WCCRATTR;
1786 	int iomode = NFSV3WRITE_FILESYNC;
1787 	int commit;
1788 	int rlen;
1789 	int error;
1790 	int len = bp->b_resid;	/* b_resid was set to shortened length */
1791 	u_int32_t *tl;
1792 
1793 	if (info->v3) {
1794 		/*
1795 		 * The write RPC returns a before and after mtime.  The
1796 		 * nfsm_wcc_data() macro checks the before n_mtime
1797 		 * against the before time and stores the after time
1798 		 * in the nfsnode's cached vattr and n_mtime field.
1799 		 * The NRMODIFIED bit will be set if the before
1800 		 * time did not match the original mtime.
1801 		 */
1802 		wccflag = NFSV3_WCCCHK;
1803 		ERROROUT(nfsm_wcc_data(info, info->vp, &wccflag));
1804 		if (error == 0) {
1805 			NULLOUT(tl = nfsm_dissect(info, 2 * NFSX_UNSIGNED + NFSX_V3WRITEVERF));
1806 			rlen = fxdr_unsigned(int, *tl++);
1807 			if (rlen == 0) {
1808 				error = NFSERR_IO;
1809 				m_freem(info->mrep);
1810 				info->mrep = NULL;
1811 				goto nfsmout;
1812 			} else if (rlen < len) {
1813 #if 0
1814 				/*
1815 				 * XXX what do we do here?
1816 				 */
1817 				backup = len - rlen;
1818 				uiop->uio_iov->iov_base = (char *)uiop->uio_iov->iov_base - backup;
1819 				uiop->uio_iov->iov_len += backup;
1820 				uiop->uio_offset -= backup;
1821 				uiop->uio_resid += backup;
1822 				len = rlen;
1823 #endif
1824 			}
1825 			commit = fxdr_unsigned(int, *tl++);
1826 
1827 			/*
1828 			 * Return the lowest committment level
1829 			 * obtained by any of the RPCs.
1830 			 */
1831 			if (iomode == NFSV3WRITE_FILESYNC)
1832 				iomode = commit;
1833 			else if (iomode == NFSV3WRITE_DATASYNC &&
1834 				commit == NFSV3WRITE_UNSTABLE)
1835 				iomode = commit;
1836 			if ((nmp->nm_state & NFSSTA_HASWRITEVERF) == 0){
1837 			    bcopy(tl, (caddr_t)nmp->nm_verf, NFSX_V3WRITEVERF);
1838 			    nmp->nm_state |= NFSSTA_HASWRITEVERF;
1839 			} else if (bcmp(tl, nmp->nm_verf, NFSX_V3WRITEVERF)) {
1840 			    info->info_writerpc.must_commit = 1;
1841 			    bcopy(tl, (caddr_t)nmp->nm_verf, NFSX_V3WRITEVERF);
1842 			}
1843 		}
1844 	} else {
1845 		ERROROUT(nfsm_loadattr(info, info->vp, NULL));
1846 	}
1847 	m_freem(info->mrep);
1848 	info->mrep = NULL;
1849 	len = 0;
1850 nfsmout:
1851 	if (info->vp->v_mount->mnt_flag & MNT_ASYNC)
1852 		iomode = NFSV3WRITE_FILESYNC;
1853 	bp->b_resid = len;
1854 
1855 	/*
1856 	 * End of RPC.  Now clean up the bp.
1857 	 *
1858 	 * When setting B_NEEDCOMMIT also set B_CLUSTEROK to try
1859 	 * to cluster the buffers needing commit.  This will allow
1860 	 * the system to submit a single commit rpc for the whole
1861 	 * cluster.  We can do this even if the buffer is not 100%
1862 	 * dirty (relative to the NFS blocksize), so we optimize the
1863 	 * append-to-file-case.
1864 	 *
1865 	 * (when clearing B_NEEDCOMMIT, B_CLUSTEROK must also be
1866 	 * cleared because write clustering only works for commit
1867 	 * rpc's, not for the data portion of the write).
1868 	 */
1869 	if (!error && iomode == NFSV3WRITE_UNSTABLE) {
1870 		bp->b_flags |= B_NEEDCOMMIT;
1871 		if (bp->b_dirtyoff == 0 && bp->b_dirtyend == bp->b_bcount)
1872 			bp->b_flags |= B_CLUSTEROK;
1873 	} else {
1874 		bp->b_flags &= ~(B_NEEDCOMMIT | B_CLUSTEROK);
1875 	}
1876 
1877 	/*
1878 	 * For an interrupted write, the buffer is still valid
1879 	 * and the write hasn't been pushed to the server yet,
1880 	 * so we can't set B_ERROR and report the interruption
1881 	 * by setting B_EINTR. For the async case, B_EINTR
1882 	 * is not relevant, so the rpc attempt is essentially
1883 	 * a noop.  For the case of a V3 write rpc not being
1884 	 * committed to stable storage, the block is still
1885 	 * dirty and requires either a commit rpc or another
1886 	 * write rpc with iomode == NFSV3WRITE_FILESYNC before
1887 	 * the block is reused. This is indicated by setting
1888 	 * the B_DELWRI and B_NEEDCOMMIT flags.
1889 	 *
1890 	 * If the buffer is marked B_PAGING, it does not reside on
1891 	 * the vp's paging queues so we cannot call bdirty().  The
1892 	 * bp in this case is not an NFS cache block so we should
1893 	 * be safe. XXX
1894 	 */
1895 	if (error == EINTR || (!error && (bp->b_flags & B_NEEDCOMMIT))) {
1896 		crit_enter();
1897 		bp->b_flags &= ~(B_INVAL|B_NOCACHE);
1898 		if ((bp->b_flags & B_PAGING) == 0)
1899 			bdirty(bp);
1900 		if (error)
1901 			bp->b_flags |= B_EINTR;
1902 		crit_exit();
1903 	} else {
1904 		if (error) {
1905 			bp->b_flags |= B_ERROR;
1906 			bp->b_error = np->n_error = error;
1907 			np->n_flag |= NWRITEERR;
1908 		}
1909 		bp->b_dirtyoff = bp->b_dirtyend = 0;
1910 	}
1911 	if (info->info_writerpc.must_commit)
1912 		nfs_clearcommit(info->vp->v_mount);
1913 	kfree(info, M_NFSREQ);
1914 	if (error) {
1915 		bp->b_flags |= B_ERROR;
1916 		bp->b_error = error;
1917 	}
1918 	biodone(bio);
1919 }
1920 
1921 /*
1922  * Nfs Version 3 commit rpc - BIO version
1923  *
1924  * This function issues the commit rpc and will chain to a write
1925  * rpc if necessary.
1926  */
1927 void
1928 nfs_commitrpc_bio(struct vnode *vp, struct bio *bio)
1929 {
1930 	struct nfsmount *nmp = VFSTONFS(vp->v_mount);
1931 	struct buf *bp = bio->bio_buf;
1932 	struct nfsm_info *info;
1933 	int error = 0;
1934 	u_int32_t *tl;
1935 
1936 	if ((nmp->nm_state & NFSSTA_HASWRITEVERF) == 0) {
1937 		bp->b_dirtyoff = bp->b_dirtyend = 0;
1938 		bp->b_flags &= ~(B_NEEDCOMMIT | B_CLUSTEROK);
1939 		bp->b_resid = 0;
1940 		biodone(bio);
1941 		return;
1942 	}
1943 
1944 	info = kmalloc(sizeof(*info), M_NFSREQ, M_WAITOK);
1945 	info->mrep = NULL;
1946 	info->v3 = 1;
1947 
1948 	nfsstats.rpccnt[NFSPROC_COMMIT]++;
1949 	nfsm_reqhead(info, vp, NFSPROC_COMMIT, NFSX_FH(1));
1950 	ERROROUT(nfsm_fhtom(info, vp));
1951 	tl = nfsm_build(info, 3 * NFSX_UNSIGNED);
1952 	txdr_hyper(bio->bio_offset + bp->b_dirtyoff, tl);
1953 	tl += 2;
1954 	*tl = txdr_unsigned(bp->b_dirtyend - bp->b_dirtyoff);
1955 	info->bio = bio;
1956 	info->done = nfs_commitrpc_bio_done;
1957 	nfsm_request_bio(info, vp, NFSPROC_COMMIT, NULL,
1958 			 nfs_vpcred(vp, ND_WRITE));
1959 	return;
1960 nfsmout:
1961 	/*
1962 	 * Chain to write RPC on (early) error
1963 	 */
1964 	kfree(info, M_NFSREQ);
1965 	nfs_writerpc_bio(vp, bio);
1966 }
1967 
1968 static void
1969 nfs_commitrpc_bio_done(nfsm_info_t info)
1970 {
1971 	struct nfsmount *nmp = VFSTONFS(info->vp->v_mount);
1972 	struct bio *bio = info->bio;
1973 	struct buf *bp = bio->bio_buf;
1974 	u_int32_t *tl;
1975 	int wccflag = NFSV3_WCCRATTR;
1976 	int error = 0;
1977 
1978 	ERROROUT(nfsm_wcc_data(info, info->vp, &wccflag));
1979 	if (error == 0) {
1980 		NULLOUT(tl = nfsm_dissect(info, NFSX_V3WRITEVERF));
1981 		if (bcmp(nmp->nm_verf, tl, NFSX_V3WRITEVERF)) {
1982 			bcopy(tl, nmp->nm_verf, NFSX_V3WRITEVERF);
1983 			error = NFSERR_STALEWRITEVERF;
1984 		}
1985 	}
1986 	m_freem(info->mrep);
1987 	info->mrep = NULL;
1988 
1989 	/*
1990 	 * On completion we must chain to a write bio if an
1991 	 * error occurred.
1992 	 */
1993 nfsmout:
1994 	kfree(info, M_NFSREQ);
1995 	if (error == 0) {
1996 		bp->b_dirtyoff = bp->b_dirtyend = 0;
1997 		bp->b_flags &= ~(B_NEEDCOMMIT | B_CLUSTEROK);
1998 		bp->b_resid = 0;
1999 		biodone(bio);
2000 	} else {
2001 		kprintf("commitrpc_bioC %lld -> CHAIN WRITE\n", bio->bio_offset);
2002 		nfs_writerpc_bio(info->vp, bio);
2003 	}
2004 }
2005 
2006