xref: /freebsd/sys/fs/fuse/fuse_io.c (revision 38a52bd3b5cac3da6f7f6eef3dd050e6aa08ebb3)
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 	ssize_t r;
307 	void *fwi_data;
308 	off_t as_written_offset;
309 	int diff;
310 	int err = 0;
311 	bool direct_io = fufh->fuse_open_flags & FOPEN_DIRECT_IO;
312 	bool wrote_anything = false;
313 	uint32_t write_flags;
314 
315 	data = fuse_get_mpdata(vp->v_mount);
316 
317 	/*
318 	 * Don't set FUSE_WRITE_LOCKOWNER in write_flags.  It can't be set
319 	 * accurately when using POSIX AIO, libfuse doesn't use it, and I'm not
320 	 * aware of any file systems that do.  It was an attempt to add
321 	 * Linux-style mandatory locking to the FUSE protocol, but mandatory
322 	 * locking is deprecated even on Linux.  See Linux commit
323 	 * f33321141b273d60cbb3a8f56a5489baad82ba5e .
324 	 */
325 	/*
326 	 * Set FUSE_WRITE_CACHE whenever we don't know the uid, gid, and/or pid
327 	 * that originated a write.  For example when writing from the
328 	 * writeback cache.  I don't know of a single file system that cares,
329 	 * but the protocol says we're supposed to do this.
330 	 */
331 	write_flags = !pages && (
332 		(ioflag & IO_DIRECT) ||
333 		!fsess_opt_datacache(vnode_mount(vp)) ||
334 		!fsess_opt_writeback(vnode_mount(vp))) ? 0 : FUSE_WRITE_CACHE;
335 
336 	if (uio->uio_resid == 0)
337 		return (0);
338 
339 	if (ioflag & IO_APPEND)
340 		uio_setoffset(uio, filesize);
341 
342 	err = vn_rlimit_fsizex(vp, uio, 0, &r, uio->uio_td);
343 	if (err != 0) {
344 		vn_rlimit_fsizex_res(uio, r);
345 		return (err);
346 	}
347 
348 	fdisp_init(&fdi, 0);
349 
350 	while (uio->uio_resid > 0) {
351 		size_t sizeof_fwi;
352 
353 		if (fuse_libabi_geq(data, 7, 9)) {
354 			sizeof_fwi = sizeof(*fwi);
355 		} else {
356 			sizeof_fwi = FUSE_COMPAT_WRITE_IN_SIZE;
357 		}
358 
359 		chunksize = MIN(uio->uio_resid, data->max_write);
360 
361 		fdi.iosize = sizeof_fwi + chunksize;
362 		fdisp_make_vp(&fdi, FUSE_WRITE, vp, uio->uio_td, cred);
363 
364 		fwi = fdi.indata;
365 		fwi->fh = fufh->fh_id;
366 		fwi->offset = uio->uio_offset;
367 		fwi->size = chunksize;
368 		fwi->write_flags = write_flags;
369 		if (fuse_libabi_geq(data, 7, 9)) {
370 			fwi->flags = fufh_type_2_fflags(fufh->fufh_type);
371 		}
372 		fwi_data = (char *)fdi.indata + sizeof_fwi;
373 
374 		if ((err = uiomove(fwi_data, chunksize, uio)))
375 			break;
376 
377 retry:
378 		err = fdisp_wait_answ(&fdi);
379 		if (err == ERESTART || err == EINTR || err == EWOULDBLOCK) {
380 			/*
381 			 * Rewind the uio so dofilewrite will know it's
382 			 * incomplete
383 			 */
384 			uio->uio_resid += fwi->size;
385 			uio->uio_offset -= fwi->size;
386 			/*
387 			 * Change ERESTART into EINTR because we can't rewind
388 			 * uio->uio_iov.  Basically, once uiomove(9) has been
389 			 * called, it's impossible to restart a syscall.
390 			 */
391 			if (err == ERESTART)
392 				err = EINTR;
393 			break;
394 		} else if (err) {
395 			break;
396 		} else {
397 			wrote_anything = true;
398 		}
399 
400 		fwo = ((struct fuse_write_out *)fdi.answ);
401 
402 		if (fwo->size > fwi->size) {
403 			fuse_warn(data, FSESS_WARN_WROTE_LONG,
404 				"wrote more data than we provided it.");
405 			/* This is bonkers.  Clear attr cache. */
406 			fvdat->flag &= ~FN_SIZECHANGE;
407 			fuse_vnode_clear_attr_cache(vp);
408 			err = EINVAL;
409 			break;
410 		}
411 
412 		/* Adjust the uio in the case of short writes */
413 		diff = fwi->size - fwo->size;
414 
415 		as_written_offset = uio->uio_offset - diff;
416 
417 		if (as_written_offset - diff > filesize) {
418 			fuse_vnode_setsize(vp, as_written_offset, false);
419 			getnanouptime(&fvdat->last_local_modify);
420 		}
421 		if (as_written_offset - diff >= filesize)
422 			fvdat->flag &= ~FN_SIZECHANGE;
423 
424 		if (diff > 0) {
425 			/* Short write */
426 			if (!direct_io) {
427 				fuse_warn(data, FSESS_WARN_SHORT_WRITE,
428 					"short writes are only allowed with "
429 					"direct_io.");
430 			}
431 			if (ioflag & IO_DIRECT) {
432 				/* Return early */
433 				uio->uio_resid += diff;
434 				uio->uio_offset -= diff;
435 				break;
436 			} else {
437 				/* Resend the unwritten portion of data */
438 				fdi.iosize = sizeof_fwi + diff;
439 				/* Refresh fdi without clearing data buffer */
440 				fdisp_refresh_vp(&fdi, FUSE_WRITE, vp,
441 					uio->uio_td, cred);
442 				fwi = fdi.indata;
443 				MPASS2(fwi == fdi.indata, "FUSE dispatcher "
444 					"reallocated despite no increase in "
445 					"size?");
446 				void *src = (char*)fwi_data + fwo->size;
447 				memmove(fwi_data, src, diff);
448 				fwi->fh = fufh->fh_id;
449 				fwi->offset = as_written_offset;
450 				fwi->size = diff;
451 				fwi->write_flags = write_flags;
452 				goto retry;
453 			}
454 		}
455 	}
456 
457 	fdisp_destroy(&fdi);
458 
459 	if (wrote_anything)
460 		fuse_vnode_undirty_cached_timestamps(vp, false);
461 
462 	vn_rlimit_fsizex_res(uio, r);
463 	return (err);
464 }
465 
466 SDT_PROBE_DEFINE6(fusefs, , io, write_biobackend_start, "int64_t", "int", "int",
467 		"struct uio*", "int", "bool");
468 SDT_PROBE_DEFINE2(fusefs, , io, write_biobackend_append_race, "long", "int");
469 SDT_PROBE_DEFINE2(fusefs, , io, write_biobackend_issue, "int", "struct buf*");
470 
471 int
472 fuse_write_biobackend(struct vnode *vp, struct uio *uio,
473     struct ucred *cred, struct fuse_filehandle *fufh, int ioflag, pid_t pid)
474 {
475 	struct fuse_vnode_data *fvdat = VTOFUD(vp);
476 	struct buf *bp;
477 	daddr_t lbn;
478 	off_t filesize;
479 	ssize_t r;
480 	int bcount;
481 	int n, on, seqcount, err = 0;
482 
483 	const int biosize = fuse_iosize(vp);
484 
485 	seqcount = ioflag >> IO_SEQSHIFT;
486 
487 	KASSERT(uio->uio_rw == UIO_WRITE, ("fuse_write_biobackend mode"));
488 	if (vp->v_type != VREG)
489 		return (EIO);
490 	if (uio->uio_offset < 0)
491 		return (EINVAL);
492 	if (uio->uio_resid == 0)
493 		return (0);
494 
495 	err = fuse_vnode_size(vp, &filesize, cred, curthread);
496 	if (err)
497 		return err;
498 
499 	if (ioflag & IO_APPEND)
500 		uio_setoffset(uio, filesize);
501 
502 	err = vn_rlimit_fsizex(vp, uio, 0, &r, uio->uio_td);
503 	if (err != 0) {
504 		vn_rlimit_fsizex_res(uio, r);
505 		return (err);
506 	}
507 
508 	do {
509 		bool direct_append, extending;
510 
511 		if (fuse_isdeadfs(vp)) {
512 			err = ENXIO;
513 			break;
514 		}
515 		lbn = uio->uio_offset / biosize;
516 		on = uio->uio_offset & (biosize - 1);
517 		n = MIN((unsigned)(biosize - on), uio->uio_resid);
518 
519 again:
520 		/* Get or create a buffer for the write */
521 		direct_append = uio->uio_offset == filesize && n;
522 		if (uio->uio_offset + n < filesize) {
523 			extending = false;
524 			if ((off_t)(lbn + 1) * biosize < filesize) {
525 				/* Not the file's last block */
526 				bcount = biosize;
527 			} else {
528 				/* The file's last block */
529 				bcount = filesize - (off_t)lbn * biosize;
530 			}
531 		} else {
532 			extending = true;
533 			bcount = on + n;
534 		}
535 		if (direct_append) {
536 			/*
537 			 * Take care to preserve the buffer's B_CACHE state so
538 			 * as not to cause an unnecessary read.
539 			 */
540 			bp = getblk(vp, lbn, on, PCATCH, 0, 0);
541 			if (bp != NULL) {
542 				uint32_t save = bp->b_flags & B_CACHE;
543 				allocbuf(bp, bcount);
544 				bp->b_flags |= save;
545 			}
546 		} else {
547 			bp = getblk(vp, lbn, bcount, PCATCH, 0, 0);
548 		}
549 		if (!bp) {
550 			err = EINTR;
551 			break;
552 		}
553 		if (extending) {
554 			/*
555 			 * Extend file _after_ locking buffer so we won't race
556 			 * with other readers
557 			 */
558 			err = fuse_vnode_setsize(vp, uio->uio_offset + n, false);
559 			filesize = uio->uio_offset + n;
560 			getnanouptime(&fvdat->last_local_modify);
561 			fvdat->flag |= FN_SIZECHANGE;
562 			if (err) {
563 				brelse(bp);
564 				break;
565 			}
566 		}
567 
568 		SDT_PROBE6(fusefs, , io, write_biobackend_start,
569 			lbn, on, n, uio, bcount, direct_append);
570 		/*
571 	         * Issue a READ if B_CACHE is not set.  In special-append
572 	         * mode, B_CACHE is based on the buffer prior to the write
573 	         * op and is typically set, avoiding the read.  If a read
574 	         * is required in special append mode, the server will
575 	         * probably send us a short-read since we extended the file
576 	         * on our end, resulting in b_resid == 0 and, thusly,
577 	         * B_CACHE getting set.
578 	         *
579 	         * We can also avoid issuing the read if the write covers
580 	         * the entire buffer.  We have to make sure the buffer state
581 	         * is reasonable in this case since we will not be initiating
582 	         * I/O.  See the comments in kern/vfs_bio.c's getblk() for
583 	         * more information.
584 	         *
585 	         * B_CACHE may also be set due to the buffer being cached
586 	         * normally.
587 	         */
588 
589 		if (on == 0 && n == bcount) {
590 			bp->b_flags |= B_CACHE;
591 			bp->b_flags &= ~B_INVAL;
592 			bp->b_ioflags &= ~BIO_ERROR;
593 		}
594 		if ((bp->b_flags & B_CACHE) == 0) {
595 			bp->b_iocmd = BIO_READ;
596 			vfs_busy_pages(bp, 0);
597 			fuse_io_strategy(vp, bp);
598 			if ((err = bp->b_error)) {
599 				brelse(bp);
600 				break;
601 			}
602 			if (bp->b_resid > 0) {
603 				/*
604 				 * Short read indicates EOF.  Update file size
605 				 * from the server and try again.
606 				 */
607 				SDT_PROBE2(fusefs, , io, trace, 1,
608 					"Short read during a RMW");
609 				brelse(bp);
610 				err = fuse_vnode_size(vp, &filesize, cred,
611 				    curthread);
612 				if (err)
613 					break;
614 				else
615 					goto again;
616 			}
617 		}
618 		if (bp->b_wcred == NOCRED)
619 			bp->b_wcred = crhold(cred);
620 
621 		/*
622 	         * If dirtyend exceeds file size, chop it down.  This should
623 	         * not normally occur but there is an append race where it
624 	         * might occur XXX, so we log it.
625 	         *
626 	         * If the chopping creates a reverse-indexed or degenerate
627 	         * situation with dirtyoff/end, we 0 both of them.
628 	         */
629 		if (bp->b_dirtyend > bcount) {
630 			SDT_PROBE2(fusefs, , io, write_biobackend_append_race,
631 			    (long)bp->b_blkno * biosize,
632 			    bp->b_dirtyend - bcount);
633 			bp->b_dirtyend = bcount;
634 		}
635 		if (bp->b_dirtyoff >= bp->b_dirtyend)
636 			bp->b_dirtyoff = bp->b_dirtyend = 0;
637 
638 		/*
639 	         * If the new write will leave a contiguous dirty
640 	         * area, just update the b_dirtyoff and b_dirtyend,
641 	         * otherwise force a write rpc of the old dirty area.
642 	         *
643 	         * While it is possible to merge discontiguous writes due to
644 	         * our having a B_CACHE buffer ( and thus valid read data
645 	         * for the hole), we don't because it could lead to
646 	         * significant cache coherency problems with multiple clients,
647 	         * especially if locking is implemented later on.
648 	         *
649 	         * as an optimization we could theoretically maintain
650 	         * a linked list of discontinuous areas, but we would still
651 	         * have to commit them separately so there isn't much
652 	         * advantage to it except perhaps a bit of asynchronization.
653 	         */
654 
655 		if (bp->b_dirtyend > 0 &&
656 		    (on > bp->b_dirtyend || (on + n) < bp->b_dirtyoff)) {
657 			/*
658 	                 * Yes, we mean it. Write out everything to "storage"
659 	                 * immediately, without hesitation. (Apart from other
660 	                 * reasons: the only way to know if a write is valid
661 	                 * if its actually written out.)
662 	                 */
663 			SDT_PROBE2(fusefs, , io, write_biobackend_issue, 0, bp);
664 			bwrite(bp);
665 			if (bp->b_error == EINTR) {
666 				err = EINTR;
667 				break;
668 			}
669 			goto again;
670 		}
671 		err = uiomove((char *)bp->b_data + on, n, uio);
672 
673 		if (err) {
674 			bp->b_ioflags |= BIO_ERROR;
675 			bp->b_error = err;
676 			brelse(bp);
677 			break;
678 			/* TODO: vfs_bio_clrbuf like ffs_write does? */
679 		}
680 		/*
681 	         * Only update dirtyoff/dirtyend if not a degenerate
682 	         * condition.
683 	         */
684 		if (n) {
685 			if (bp->b_dirtyend > 0) {
686 				bp->b_dirtyoff = MIN(on, bp->b_dirtyoff);
687 				bp->b_dirtyend = MAX((on + n), bp->b_dirtyend);
688 			} else {
689 				bp->b_dirtyoff = on;
690 				bp->b_dirtyend = on + n;
691 			}
692 			vfs_bio_set_valid(bp, on, n);
693 		}
694 
695 		vfs_bio_set_flags(bp, ioflag);
696 
697 		bp->b_flags |= B_FUSEFS_WRITE_CACHE;
698 		if (ioflag & IO_SYNC) {
699 			SDT_PROBE2(fusefs, , io, write_biobackend_issue, 2, bp);
700 			if (!(ioflag & IO_VMIO))
701 				bp->b_flags &= ~B_FUSEFS_WRITE_CACHE;
702 			err = bwrite(bp);
703 		} else if (vm_page_count_severe() ||
704 			    buf_dirty_count_severe() ||
705 			    (ioflag & IO_ASYNC)) {
706 			bp->b_flags |= B_CLUSTEROK;
707 			SDT_PROBE2(fusefs, , io, write_biobackend_issue, 3, bp);
708 			bawrite(bp);
709 		} else if (on == 0 && n == bcount) {
710 			if ((vp->v_mount->mnt_flag & MNT_NOCLUSTERW) == 0) {
711 				bp->b_flags |= B_CLUSTEROK;
712 				SDT_PROBE2(fusefs, , io, write_biobackend_issue,
713 					4, bp);
714 				cluster_write(vp, &fvdat->clusterw, bp,
715 				    filesize, seqcount, 0);
716 			} else {
717 				SDT_PROBE2(fusefs, , io, write_biobackend_issue,
718 					5, bp);
719 				bawrite(bp);
720 			}
721 		} else if (ioflag & IO_DIRECT) {
722 			bp->b_flags |= B_CLUSTEROK;
723 			SDT_PROBE2(fusefs, , io, write_biobackend_issue, 6, bp);
724 			bawrite(bp);
725 		} else {
726 			bp->b_flags &= ~B_CLUSTEROK;
727 			SDT_PROBE2(fusefs, , io, write_biobackend_issue, 7, bp);
728 			bdwrite(bp);
729 		}
730 		if (err)
731 			break;
732 	} while (uio->uio_resid > 0 && n > 0);
733 
734 	vn_rlimit_fsizex_res(uio, r);
735 	return (err);
736 }
737 
738 int
739 fuse_io_strategy(struct vnode *vp, struct buf *bp)
740 {
741 	struct fuse_vnode_data *fvdat = VTOFUD(vp);
742 	struct fuse_filehandle *fufh;
743 	struct ucred *cred;
744 	struct uio *uiop;
745 	struct uio uio;
746 	struct iovec io;
747 	off_t filesize;
748 	int error = 0;
749 	int fflag;
750 	/* We don't know the true pid when we're dealing with the cache */
751 	pid_t pid = 0;
752 
753 	const int biosize = fuse_iosize(vp);
754 
755 	MPASS(vp->v_type == VREG || vp->v_type == VDIR);
756 	MPASS(bp->b_iocmd == BIO_READ || bp->b_iocmd == BIO_WRITE);
757 
758 	fflag = bp->b_iocmd == BIO_READ ? FREAD : FWRITE;
759 	cred = bp->b_iocmd == BIO_READ ? bp->b_rcred : bp->b_wcred;
760 	error = fuse_filehandle_getrw(vp, fflag, &fufh, cred, pid);
761 	if (bp->b_iocmd == BIO_READ && error == EBADF) {
762 		/*
763 		 * This may be a read-modify-write operation on a cached file
764 		 * opened O_WRONLY.  The FUSE protocol allows this.
765 		 */
766 		error = fuse_filehandle_get(vp, FWRITE, &fufh, cred, pid);
767 	}
768 	if (error) {
769 		printf("FUSE: strategy: filehandles are closed\n");
770 		bp->b_ioflags |= BIO_ERROR;
771 		bp->b_error = error;
772 		bufdone(bp);
773 		return (error);
774 	}
775 
776 	uiop = &uio;
777 	uiop->uio_iov = &io;
778 	uiop->uio_iovcnt = 1;
779 	uiop->uio_segflg = UIO_SYSSPACE;
780 	uiop->uio_td = curthread;
781 
782 	/*
783          * clear BIO_ERROR and B_INVAL state prior to initiating the I/O.  We
784          * do this here so we do not have to do it in all the code that
785          * calls us.
786          */
787 	bp->b_flags &= ~B_INVAL;
788 	bp->b_ioflags &= ~BIO_ERROR;
789 
790 	KASSERT(!(bp->b_flags & B_DONE),
791 	    ("fuse_io_strategy: bp %p already marked done", bp));
792 	if (bp->b_iocmd == BIO_READ) {
793 		ssize_t left;
794 
795 		io.iov_len = uiop->uio_resid = bp->b_bcount;
796 		io.iov_base = bp->b_data;
797 		uiop->uio_rw = UIO_READ;
798 
799 		uiop->uio_offset = ((off_t)bp->b_lblkno) * biosize;
800 		error = fuse_read_directbackend(vp, uiop, cred, fufh);
801 		/*
802 		 * Store the amount we failed to read in the buffer's private
803 		 * field, so callers can truncate the file if necessary'
804 		 */
805 
806 		if (!error && uiop->uio_resid) {
807 			int nread = bp->b_bcount - uiop->uio_resid;
808 			left = uiop->uio_resid;
809 			bzero((char *)bp->b_data + nread, left);
810 
811 			if ((fvdat->flag & FN_SIZECHANGE) == 0) {
812 				/*
813 				 * A short read with no error, when not using
814 				 * direct io, and when no writes are cached,
815 				 * indicates EOF caused by a server-side
816 				 * truncation.  Clear the attr cache so we'll
817 				 * pick up the new file size and timestamps.
818 				 *
819 				 * We must still bzero the remaining buffer so
820 				 * uninitialized data doesn't get exposed by a
821 				 * future truncate that extends the file.
822 				 *
823 				 * To prevent lock order problems, we must
824 				 * truncate the file upstack, not here.
825 				 */
826 				SDT_PROBE2(fusefs, , io, trace, 1,
827 					"Short read of a clean file");
828 				fuse_vnode_clear_attr_cache(vp);
829 			} else {
830 				/*
831 				 * If dirty writes _are_ cached beyond EOF,
832 				 * that indicates a newly created hole that the
833 				 * server doesn't know about.  Those don't pose
834 				 * any problem.
835 				 * XXX: we don't currently track whether dirty
836 				 * writes are cached beyond EOF, before EOF, or
837 				 * both.
838 				 */
839 				SDT_PROBE2(fusefs, , io, trace, 1,
840 					"Short read of a dirty file");
841 				uiop->uio_resid = 0;
842 			}
843 		}
844 		if (error) {
845 			bp->b_ioflags |= BIO_ERROR;
846 			bp->b_error = error;
847 		}
848 	} else {
849 		/*
850 	         * Setup for actual write
851 	         */
852 		/*
853 		 * If the file's size is cached, use that value, even if the
854 		 * cache is expired.  At this point we're already committed to
855 		 * writing something.  If the FUSE server has changed the
856 		 * file's size behind our back, it's too late for us to do
857 		 * anything about it.  In particular, we can't invalidate any
858 		 * part of the file's buffers because VOP_STRATEGY is called
859 		 * with them already locked.
860 		 */
861 		filesize = fvdat->cached_attrs.va_size;
862 		/* filesize must've been cached by fuse_vnop_open.  */
863 		KASSERT(filesize != VNOVAL, ("filesize should've been cached"));
864 
865 		if ((off_t)bp->b_lblkno * biosize + bp->b_dirtyend > filesize)
866 			bp->b_dirtyend = filesize -
867 				(off_t)bp->b_lblkno * biosize;
868 
869 		if (bp->b_dirtyend > bp->b_dirtyoff) {
870 			io.iov_len = uiop->uio_resid = bp->b_dirtyend
871 			    - bp->b_dirtyoff;
872 			uiop->uio_offset = (off_t)bp->b_lblkno * biosize
873 			    + bp->b_dirtyoff;
874 			io.iov_base = (char *)bp->b_data + bp->b_dirtyoff;
875 			uiop->uio_rw = UIO_WRITE;
876 
877 			bool pages = bp->b_flags & B_FUSEFS_WRITE_CACHE;
878 			error = fuse_write_directbackend(vp, uiop, cred, fufh,
879 				filesize, 0, pages);
880 
881 			if (error == EINTR || error == ETIMEDOUT) {
882 				bp->b_flags &= ~(B_INVAL | B_NOCACHE);
883 				if ((bp->b_flags & B_PAGING) == 0) {
884 					bdirty(bp);
885 					bp->b_flags &= ~B_DONE;
886 				}
887 				if ((error == EINTR || error == ETIMEDOUT) &&
888 				    (bp->b_flags & B_ASYNC) == 0)
889 					bp->b_flags |= B_EINTR;
890 			} else {
891 				if (error) {
892 					bp->b_ioflags |= BIO_ERROR;
893 					bp->b_flags |= B_INVAL;
894 					bp->b_error = error;
895 				}
896 				bp->b_dirtyoff = bp->b_dirtyend = 0;
897 			}
898 		} else {
899 			bp->b_resid = 0;
900 			bufdone(bp);
901 			return (0);
902 		}
903 	}
904 	bp->b_resid = uiop->uio_resid;
905 	bufdone(bp);
906 	return (error);
907 }
908 
909 int
910 fuse_io_flushbuf(struct vnode *vp, int waitfor, struct thread *td)
911 {
912 
913 	return (vn_fsync_buf(vp, waitfor));
914 }
915 
916 /*
917  * Flush and invalidate all dirty buffers. If another process is already
918  * doing the flush, just wait for completion.
919  */
920 int
921 fuse_io_invalbuf(struct vnode *vp, struct thread *td)
922 {
923 	struct fuse_vnode_data *fvdat = VTOFUD(vp);
924 	int error = 0;
925 
926 	if (VN_IS_DOOMED(vp))
927 		return 0;
928 
929 	ASSERT_VOP_ELOCKED(vp, "fuse_io_invalbuf");
930 
931 	while (fvdat->flag & FN_FLUSHINPROG) {
932 		struct proc *p = td->td_proc;
933 
934 		if (vp->v_mount->mnt_kern_flag & MNTK_UNMOUNTF)
935 			return EIO;
936 		fvdat->flag |= FN_FLUSHWANT;
937 		tsleep(&fvdat->flag, PRIBIO + 2, "fusevinv", 2 * hz);
938 		error = 0;
939 		if (p != NULL) {
940 			PROC_LOCK(p);
941 			if (SIGNOTEMPTY(p->p_siglist) ||
942 			    SIGNOTEMPTY(td->td_siglist))
943 				error = EINTR;
944 			PROC_UNLOCK(p);
945 		}
946 		if (error == EINTR)
947 			return EINTR;
948 	}
949 	fvdat->flag |= FN_FLUSHINPROG;
950 
951 	if (vp->v_bufobj.bo_object != NULL) {
952 		VM_OBJECT_WLOCK(vp->v_bufobj.bo_object);
953 		vm_object_page_clean(vp->v_bufobj.bo_object, 0, 0, OBJPC_SYNC);
954 		VM_OBJECT_WUNLOCK(vp->v_bufobj.bo_object);
955 	}
956 	error = vinvalbuf(vp, V_SAVE, PCATCH, 0);
957 	while (error) {
958 		if (error == ERESTART || error == EINTR) {
959 			fvdat->flag &= ~FN_FLUSHINPROG;
960 			if (fvdat->flag & FN_FLUSHWANT) {
961 				fvdat->flag &= ~FN_FLUSHWANT;
962 				wakeup(&fvdat->flag);
963 			}
964 			return EINTR;
965 		}
966 		error = vinvalbuf(vp, V_SAVE, PCATCH, 0);
967 	}
968 	fvdat->flag &= ~FN_FLUSHINPROG;
969 	if (fvdat->flag & FN_FLUSHWANT) {
970 		fvdat->flag &= ~FN_FLUSHWANT;
971 		wakeup(&fvdat->flag);
972 	}
973 	return (error);
974 }
975