xref: /dragonfly/sys/vfs/nfs/nfs_bio.c (revision 52e9aa73)
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  */
39 
40 
41 #include <sys/param.h>
42 #include <sys/systm.h>
43 #include <sys/resourcevar.h>
44 #include <sys/signalvar.h>
45 #include <sys/proc.h>
46 #include <sys/buf.h>
47 #include <sys/vnode.h>
48 #include <sys/mount.h>
49 #include <sys/kernel.h>
50 #include <sys/mbuf.h>
51 
52 #include <vm/vm.h>
53 #include <vm/vm_extern.h>
54 #include <vm/vm_page.h>
55 #include <vm/vm_object.h>
56 #include <vm/vm_pager.h>
57 #include <vm/vnode_pager.h>
58 
59 #include <sys/buf2.h>
60 #include <sys/thread2.h>
61 #include <vm/vm_page2.h>
62 
63 #include "rpcv2.h"
64 #include "nfsproto.h"
65 #include "nfs.h"
66 #include "nfsmount.h"
67 #include "nfsnode.h"
68 #include "xdr_subs.h"
69 #include "nfsm_subs.h"
70 
71 
72 static struct buf *nfs_getcacheblk(struct vnode *vp, off_t loffset,
73 				   int size, struct thread *td);
74 static int nfs_check_dirent(struct nfs_dirent *dp, int maxlen);
75 static void nfsiodone_sync(struct bio *bio);
76 static void nfs_readrpc_bio_done(nfsm_info_t info);
77 static void nfs_writerpc_bio_done(nfsm_info_t info);
78 static void nfs_commitrpc_bio_done(nfsm_info_t info);
79 
80 /*
81  * Vnode op for read using bio
82  */
83 int
84 nfs_bioread(struct vnode *vp, struct uio *uio, int ioflag)
85 {
86 	struct nfsnode *np = VTONFS(vp);
87 	int biosize, i;
88 	struct buf *bp, *rabp;
89 	struct vattr vattr;
90 	struct thread *td;
91 	struct nfsmount *nmp = VFSTONFS(vp->v_mount);
92 	off_t lbn, rabn;
93 	off_t raoffset;
94 	off_t loffset;
95 	int seqcount;
96 	int nra, error = 0;
97 	int boff = 0;
98 	size_t n;
99 
100 #ifdef DIAGNOSTIC
101 	if (uio->uio_rw != UIO_READ)
102 		panic("nfs_read mode");
103 #endif
104 	if (uio->uio_resid == 0)
105 		return (0);
106 	if (uio->uio_offset < 0)	/* XXX VDIR cookies can be negative */
107 		return (EINVAL);
108 	td = uio->uio_td;
109 
110 	if ((nmp->nm_flag & NFSMNT_NFSV3) != 0 &&
111 	    (nmp->nm_state & NFSSTA_GOTFSINFO) == 0)
112 		(void)nfs_fsinfo(nmp, vp, td);
113 	if (vp->v_type != VDIR &&
114 	    (uio->uio_offset + uio->uio_resid) > nmp->nm_maxfilesize)
115 		return (EFBIG);
116 	biosize = vp->v_mount->mnt_stat.f_iosize;
117 	seqcount = (int)((off_t)(ioflag >> IO_SEQSHIFT) * biosize / BKVASIZE);
118 
119 	/*
120 	 * For nfs, cache consistency can only be maintained approximately.
121 	 * Although RFC1094 does not specify the criteria, the following is
122 	 * believed to be compatible with the reference port.
123 	 *
124 	 * NFS:		If local changes have been made and this is a
125 	 *		directory, the directory must be invalidated and
126 	 *		the attribute cache must be cleared.
127 	 *
128 	 *		GETATTR is called to synchronize the file size.
129 	 *
130 	 *		If remote changes are detected local data is flushed
131 	 *		and the cache is invalidated.
132 	 *
133 	 *		NOTE: In the normal case the attribute cache is not
134 	 *		cleared which means GETATTR may use cached data and
135 	 *		not immediately detect changes made on the server.
136 	 */
137 	if ((np->n_flag & NLMODIFIED) && vp->v_type == VDIR) {
138 		nfs_invaldir(vp);
139 		error = nfs_vinvalbuf(vp, V_SAVE, 1);
140 		if (error)
141 			return (error);
142 		np->n_attrstamp = 0;
143 	}
144 	error = VOP_GETATTR(vp, &vattr);
145 	if (error)
146 		return (error);
147 
148 	/*
149 	 * This can deadlock getpages/putpages for regular
150 	 * files.  Only do it for directories.
151 	 */
152 	if (np->n_flag & NRMODIFIED) {
153 		if (vp->v_type == VDIR) {
154 			nfs_invaldir(vp);
155 			error = nfs_vinvalbuf(vp, V_SAVE, 1);
156 			if (error)
157 				return (error);
158 			np->n_flag &= ~NRMODIFIED;
159 		}
160 	}
161 
162 	/*
163 	 * Loop until uio exhausted or we hit EOF
164 	 */
165 	do {
166 	    bp = NULL;
167 
168 	    switch (vp->v_type) {
169 	    case VREG:
170 		nfsstats.biocache_reads++;
171 		lbn = uio->uio_offset / biosize;
172 		boff = uio->uio_offset & (biosize - 1);
173 		loffset = lbn * biosize;
174 
175 		/*
176 		 * Start the read ahead(s), as required.
177 		 */
178 		if (nmp->nm_readahead > 0 && nfs_asyncok(nmp)) {
179 		    for (nra = 0; nra < nmp->nm_readahead && nra < seqcount &&
180 			(off_t)(lbn + 1 + nra) * biosize < np->n_size; nra++) {
181 			rabn = lbn + 1 + nra;
182 			raoffset = rabn * biosize;
183 			if (findblk(vp, raoffset, FINDBLK_TEST) == NULL) {
184 			    rabp = nfs_getcacheblk(vp, raoffset, biosize, td);
185 			    if (!rabp)
186 				return (EINTR);
187 			    if ((rabp->b_flags & (B_CACHE|B_DELWRI)) == 0) {
188 				rabp->b_cmd = BUF_CMD_READ;
189 				vfs_busy_pages(vp, rabp);
190 				nfs_asyncio(vp, &rabp->b_bio2);
191 			    } else {
192 				brelse(rabp);
193 			    }
194 			}
195 		    }
196 		}
197 
198 		/*
199 		 * Obtain the buffer cache block.  Figure out the buffer size
200 		 * when we are at EOF.  If we are modifying the size of the
201 		 * buffer based on an EOF condition we need to hold
202 		 * nfs_rslock() through obtaining the buffer to prevent
203 		 * a potential writer-appender from messing with n_size.
204 		 * Otherwise we may accidently truncate the buffer and
205 		 * lose dirty data.
206 		 *
207 		 * Note that bcount is *not* DEV_BSIZE aligned.
208 		 */
209 		if (loffset + boff >= np->n_size) {
210 			n = 0;
211 			break;
212 		}
213 		bp = nfs_getcacheblk(vp, loffset, biosize, td);
214 
215 		if (bp == NULL)
216 			return (EINTR);
217 
218 		/*
219 		 * If B_CACHE is not set, we must issue the read.  If this
220 		 * fails, we return an error.
221 		 */
222 		if ((bp->b_flags & B_CACHE) == 0) {
223 			bp->b_cmd = BUF_CMD_READ;
224 			bp->b_bio2.bio_done = nfsiodone_sync;
225 			bp->b_bio2.bio_flags |= BIO_SYNC;
226 			vfs_busy_pages(vp, bp);
227 			error = nfs_doio(vp, &bp->b_bio2, td);
228 			if (error) {
229 				brelse(bp);
230 				return (error);
231 			}
232 		}
233 
234 		/*
235 		 * on is the offset into the current bp.  Figure out how many
236 		 * bytes we can copy out of the bp.  Note that bcount is
237 		 * NOT DEV_BSIZE aligned.
238 		 *
239 		 * Then figure out how many bytes we can copy into the uio.
240 		 */
241 		n = biosize - boff;
242 		if (n > uio->uio_resid)
243 			n = uio->uio_resid;
244 		if (loffset + boff + n > np->n_size)
245 			n = np->n_size - loffset - boff;
246 		break;
247 	    case VLNK:
248 		biosize = min(NFS_MAXPATHLEN, np->n_size);
249 		nfsstats.biocache_readlinks++;
250 		bp = nfs_getcacheblk(vp, (off_t)0, biosize, td);
251 		if (bp == NULL)
252 			return (EINTR);
253 		if ((bp->b_flags & B_CACHE) == 0) {
254 			bp->b_cmd = BUF_CMD_READ;
255 			bp->b_bio2.bio_done = nfsiodone_sync;
256 			bp->b_bio2.bio_flags |= BIO_SYNC;
257 			vfs_busy_pages(vp, bp);
258 			error = nfs_doio(vp, &bp->b_bio2, td);
259 			if (error) {
260 				bp->b_flags |= B_ERROR | B_INVAL;
261 				brelse(bp);
262 				return (error);
263 			}
264 		}
265 		n = szmin(uio->uio_resid, (size_t)bp->b_bcount - bp->b_resid);
266 		boff = 0;
267 		break;
268 	    case VDIR:
269 		nfsstats.biocache_readdirs++;
270 		if (np->n_direofoffset &&
271 		    uio->uio_offset >= np->n_direofoffset
272 		) {
273 			return (0);
274 		}
275 		lbn = (uoff_t)uio->uio_offset / NFS_DIRBLKSIZ;
276 		boff = uio->uio_offset & (NFS_DIRBLKSIZ - 1);
277 		loffset = uio->uio_offset - boff;
278 		bp = nfs_getcacheblk(vp, loffset, NFS_DIRBLKSIZ, td);
279 		if (bp == NULL)
280 			return (EINTR);
281 
282 		if ((bp->b_flags & B_CACHE) == 0) {
283 		    bp->b_cmd = BUF_CMD_READ;
284 		    bp->b_bio2.bio_done = nfsiodone_sync;
285 		    bp->b_bio2.bio_flags |= BIO_SYNC;
286 		    vfs_busy_pages(vp, bp);
287 		    error = nfs_doio(vp, &bp->b_bio2, td);
288 		    if (error)
289 			    brelse(bp);
290 		    while (error == NFSERR_BAD_COOKIE) {
291 			kprintf("got bad cookie vp %p bp %p\n", vp, bp);
292 			nfs_invaldir(vp);
293 			error = nfs_vinvalbuf(vp, 0, 1);
294 			/*
295 			 * Yuck! The directory has been modified on the
296 			 * server. The only way to get the block is by
297 			 * reading from the beginning to get all the
298 			 * offset cookies.
299 			 *
300 			 * Leave the last bp intact unless there is an error.
301 			 * Loop back up to the while if the error is another
302 			 * NFSERR_BAD_COOKIE (double yuch!).
303 			 */
304 			for (i = 0; i <= lbn && !error; i++) {
305 			    if (np->n_direofoffset
306 				&& (i * NFS_DIRBLKSIZ) >= np->n_direofoffset)
307 				    return (0);
308 			    bp = nfs_getcacheblk(vp, (off_t)i * NFS_DIRBLKSIZ,
309 						 NFS_DIRBLKSIZ, td);
310 			    if (!bp)
311 				return (EINTR);
312 			    if ((bp->b_flags & B_CACHE) == 0) {
313 				    bp->b_cmd = BUF_CMD_READ;
314 				    bp->b_bio2.bio_done = nfsiodone_sync;
315 				    bp->b_bio2.bio_flags |= BIO_SYNC;
316 				    vfs_busy_pages(vp, bp);
317 				    error = nfs_doio(vp, &bp->b_bio2, td);
318 				    /*
319 				     * no error + B_INVAL == directory EOF,
320 				     * use the block.
321 				     */
322 				    if (error == 0 && (bp->b_flags & B_INVAL))
323 					    break;
324 			    }
325 			    /*
326 			     * An error will throw away the block and the
327 			     * for loop will break out.  If no error and this
328 			     * is not the block we want, we throw away the
329 			     * block and go for the next one via the for loop.
330 			     */
331 			    if (error || i < lbn)
332 				    brelse(bp);
333 			}
334 		    }
335 		    /*
336 		     * The above while is repeated if we hit another cookie
337 		     * error.  If we hit an error and it wasn't a cookie error,
338 		     * we give up.
339 		     */
340 		    if (error)
341 			    return (error);
342 		}
343 
344 		/*
345 		 * If not eof and read aheads are enabled, start one.
346 		 * (You need the current block first, so that you have the
347 		 *  directory offset cookie of the next block.)
348 		 */
349 		if (nmp->nm_readahead > 0 && nfs_asyncok(nmp) &&
350 		    (bp->b_flags & B_INVAL) == 0 &&
351 		    (np->n_direofoffset == 0 ||
352 		    loffset + NFS_DIRBLKSIZ < np->n_direofoffset) &&
353 		    findblk(vp, loffset + NFS_DIRBLKSIZ, FINDBLK_TEST) == NULL
354 		) {
355 			rabp = nfs_getcacheblk(vp, loffset + NFS_DIRBLKSIZ,
356 					       NFS_DIRBLKSIZ, td);
357 			if (rabp) {
358 			    if ((rabp->b_flags & (B_CACHE|B_DELWRI)) == 0) {
359 				rabp->b_cmd = BUF_CMD_READ;
360 				vfs_busy_pages(vp, rabp);
361 				nfs_asyncio(vp, &rabp->b_bio2);
362 			    } else {
363 				brelse(rabp);
364 			    }
365 			}
366 		}
367 		/*
368 		 * Unlike VREG files, whos buffer size ( bp->b_bcount ) is
369 		 * chopped for the EOF condition, we cannot tell how large
370 		 * NFS directories are going to be until we hit EOF.  So
371 		 * an NFS directory buffer is *not* chopped to its EOF.  Now,
372 		 * it just so happens that b_resid will effectively chop it
373 		 * to EOF.  *BUT* this information is lost if the buffer goes
374 		 * away and is reconstituted into a B_CACHE state ( due to
375 		 * being VMIO ) later.  So we keep track of the directory eof
376 		 * in np->n_direofoffset and chop it off as an extra step
377 		 * right here.
378 		 *
379 		 * NOTE: boff could already be beyond EOF.
380 		 */
381 		if ((size_t)boff > NFS_DIRBLKSIZ - bp->b_resid) {
382 			n = 0;
383 		} else {
384 			n = szmin(uio->uio_resid,
385 				  NFS_DIRBLKSIZ - bp->b_resid - (size_t)boff);
386 		}
387 		if (np->n_direofoffset &&
388 		    n > (size_t)(np->n_direofoffset - uio->uio_offset)) {
389 			n = (size_t)(np->n_direofoffset - uio->uio_offset);
390 		}
391 		break;
392 	    default:
393 		kprintf(" nfs_bioread: type %x unexpected\n",vp->v_type);
394 		n = 0;
395 		break;
396 	    };
397 
398 	    switch (vp->v_type) {
399 	    case VREG:
400 		if (n > 0)
401 		    error = uiomovebp(bp, bp->b_data + boff, n, uio);
402 		break;
403 	    case VLNK:
404 		if (n > 0)
405 		    error = uiomovebp(bp, bp->b_data + boff, n, uio);
406 		n = 0;
407 		break;
408 	    case VDIR:
409 		if (n > 0) {
410 		    off_t old_off = uio->uio_offset;
411 		    caddr_t cpos, epos;
412 		    struct nfs_dirent *dp;
413 
414 		    /*
415 		     * We are casting cpos to nfs_dirent, it must be
416 		     * int-aligned.
417 		     */
418 		    if (boff & 3) {
419 			error = EINVAL;
420 			break;
421 		    }
422 
423 		    cpos = bp->b_data + boff;
424 		    epos = bp->b_data + boff + n;
425 		    while (cpos < epos && error == 0 && uio->uio_resid > 0) {
426 			    dp = (struct nfs_dirent *)cpos;
427 			    error = nfs_check_dirent(dp, (int)(epos - cpos));
428 			    if (error)
429 				    break;
430 			    if (vop_write_dirent(&error, uio, dp->nfs_ino,
431 				dp->nfs_type, dp->nfs_namlen, dp->nfs_name)) {
432 				    break;
433 			    }
434 			    cpos += dp->nfs_reclen;
435 		    }
436 		    n = 0;
437 		    if (error == 0) {
438 			    uio->uio_offset = old_off + cpos -
439 					      bp->b_data - boff;
440 		    }
441 		}
442 		break;
443 	    default:
444 		kprintf(" nfs_bioread: type %x unexpected\n",vp->v_type);
445 	    }
446 	    if (bp)
447 		    brelse(bp);
448 	} while (error == 0 && uio->uio_resid > 0 && n > 0);
449 	return (error);
450 }
451 
452 /*
453  * Userland can supply any 'seek' offset when reading a NFS directory.
454  * Validate the structure so we don't panic the kernel.  Note that
455  * the element name is nul terminated and the nul is not included
456  * in nfs_namlen.
457  */
458 static
459 int
460 nfs_check_dirent(struct nfs_dirent *dp, int maxlen)
461 {
462 	int nfs_name_off = offsetof(struct nfs_dirent, nfs_name[0]);
463 
464 	if (nfs_name_off >= maxlen)
465 		return (EINVAL);
466 	if (dp->nfs_reclen < nfs_name_off || dp->nfs_reclen > maxlen)
467 		return (EINVAL);
468 	if (nfs_name_off + dp->nfs_namlen >= dp->nfs_reclen)
469 		return (EINVAL);
470 	if (dp->nfs_reclen & 3)
471 		return (EINVAL);
472 	return (0);
473 }
474 
475 /*
476  * Vnode op for write using bio
477  *
478  * nfs_write(struct vnode *a_vp, struct uio *a_uio, int a_ioflag,
479  *	     struct ucred *a_cred)
480  */
481 int
482 nfs_write(struct vop_write_args *ap)
483 {
484 	struct uio *uio = ap->a_uio;
485 	struct thread *td = uio->uio_td;
486 	struct vnode *vp = ap->a_vp;
487 	struct nfsnode *np = VTONFS(vp);
488 	int ioflag = ap->a_ioflag;
489 	struct buf *bp;
490 	struct vattr vattr;
491 	struct nfsmount *nmp = VFSTONFS(vp->v_mount);
492 	off_t loffset;
493 	int boff, bytes;
494 	int error = 0;
495 	int haverslock = 0;
496 	int bcount;
497 	int biosize;
498 	int trivial;
499 
500 #ifdef DIAGNOSTIC
501 	if (uio->uio_rw != UIO_WRITE)
502 		panic("nfs_write mode");
503 	if (uio->uio_segflg == UIO_USERSPACE && uio->uio_td != curthread)
504 		panic("nfs_write proc");
505 #endif
506 	if (vp->v_type != VREG)
507 		return (EIO);
508 
509 	lwkt_gettoken(&nmp->nm_token);
510 
511 	if (np->n_flag & NWRITEERR) {
512 		np->n_flag &= ~NWRITEERR;
513 		lwkt_reltoken(&nmp->nm_token);
514 		return (np->n_error);
515 	}
516 	if ((nmp->nm_flag & NFSMNT_NFSV3) != 0 &&
517 	    (nmp->nm_state & NFSSTA_GOTFSINFO) == 0) {
518 		(void)nfs_fsinfo(nmp, vp, td);
519 	}
520 
521 	/*
522 	 * Synchronously flush pending buffers if we are in synchronous
523 	 * mode or if we are appending.
524 	 */
525 	if (ioflag & (IO_APPEND | IO_SYNC)) {
526 		if (np->n_flag & NLMODIFIED) {
527 			np->n_attrstamp = 0;
528 			error = nfs_flush(vp, MNT_WAIT, td, 0);
529 			/* error = nfs_vinvalbuf(vp, V_SAVE, 1); */
530 			if (error)
531 				goto  done;
532 		}
533 	}
534 
535 	/*
536 	 * If IO_APPEND then load uio_offset.  We restart here if we cannot
537 	 * get the append lock.
538 	 */
539 restart:
540 	if (ioflag & IO_APPEND) {
541 		np->n_attrstamp = 0;
542 		error = VOP_GETATTR(vp, &vattr);
543 		if (error)
544 			goto done;
545 		uio->uio_offset = np->n_size;
546 	}
547 
548 	if (uio->uio_offset < 0) {
549 		error = EINVAL;
550 		goto done;
551 	}
552 	if ((uio->uio_offset + uio->uio_resid) > nmp->nm_maxfilesize) {
553 		error = EFBIG;
554 		goto done;
555 	}
556 	if (uio->uio_resid == 0) {
557 		error = 0;
558 		goto done;
559 	}
560 
561 	/*
562 	 * We need to obtain the rslock if we intend to modify np->n_size
563 	 * in order to guarentee the append point with multiple contending
564 	 * writers, to guarentee that no other appenders modify n_size
565 	 * while we are trying to obtain a truncated buffer (i.e. to avoid
566 	 * accidently truncating data written by another appender due to
567 	 * the race), and to ensure that the buffer is populated prior to
568 	 * our extending of the file.  We hold rslock through the entire
569 	 * operation.
570 	 *
571 	 * Note that we do not synchronize the case where someone truncates
572 	 * the file while we are appending to it because attempting to lock
573 	 * this case may deadlock other parts of the system unexpectedly.
574 	 */
575 	if ((ioflag & IO_APPEND) ||
576 	    uio->uio_offset + uio->uio_resid > np->n_size) {
577 		switch(nfs_rslock(np)) {
578 		case ENOLCK:
579 			goto restart;
580 			/* not reached */
581 		case EINTR:
582 		case ERESTART:
583 			error = EINTR;
584 			goto done;
585 			/* not reached */
586 		default:
587 			break;
588 		}
589 		haverslock = 1;
590 	}
591 
592 	/*
593 	 * Maybe this should be above the vnode op call, but so long as
594 	 * file servers have no limits, i don't think it matters
595 	 */
596 	if (td && td->td_proc && uio->uio_offset + uio->uio_resid >
597 	      td->td_proc->p_rlimit[RLIMIT_FSIZE].rlim_cur) {
598 		lwpsignal(td->td_proc, td->td_lwp, SIGXFSZ);
599 		if (haverslock)
600 			nfs_rsunlock(np);
601 		error = EFBIG;
602 		goto done;
603 	}
604 
605 	biosize = vp->v_mount->mnt_stat.f_iosize;
606 
607 	do {
608 		nfsstats.biocache_writes++;
609 		boff = uio->uio_offset & (biosize-1);
610 		loffset = uio->uio_offset - boff;
611 		bytes = (int)szmin((unsigned)(biosize - boff), uio->uio_resid);
612 again:
613 		/*
614 		 * Handle direct append and file extension cases, calculate
615 		 * unaligned buffer size.  When extending B_CACHE will be
616 		 * set if possible.  See UIO_NOCOPY note below.
617 		 */
618 		if (uio->uio_offset + bytes > np->n_size) {
619 			np->n_flag |= NLMODIFIED;
620 			trivial = (uio->uio_segflg != UIO_NOCOPY &&
621 				   uio->uio_offset <= np->n_size);
622 			nfs_meta_setsize(vp, td, uio->uio_offset + bytes,
623 					 trivial);
624 		}
625 		bp = nfs_getcacheblk(vp, loffset, biosize, td);
626 		if (bp == NULL) {
627 			error = EINTR;
628 			break;
629 		}
630 
631 		/*
632 		 * Actual bytes in buffer which we care about
633 		 */
634 		if (loffset + biosize < np->n_size)
635 			bcount = biosize;
636 		else
637 			bcount = (int)(np->n_size - loffset);
638 
639 		/*
640 		 * Avoid a read by setting B_CACHE where the data we
641 		 * intend to write covers the entire buffer.  Note
642 		 * that the buffer may have been set to B_CACHE by
643 		 * nfs_meta_setsize() above or otherwise inherited the
644 		 * flag, but if B_CACHE isn't set the buffer may be
645 		 * uninitialized and must be zero'd to accomodate
646 		 * future seek+write's.
647 		 *
648 		 * See the comments in kern/vfs_bio.c's getblk() for
649 		 * more information.
650 		 *
651 		 * When doing a UIO_NOCOPY write the buffer is not
652 		 * overwritten and we cannot just set B_CACHE unconditionally
653 		 * for full-block writes.
654 		 */
655 		if (boff == 0 && bytes == biosize &&
656 		    uio->uio_segflg != UIO_NOCOPY) {
657 			bp->b_flags |= B_CACHE;
658 			bp->b_flags &= ~(B_ERROR | B_INVAL);
659 		}
660 
661 		/*
662 		 * b_resid may be set due to file EOF if we extended out.
663 		 * The NFS bio code will zero the difference anyway so
664 		 * just acknowledged the fact and set b_resid to 0.
665 		 */
666 		if ((bp->b_flags & B_CACHE) == 0) {
667 			bp->b_cmd = BUF_CMD_READ;
668 			bp->b_bio2.bio_done = nfsiodone_sync;
669 			bp->b_bio2.bio_flags |= BIO_SYNC;
670 			vfs_busy_pages(vp, bp);
671 			error = nfs_doio(vp, &bp->b_bio2, td);
672 			if (error) {
673 				brelse(bp);
674 				break;
675 			}
676 			bp->b_resid = 0;
677 		}
678 		np->n_flag |= NLMODIFIED;
679 
680 		/*
681 		 * If dirtyend exceeds file size, chop it down.  This should
682 		 * not normally occur but there is an append race where it
683 		 * might occur XXX, so we log it.
684 		 *
685 		 * If the chopping creates a reverse-indexed or degenerate
686 		 * situation with dirtyoff/end, we 0 both of them.
687 		 */
688 		if (bp->b_dirtyend > bcount) {
689 			kprintf("NFS append race @%08llx:%d\n",
690 			    (long long)bp->b_bio2.bio_offset,
691 			    bp->b_dirtyend - bcount);
692 			bp->b_dirtyend = bcount;
693 		}
694 
695 		if (bp->b_dirtyoff >= bp->b_dirtyend)
696 			bp->b_dirtyoff = bp->b_dirtyend = 0;
697 
698 		/*
699 		 * If the new write will leave a contiguous dirty
700 		 * area, just update the b_dirtyoff and b_dirtyend,
701 		 * otherwise force a write rpc of the old dirty area.
702 		 *
703 		 * While it is possible to merge discontiguous writes due to
704 		 * our having a B_CACHE buffer ( and thus valid read data
705 		 * for the hole), we don't because it could lead to
706 		 * significant cache coherency problems with multiple clients,
707 		 * especially if locking is implemented later on.
708 		 *
709 		 * as an optimization we could theoretically maintain
710 		 * a linked list of discontinuous areas, but we would still
711 		 * have to commit them separately so there isn't much
712 		 * advantage to it except perhaps a bit of asynchronization.
713 		 */
714 		if (bp->b_dirtyend > 0 &&
715 		    (boff > bp->b_dirtyend ||
716 		     (boff + bytes) < bp->b_dirtyoff)
717 		) {
718 			if (bwrite(bp) == EINTR) {
719 				error = EINTR;
720 				break;
721 			}
722 			goto again;
723 		}
724 
725 		error = uiomovebp(bp, bp->b_data + boff, bytes, uio);
726 
727 		/*
728 		 * Since this block is being modified, it must be written
729 		 * again and not just committed.  Since write clustering does
730 		 * not work for the stage 1 data write, only the stage 2
731 		 * commit rpc, we have to clear B_CLUSTEROK as well.
732 		 */
733 		bp->b_flags &= ~(B_NEEDCOMMIT | B_CLUSTEROK);
734 
735 		if (error) {
736 			brelse(bp);
737 			break;
738 		}
739 
740 		/*
741 		 * Only update dirtyoff/dirtyend if not a degenerate
742 		 * condition.
743 		 *
744 		 * The underlying VM pages have been marked valid by
745 		 * virtue of acquiring the bp.  Because the entire buffer
746 		 * is marked dirty we do not have to worry about cleaning
747 		 * out the related dirty bits (and wouldn't really know
748 		 * how to deal with byte ranges anyway)
749 		 */
750 		if (bytes) {
751 			if (bp->b_dirtyend > 0) {
752 				bp->b_dirtyoff = imin(boff, bp->b_dirtyoff);
753 				bp->b_dirtyend = imax(boff + bytes,
754 						      bp->b_dirtyend);
755 			} else {
756 				bp->b_dirtyoff = boff;
757 				bp->b_dirtyend = boff + bytes;
758 			}
759 		}
760 
761 		/*
762 		 * If the lease is non-cachable or IO_SYNC do bwrite().
763 		 *
764 		 * IO_INVAL appears to be unused.  The idea appears to be
765 		 * to turn off caching in this case.  Very odd.  XXX
766 		 *
767 		 * If nfs_async is set bawrite() will use an unstable write
768 		 * (build dirty bufs on the server), so we might as well
769 		 * push it out with bawrite().  If nfs_async is not set we
770 		 * use bdwrite() to cache dirty bufs on the client.
771 		 */
772 		if (ioflag & IO_SYNC) {
773 			if (ioflag & IO_INVAL)
774 				bp->b_flags |= B_NOCACHE;
775 			error = bwrite(bp);
776 			if (error)
777 				break;
778 		} else if (boff + bytes == biosize && nfs_async) {
779 			bawrite(bp);
780 		} else {
781 			bdwrite(bp);
782 		}
783 	} while (uio->uio_resid > 0 && bytes > 0);
784 
785 	if (haverslock)
786 		nfs_rsunlock(np);
787 
788 done:
789 	lwkt_reltoken(&nmp->nm_token);
790 	return (error);
791 }
792 
793 /*
794  * Get an nfs cache block.
795  *
796  * Allocate a new one if the block isn't currently in the cache
797  * and return the block marked busy. If the calling process is
798  * interrupted by a signal for an interruptible mount point, return
799  * NULL.
800  *
801  * The caller must carefully deal with the possible B_INVAL state of
802  * the buffer.  nfs_startio() clears B_INVAL (and nfs_asyncio() clears it
803  * indirectly), so synchronous reads can be issued without worrying about
804  * the B_INVAL state.  We have to be a little more careful when dealing
805  * with writes (see comments in nfs_write()) when extending a file past
806  * its EOF.
807  */
808 static struct buf *
809 nfs_getcacheblk(struct vnode *vp, off_t loffset, int size, struct thread *td)
810 {
811 	struct buf *bp;
812 	struct mount *mp;
813 	struct nfsmount *nmp;
814 
815 	mp = vp->v_mount;
816 	nmp = VFSTONFS(mp);
817 
818 	if (nmp->nm_flag & NFSMNT_INT) {
819 		bp = getblk(vp, loffset, size, GETBLK_PCATCH, 0);
820 		while (bp == NULL) {
821 			if (nfs_sigintr(nmp, NULL, td))
822 				return (NULL);
823 			bp = getblk(vp, loffset, size, 0, 2 * hz);
824 		}
825 	} else {
826 		bp = getblk(vp, loffset, size, 0, 0);
827 	}
828 
829 	/*
830 	 * bio2, the 'device' layer.  Since BIOs use 64 bit byte offsets
831 	 * now, no translation is necessary.
832 	 */
833 	bp->b_bio2.bio_offset = loffset;
834 	return (bp);
835 }
836 
837 /*
838  * Flush and invalidate all dirty buffers. If another process is already
839  * doing the flush, just wait for completion.
840  */
841 int
842 nfs_vinvalbuf(struct vnode *vp, int flags, int intrflg)
843 {
844 	struct nfsnode *np = VTONFS(vp);
845 	struct nfsmount *nmp = VFSTONFS(vp->v_mount);
846 	int error = 0, slpflag, slptimeo;
847 	thread_t td = curthread;
848 
849 	if (vp->v_flag & VRECLAIMED)
850 		return (0);
851 
852 	if ((nmp->nm_flag & NFSMNT_INT) == 0)
853 		intrflg = 0;
854 	if (intrflg) {
855 		slpflag = PCATCH;
856 		slptimeo = 2 * hz;
857 	} else {
858 		slpflag = 0;
859 		slptimeo = 0;
860 	}
861 	/*
862 	 * First wait for any other process doing a flush to complete.
863 	 */
864 	while (np->n_flag & NFLUSHINPROG) {
865 		np->n_flag |= NFLUSHWANT;
866 		error = tsleep((caddr_t)&np->n_flag, 0, "nfsvinval", slptimeo);
867 		if (error && intrflg && nfs_sigintr(nmp, NULL, td))
868 			return (EINTR);
869 	}
870 
871 	/*
872 	 * Now, flush as required.
873 	 */
874 	np->n_flag |= NFLUSHINPROG;
875 	error = vinvalbuf(vp, flags, slpflag, 0);
876 	while (error) {
877 		if (intrflg && nfs_sigintr(nmp, NULL, td)) {
878 			np->n_flag &= ~NFLUSHINPROG;
879 			if (np->n_flag & NFLUSHWANT) {
880 				np->n_flag &= ~NFLUSHWANT;
881 				wakeup((caddr_t)&np->n_flag);
882 			}
883 			return (EINTR);
884 		}
885 		error = vinvalbuf(vp, flags, 0, slptimeo);
886 	}
887 	np->n_flag &= ~(NLMODIFIED | NFLUSHINPROG);
888 	if (np->n_flag & NFLUSHWANT) {
889 		np->n_flag &= ~NFLUSHWANT;
890 		wakeup((caddr_t)&np->n_flag);
891 	}
892 	return (0);
893 }
894 
895 /*
896  * Return true (non-zero) if the txthread and rxthread are operational
897  * and we do not already have too many not-yet-started BIO's built up.
898  */
899 int
900 nfs_asyncok(struct nfsmount *nmp)
901 {
902 	return (nmp->nm_bioqlen < nfs_maxasyncbio &&
903 		nmp->nm_bioqlen < nmp->nm_maxasync_scaled / NFS_ASYSCALE &&
904 		nmp->nm_rxstate <= NFSSVC_PENDING &&
905 		nmp->nm_txstate <= NFSSVC_PENDING);
906 }
907 
908 /*
909  * The read-ahead code calls this to queue a bio to the txthread.
910  *
911  * We don't touch the bio otherwise... that is, we do not even
912  * construct or send the initial rpc.  The txthread will do it
913  * for us.
914  *
915  * NOTE!  nm_bioqlen is not decremented until the request completes,
916  *	  so it does not reflect the number of bio's on bioq.
917  */
918 void
919 nfs_asyncio(struct vnode *vp, struct bio *bio)
920 {
921 	struct buf *bp = bio->bio_buf;
922 	struct nfsmount *nmp = VFSTONFS(vp->v_mount);
923 
924 	KKASSERT(vp->v_tag == VT_NFS);
925 	BUF_KERNPROC(bp);
926 
927 	/*
928 	 * Shortcut swap cache (not done automatically because we are not
929 	 * using bread()).
930 	 */
931 	if (vn_cache_strategy(vp, bio))
932 		return;
933 
934 	bio->bio_driver_info = vp;
935 	crit_enter();
936 	TAILQ_INSERT_TAIL(&nmp->nm_bioq, bio, bio_act);
937 	atomic_add_int(&nmp->nm_bioqlen, 1);
938 	crit_exit();
939 	nfssvc_iod_writer_wakeup(nmp);
940 }
941 
942 /*
943  * nfs_doio()	- Execute a BIO operation synchronously.  The BIO will be
944  *		  completed and its error returned.  The caller is responsible
945  *		  for brelse()ing it.  ONLY USE FOR BIO_SYNC IOs!  Otherwise
946  *		  our error probe will be against an invalid pointer.
947  *
948  * nfs_startio()- Execute a BIO operation assynchronously.
949  *
950  * NOTE: nfs_asyncio() is used to initiate an asynchronous BIO operation,
951  *	 which basically just queues it to the txthread.  nfs_startio()
952  *	 actually initiates the I/O AFTER it has gotten to the txthread.
953  *
954  * NOTE: td might be NULL.
955  *
956  * NOTE: Caller has already busied the I/O.
957  */
958 void
959 nfs_startio(struct vnode *vp, struct bio *bio, struct thread *td)
960 {
961 	struct buf *bp = bio->bio_buf;
962 
963 	KKASSERT(vp->v_tag == VT_NFS);
964 
965 	/*
966 	 * clear B_ERROR and B_INVAL state prior to initiating the I/O.  We
967 	 * do this here so we do not have to do it in all the code that
968 	 * calls us.
969 	 */
970 	bp->b_flags &= ~(B_ERROR | B_INVAL);
971 
972 	KASSERT(bp->b_cmd != BUF_CMD_DONE,
973 		("nfs_doio: bp %p already marked done!", bp));
974 
975 	if (bp->b_cmd == BUF_CMD_READ) {
976 	    switch (vp->v_type) {
977 	    case VREG:
978 		nfsstats.read_bios++;
979 		nfs_readrpc_bio(vp, bio);
980 		break;
981 	    case VLNK:
982 #if 0
983 		bio->bio_offset = 0;
984 		nfsstats.readlink_bios++;
985 		nfs_readlinkrpc_bio(vp, bio);
986 #else
987 		nfs_doio(vp, bio, td);
988 #endif
989 		break;
990 	    case VDIR:
991 		/*
992 		 * NOTE: If nfs_readdirplusrpc_bio() is requested but
993 		 *	 not supported, it will chain to
994 		 *	 nfs_readdirrpc_bio().
995 		 */
996 #if 0
997 		nfsstats.readdir_bios++;
998 		uiop->uio_offset = bio->bio_offset;
999 		if (nmp->nm_flag & NFSMNT_RDIRPLUS)
1000 			nfs_readdirplusrpc_bio(vp, bio);
1001 		else
1002 			nfs_readdirrpc_bio(vp, bio);
1003 #else
1004 		nfs_doio(vp, bio, td);
1005 #endif
1006 		break;
1007 	    default:
1008 		kprintf("nfs_doio:  type %x unexpected\n",vp->v_type);
1009 		bp->b_flags |= B_ERROR;
1010 		bp->b_error = EINVAL;
1011 		biodone(bio);
1012 		break;
1013 	    }
1014 	} else {
1015 	    /*
1016 	     * If we only need to commit, try to commit.  If this fails
1017 	     * it will chain through to the write.  Basically all the logic
1018 	     * in nfs_doio() is replicated.
1019 	     */
1020 	    KKASSERT(bp->b_cmd == BUF_CMD_WRITE);
1021 	    if (bp->b_flags & B_NEEDCOMMIT)
1022 		nfs_commitrpc_bio(vp, bio);
1023 	    else
1024 		nfs_writerpc_bio(vp, bio);
1025 	}
1026 }
1027 
1028 int
1029 nfs_doio(struct vnode *vp, struct bio *bio, struct thread *td)
1030 {
1031 	struct buf *bp = bio->bio_buf;
1032 	struct uio *uiop;
1033 	struct nfsnode *np;
1034 	struct nfsmount *nmp;
1035 	int error = 0;
1036 	int iomode, must_commit;
1037 	size_t n;
1038 	struct uio uio;
1039 	struct iovec io;
1040 
1041 #if 0
1042 	/*
1043 	 * Shortcut swap cache (not done automatically because we are not
1044 	 * using bread()).
1045 	 *
1046 	 * XXX The biowait is a hack until we can figure out how to stop a
1047 	 * biodone chain when a middle element is BIO_SYNC.  BIO_SYNC is
1048 	 * set so the bp shouldn't get ripped out from under us.  The only
1049 	 * use-cases are fully synchronous I/O cases.
1050 	 *
1051 	 * XXX This is having problems, give up for now.
1052 	 */
1053 	if (vn_cache_strategy(vp, bio)) {
1054 		error = biowait(&bio->bio_buf->b_bio1, "nfsrsw");
1055 		return (error);
1056 	}
1057 #endif
1058 
1059 	KKASSERT(vp->v_tag == VT_NFS);
1060 	np = VTONFS(vp);
1061 	nmp = VFSTONFS(vp->v_mount);
1062 	uiop = &uio;
1063 	uiop->uio_iov = &io;
1064 	uiop->uio_iovcnt = 1;
1065 	uiop->uio_segflg = UIO_SYSSPACE;
1066 	uiop->uio_td = td;
1067 
1068 	/*
1069 	 * clear B_ERROR and B_INVAL state prior to initiating the I/O.  We
1070 	 * do this here so we do not have to do it in all the code that
1071 	 * calls us.
1072 	 */
1073 	bp->b_flags &= ~(B_ERROR | B_INVAL);
1074 
1075 	KASSERT(bp->b_cmd != BUF_CMD_DONE,
1076 		("nfs_doio: bp %p already marked done!", bp));
1077 
1078 	if (bp->b_cmd == BUF_CMD_READ) {
1079 	    io.iov_len = uiop->uio_resid = (size_t)bp->b_bcount;
1080 	    io.iov_base = bp->b_data;
1081 	    uiop->uio_rw = UIO_READ;
1082 
1083 	    switch (vp->v_type) {
1084 	    case VREG:
1085 		/*
1086 		 * When reading from a regular file zero-fill any residual.
1087 		 * Note that this residual has nothing to do with NFS short
1088 		 * reads, which nfs_readrpc_uio() will handle for us.
1089 		 *
1090 		 * We have to do this because when we are write extending
1091 		 * a file the server may not have the same notion of
1092 		 * filesize as we do.  Our BIOs should already be sized
1093 		 * (b_bcount) to account for the file EOF.
1094 		 */
1095 		nfsstats.read_bios++;
1096 		uiop->uio_offset = bio->bio_offset;
1097 		error = nfs_readrpc_uio(vp, uiop);
1098 		if (error == 0 && uiop->uio_resid) {
1099 			n = (size_t)bp->b_bcount - uiop->uio_resid;
1100 			bzero(bp->b_data + n, bp->b_bcount - n);
1101 			uiop->uio_resid = 0;
1102 		}
1103 		if (td && td->td_proc && (vp->v_flag & VTEXT) &&
1104 		    np->n_mtime != np->n_vattr.va_mtime.tv_sec) {
1105 			uprintf("Process killed due to text file modification\n");
1106 			ksignal(td->td_proc, SIGKILL);
1107 		}
1108 		break;
1109 	    case VLNK:
1110 		uiop->uio_offset = 0;
1111 		nfsstats.readlink_bios++;
1112 		error = nfs_readlinkrpc_uio(vp, uiop);
1113 		break;
1114 	    case VDIR:
1115 		nfsstats.readdir_bios++;
1116 		uiop->uio_offset = bio->bio_offset;
1117 		if (nmp->nm_flag & NFSMNT_RDIRPLUS) {
1118 			error = nfs_readdirplusrpc_uio(vp, uiop);
1119 			if (error == NFSERR_NOTSUPP)
1120 				nmp->nm_flag &= ~NFSMNT_RDIRPLUS;
1121 		}
1122 		if ((nmp->nm_flag & NFSMNT_RDIRPLUS) == 0)
1123 			error = nfs_readdirrpc_uio(vp, uiop);
1124 		/*
1125 		 * end-of-directory sets B_INVAL but does not generate an
1126 		 * error.
1127 		 */
1128 		if (error == 0 && uiop->uio_resid == bp->b_bcount)
1129 			bp->b_flags |= B_INVAL;
1130 		break;
1131 	    default:
1132 		kprintf("nfs_doio:  type %x unexpected\n",vp->v_type);
1133 		break;
1134 	    };
1135 	    if (error) {
1136 		bp->b_flags |= B_ERROR;
1137 		bp->b_error = error;
1138 	    }
1139 	    bp->b_resid = uiop->uio_resid;
1140 	} else {
1141 	    /*
1142 	     * If we only need to commit, try to commit.
1143 	     *
1144 	     * NOTE: The I/O has already been staged for the write and
1145 	     *	     its pages busied, so b_dirtyoff/end is valid.
1146 	     */
1147 	    KKASSERT(bp->b_cmd == BUF_CMD_WRITE);
1148 	    if (bp->b_flags & B_NEEDCOMMIT) {
1149 		    int retv;
1150 		    off_t off;
1151 
1152 		    off = bio->bio_offset + bp->b_dirtyoff;
1153 		    retv = nfs_commitrpc_uio(vp, off,
1154 					     bp->b_dirtyend - bp->b_dirtyoff,
1155 					     td);
1156 		    if (retv == 0) {
1157 			    bp->b_dirtyoff = bp->b_dirtyend = 0;
1158 			    bp->b_flags &= ~(B_NEEDCOMMIT | B_CLUSTEROK);
1159 			    bp->b_resid = 0;
1160 			    biodone(bio);
1161 			    return(0);
1162 		    }
1163 		    if (retv == NFSERR_STALEWRITEVERF) {
1164 			    nfs_clearcommit(vp->v_mount);
1165 		    }
1166 	    }
1167 
1168 	    /*
1169 	     * Setup for actual write
1170 	     */
1171 	    if (bio->bio_offset + bp->b_dirtyend > np->n_size)
1172 		bp->b_dirtyend = np->n_size - bio->bio_offset;
1173 
1174 	    if (bp->b_dirtyend > bp->b_dirtyoff) {
1175 		io.iov_len = uiop->uio_resid = bp->b_dirtyend
1176 		    - bp->b_dirtyoff;
1177 		uiop->uio_offset = bio->bio_offset + bp->b_dirtyoff;
1178 		io.iov_base = (char *)bp->b_data + bp->b_dirtyoff;
1179 		uiop->uio_rw = UIO_WRITE;
1180 		nfsstats.write_bios++;
1181 
1182 		if ((bp->b_flags & (B_NEEDCOMMIT | B_NOCACHE | B_CLUSTER)) == 0)
1183 		    iomode = NFSV3WRITE_UNSTABLE;
1184 		else
1185 		    iomode = NFSV3WRITE_FILESYNC;
1186 
1187 		must_commit = 0;
1188 		error = nfs_writerpc_uio(vp, uiop, &iomode, &must_commit);
1189 
1190 		/*
1191 		 * We no longer try to use kern/vfs_bio's cluster code to
1192 		 * cluster commits, so B_CLUSTEROK is no longer set with
1193 		 * B_NEEDCOMMIT.  The problem is that a vfs_busy_pages()
1194 		 * may have to clear B_NEEDCOMMIT if it finds underlying
1195 		 * pages have been redirtied through a memory mapping
1196 		 * and doing this on a clustered bp will probably cause
1197 		 * a panic, plus the flag in the underlying NFS bufs
1198 		 * making up the cluster bp will not be properly cleared.
1199 		 */
1200 		if (!error && iomode == NFSV3WRITE_UNSTABLE) {
1201 		    bp->b_flags |= B_NEEDCOMMIT;
1202 #if 0
1203 		    /* XXX do not enable commit clustering */
1204 		    if (bp->b_dirtyoff == 0
1205 			&& bp->b_dirtyend == bp->b_bcount)
1206 			bp->b_flags |= B_CLUSTEROK;
1207 #endif
1208 		} else {
1209 		    bp->b_flags &= ~(B_NEEDCOMMIT | B_CLUSTEROK);
1210 		}
1211 
1212 		/*
1213 		 * For an interrupted write, the buffer is still valid
1214 		 * and the write hasn't been pushed to the server yet,
1215 		 * so we can't set B_ERROR and report the interruption
1216 		 * by setting B_EINTR. For the async case, B_EINTR
1217 		 * is not relevant, so the rpc attempt is essentially
1218 		 * a noop.  For the case of a V3 write rpc not being
1219 		 * committed to stable storage, the block is still
1220 		 * dirty and requires either a commit rpc or another
1221 		 * write rpc with iomode == NFSV3WRITE_FILESYNC before
1222 		 * the block is reused. This is indicated by setting
1223 		 * the B_DELWRI and B_NEEDCOMMIT flags.
1224 		 *
1225 		 * If the buffer is marked B_PAGING, it does not reside on
1226 		 * the vp's paging queues so we cannot call bdirty().  The
1227 		 * bp in this case is not an NFS cache block so we should
1228 		 * be safe. XXX
1229 		 */
1230     		if (error == EINTR
1231 		    || (!error && (bp->b_flags & B_NEEDCOMMIT))) {
1232 			crit_enter();
1233 			bp->b_flags &= ~(B_INVAL|B_NOCACHE);
1234 			if ((bp->b_flags & B_PAGING) == 0)
1235 			    bdirty(bp);
1236 			if (error)
1237 			    bp->b_flags |= B_EINTR;
1238 			crit_exit();
1239 	    	} else {
1240 		    if (error) {
1241 			bp->b_flags |= B_ERROR;
1242 			bp->b_error = np->n_error = error;
1243 			np->n_flag |= NWRITEERR;
1244 		    }
1245 		    bp->b_dirtyoff = bp->b_dirtyend = 0;
1246 		}
1247 		if (must_commit)
1248 		    nfs_clearcommit(vp->v_mount);
1249 		bp->b_resid = uiop->uio_resid;
1250 	    } else {
1251 		bp->b_resid = 0;
1252 	    }
1253 	}
1254 
1255 	/*
1256 	 * I/O was run synchronously, biodone() it and calculate the
1257 	 * error to return.
1258 	 */
1259 	biodone(bio);
1260 	KKASSERT(bp->b_cmd == BUF_CMD_DONE);
1261 	if (bp->b_flags & B_EINTR)
1262 		return (EINTR);
1263 	if (bp->b_flags & B_ERROR)
1264 		return (bp->b_error ? bp->b_error : EIO);
1265 	return (0);
1266 }
1267 
1268 /*
1269  * Handle all truncation, write-extend, and ftruncate()-extend operations
1270  * on the NFS lcient side.
1271  *
1272  * We use the new API in kern/vfs_vm.c to perform these operations in a
1273  * VM-friendly way.  With this API VM pages are properly zerod and pages
1274  * still mapped into the buffer straddling EOF are not invalidated.
1275  */
1276 int
1277 nfs_meta_setsize(struct vnode *vp, struct thread *td, off_t nsize, int trivial)
1278 {
1279 	struct nfsnode *np = VTONFS(vp);
1280 	off_t osize;
1281 	int biosize = vp->v_mount->mnt_stat.f_iosize;
1282 	int error;
1283 
1284 	osize = np->n_size;
1285 	np->n_size = nsize;
1286 
1287 	if (nsize < osize) {
1288 		error = nvtruncbuf(vp, nsize, biosize, -1, 0);
1289 	} else {
1290 		error = nvextendbuf(vp, osize, nsize,
1291 				    biosize, biosize, -1, -1,
1292 				    trivial);
1293 	}
1294 	return(error);
1295 }
1296 
1297 /*
1298  * Synchronous completion for nfs_doio.  Call bpdone() with elseit=FALSE.
1299  * Caller is responsible for brelse()'ing the bp.
1300  */
1301 static void
1302 nfsiodone_sync(struct bio *bio)
1303 {
1304 	bio->bio_flags = 0;
1305 	bpdone(bio->bio_buf, 0);
1306 }
1307 
1308 /*
1309  * nfs read rpc - BIO version
1310  */
1311 void
1312 nfs_readrpc_bio(struct vnode *vp, struct bio *bio)
1313 {
1314 	struct buf *bp = bio->bio_buf;
1315 	u_int32_t *tl;
1316 	struct nfsmount *nmp;
1317 	int error = 0, len, tsiz;
1318 	struct nfsm_info *info;
1319 
1320 	info = kmalloc(sizeof(*info), M_NFSREQ, M_WAITOK);
1321 	info->mrep = NULL;
1322 	info->v3 = NFS_ISV3(vp);
1323 
1324 	nmp = VFSTONFS(vp->v_mount);
1325 	tsiz = bp->b_bcount;
1326 	KKASSERT(tsiz <= nmp->nm_rsize);
1327 	if (bio->bio_offset + tsiz > nmp->nm_maxfilesize) {
1328 		error = EFBIG;
1329 		goto nfsmout;
1330 	}
1331 	nfsstats.rpccnt[NFSPROC_READ]++;
1332 	len = tsiz;
1333 	nfsm_reqhead(info, vp, NFSPROC_READ,
1334 		     NFSX_FH(info->v3) + NFSX_UNSIGNED * 3);
1335 	ERROROUT(nfsm_fhtom(info, vp));
1336 	tl = nfsm_build(info, NFSX_UNSIGNED * 3);
1337 	if (info->v3) {
1338 		txdr_hyper(bio->bio_offset, tl);
1339 		*(tl + 2) = txdr_unsigned(len);
1340 	} else {
1341 		*tl++ = txdr_unsigned(bio->bio_offset);
1342 		*tl++ = txdr_unsigned(len);
1343 		*tl = 0;
1344 	}
1345 	info->bio = bio;
1346 	info->done = nfs_readrpc_bio_done;
1347 	nfsm_request_bio(info, vp, NFSPROC_READ, NULL,
1348 			 nfs_vpcred(vp, ND_READ));
1349 	return;
1350 nfsmout:
1351 	kfree(info, M_NFSREQ);
1352 	bp->b_error = error;
1353 	bp->b_flags |= B_ERROR;
1354 	biodone(bio);
1355 }
1356 
1357 static void
1358 nfs_readrpc_bio_done(nfsm_info_t info)
1359 {
1360 	struct nfsmount *nmp = VFSTONFS(info->vp->v_mount);
1361 	struct bio *bio = info->bio;
1362 	struct buf *bp = bio->bio_buf;
1363 	u_int32_t *tl;
1364 	int attrflag;
1365 	int retlen;
1366 	int eof;
1367 	int error = 0;
1368 
1369 	KKASSERT(info->state == NFSM_STATE_DONE);
1370 
1371 	lwkt_gettoken(&nmp->nm_token);
1372 
1373 	if (info->v3) {
1374 		ERROROUT(nfsm_postop_attr(info, info->vp, &attrflag,
1375 					 NFS_LATTR_NOSHRINK));
1376 		NULLOUT(tl = nfsm_dissect(info, 2 * NFSX_UNSIGNED));
1377 		eof = fxdr_unsigned(int, *(tl + 1));
1378 	} else {
1379 		ERROROUT(nfsm_loadattr(info, info->vp, NULL));
1380 		eof = 0;
1381 	}
1382 	NEGATIVEOUT(retlen = nfsm_strsiz(info, nmp->nm_rsize));
1383 	ERROROUT(nfsm_mtobio(info, bio, retlen));
1384 	m_freem(info->mrep);
1385 	info->mrep = NULL;
1386 
1387 	/*
1388 	 * No error occured, if retlen is less then bcount and no EOF
1389 	 * and NFSv3 a zero-fill short read occured.
1390 	 *
1391 	 * For NFSv2 a short-read indicates EOF.
1392 	 */
1393 	if (retlen < bp->b_bcount && info->v3 && eof == 0) {
1394 		bzero(bp->b_data + retlen, bp->b_bcount - retlen);
1395 		retlen = bp->b_bcount;
1396 	}
1397 
1398 	/*
1399 	 * If we hit an EOF we still zero-fill, but return the expected
1400 	 * b_resid anyway.  This should normally not occur since async
1401 	 * BIOs are not used for read-before-write case.  Races against
1402 	 * the server can cause it though and we don't want to leave
1403 	 * garbage in the buffer.
1404 	 */
1405 	if (retlen < bp->b_bcount) {
1406 		bzero(bp->b_data + retlen, bp->b_bcount - retlen);
1407 	}
1408 	bp->b_resid = 0;
1409 	/* bp->b_resid = bp->b_bcount - retlen; */
1410 nfsmout:
1411 	lwkt_reltoken(&nmp->nm_token);
1412 	kfree(info, M_NFSREQ);
1413 	if (error) {
1414 		bp->b_error = error;
1415 		bp->b_flags |= B_ERROR;
1416 	}
1417 	biodone(bio);
1418 }
1419 
1420 /*
1421  * nfs write call - BIO version
1422  *
1423  * NOTE: Caller has already busied the I/O.
1424  */
1425 void
1426 nfs_writerpc_bio(struct vnode *vp, struct bio *bio)
1427 {
1428 	struct nfsmount *nmp = VFSTONFS(vp->v_mount);
1429 	struct nfsnode *np = VTONFS(vp);
1430 	struct buf *bp = bio->bio_buf;
1431 	u_int32_t *tl;
1432 	int len;
1433 	int iomode;
1434 	int error = 0;
1435 	struct nfsm_info *info;
1436 	off_t offset;
1437 
1438 	/*
1439 	 * Setup for actual write.  Just clean up the bio if there
1440 	 * is nothing to do.  b_dirtyoff/end have already been staged
1441 	 * by the bp's pages getting busied.
1442 	 */
1443 	if (bio->bio_offset + bp->b_dirtyend > np->n_size)
1444 		bp->b_dirtyend = np->n_size - bio->bio_offset;
1445 
1446 	if (bp->b_dirtyend <= bp->b_dirtyoff) {
1447 		bp->b_resid = 0;
1448 		biodone(bio);
1449 		return;
1450 	}
1451 	len = bp->b_dirtyend - bp->b_dirtyoff;
1452 	offset = bio->bio_offset + bp->b_dirtyoff;
1453 	if (offset + len > nmp->nm_maxfilesize) {
1454 		bp->b_flags |= B_ERROR;
1455 		bp->b_error = EFBIG;
1456 		biodone(bio);
1457 		return;
1458 	}
1459 	bp->b_resid = len;
1460 	nfsstats.write_bios++;
1461 
1462 	info = kmalloc(sizeof(*info), M_NFSREQ, M_WAITOK);
1463 	info->mrep = NULL;
1464 	info->v3 = NFS_ISV3(vp);
1465 	info->info_writerpc.must_commit = 0;
1466 	if ((bp->b_flags & (B_NEEDCOMMIT | B_NOCACHE | B_CLUSTER)) == 0)
1467 		iomode = NFSV3WRITE_UNSTABLE;
1468 	else
1469 		iomode = NFSV3WRITE_FILESYNC;
1470 
1471 	KKASSERT(len <= nmp->nm_wsize);
1472 
1473 	nfsstats.rpccnt[NFSPROC_WRITE]++;
1474 	nfsm_reqhead(info, vp, NFSPROC_WRITE,
1475 		     NFSX_FH(info->v3) + 5 * NFSX_UNSIGNED + nfsm_rndup(len));
1476 	ERROROUT(nfsm_fhtom(info, vp));
1477 	if (info->v3) {
1478 		tl = nfsm_build(info, 5 * NFSX_UNSIGNED);
1479 		txdr_hyper(offset, tl);
1480 		tl += 2;
1481 		*tl++ = txdr_unsigned(len);
1482 		*tl++ = txdr_unsigned(iomode);
1483 		*tl = txdr_unsigned(len);
1484 	} else {
1485 		u_int32_t x;
1486 
1487 		tl = nfsm_build(info, 4 * NFSX_UNSIGNED);
1488 		/* Set both "begin" and "current" to non-garbage. */
1489 		x = txdr_unsigned((u_int32_t)offset);
1490 		*tl++ = x;	/* "begin offset" */
1491 		*tl++ = x;	/* "current offset" */
1492 		x = txdr_unsigned(len);
1493 		*tl++ = x;	/* total to this offset */
1494 		*tl = x;	/* size of this write */
1495 	}
1496 	ERROROUT(nfsm_biotom(info, bio, bp->b_dirtyoff, len));
1497 	info->bio = bio;
1498 	info->done = nfs_writerpc_bio_done;
1499 	nfsm_request_bio(info, vp, NFSPROC_WRITE, NULL,
1500 			 nfs_vpcred(vp, ND_WRITE));
1501 	return;
1502 nfsmout:
1503 	kfree(info, M_NFSREQ);
1504 	bp->b_error = error;
1505 	bp->b_flags |= B_ERROR;
1506 	biodone(bio);
1507 }
1508 
1509 static void
1510 nfs_writerpc_bio_done(nfsm_info_t info)
1511 {
1512 	struct nfsmount *nmp = VFSTONFS(info->vp->v_mount);
1513 	struct nfsnode *np = VTONFS(info->vp);
1514 	struct bio *bio = info->bio;
1515 	struct buf *bp = bio->bio_buf;
1516 	int wccflag = NFSV3_WCCRATTR;
1517 	int iomode = NFSV3WRITE_FILESYNC;
1518 	int commit;
1519 	int rlen;
1520 	int error;
1521 	int len = bp->b_resid;	/* b_resid was set to shortened length */
1522 	u_int32_t *tl;
1523 
1524 	lwkt_gettoken(&nmp->nm_token);
1525 
1526 	if (info->v3) {
1527 		/*
1528 		 * The write RPC returns a before and after mtime.  The
1529 		 * nfsm_wcc_data() macro checks the before n_mtime
1530 		 * against the before time and stores the after time
1531 		 * in the nfsnode's cached vattr and n_mtime field.
1532 		 * The NRMODIFIED bit will be set if the before
1533 		 * time did not match the original mtime.
1534 		 */
1535 		wccflag = NFSV3_WCCCHK;
1536 		ERROROUT(nfsm_wcc_data(info, info->vp, &wccflag));
1537 		if (error == 0) {
1538 			NULLOUT(tl = nfsm_dissect(info, 2 * NFSX_UNSIGNED + NFSX_V3WRITEVERF));
1539 			rlen = fxdr_unsigned(int, *tl++);
1540 			if (rlen == 0) {
1541 				error = NFSERR_IO;
1542 				m_freem(info->mrep);
1543 				info->mrep = NULL;
1544 				goto nfsmout;
1545 			} else if (rlen < len) {
1546 #if 0
1547 				/*
1548 				 * XXX what do we do here?
1549 				 */
1550 				backup = len - rlen;
1551 				uiop->uio_iov->iov_base = (char *)uiop->uio_iov->iov_base - backup;
1552 				uiop->uio_iov->iov_len += backup;
1553 				uiop->uio_offset -= backup;
1554 				uiop->uio_resid += backup;
1555 				len = rlen;
1556 #endif
1557 			}
1558 			commit = fxdr_unsigned(int, *tl++);
1559 
1560 			/*
1561 			 * Return the lowest committment level
1562 			 * obtained by any of the RPCs.
1563 			 */
1564 			if (iomode == NFSV3WRITE_FILESYNC)
1565 				iomode = commit;
1566 			else if (iomode == NFSV3WRITE_DATASYNC &&
1567 				commit == NFSV3WRITE_UNSTABLE)
1568 				iomode = commit;
1569 			if ((nmp->nm_state & NFSSTA_HASWRITEVERF) == 0){
1570 			    bcopy(tl, (caddr_t)nmp->nm_verf, NFSX_V3WRITEVERF);
1571 			    nmp->nm_state |= NFSSTA_HASWRITEVERF;
1572 			} else if (bcmp(tl, nmp->nm_verf, NFSX_V3WRITEVERF)) {
1573 			    info->info_writerpc.must_commit = 1;
1574 			    bcopy(tl, (caddr_t)nmp->nm_verf, NFSX_V3WRITEVERF);
1575 			}
1576 		}
1577 	} else {
1578 		ERROROUT(nfsm_loadattr(info, info->vp, NULL));
1579 	}
1580 	m_freem(info->mrep);
1581 	info->mrep = NULL;
1582 	len = 0;
1583 nfsmout:
1584 	if (info->vp->v_mount->mnt_flag & MNT_ASYNC)
1585 		iomode = NFSV3WRITE_FILESYNC;
1586 	bp->b_resid = len;
1587 
1588 	/*
1589 	 * End of RPC.  Now clean up the bp.
1590 	 *
1591 	 * We no longer enable write clustering for commit operations,
1592 	 * See around line 1157 for a more detailed comment.
1593 	 */
1594 	if (!error && iomode == NFSV3WRITE_UNSTABLE) {
1595 		bp->b_flags |= B_NEEDCOMMIT;
1596 #if 0
1597 		/* XXX do not enable commit clustering */
1598 		if (bp->b_dirtyoff == 0 && bp->b_dirtyend == bp->b_bcount)
1599 			bp->b_flags |= B_CLUSTEROK;
1600 #endif
1601 	} else {
1602 		bp->b_flags &= ~(B_NEEDCOMMIT | B_CLUSTEROK);
1603 	}
1604 
1605 	/*
1606 	 * For an interrupted write, the buffer is still valid
1607 	 * and the write hasn't been pushed to the server yet,
1608 	 * so we can't set B_ERROR and report the interruption
1609 	 * by setting B_EINTR. For the async case, B_EINTR
1610 	 * is not relevant, so the rpc attempt is essentially
1611 	 * a noop.  For the case of a V3 write rpc not being
1612 	 * committed to stable storage, the block is still
1613 	 * dirty and requires either a commit rpc or another
1614 	 * write rpc with iomode == NFSV3WRITE_FILESYNC before
1615 	 * the block is reused. This is indicated by setting
1616 	 * the B_DELWRI and B_NEEDCOMMIT flags.
1617 	 *
1618 	 * If the buffer is marked B_PAGING, it does not reside on
1619 	 * the vp's paging queues so we cannot call bdirty().  The
1620 	 * bp in this case is not an NFS cache block so we should
1621 	 * be safe. XXX
1622 	 */
1623 	if (error == EINTR || (!error && (bp->b_flags & B_NEEDCOMMIT))) {
1624 		crit_enter();
1625 		bp->b_flags &= ~(B_INVAL|B_NOCACHE);
1626 		if ((bp->b_flags & B_PAGING) == 0)
1627 			bdirty(bp);
1628 		if (error)
1629 			bp->b_flags |= B_EINTR;
1630 		crit_exit();
1631 	} else {
1632 		if (error) {
1633 			bp->b_flags |= B_ERROR;
1634 			bp->b_error = np->n_error = error;
1635 			np->n_flag |= NWRITEERR;
1636 		}
1637 		bp->b_dirtyoff = bp->b_dirtyend = 0;
1638 	}
1639 	if (info->info_writerpc.must_commit)
1640 		nfs_clearcommit(info->vp->v_mount);
1641 	lwkt_reltoken(&nmp->nm_token);
1642 
1643 	kfree(info, M_NFSREQ);
1644 	if (error) {
1645 		bp->b_flags |= B_ERROR;
1646 		bp->b_error = error;
1647 	}
1648 	biodone(bio);
1649 }
1650 
1651 /*
1652  * Nfs Version 3 commit rpc - BIO version
1653  *
1654  * This function issues the commit rpc and will chain to a write
1655  * rpc if necessary.
1656  */
1657 void
1658 nfs_commitrpc_bio(struct vnode *vp, struct bio *bio)
1659 {
1660 	struct nfsmount *nmp = VFSTONFS(vp->v_mount);
1661 	struct buf *bp = bio->bio_buf;
1662 	struct nfsm_info *info;
1663 	int error = 0;
1664 	u_int32_t *tl;
1665 
1666 	if ((nmp->nm_state & NFSSTA_HASWRITEVERF) == 0) {
1667 		bp->b_dirtyoff = bp->b_dirtyend = 0;
1668 		bp->b_flags &= ~(B_NEEDCOMMIT | B_CLUSTEROK);
1669 		bp->b_resid = 0;
1670 		biodone(bio);
1671 		return;
1672 	}
1673 
1674 	info = kmalloc(sizeof(*info), M_NFSREQ, M_WAITOK);
1675 	info->mrep = NULL;
1676 	info->v3 = 1;
1677 
1678 	nfsstats.rpccnt[NFSPROC_COMMIT]++;
1679 	nfsm_reqhead(info, vp, NFSPROC_COMMIT, NFSX_FH(1));
1680 	ERROROUT(nfsm_fhtom(info, vp));
1681 	tl = nfsm_build(info, 3 * NFSX_UNSIGNED);
1682 	txdr_hyper(bio->bio_offset + bp->b_dirtyoff, tl);
1683 	tl += 2;
1684 	*tl = txdr_unsigned(bp->b_dirtyend - bp->b_dirtyoff);
1685 	info->bio = bio;
1686 	info->done = nfs_commitrpc_bio_done;
1687 	nfsm_request_bio(info, vp, NFSPROC_COMMIT, NULL,
1688 			 nfs_vpcred(vp, ND_WRITE));
1689 	return;
1690 nfsmout:
1691 	/*
1692 	 * Chain to write RPC on (early) error
1693 	 */
1694 	kfree(info, M_NFSREQ);
1695 	nfs_writerpc_bio(vp, bio);
1696 }
1697 
1698 static void
1699 nfs_commitrpc_bio_done(nfsm_info_t info)
1700 {
1701 	struct nfsmount *nmp = VFSTONFS(info->vp->v_mount);
1702 	struct bio *bio = info->bio;
1703 	struct buf *bp = bio->bio_buf;
1704 	u_int32_t *tl;
1705 	int wccflag = NFSV3_WCCRATTR;
1706 	int error = 0;
1707 
1708 	lwkt_gettoken(&nmp->nm_token);
1709 
1710 	ERROROUT(nfsm_wcc_data(info, info->vp, &wccflag));
1711 	if (error == 0) {
1712 		NULLOUT(tl = nfsm_dissect(info, NFSX_V3WRITEVERF));
1713 		if (bcmp(nmp->nm_verf, tl, NFSX_V3WRITEVERF)) {
1714 			bcopy(tl, nmp->nm_verf, NFSX_V3WRITEVERF);
1715 			error = NFSERR_STALEWRITEVERF;
1716 		}
1717 	}
1718 	m_freem(info->mrep);
1719 	info->mrep = NULL;
1720 
1721 	/*
1722 	 * On completion we must chain to a write bio if an
1723 	 * error occurred.
1724 	 */
1725 nfsmout:
1726 	if (error == 0) {
1727 		bp->b_dirtyoff = bp->b_dirtyend = 0;
1728 		bp->b_flags &= ~(B_NEEDCOMMIT | B_CLUSTEROK);
1729 		bp->b_resid = 0;
1730 		biodone(bio);
1731 	} else {
1732 		nfs_writerpc_bio(info->vp, bio);
1733 	}
1734 	kfree(info, M_NFSREQ);
1735 	lwkt_reltoken(&nmp->nm_token);
1736 }
1737 
1738