xref: /freebsd/sys/fs/fuse/fuse_io.c (revision 43a5ec4eb41567cc92586503212743d89686d78f)
1 /*-
2  * SPDX-License-Identifier: BSD-3-Clause
3  *
4  * Copyright (c) 2007-2009 Google Inc.
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions are
9  * met:
10  *
11  * * Redistributions of source code must retain the above copyright
12  *   notice, this list of conditions and the following disclaimer.
13  * * Redistributions in binary form must reproduce the above
14  *   copyright notice, this list of conditions and the following disclaimer
15  *   in the documentation and/or other materials provided with the
16  *   distribution.
17  * * Neither the name of Google Inc. nor the names of its
18  *   contributors may be used to endorse or promote products derived from
19  *   this software without specific prior written permission.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
22  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
23  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
24  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
25  * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
26  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
27  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
28  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
29  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
30  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
31  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
32  *
33  * Copyright (C) 2005 Csaba Henk.
34  * All rights reserved.
35  *
36  * Copyright (c) 2019 The FreeBSD Foundation
37  *
38  * Portions of this software were developed by BFF Storage Systems, LLC under
39  * sponsorship from the FreeBSD Foundation.
40  *
41  * Redistribution and use in source and binary forms, with or without
42  * modification, are permitted provided that the following conditions
43  * are met:
44  * 1. Redistributions of source code must retain the above copyright
45  *    notice, this list of conditions and the following disclaimer.
46  * 2. Redistributions in binary form must reproduce the above copyright
47  *    notice, this list of conditions and the following disclaimer in the
48  *    documentation and/or other materials provided with the distribution.
49  *
50  * THIS SOFTWARE IS PROVIDED BY AUTHOR AND CONTRIBUTORS ``AS IS'' AND
51  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
52  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
53  * ARE DISCLAIMED.  IN NO EVENT SHALL AUTHOR OR CONTRIBUTORS BE LIABLE
54  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
55  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
56  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
57  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
58  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
59  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
60  * SUCH DAMAGE.
61  */
62 
63 #include <sys/cdefs.h>
64 __FBSDID("$FreeBSD$");
65 
66 #include <sys/types.h>
67 #include <sys/param.h>
68 #include <sys/module.h>
69 #include <sys/systm.h>
70 #include <sys/errno.h>
71 #include <sys/param.h>
72 #include <sys/kernel.h>
73 #include <sys/conf.h>
74 #include <sys/uio.h>
75 #include <sys/malloc.h>
76 #include <sys/queue.h>
77 #include <sys/lock.h>
78 #include <sys/sx.h>
79 #include <sys/mutex.h>
80 #include <sys/rwlock.h>
81 #include <sys/priv.h>
82 #include <sys/proc.h>
83 #include <sys/mount.h>
84 #include <sys/vnode.h>
85 #include <sys/stat.h>
86 #include <sys/unistd.h>
87 #include <sys/filedesc.h>
88 #include <sys/file.h>
89 #include <sys/fcntl.h>
90 #include <sys/bio.h>
91 #include <sys/buf.h>
92 #include <sys/sysctl.h>
93 #include <sys/vmmeter.h>
94 
95 #include <vm/vm.h>
96 #include <vm/vm_extern.h>
97 #include <vm/pmap.h>
98 #include <vm/vm_map.h>
99 #include <vm/vm_page.h>
100 #include <vm/vm_object.h>
101 
102 #include "fuse.h"
103 #include "fuse_file.h"
104 #include "fuse_node.h"
105 #include "fuse_internal.h"
106 #include "fuse_ipc.h"
107 #include "fuse_io.h"
108 
109 /*
110  * Set in a struct buf to indicate that the write came from the buffer cache
111  * and the originating cred and pid are no longer known.
112  */
113 #define B_FUSEFS_WRITE_CACHE B_FS_FLAG1
114 
115 SDT_PROVIDER_DECLARE(fusefs);
116 /*
117  * Fuse trace probe:
118  * arg0: verbosity.  Higher numbers give more verbose messages
119  * arg1: Textual message
120  */
121 SDT_PROBE_DEFINE2(fusefs, , io, trace, "int", "char*");
122 
123 SDT_PROBE_DEFINE4(fusefs, , io, read_bio_backend_start, "int", "int", "int", "int");
124 SDT_PROBE_DEFINE2(fusefs, , io, read_bio_backend_feed, "int", "struct buf*");
125 SDT_PROBE_DEFINE4(fusefs, , io, read_bio_backend_end, "int", "ssize_t", "int",
126 		"struct buf*");
127 int
128 fuse_read_biobackend(struct vnode *vp, struct uio *uio, int ioflag,
129     struct ucred *cred, struct fuse_filehandle *fufh, pid_t pid)
130 {
131 	struct buf *bp;
132 	struct mount *mp;
133 	struct fuse_data *data;
134 	daddr_t lbn, nextlbn;
135 	int bcount, nextsize;
136 	int err, n = 0, on = 0, seqcount;
137 	off_t filesize;
138 
139 	const int biosize = fuse_iosize(vp);
140 	mp = vnode_mount(vp);
141 	data = fuse_get_mpdata(mp);
142 
143 	if (uio->uio_offset < 0)
144 		return (EINVAL);
145 
146 	seqcount = ioflag >> IO_SEQSHIFT;
147 
148 	err = fuse_vnode_size(vp, &filesize, cred, curthread);
149 	if (err)
150 		return err;
151 
152 	for (err = 0, bp = NULL; uio->uio_resid > 0; bp = NULL) {
153 		if (fuse_isdeadfs(vp)) {
154 			err = ENXIO;
155 			break;
156 		}
157 		if (filesize - uio->uio_offset <= 0)
158 			break;
159 		lbn = uio->uio_offset / biosize;
160 		on = uio->uio_offset & (biosize - 1);
161 
162 		if ((off_t)lbn * biosize >= filesize) {
163 			bcount = 0;
164 		} else if ((off_t)(lbn + 1) * biosize > filesize) {
165 			bcount = filesize - (off_t)lbn *biosize;
166 		} else {
167 			bcount = biosize;
168 		}
169 		nextlbn = lbn + 1;
170 		nextsize = MIN(biosize, filesize - nextlbn * biosize);
171 
172 		SDT_PROBE4(fusefs, , io, read_bio_backend_start,
173 			biosize, (int)lbn, on, bcount);
174 
175 		if (bcount < biosize) {
176 			/* If near EOF, don't do readahead */
177 			err = bread(vp, lbn, bcount, NOCRED, &bp);
178 		} else if ((vp->v_mount->mnt_flag & MNT_NOCLUSTERR) == 0) {
179 			/* Try clustered read */
180 			long totread = uio->uio_resid + on;
181 			seqcount = MIN(seqcount,
182 				data->max_readahead_blocks + 1);
183 			err = cluster_read(vp, filesize, lbn, bcount, NOCRED,
184 				totread, seqcount, 0, &bp);
185 		} else if (seqcount > 1 && data->max_readahead_blocks >= 1) {
186 			/* Try non-clustered readahead */
187 			err = breadn(vp, lbn, bcount, &nextlbn, &nextsize, 1,
188 				NOCRED, &bp);
189 		} else {
190 			/* Just read what was requested */
191 			err = bread(vp, lbn, bcount, NOCRED, &bp);
192 		}
193 
194 		if (err) {
195 			brelse(bp);
196 			bp = NULL;
197 			break;
198 		}
199 
200 		/*
201 	         * on is the offset into the current bp.  Figure out how many
202 	         * bytes we can copy out of the bp.  Note that bcount is
203 	         * NOT DEV_BSIZE aligned.
204 	         *
205 	         * Then figure out how many bytes we can copy into the uio.
206 	         */
207 
208 		n = 0;
209 		if (on < bcount - bp->b_resid)
210 			n = MIN((unsigned)(bcount - bp->b_resid - on),
211 			    uio->uio_resid);
212 		if (n > 0) {
213 			SDT_PROBE2(fusefs, , io, read_bio_backend_feed, n, bp);
214 			err = uiomove(bp->b_data + on, n, uio);
215 		}
216 		vfs_bio_brelse(bp, ioflag);
217 		SDT_PROBE4(fusefs, , io, read_bio_backend_end, err,
218 			uio->uio_resid, n, bp);
219 		if (bp->b_resid > 0) {
220 			/* Short read indicates EOF */
221 			break;
222 		}
223 	}
224 
225 	return (err);
226 }
227 
228 SDT_PROBE_DEFINE1(fusefs, , io, read_directbackend_start,
229 	"struct fuse_read_in*");
230 SDT_PROBE_DEFINE3(fusefs, , io, read_directbackend_complete,
231 	"struct fuse_dispatcher*", "struct fuse_read_in*", "struct uio*");
232 
233 int
234 fuse_read_directbackend(struct vnode *vp, struct uio *uio,
235     struct ucred *cred, struct fuse_filehandle *fufh)
236 {
237 	struct fuse_data *data;
238 	struct fuse_dispatcher fdi;
239 	struct fuse_read_in *fri;
240 	int err = 0;
241 
242 	data = fuse_get_mpdata(vp->v_mount);
243 
244 	if (uio->uio_resid == 0)
245 		return (0);
246 
247 	fdisp_init(&fdi, 0);
248 
249 	/*
250          * XXX In "normal" case we use an intermediate kernel buffer for
251          * transmitting data from daemon's context to ours. Eventually, we should
252          * get rid of this. Anyway, if the target uio lives in sysspace (we are
253          * called from pageops), and the input data doesn't need kernel-side
254          * processing (we are not called from readdir) we can already invoke
255          * an optimized, "peer-to-peer" I/O routine.
256          */
257 	while (uio->uio_resid > 0) {
258 		fdi.iosize = sizeof(*fri);
259 		fdisp_make_vp(&fdi, FUSE_READ, vp, uio->uio_td, cred);
260 		fri = fdi.indata;
261 		fri->fh = fufh->fh_id;
262 		fri->offset = uio->uio_offset;
263 		fri->size = MIN(uio->uio_resid,
264 		    fuse_get_mpdata(vp->v_mount)->max_read);
265 		if (fuse_libabi_geq(data, 7, 9)) {
266 			/* See comment regarding FUSE_WRITE_LOCKOWNER */
267 			fri->read_flags = 0;
268 			fri->flags = fufh_type_2_fflags(fufh->fufh_type);
269 		}
270 
271 		SDT_PROBE1(fusefs, , io, read_directbackend_start, fri);
272 
273 		if ((err = fdisp_wait_answ(&fdi)))
274 			goto out;
275 
276 		SDT_PROBE3(fusefs, , io, read_directbackend_complete,
277 			&fdi, fri, uio);
278 
279 		if ((err = uiomove(fdi.answ, MIN(fri->size, fdi.iosize), uio)))
280 			break;
281 		if (fdi.iosize < fri->size) {
282 			/*
283 			 * Short read.  Should only happen at EOF or with
284 			 * direct io.
285 			 */
286 			break;
287 		}
288 	}
289 
290 out:
291 	fdisp_destroy(&fdi);
292 	return (err);
293 }
294 
295 int
296 fuse_write_directbackend(struct vnode *vp, struct uio *uio,
297     struct ucred *cred, struct fuse_filehandle *fufh, off_t filesize,
298     int ioflag, bool pages)
299 {
300 	struct fuse_vnode_data *fvdat = VTOFUD(vp);
301 	struct fuse_data *data;
302 	struct fuse_write_in *fwi;
303 	struct fuse_write_out *fwo;
304 	struct fuse_dispatcher fdi;
305 	size_t chunksize;
306 	void *fwi_data;
307 	off_t as_written_offset;
308 	int diff;
309 	int err = 0;
310 	bool direct_io = fufh->fuse_open_flags & FOPEN_DIRECT_IO;
311 	bool wrote_anything = false;
312 	uint32_t write_flags;
313 
314 	data = fuse_get_mpdata(vp->v_mount);
315 
316 	/*
317 	 * Don't set FUSE_WRITE_LOCKOWNER in write_flags.  It can't be set
318 	 * accurately when using POSIX AIO, libfuse doesn't use it, and I'm not
319 	 * aware of any file systems that do.  It was an attempt to add
320 	 * Linux-style mandatory locking to the FUSE protocol, but mandatory
321 	 * locking is deprecated even on Linux.  See Linux commit
322 	 * f33321141b273d60cbb3a8f56a5489baad82ba5e .
323 	 */
324 	/*
325 	 * Set FUSE_WRITE_CACHE whenever we don't know the uid, gid, and/or pid
326 	 * that originated a write.  For example when writing from the
327 	 * writeback cache.  I don't know of a single file system that cares,
328 	 * but the protocol says we're supposed to do this.
329 	 */
330 	write_flags = !pages && (
331 		(ioflag & IO_DIRECT) ||
332 		!fsess_opt_datacache(vnode_mount(vp)) ||
333 		!fsess_opt_writeback(vnode_mount(vp))) ? 0 : FUSE_WRITE_CACHE;
334 
335 	if (uio->uio_resid == 0)
336 		return (0);
337 
338 	if (ioflag & IO_APPEND)
339 		uio_setoffset(uio, filesize);
340 
341 	if (vn_rlimit_fsize(vp, uio, uio->uio_td))
342 		return (EFBIG);
343 
344 	fdisp_init(&fdi, 0);
345 
346 	while (uio->uio_resid > 0) {
347 		size_t sizeof_fwi;
348 
349 		if (fuse_libabi_geq(data, 7, 9)) {
350 			sizeof_fwi = sizeof(*fwi);
351 		} else {
352 			sizeof_fwi = FUSE_COMPAT_WRITE_IN_SIZE;
353 		}
354 
355 		chunksize = MIN(uio->uio_resid, data->max_write);
356 
357 		fdi.iosize = sizeof_fwi + chunksize;
358 		fdisp_make_vp(&fdi, FUSE_WRITE, vp, uio->uio_td, cred);
359 
360 		fwi = fdi.indata;
361 		fwi->fh = fufh->fh_id;
362 		fwi->offset = uio->uio_offset;
363 		fwi->size = chunksize;
364 		fwi->write_flags = write_flags;
365 		if (fuse_libabi_geq(data, 7, 9)) {
366 			fwi->flags = fufh_type_2_fflags(fufh->fufh_type);
367 		}
368 		fwi_data = (char *)fdi.indata + sizeof_fwi;
369 
370 		if ((err = uiomove(fwi_data, chunksize, uio)))
371 			break;
372 
373 retry:
374 		err = fdisp_wait_answ(&fdi);
375 		if (err == ERESTART || err == EINTR || err == EWOULDBLOCK) {
376 			/*
377 			 * Rewind the uio so dofilewrite will know it's
378 			 * incomplete
379 			 */
380 			uio->uio_resid += fwi->size;
381 			uio->uio_offset -= fwi->size;
382 			/*
383 			 * Change ERESTART into EINTR because we can't rewind
384 			 * uio->uio_iov.  Basically, once uiomove(9) has been
385 			 * called, it's impossible to restart a syscall.
386 			 */
387 			if (err == ERESTART)
388 				err = EINTR;
389 			break;
390 		} else if (err) {
391 			break;
392 		} else {
393 			wrote_anything = true;
394 		}
395 
396 		fwo = ((struct fuse_write_out *)fdi.answ);
397 
398 		/* Adjust the uio in the case of short writes */
399 		diff = fwi->size - fwo->size;
400 		as_written_offset = uio->uio_offset - diff;
401 
402 		if (as_written_offset - diff > filesize) {
403 			fuse_vnode_setsize(vp, as_written_offset, false);
404 			getnanouptime(&fvdat->last_local_modify);
405 		}
406 		if (as_written_offset - diff >= filesize)
407 			fvdat->flag &= ~FN_SIZECHANGE;
408 
409 		if (diff < 0) {
410 			fuse_warn(data, FSESS_WARN_WROTE_LONG,
411 				"wrote more data than we provided it.");
412 			err = EINVAL;
413 			break;
414 		} else if (diff > 0) {
415 			/* Short write */
416 			if (!direct_io) {
417 				fuse_warn(data, FSESS_WARN_SHORT_WRITE,
418 					"short writes are only allowed with "
419 					"direct_io.");
420 			}
421 			if (ioflag & IO_DIRECT) {
422 				/* Return early */
423 				uio->uio_resid += diff;
424 				uio->uio_offset -= diff;
425 				break;
426 			} else {
427 				/* Resend the unwritten portion of data */
428 				fdi.iosize = sizeof_fwi + diff;
429 				/* Refresh fdi without clearing data buffer */
430 				fdisp_refresh_vp(&fdi, FUSE_WRITE, vp,
431 					uio->uio_td, cred);
432 				fwi = fdi.indata;
433 				MPASS2(fwi == fdi.indata, "FUSE dispatcher "
434 					"reallocated despite no increase in "
435 					"size?");
436 				void *src = (char*)fwi_data + fwo->size;
437 				memmove(fwi_data, src, diff);
438 				fwi->fh = fufh->fh_id;
439 				fwi->offset = as_written_offset;
440 				fwi->size = diff;
441 				fwi->write_flags = write_flags;
442 				goto retry;
443 			}
444 		}
445 	}
446 
447 	fdisp_destroy(&fdi);
448 
449 	if (wrote_anything)
450 		fuse_vnode_undirty_cached_timestamps(vp, false);
451 
452 	return (err);
453 }
454 
455 SDT_PROBE_DEFINE6(fusefs, , io, write_biobackend_start, "int64_t", "int", "int",
456 		"struct uio*", "int", "bool");
457 SDT_PROBE_DEFINE2(fusefs, , io, write_biobackend_append_race, "long", "int");
458 SDT_PROBE_DEFINE2(fusefs, , io, write_biobackend_issue, "int", "struct buf*");
459 
460 int
461 fuse_write_biobackend(struct vnode *vp, struct uio *uio,
462     struct ucred *cred, struct fuse_filehandle *fufh, int ioflag, pid_t pid)
463 {
464 	struct fuse_vnode_data *fvdat = VTOFUD(vp);
465 	struct buf *bp;
466 	daddr_t lbn;
467 	off_t filesize;
468 	int bcount;
469 	int n, on, seqcount, err = 0;
470 	bool last_page;
471 
472 	const int biosize = fuse_iosize(vp);
473 
474 	seqcount = ioflag >> IO_SEQSHIFT;
475 
476 	KASSERT(uio->uio_rw == UIO_WRITE, ("fuse_write_biobackend mode"));
477 	if (vp->v_type != VREG)
478 		return (EIO);
479 	if (uio->uio_offset < 0)
480 		return (EINVAL);
481 	if (uio->uio_resid == 0)
482 		return (0);
483 
484 	err = fuse_vnode_size(vp, &filesize, cred, curthread);
485 	if (err)
486 		return err;
487 
488 	if (ioflag & IO_APPEND)
489 		uio_setoffset(uio, filesize);
490 
491 	if (vn_rlimit_fsize(vp, uio, uio->uio_td))
492 		return (EFBIG);
493 
494 	do {
495 		bool direct_append, extending;
496 
497 		if (fuse_isdeadfs(vp)) {
498 			err = ENXIO;
499 			break;
500 		}
501 		lbn = uio->uio_offset / biosize;
502 		on = uio->uio_offset & (biosize - 1);
503 		n = MIN((unsigned)(biosize - on), uio->uio_resid);
504 
505 again:
506 		/* Get or create a buffer for the write */
507 		direct_append = uio->uio_offset == filesize && n;
508 		if (uio->uio_offset + n < filesize) {
509 			extending = false;
510 			if ((off_t)(lbn + 1) * biosize < filesize) {
511 				/* Not the file's last block */
512 				bcount = biosize;
513 			} else {
514 				/* The file's last block */
515 				bcount = filesize - (off_t)lbn * biosize;
516 			}
517 		} else {
518 			extending = true;
519 			bcount = on + n;
520 		}
521 		if (howmany(((off_t)lbn * biosize + on + n - 1), PAGE_SIZE) >=
522 		    howmany(filesize, PAGE_SIZE))
523 			last_page = true;
524 		else
525 			last_page = false;
526 		if (direct_append) {
527 			/*
528 			 * Take care to preserve the buffer's B_CACHE state so
529 			 * as not to cause an unnecessary read.
530 			 */
531 			bp = getblk(vp, lbn, on, PCATCH, 0, 0);
532 			if (bp != NULL) {
533 				uint32_t save = bp->b_flags & B_CACHE;
534 				allocbuf(bp, bcount);
535 				bp->b_flags |= save;
536 			}
537 		} else {
538 			bp = getblk(vp, lbn, bcount, PCATCH, 0, 0);
539 		}
540 		if (!bp) {
541 			err = EINTR;
542 			break;
543 		}
544 		if (extending) {
545 			/*
546 			 * Extend file _after_ locking buffer so we won't race
547 			 * with other readers
548 			 */
549 			err = fuse_vnode_setsize(vp, uio->uio_offset + n, false);
550 			filesize = uio->uio_offset + n;
551 			getnanouptime(&fvdat->last_local_modify);
552 			fvdat->flag |= FN_SIZECHANGE;
553 			if (err) {
554 				brelse(bp);
555 				break;
556 			}
557 		}
558 
559 		SDT_PROBE6(fusefs, , io, write_biobackend_start,
560 			lbn, on, n, uio, bcount, direct_append);
561 		/*
562 	         * Issue a READ if B_CACHE is not set.  In special-append
563 	         * mode, B_CACHE is based on the buffer prior to the write
564 	         * op and is typically set, avoiding the read.  If a read
565 	         * is required in special append mode, the server will
566 	         * probably send us a short-read since we extended the file
567 	         * on our end, resulting in b_resid == 0 and, thusly,
568 	         * B_CACHE getting set.
569 	         *
570 	         * We can also avoid issuing the read if the write covers
571 	         * the entire buffer.  We have to make sure the buffer state
572 	         * is reasonable in this case since we will not be initiating
573 	         * I/O.  See the comments in kern/vfs_bio.c's getblk() for
574 	         * more information.
575 	         *
576 	         * B_CACHE may also be set due to the buffer being cached
577 	         * normally.
578 	         */
579 
580 		if (on == 0 && n == bcount) {
581 			bp->b_flags |= B_CACHE;
582 			bp->b_flags &= ~B_INVAL;
583 			bp->b_ioflags &= ~BIO_ERROR;
584 		}
585 		if ((bp->b_flags & B_CACHE) == 0) {
586 			bp->b_iocmd = BIO_READ;
587 			vfs_busy_pages(bp, 0);
588 			fuse_io_strategy(vp, bp);
589 			if ((err = bp->b_error)) {
590 				brelse(bp);
591 				break;
592 			}
593 			if (bp->b_resid > 0) {
594 				/*
595 				 * Short read indicates EOF.  Update file size
596 				 * from the server and try again.
597 				 */
598 				SDT_PROBE2(fusefs, , io, trace, 1,
599 					"Short read during a RMW");
600 				brelse(bp);
601 				err = fuse_vnode_size(vp, &filesize, cred,
602 				    curthread);
603 				if (err)
604 					break;
605 				else
606 					goto again;
607 			}
608 		}
609 		if (bp->b_wcred == NOCRED)
610 			bp->b_wcred = crhold(cred);
611 
612 		/*
613 	         * If dirtyend exceeds file size, chop it down.  This should
614 	         * not normally occur but there is an append race where it
615 	         * might occur XXX, so we log it.
616 	         *
617 	         * If the chopping creates a reverse-indexed or degenerate
618 	         * situation with dirtyoff/end, we 0 both of them.
619 	         */
620 		if (bp->b_dirtyend > bcount) {
621 			SDT_PROBE2(fusefs, , io, write_biobackend_append_race,
622 			    (long)bp->b_blkno * biosize,
623 			    bp->b_dirtyend - bcount);
624 			bp->b_dirtyend = bcount;
625 		}
626 		if (bp->b_dirtyoff >= bp->b_dirtyend)
627 			bp->b_dirtyoff = bp->b_dirtyend = 0;
628 
629 		/*
630 	         * If the new write will leave a contiguous dirty
631 	         * area, just update the b_dirtyoff and b_dirtyend,
632 	         * otherwise force a write rpc of the old dirty area.
633 	         *
634 	         * While it is possible to merge discontiguous writes due to
635 	         * our having a B_CACHE buffer ( and thus valid read data
636 	         * for the hole), we don't because it could lead to
637 	         * significant cache coherency problems with multiple clients,
638 	         * especially if locking is implemented later on.
639 	         *
640 	         * as an optimization we could theoretically maintain
641 	         * a linked list of discontinuous areas, but we would still
642 	         * have to commit them separately so there isn't much
643 	         * advantage to it except perhaps a bit of asynchronization.
644 	         */
645 
646 		if (bp->b_dirtyend > 0 &&
647 		    (on > bp->b_dirtyend || (on + n) < bp->b_dirtyoff)) {
648 			/*
649 	                 * Yes, we mean it. Write out everything to "storage"
650 	                 * immediately, without hesitation. (Apart from other
651 	                 * reasons: the only way to know if a write is valid
652 	                 * if its actually written out.)
653 	                 */
654 			SDT_PROBE2(fusefs, , io, write_biobackend_issue, 0, bp);
655 			bwrite(bp);
656 			if (bp->b_error == EINTR) {
657 				err = EINTR;
658 				break;
659 			}
660 			goto again;
661 		}
662 		err = uiomove((char *)bp->b_data + on, n, uio);
663 
664 		if (err) {
665 			bp->b_ioflags |= BIO_ERROR;
666 			bp->b_error = err;
667 			brelse(bp);
668 			break;
669 			/* TODO: vfs_bio_clrbuf like ffs_write does? */
670 		}
671 		/*
672 	         * Only update dirtyoff/dirtyend if not a degenerate
673 	         * condition.
674 	         */
675 		if (n) {
676 			if (bp->b_dirtyend > 0) {
677 				bp->b_dirtyoff = MIN(on, bp->b_dirtyoff);
678 				bp->b_dirtyend = MAX((on + n), bp->b_dirtyend);
679 			} else {
680 				bp->b_dirtyoff = on;
681 				bp->b_dirtyend = on + n;
682 			}
683 			vfs_bio_set_valid(bp, on, n);
684 		}
685 
686 		vfs_bio_set_flags(bp, ioflag);
687 
688 		bp->b_flags |= B_FUSEFS_WRITE_CACHE;
689 		if (ioflag & IO_SYNC) {
690 			SDT_PROBE2(fusefs, , io, write_biobackend_issue, 2, bp);
691 			if (!(ioflag & IO_VMIO))
692 				bp->b_flags &= ~B_FUSEFS_WRITE_CACHE;
693 			err = bwrite(bp);
694 		} else if (vm_page_count_severe() ||
695 			    buf_dirty_count_severe() ||
696 			    (ioflag & IO_ASYNC)) {
697 			bp->b_flags |= B_CLUSTEROK;
698 			SDT_PROBE2(fusefs, , io, write_biobackend_issue, 3, bp);
699 			bawrite(bp);
700 		} else if (on == 0 && n == bcount) {
701 			if ((vp->v_mount->mnt_flag & MNT_NOCLUSTERW) == 0) {
702 				bp->b_flags |= B_CLUSTEROK;
703 				SDT_PROBE2(fusefs, , io, write_biobackend_issue,
704 					4, bp);
705 				cluster_write(vp, &fvdat->clusterw, bp,
706 				    filesize, seqcount, 0);
707 			} else {
708 				SDT_PROBE2(fusefs, , io, write_biobackend_issue,
709 					5, bp);
710 				bawrite(bp);
711 			}
712 		} else if (ioflag & IO_DIRECT) {
713 			bp->b_flags |= B_CLUSTEROK;
714 			SDT_PROBE2(fusefs, , io, write_biobackend_issue, 6, bp);
715 			bawrite(bp);
716 		} else {
717 			bp->b_flags &= ~B_CLUSTEROK;
718 			SDT_PROBE2(fusefs, , io, write_biobackend_issue, 7, bp);
719 			bdwrite(bp);
720 		}
721 		if (err)
722 			break;
723 	} while (uio->uio_resid > 0 && n > 0);
724 
725 	return (err);
726 }
727 
728 int
729 fuse_io_strategy(struct vnode *vp, struct buf *bp)
730 {
731 	struct fuse_vnode_data *fvdat = VTOFUD(vp);
732 	struct fuse_filehandle *fufh;
733 	struct ucred *cred;
734 	struct uio *uiop;
735 	struct uio uio;
736 	struct iovec io;
737 	off_t filesize;
738 	int error = 0;
739 	int fflag;
740 	/* We don't know the true pid when we're dealing with the cache */
741 	pid_t pid = 0;
742 
743 	const int biosize = fuse_iosize(vp);
744 
745 	MPASS(vp->v_type == VREG || vp->v_type == VDIR);
746 	MPASS(bp->b_iocmd == BIO_READ || bp->b_iocmd == BIO_WRITE);
747 
748 	fflag = bp->b_iocmd == BIO_READ ? FREAD : FWRITE;
749 	cred = bp->b_iocmd == BIO_READ ? bp->b_rcred : bp->b_wcred;
750 	error = fuse_filehandle_getrw(vp, fflag, &fufh, cred, pid);
751 	if (bp->b_iocmd == BIO_READ && error == EBADF) {
752 		/*
753 		 * This may be a read-modify-write operation on a cached file
754 		 * opened O_WRONLY.  The FUSE protocol allows this.
755 		 */
756 		error = fuse_filehandle_get(vp, FWRITE, &fufh, cred, pid);
757 	}
758 	if (error) {
759 		printf("FUSE: strategy: filehandles are closed\n");
760 		bp->b_ioflags |= BIO_ERROR;
761 		bp->b_error = error;
762 		bufdone(bp);
763 		return (error);
764 	}
765 
766 	uiop = &uio;
767 	uiop->uio_iov = &io;
768 	uiop->uio_iovcnt = 1;
769 	uiop->uio_segflg = UIO_SYSSPACE;
770 	uiop->uio_td = curthread;
771 
772 	/*
773          * clear BIO_ERROR and B_INVAL state prior to initiating the I/O.  We
774          * do this here so we do not have to do it in all the code that
775          * calls us.
776          */
777 	bp->b_flags &= ~B_INVAL;
778 	bp->b_ioflags &= ~BIO_ERROR;
779 
780 	KASSERT(!(bp->b_flags & B_DONE),
781 	    ("fuse_io_strategy: bp %p already marked done", bp));
782 	if (bp->b_iocmd == BIO_READ) {
783 		ssize_t left;
784 
785 		io.iov_len = uiop->uio_resid = bp->b_bcount;
786 		io.iov_base = bp->b_data;
787 		uiop->uio_rw = UIO_READ;
788 
789 		uiop->uio_offset = ((off_t)bp->b_lblkno) * biosize;
790 		error = fuse_read_directbackend(vp, uiop, cred, fufh);
791 		/*
792 		 * Store the amount we failed to read in the buffer's private
793 		 * field, so callers can truncate the file if necessary'
794 		 */
795 
796 		if (!error && uiop->uio_resid) {
797 			int nread = bp->b_bcount - uiop->uio_resid;
798 			left = uiop->uio_resid;
799 			bzero((char *)bp->b_data + nread, left);
800 
801 			if ((fvdat->flag & FN_SIZECHANGE) == 0) {
802 				/*
803 				 * A short read with no error, when not using
804 				 * direct io, and when no writes are cached,
805 				 * indicates EOF caused by a server-side
806 				 * truncation.  Clear the attr cache so we'll
807 				 * pick up the new file size and timestamps.
808 				 *
809 				 * We must still bzero the remaining buffer so
810 				 * uninitialized data doesn't get exposed by a
811 				 * future truncate that extends the file.
812 				 *
813 				 * To prevent lock order problems, we must
814 				 * truncate the file upstack, not here.
815 				 */
816 				SDT_PROBE2(fusefs, , io, trace, 1,
817 					"Short read of a clean file");
818 				fuse_vnode_clear_attr_cache(vp);
819 			} else {
820 				/*
821 				 * If dirty writes _are_ cached beyond EOF,
822 				 * that indicates a newly created hole that the
823 				 * server doesn't know about.  Those don't pose
824 				 * any problem.
825 				 * XXX: we don't currently track whether dirty
826 				 * writes are cached beyond EOF, before EOF, or
827 				 * both.
828 				 */
829 				SDT_PROBE2(fusefs, , io, trace, 1,
830 					"Short read of a dirty file");
831 				uiop->uio_resid = 0;
832 			}
833 		}
834 		if (error) {
835 			bp->b_ioflags |= BIO_ERROR;
836 			bp->b_error = error;
837 		}
838 	} else {
839 		/*
840 	         * Setup for actual write
841 	         */
842 		/*
843 		 * If the file's size is cached, use that value, even if the
844 		 * cache is expired.  At this point we're already committed to
845 		 * writing something.  If the FUSE server has changed the
846 		 * file's size behind our back, it's too late for us to do
847 		 * anything about it.  In particular, we can't invalidate any
848 		 * part of the file's buffers because VOP_STRATEGY is called
849 		 * with them already locked.
850 		 */
851 		filesize = fvdat->cached_attrs.va_size;
852 		/* filesize must've been cached by fuse_vnop_open.  */
853 		KASSERT(filesize != VNOVAL, ("filesize should've been cached"));
854 
855 		if ((off_t)bp->b_lblkno * biosize + bp->b_dirtyend > filesize)
856 			bp->b_dirtyend = filesize -
857 				(off_t)bp->b_lblkno * biosize;
858 
859 		if (bp->b_dirtyend > bp->b_dirtyoff) {
860 			io.iov_len = uiop->uio_resid = bp->b_dirtyend
861 			    - bp->b_dirtyoff;
862 			uiop->uio_offset = (off_t)bp->b_lblkno * biosize
863 			    + bp->b_dirtyoff;
864 			io.iov_base = (char *)bp->b_data + bp->b_dirtyoff;
865 			uiop->uio_rw = UIO_WRITE;
866 
867 			bool pages = bp->b_flags & B_FUSEFS_WRITE_CACHE;
868 			error = fuse_write_directbackend(vp, uiop, cred, fufh,
869 				filesize, 0, pages);
870 
871 			if (error == EINTR || error == ETIMEDOUT) {
872 				bp->b_flags &= ~(B_INVAL | B_NOCACHE);
873 				if ((bp->b_flags & B_PAGING) == 0) {
874 					bdirty(bp);
875 					bp->b_flags &= ~B_DONE;
876 				}
877 				if ((error == EINTR || error == ETIMEDOUT) &&
878 				    (bp->b_flags & B_ASYNC) == 0)
879 					bp->b_flags |= B_EINTR;
880 			} else {
881 				if (error) {
882 					bp->b_ioflags |= BIO_ERROR;
883 					bp->b_flags |= B_INVAL;
884 					bp->b_error = error;
885 				}
886 				bp->b_dirtyoff = bp->b_dirtyend = 0;
887 			}
888 		} else {
889 			bp->b_resid = 0;
890 			bufdone(bp);
891 			return (0);
892 		}
893 	}
894 	bp->b_resid = uiop->uio_resid;
895 	bufdone(bp);
896 	return (error);
897 }
898 
899 int
900 fuse_io_flushbuf(struct vnode *vp, int waitfor, struct thread *td)
901 {
902 
903 	return (vn_fsync_buf(vp, waitfor));
904 }
905 
906 /*
907  * Flush and invalidate all dirty buffers. If another process is already
908  * doing the flush, just wait for completion.
909  */
910 int
911 fuse_io_invalbuf(struct vnode *vp, struct thread *td)
912 {
913 	struct fuse_vnode_data *fvdat = VTOFUD(vp);
914 	int error = 0;
915 
916 	if (VN_IS_DOOMED(vp))
917 		return 0;
918 
919 	ASSERT_VOP_ELOCKED(vp, "fuse_io_invalbuf");
920 
921 	while (fvdat->flag & FN_FLUSHINPROG) {
922 		struct proc *p = td->td_proc;
923 
924 		if (vp->v_mount->mnt_kern_flag & MNTK_UNMOUNTF)
925 			return EIO;
926 		fvdat->flag |= FN_FLUSHWANT;
927 		tsleep(&fvdat->flag, PRIBIO + 2, "fusevinv", 2 * hz);
928 		error = 0;
929 		if (p != NULL) {
930 			PROC_LOCK(p);
931 			if (SIGNOTEMPTY(p->p_siglist) ||
932 			    SIGNOTEMPTY(td->td_siglist))
933 				error = EINTR;
934 			PROC_UNLOCK(p);
935 		}
936 		if (error == EINTR)
937 			return EINTR;
938 	}
939 	fvdat->flag |= FN_FLUSHINPROG;
940 
941 	if (vp->v_bufobj.bo_object != NULL) {
942 		VM_OBJECT_WLOCK(vp->v_bufobj.bo_object);
943 		vm_object_page_clean(vp->v_bufobj.bo_object, 0, 0, OBJPC_SYNC);
944 		VM_OBJECT_WUNLOCK(vp->v_bufobj.bo_object);
945 	}
946 	error = vinvalbuf(vp, V_SAVE, PCATCH, 0);
947 	while (error) {
948 		if (error == ERESTART || error == EINTR) {
949 			fvdat->flag &= ~FN_FLUSHINPROG;
950 			if (fvdat->flag & FN_FLUSHWANT) {
951 				fvdat->flag &= ~FN_FLUSHWANT;
952 				wakeup(&fvdat->flag);
953 			}
954 			return EINTR;
955 		}
956 		error = vinvalbuf(vp, V_SAVE, PCATCH, 0);
957 	}
958 	fvdat->flag &= ~FN_FLUSHINPROG;
959 	if (fvdat->flag & FN_FLUSHWANT) {
960 		fvdat->flag &= ~FN_FLUSHWANT;
961 		wakeup(&fvdat->flag);
962 	}
963 	return (error);
964 }
965