xref: /freebsd/sys/fs/fuse/fuse_io.c (revision bdcfd222ce6369e7aeaceb9a92ffdde84bdbf6cd)
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/module.h>
68 #include <sys/systm.h>
69 #include <sys/errno.h>
70 #include <sys/param.h>
71 #include <sys/kernel.h>
72 #include <sys/conf.h>
73 #include <sys/uio.h>
74 #include <sys/malloc.h>
75 #include <sys/queue.h>
76 #include <sys/lock.h>
77 #include <sys/sx.h>
78 #include <sys/mutex.h>
79 #include <sys/rwlock.h>
80 #include <sys/priv.h>
81 #include <sys/proc.h>
82 #include <sys/mount.h>
83 #include <sys/vnode.h>
84 #include <sys/stat.h>
85 #include <sys/unistd.h>
86 #include <sys/filedesc.h>
87 #include <sys/file.h>
88 #include <sys/fcntl.h>
89 #include <sys/bio.h>
90 #include <sys/buf.h>
91 #include <sys/sysctl.h>
92 #include <sys/vmmeter.h>
93 
94 #include <vm/vm.h>
95 #include <vm/vm_extern.h>
96 #include <vm/pmap.h>
97 #include <vm/vm_map.h>
98 #include <vm/vm_page.h>
99 #include <vm/vm_object.h>
100 
101 #include "fuse.h"
102 #include "fuse_file.h"
103 #include "fuse_node.h"
104 #include "fuse_internal.h"
105 #include "fuse_ipc.h"
106 #include "fuse_io.h"
107 
108 /*
109  * Set in a struct buf to indicate that the write came from the buffer cache
110  * and the originating cred and pid are no longer known.
111  */
112 #define B_FUSEFS_WRITE_CACHE B_FS_FLAG1
113 
114 SDT_PROVIDER_DECLARE(fusefs);
115 /*
116  * Fuse trace probe:
117  * arg0: verbosity.  Higher numbers give more verbose messages
118  * arg1: Textual message
119  */
120 SDT_PROBE_DEFINE2(fusefs, , io, trace, "int", "char*");
121 
122 static int
123 fuse_inval_buf_range(struct vnode *vp, off_t filesize, off_t start, off_t end);
124 static int
125 fuse_read_directbackend(struct vnode *vp, struct uio *uio,
126     struct ucred *cred, struct fuse_filehandle *fufh);
127 static 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 static int
131 fuse_write_directbackend(struct vnode *vp, struct uio *uio,
132     struct ucred *cred, struct fuse_filehandle *fufh, off_t filesize,
133     int ioflag, bool pages);
134 static int
135 fuse_write_biobackend(struct vnode *vp, struct uio *uio,
136     struct ucred *cred, struct fuse_filehandle *fufh, int ioflag, pid_t pid);
137 
138 /* Invalidate a range of cached data, whether dirty of not */
139 static int
140 fuse_inval_buf_range(struct vnode *vp, off_t filesize, off_t start, off_t end)
141 {
142 	struct buf *bp;
143 	daddr_t left_lbn, end_lbn, right_lbn;
144 	off_t new_filesize;
145 	int iosize, left_on, right_on, right_blksize;
146 
147 	iosize = fuse_iosize(vp);
148 	left_lbn = start / iosize;
149 	end_lbn = howmany(end, iosize);
150 	left_on = start & (iosize - 1);
151 	if (left_on != 0) {
152 		bp = getblk(vp, left_lbn, iosize, PCATCH, 0, 0);
153 		if ((bp->b_flags & B_CACHE) != 0 && bp->b_dirtyend >= left_on) {
154 			/*
155 			 * Flush the dirty buffer, because we don't have a
156 			 * byte-granular way to record which parts of the
157 			 * buffer are valid.
158 			 */
159 			bwrite(bp);
160 			if (bp->b_error)
161 				return (bp->b_error);
162 		} else {
163 			brelse(bp);
164 		}
165 	}
166 	right_on = end & (iosize - 1);
167 	if (right_on != 0) {
168 		right_lbn = end / iosize;
169 		new_filesize = MAX(filesize, end);
170 		right_blksize = MIN(iosize, new_filesize - iosize * right_lbn);
171 		bp = getblk(vp, right_lbn, right_blksize, PCATCH, 0, 0);
172 		if ((bp->b_flags & B_CACHE) != 0 && bp->b_dirtyoff < right_on) {
173 			/*
174 			 * Flush the dirty buffer, because we don't have a
175 			 * byte-granular way to record which parts of the
176 			 * buffer are valid.
177 			 */
178 			bwrite(bp);
179 			if (bp->b_error)
180 				return (bp->b_error);
181 		} else {
182 			brelse(bp);
183 		}
184 	}
185 
186 	v_inval_buf_range(vp, left_lbn, end_lbn, iosize);
187 	return (0);
188 }
189 
190 SDT_PROBE_DEFINE5(fusefs, , io, io_dispatch, "struct vnode*", "struct uio*",
191 		"int", "struct ucred*", "struct fuse_filehandle*");
192 SDT_PROBE_DEFINE4(fusefs, , io, io_dispatch_filehandles_closed, "struct vnode*",
193     "struct uio*", "int", "struct ucred*");
194 int
195 fuse_io_dispatch(struct vnode *vp, struct uio *uio, int ioflag,
196     struct ucred *cred, pid_t pid)
197 {
198 	struct fuse_filehandle *fufh;
199 	int err, directio;
200 	int fflag;
201 	bool closefufh = false;
202 
203 	MPASS(vp->v_type == VREG || vp->v_type == VDIR);
204 
205 	fflag = (uio->uio_rw == UIO_READ) ? FREAD : FWRITE;
206 	err = fuse_filehandle_getrw(vp, fflag, &fufh, cred, pid);
207 	if (err == EBADF && vnode_mount(vp)->mnt_flag & MNT_EXPORTED) {
208 		/*
209 		 * nfsd will do I/O without first doing VOP_OPEN.  We
210 		 * must implicitly open the file here
211 		 */
212 		err = fuse_filehandle_open(vp, fflag, &fufh, curthread, cred);
213 		closefufh = true;
214 	}
215 	else if (err) {
216 		SDT_PROBE4(fusefs, , io, io_dispatch_filehandles_closed,
217 			vp, uio, ioflag, cred);
218 		printf("FUSE: io dispatch: filehandles are closed\n");
219 		return err;
220 	}
221 	if (err)
222 		goto out;
223 	SDT_PROBE5(fusefs, , io, io_dispatch, vp, uio, ioflag, cred, fufh);
224 
225 	/*
226          * Ideally, when the daemon asks for direct io at open time, the
227          * standard file flag should be set according to this, so that would
228          * just change the default mode, which later on could be changed via
229          * fcntl(2).
230          * But this doesn't work, the O_DIRECT flag gets cleared at some point
231          * (don't know where). So to make any use of the Fuse direct_io option,
232          * we hardwire it into the file's private data (similarly to Linux,
233          * btw.).
234          */
235 	directio = (ioflag & IO_DIRECT) || !fsess_opt_datacache(vnode_mount(vp));
236 
237 	switch (uio->uio_rw) {
238 	case UIO_READ:
239 		fuse_vnode_update(vp, FN_ATIMECHANGE);
240 		if (directio) {
241 			SDT_PROBE2(fusefs, , io, trace, 1,
242 				"direct read of vnode");
243 			err = fuse_read_directbackend(vp, uio, cred, fufh);
244 		} else {
245 			SDT_PROBE2(fusefs, , io, trace, 1,
246 				"buffered read of vnode");
247 			err = fuse_read_biobackend(vp, uio, ioflag, cred, fufh,
248 				pid);
249 		}
250 		break;
251 	case UIO_WRITE:
252 		fuse_vnode_update(vp, FN_MTIMECHANGE | FN_CTIMECHANGE);
253 		if (directio) {
254 			off_t start, end, filesize;
255 			bool pages = (ioflag & IO_VMIO) != 0;
256 
257 			SDT_PROBE2(fusefs, , io, trace, 1,
258 				"direct write of vnode");
259 
260 			err = fuse_vnode_size(vp, &filesize, cred, curthread);
261 			if (err)
262 				goto out;
263 
264 			start = uio->uio_offset;
265 			end = start + uio->uio_resid;
266 			if (!pages) {
267 				err = fuse_inval_buf_range(vp, filesize, start,
268 				    end);
269 				if (err)
270 					return (err);
271 			}
272 			err = fuse_write_directbackend(vp, uio, cred, fufh,
273 				filesize, ioflag, pages);
274 		} else {
275 			SDT_PROBE2(fusefs, , io, trace, 1,
276 				"buffered write of vnode");
277 			if (!fsess_opt_writeback(vnode_mount(vp)))
278 				ioflag |= IO_SYNC;
279 			err = fuse_write_biobackend(vp, uio, cred, fufh, ioflag,
280 				pid);
281 		}
282 		fuse_internal_clear_suid_on_write(vp, cred, uio->uio_td);
283 		break;
284 	default:
285 		panic("uninterpreted mode passed to fuse_io_dispatch");
286 	}
287 
288 out:
289 	if (closefufh)
290 		fuse_filehandle_close(vp, fufh, curthread, cred);
291 
292 	return (err);
293 }
294 
295 SDT_PROBE_DEFINE4(fusefs, , io, read_bio_backend_start, "int", "int", "int", "int");
296 SDT_PROBE_DEFINE2(fusefs, , io, read_bio_backend_feed, "int", "struct buf*");
297 SDT_PROBE_DEFINE4(fusefs, , io, read_bio_backend_end, "int", "ssize_t", "int",
298 		"struct buf*");
299 static int
300 fuse_read_biobackend(struct vnode *vp, struct uio *uio, int ioflag,
301     struct ucred *cred, struct fuse_filehandle *fufh, pid_t pid)
302 {
303 	struct buf *bp;
304 	struct mount *mp;
305 	struct fuse_data *data;
306 	daddr_t lbn, nextlbn;
307 	int bcount, nextsize;
308 	int err, n = 0, on = 0, seqcount;
309 	off_t filesize;
310 
311 	const int biosize = fuse_iosize(vp);
312 	mp = vnode_mount(vp);
313 	data = fuse_get_mpdata(mp);
314 
315 	if (uio->uio_offset < 0)
316 		return (EINVAL);
317 
318 	seqcount = ioflag >> IO_SEQSHIFT;
319 
320 	err = fuse_vnode_size(vp, &filesize, cred, curthread);
321 	if (err)
322 		return err;
323 
324 	for (err = 0, bp = NULL; uio->uio_resid > 0; bp = NULL) {
325 		if (fuse_isdeadfs(vp)) {
326 			err = ENXIO;
327 			break;
328 		}
329 		if (filesize - uio->uio_offset <= 0)
330 			break;
331 		lbn = uio->uio_offset / biosize;
332 		on = uio->uio_offset & (biosize - 1);
333 
334 		if ((off_t)lbn * biosize >= filesize) {
335 			bcount = 0;
336 		} else if ((off_t)(lbn + 1) * biosize > filesize) {
337 			bcount = filesize - (off_t)lbn *biosize;
338 		} else {
339 			bcount = biosize;
340 		}
341 		nextlbn = lbn + 1;
342 		nextsize = MIN(biosize, filesize - nextlbn * biosize);
343 
344 		SDT_PROBE4(fusefs, , io, read_bio_backend_start,
345 			biosize, (int)lbn, on, bcount);
346 
347 		if (bcount < biosize) {
348 			/* If near EOF, don't do readahead */
349 			err = bread(vp, lbn, bcount, NOCRED, &bp);
350 		} else if ((vp->v_mount->mnt_flag & MNT_NOCLUSTERR) == 0) {
351 			/* Try clustered read */
352 			long totread = uio->uio_resid + on;
353 			seqcount = MIN(seqcount,
354 				data->max_readahead_blocks + 1);
355 			err = cluster_read(vp, filesize, lbn, bcount, NOCRED,
356 				totread, seqcount, 0, &bp);
357 		} else if (seqcount > 1 && data->max_readahead_blocks >= 1) {
358 			/* Try non-clustered readahead */
359 			err = breadn(vp, lbn, bcount, &nextlbn, &nextsize, 1,
360 				NOCRED, &bp);
361 		} else {
362 			/* Just read what was requested */
363 			err = bread(vp, lbn, bcount, NOCRED, &bp);
364 		}
365 
366 		if (err) {
367 			brelse(bp);
368 			bp = NULL;
369 			break;
370 		}
371 
372 		/*
373 	         * on is the offset into the current bp.  Figure out how many
374 	         * bytes we can copy out of the bp.  Note that bcount is
375 	         * NOT DEV_BSIZE aligned.
376 	         *
377 	         * Then figure out how many bytes we can copy into the uio.
378 	         */
379 
380 		n = 0;
381 		if (on < bcount - bp->b_resid)
382 			n = MIN((unsigned)(bcount - bp->b_resid - on),
383 			    uio->uio_resid);
384 		if (n > 0) {
385 			SDT_PROBE2(fusefs, , io, read_bio_backend_feed, n, bp);
386 			err = uiomove(bp->b_data + on, n, uio);
387 		}
388 		vfs_bio_brelse(bp, ioflag);
389 		SDT_PROBE4(fusefs, , io, read_bio_backend_end, err,
390 			uio->uio_resid, n, bp);
391 		if (bp->b_resid > 0) {
392 			/* Short read indicates EOF */
393 			break;
394 		}
395 	}
396 
397 	return (err);
398 }
399 
400 SDT_PROBE_DEFINE1(fusefs, , io, read_directbackend_start,
401 	"struct fuse_read_in*");
402 SDT_PROBE_DEFINE3(fusefs, , io, read_directbackend_complete,
403 	"struct fuse_dispatcher*", "struct fuse_read_in*", "struct uio*");
404 
405 static int
406 fuse_read_directbackend(struct vnode *vp, struct uio *uio,
407     struct ucred *cred, struct fuse_filehandle *fufh)
408 {
409 	struct fuse_data *data;
410 	struct fuse_dispatcher fdi;
411 	struct fuse_read_in *fri;
412 	int err = 0;
413 
414 	data = fuse_get_mpdata(vp->v_mount);
415 
416 	if (uio->uio_resid == 0)
417 		return (0);
418 
419 	fdisp_init(&fdi, 0);
420 
421 	/*
422          * XXX In "normal" case we use an intermediate kernel buffer for
423          * transmitting data from daemon's context to ours. Eventually, we should
424          * get rid of this. Anyway, if the target uio lives in sysspace (we are
425          * called from pageops), and the input data doesn't need kernel-side
426          * processing (we are not called from readdir) we can already invoke
427          * an optimized, "peer-to-peer" I/O routine.
428          */
429 	while (uio->uio_resid > 0) {
430 		fdi.iosize = sizeof(*fri);
431 		fdisp_make_vp(&fdi, FUSE_READ, vp, uio->uio_td, cred);
432 		fri = fdi.indata;
433 		fri->fh = fufh->fh_id;
434 		fri->offset = uio->uio_offset;
435 		fri->size = MIN(uio->uio_resid,
436 		    fuse_get_mpdata(vp->v_mount)->max_read);
437 		if (fuse_libabi_geq(data, 7, 9)) {
438 			/* See comment regarding FUSE_WRITE_LOCKOWNER */
439 			fri->read_flags = 0;
440 			fri->flags = fufh_type_2_fflags(fufh->fufh_type);
441 		}
442 
443 		SDT_PROBE1(fusefs, , io, read_directbackend_start, fri);
444 
445 		if ((err = fdisp_wait_answ(&fdi)))
446 			goto out;
447 
448 		SDT_PROBE3(fusefs, , io, read_directbackend_complete,
449 			&fdi, fri, uio);
450 
451 		if ((err = uiomove(fdi.answ, MIN(fri->size, fdi.iosize), uio)))
452 			break;
453 		if (fdi.iosize < fri->size) {
454 			/*
455 			 * Short read.  Should only happen at EOF or with
456 			 * direct io.
457 			 */
458 			break;
459 		}
460 	}
461 
462 out:
463 	fdisp_destroy(&fdi);
464 	return (err);
465 }
466 
467 static int
468 fuse_write_directbackend(struct vnode *vp, struct uio *uio,
469     struct ucred *cred, struct fuse_filehandle *fufh, off_t filesize,
470     int ioflag, bool pages)
471 {
472 	struct fuse_vnode_data *fvdat = VTOFUD(vp);
473 	struct fuse_data *data;
474 	struct fuse_write_in *fwi;
475 	struct fuse_write_out *fwo;
476 	struct fuse_dispatcher fdi;
477 	size_t chunksize;
478 	void *fwi_data;
479 	off_t as_written_offset;
480 	int diff;
481 	int err = 0;
482 	bool direct_io = fufh->fuse_open_flags & FOPEN_DIRECT_IO;
483 	bool wrote_anything = false;
484 	uint32_t write_flags;
485 
486 	data = fuse_get_mpdata(vp->v_mount);
487 
488 	/*
489 	 * Don't set FUSE_WRITE_LOCKOWNER in write_flags.  It can't be set
490 	 * accurately when using POSIX AIO, libfuse doesn't use it, and I'm not
491 	 * aware of any file systems that do.  It was an attempt to add
492 	 * Linux-style mandatory locking to the FUSE protocol, but mandatory
493 	 * locking is deprecated even on Linux.  See Linux commit
494 	 * f33321141b273d60cbb3a8f56a5489baad82ba5e .
495 	 */
496 	/*
497 	 * Set FUSE_WRITE_CACHE whenever we don't know the uid, gid, and/or pid
498 	 * that originated a write.  For example when writing from the
499 	 * writeback cache.  I don't know of a single file system that cares,
500 	 * but the protocol says we're supposed to do this.
501 	 */
502 	write_flags = !pages && (
503 		(ioflag & IO_DIRECT) ||
504 		!fsess_opt_datacache(vnode_mount(vp)) ||
505 		!fsess_opt_writeback(vnode_mount(vp))) ? 0 : FUSE_WRITE_CACHE;
506 
507 	if (uio->uio_resid == 0)
508 		return (0);
509 
510 	if (ioflag & IO_APPEND)
511 		uio_setoffset(uio, filesize);
512 
513 	if (vn_rlimit_fsize(vp, uio, uio->uio_td))
514 		return (EFBIG);
515 
516 	fdisp_init(&fdi, 0);
517 
518 	while (uio->uio_resid > 0) {
519 		size_t sizeof_fwi;
520 
521 		if (fuse_libabi_geq(data, 7, 9)) {
522 			sizeof_fwi = sizeof(*fwi);
523 		} else {
524 			sizeof_fwi = FUSE_COMPAT_WRITE_IN_SIZE;
525 		}
526 
527 		chunksize = MIN(uio->uio_resid, data->max_write);
528 
529 		fdi.iosize = sizeof_fwi + chunksize;
530 		fdisp_make_vp(&fdi, FUSE_WRITE, vp, uio->uio_td, cred);
531 
532 		fwi = fdi.indata;
533 		fwi->fh = fufh->fh_id;
534 		fwi->offset = uio->uio_offset;
535 		fwi->size = chunksize;
536 		fwi->write_flags = write_flags;
537 		if (fuse_libabi_geq(data, 7, 9)) {
538 			fwi->flags = fufh_type_2_fflags(fufh->fufh_type);
539 		}
540 		fwi_data = (char *)fdi.indata + sizeof_fwi;
541 
542 		if ((err = uiomove(fwi_data, chunksize, uio)))
543 			break;
544 
545 retry:
546 		err = fdisp_wait_answ(&fdi);
547 		if (err == ERESTART || err == EINTR || err == EWOULDBLOCK) {
548 			/*
549 			 * Rewind the uio so dofilewrite will know it's
550 			 * incomplete
551 			 */
552 			uio->uio_resid += fwi->size;
553 			uio->uio_offset -= fwi->size;
554 			/*
555 			 * Change ERESTART into EINTR because we can't rewind
556 			 * uio->uio_iov.  Basically, once uiomove(9) has been
557 			 * called, it's impossible to restart a syscall.
558 			 */
559 			if (err == ERESTART)
560 				err = EINTR;
561 			break;
562 		} else if (err) {
563 			break;
564 		} else {
565 			wrote_anything = true;
566 		}
567 
568 		fwo = ((struct fuse_write_out *)fdi.answ);
569 
570 		/* Adjust the uio in the case of short writes */
571 		diff = fwi->size - fwo->size;
572 		as_written_offset = uio->uio_offset - diff;
573 
574 		if (as_written_offset - diff > filesize)
575 			fuse_vnode_setsize(vp, as_written_offset, false);
576 		if (as_written_offset - diff >= filesize)
577 			fvdat->flag &= ~FN_SIZECHANGE;
578 
579 		if (diff < 0) {
580 			fuse_warn(data, FSESS_WARN_WROTE_LONG,
581 				"wrote more data than we provided it.");
582 			err = EINVAL;
583 			break;
584 		} else if (diff > 0) {
585 			/* Short write */
586 			if (!direct_io) {
587 				fuse_warn(data, FSESS_WARN_SHORT_WRITE,
588 					"short writes are only allowed with "
589 					"direct_io.");
590 			}
591 			if (ioflag & IO_DIRECT) {
592 				/* Return early */
593 				uio->uio_resid += diff;
594 				uio->uio_offset -= diff;
595 				break;
596 			} else {
597 				/* Resend the unwritten portion of data */
598 				fdi.iosize = sizeof_fwi + diff;
599 				/* Refresh fdi without clearing data buffer */
600 				fdisp_refresh_vp(&fdi, FUSE_WRITE, vp,
601 					uio->uio_td, cred);
602 				fwi = fdi.indata;
603 				MPASS2(fwi == fdi.indata, "FUSE dispatcher "
604 					"reallocated despite no increase in "
605 					"size?");
606 				void *src = (char*)fwi_data + fwo->size;
607 				memmove(fwi_data, src, diff);
608 				fwi->fh = fufh->fh_id;
609 				fwi->offset = as_written_offset;
610 				fwi->size = diff;
611 				fwi->write_flags = write_flags;
612 				goto retry;
613 			}
614 		}
615 	}
616 
617 	fdisp_destroy(&fdi);
618 
619 	if (wrote_anything)
620 		fuse_vnode_undirty_cached_timestamps(vp, false);
621 
622 	return (err);
623 }
624 
625 SDT_PROBE_DEFINE6(fusefs, , io, write_biobackend_start, "int64_t", "int", "int",
626 		"struct uio*", "int", "bool");
627 SDT_PROBE_DEFINE2(fusefs, , io, write_biobackend_append_race, "long", "int");
628 SDT_PROBE_DEFINE2(fusefs, , io, write_biobackend_issue, "int", "struct buf*");
629 
630 static int
631 fuse_write_biobackend(struct vnode *vp, struct uio *uio,
632     struct ucred *cred, struct fuse_filehandle *fufh, int ioflag, pid_t pid)
633 {
634 	struct fuse_vnode_data *fvdat = VTOFUD(vp);
635 	struct buf *bp;
636 	daddr_t lbn;
637 	off_t filesize;
638 	int bcount;
639 	int n, on, seqcount, err = 0;
640 	bool last_page;
641 
642 	const int biosize = fuse_iosize(vp);
643 
644 	seqcount = ioflag >> IO_SEQSHIFT;
645 
646 	KASSERT(uio->uio_rw == UIO_WRITE, ("fuse_write_biobackend mode"));
647 	if (vp->v_type != VREG)
648 		return (EIO);
649 	if (uio->uio_offset < 0)
650 		return (EINVAL);
651 	if (uio->uio_resid == 0)
652 		return (0);
653 
654 	err = fuse_vnode_size(vp, &filesize, cred, curthread);
655 	if (err)
656 		return err;
657 
658 	if (ioflag & IO_APPEND)
659 		uio_setoffset(uio, filesize);
660 
661 	if (vn_rlimit_fsize(vp, uio, uio->uio_td))
662 		return (EFBIG);
663 
664 	do {
665 		bool direct_append, extending;
666 
667 		if (fuse_isdeadfs(vp)) {
668 			err = ENXIO;
669 			break;
670 		}
671 		lbn = uio->uio_offset / biosize;
672 		on = uio->uio_offset & (biosize - 1);
673 		n = MIN((unsigned)(biosize - on), uio->uio_resid);
674 
675 again:
676 		/* Get or create a buffer for the write */
677 		direct_append = uio->uio_offset == filesize && n;
678 		if (uio->uio_offset + n < filesize) {
679 			extending = false;
680 			if ((off_t)(lbn + 1) * biosize < filesize) {
681 				/* Not the file's last block */
682 				bcount = biosize;
683 			} else {
684 				/* The file's last block */
685 				bcount = filesize - (off_t)lbn * biosize;
686 			}
687 		} else {
688 			extending = true;
689 			bcount = on + n;
690 		}
691 		if (howmany(((off_t)lbn * biosize + on + n - 1), PAGE_SIZE) >=
692 		    howmany(filesize, PAGE_SIZE))
693 			last_page = true;
694 		else
695 			last_page = false;
696 		if (direct_append) {
697 			/*
698 			 * Take care to preserve the buffer's B_CACHE state so
699 			 * as not to cause an unnecessary read.
700 			 */
701 			bp = getblk(vp, lbn, on, PCATCH, 0, 0);
702 			if (bp != NULL) {
703 				uint32_t save = bp->b_flags & B_CACHE;
704 				allocbuf(bp, bcount);
705 				bp->b_flags |= save;
706 			}
707 		} else {
708 			bp = getblk(vp, lbn, bcount, PCATCH, 0, 0);
709 		}
710 		if (!bp) {
711 			err = EINTR;
712 			break;
713 		}
714 		if (extending) {
715 			/*
716 			 * Extend file _after_ locking buffer so we won't race
717 			 * with other readers
718 			 */
719 			err = fuse_vnode_setsize(vp, uio->uio_offset + n, false);
720 			filesize = uio->uio_offset + n;
721 			fvdat->flag |= FN_SIZECHANGE;
722 			if (err) {
723 				brelse(bp);
724 				break;
725 			}
726 		}
727 
728 		SDT_PROBE6(fusefs, , io, write_biobackend_start,
729 			lbn, on, n, uio, bcount, direct_append);
730 		/*
731 	         * Issue a READ if B_CACHE is not set.  In special-append
732 	         * mode, B_CACHE is based on the buffer prior to the write
733 	         * op and is typically set, avoiding the read.  If a read
734 	         * is required in special append mode, the server will
735 	         * probably send us a short-read since we extended the file
736 	         * on our end, resulting in b_resid == 0 and, thusly,
737 	         * B_CACHE getting set.
738 	         *
739 	         * We can also avoid issuing the read if the write covers
740 	         * the entire buffer.  We have to make sure the buffer state
741 	         * is reasonable in this case since we will not be initiating
742 	         * I/O.  See the comments in kern/vfs_bio.c's getblk() for
743 	         * more information.
744 	         *
745 	         * B_CACHE may also be set due to the buffer being cached
746 	         * normally.
747 	         */
748 
749 		if (on == 0 && n == bcount) {
750 			bp->b_flags |= B_CACHE;
751 			bp->b_flags &= ~B_INVAL;
752 			bp->b_ioflags &= ~BIO_ERROR;
753 		}
754 		if ((bp->b_flags & B_CACHE) == 0) {
755 			bp->b_iocmd = BIO_READ;
756 			vfs_busy_pages(bp, 0);
757 			fuse_io_strategy(vp, bp);
758 			if ((err = bp->b_error)) {
759 				brelse(bp);
760 				break;
761 			}
762 			if (bp->b_resid > 0) {
763 				/*
764 				 * Short read indicates EOF.  Update file size
765 				 * from the server and try again.
766 				 */
767 				SDT_PROBE2(fusefs, , io, trace, 1,
768 					"Short read during a RMW");
769 				brelse(bp);
770 				err = fuse_vnode_size(vp, &filesize, cred,
771 				    curthread);
772 				if (err)
773 					break;
774 				else
775 					goto again;
776 			}
777 		}
778 		if (bp->b_wcred == NOCRED)
779 			bp->b_wcred = crhold(cred);
780 
781 		/*
782 	         * If dirtyend exceeds file size, chop it down.  This should
783 	         * not normally occur but there is an append race where it
784 	         * might occur XXX, so we log it.
785 	         *
786 	         * If the chopping creates a reverse-indexed or degenerate
787 	         * situation with dirtyoff/end, we 0 both of them.
788 	         */
789 		if (bp->b_dirtyend > bcount) {
790 			SDT_PROBE2(fusefs, , io, write_biobackend_append_race,
791 			    (long)bp->b_blkno * biosize,
792 			    bp->b_dirtyend - bcount);
793 			bp->b_dirtyend = bcount;
794 		}
795 		if (bp->b_dirtyoff >= bp->b_dirtyend)
796 			bp->b_dirtyoff = bp->b_dirtyend = 0;
797 
798 		/*
799 	         * If the new write will leave a contiguous dirty
800 	         * area, just update the b_dirtyoff and b_dirtyend,
801 	         * otherwise force a write rpc of the old dirty area.
802 	         *
803 	         * While it is possible to merge discontiguous writes due to
804 	         * our having a B_CACHE buffer ( and thus valid read data
805 	         * for the hole), we don't because it could lead to
806 	         * significant cache coherency problems with multiple clients,
807 	         * especially if locking is implemented later on.
808 	         *
809 	         * as an optimization we could theoretically maintain
810 	         * a linked list of discontinuous areas, but we would still
811 	         * have to commit them separately so there isn't much
812 	         * advantage to it except perhaps a bit of asynchronization.
813 	         */
814 
815 		if (bp->b_dirtyend > 0 &&
816 		    (on > bp->b_dirtyend || (on + n) < bp->b_dirtyoff)) {
817 			/*
818 	                 * Yes, we mean it. Write out everything to "storage"
819 	                 * immediately, without hesitation. (Apart from other
820 	                 * reasons: the only way to know if a write is valid
821 	                 * if its actually written out.)
822 	                 */
823 			SDT_PROBE2(fusefs, , io, write_biobackend_issue, 0, bp);
824 			bwrite(bp);
825 			if (bp->b_error == EINTR) {
826 				err = EINTR;
827 				break;
828 			}
829 			goto again;
830 		}
831 		err = uiomove((char *)bp->b_data + on, n, uio);
832 
833 		if (err) {
834 			bp->b_ioflags |= BIO_ERROR;
835 			bp->b_error = err;
836 			brelse(bp);
837 			break;
838 			/* TODO: vfs_bio_clrbuf like ffs_write does? */
839 		}
840 		/*
841 	         * Only update dirtyoff/dirtyend if not a degenerate
842 	         * condition.
843 	         */
844 		if (n) {
845 			if (bp->b_dirtyend > 0) {
846 				bp->b_dirtyoff = MIN(on, bp->b_dirtyoff);
847 				bp->b_dirtyend = MAX((on + n), bp->b_dirtyend);
848 			} else {
849 				bp->b_dirtyoff = on;
850 				bp->b_dirtyend = on + n;
851 			}
852 			vfs_bio_set_valid(bp, on, n);
853 		}
854 
855 		vfs_bio_set_flags(bp, ioflag);
856 
857 		bp->b_flags |= B_FUSEFS_WRITE_CACHE;
858 		if (ioflag & IO_SYNC) {
859 			SDT_PROBE2(fusefs, , io, write_biobackend_issue, 2, bp);
860 			if (!(ioflag & IO_VMIO))
861 				bp->b_flags &= ~B_FUSEFS_WRITE_CACHE;
862 			err = bwrite(bp);
863 		} else if (vm_page_count_severe() ||
864 			    buf_dirty_count_severe() ||
865 			    (ioflag & IO_ASYNC)) {
866 			bp->b_flags |= B_CLUSTEROK;
867 			SDT_PROBE2(fusefs, , io, write_biobackend_issue, 3, bp);
868 			bawrite(bp);
869 		} else if (on == 0 && n == bcount) {
870 			if ((vp->v_mount->mnt_flag & MNT_NOCLUSTERW) == 0) {
871 				bp->b_flags |= B_CLUSTEROK;
872 				SDT_PROBE2(fusefs, , io, write_biobackend_issue,
873 					4, bp);
874 				cluster_write(vp, &fvdat->clusterw, bp,
875 				    filesize, seqcount, 0);
876 			} else {
877 				SDT_PROBE2(fusefs, , io, write_biobackend_issue,
878 					5, bp);
879 				bawrite(bp);
880 			}
881 		} else if (ioflag & IO_DIRECT) {
882 			bp->b_flags |= B_CLUSTEROK;
883 			SDT_PROBE2(fusefs, , io, write_biobackend_issue, 6, bp);
884 			bawrite(bp);
885 		} else {
886 			bp->b_flags &= ~B_CLUSTEROK;
887 			SDT_PROBE2(fusefs, , io, write_biobackend_issue, 7, bp);
888 			bdwrite(bp);
889 		}
890 		if (err)
891 			break;
892 	} while (uio->uio_resid > 0 && n > 0);
893 
894 	return (err);
895 }
896 
897 int
898 fuse_io_strategy(struct vnode *vp, struct buf *bp)
899 {
900 	struct fuse_vnode_data *fvdat = VTOFUD(vp);
901 	struct fuse_filehandle *fufh;
902 	struct ucred *cred;
903 	struct uio *uiop;
904 	struct uio uio;
905 	struct iovec io;
906 	off_t filesize;
907 	int error = 0;
908 	int fflag;
909 	/* We don't know the true pid when we're dealing with the cache */
910 	pid_t pid = 0;
911 
912 	const int biosize = fuse_iosize(vp);
913 
914 	MPASS(vp->v_type == VREG || vp->v_type == VDIR);
915 	MPASS(bp->b_iocmd == BIO_READ || bp->b_iocmd == BIO_WRITE);
916 
917 	fflag = bp->b_iocmd == BIO_READ ? FREAD : FWRITE;
918 	cred = bp->b_iocmd == BIO_READ ? bp->b_rcred : bp->b_wcred;
919 	error = fuse_filehandle_getrw(vp, fflag, &fufh, cred, pid);
920 	if (bp->b_iocmd == BIO_READ && error == EBADF) {
921 		/*
922 		 * This may be a read-modify-write operation on a cached file
923 		 * opened O_WRONLY.  The FUSE protocol allows this.
924 		 */
925 		error = fuse_filehandle_get(vp, FWRITE, &fufh, cred, pid);
926 	}
927 	if (error) {
928 		printf("FUSE: strategy: filehandles are closed\n");
929 		bp->b_ioflags |= BIO_ERROR;
930 		bp->b_error = error;
931 		bufdone(bp);
932 		return (error);
933 	}
934 
935 	uiop = &uio;
936 	uiop->uio_iov = &io;
937 	uiop->uio_iovcnt = 1;
938 	uiop->uio_segflg = UIO_SYSSPACE;
939 	uiop->uio_td = curthread;
940 
941 	/*
942          * clear BIO_ERROR and B_INVAL state prior to initiating the I/O.  We
943          * do this here so we do not have to do it in all the code that
944          * calls us.
945          */
946 	bp->b_flags &= ~B_INVAL;
947 	bp->b_ioflags &= ~BIO_ERROR;
948 
949 	KASSERT(!(bp->b_flags & B_DONE),
950 	    ("fuse_io_strategy: bp %p already marked done", bp));
951 	if (bp->b_iocmd == BIO_READ) {
952 		ssize_t left;
953 
954 		io.iov_len = uiop->uio_resid = bp->b_bcount;
955 		io.iov_base = bp->b_data;
956 		uiop->uio_rw = UIO_READ;
957 
958 		uiop->uio_offset = ((off_t)bp->b_lblkno) * biosize;
959 		error = fuse_read_directbackend(vp, uiop, cred, fufh);
960 		/*
961 		 * Store the amount we failed to read in the buffer's private
962 		 * field, so callers can truncate the file if necessary'
963 		 */
964 
965 		if (!error && uiop->uio_resid) {
966 			int nread = bp->b_bcount - uiop->uio_resid;
967 			left = uiop->uio_resid;
968 			bzero((char *)bp->b_data + nread, left);
969 
970 			if ((fvdat->flag & FN_SIZECHANGE) == 0) {
971 				/*
972 				 * A short read with no error, when not using
973 				 * direct io, and when no writes are cached,
974 				 * indicates EOF caused by a server-side
975 				 * truncation.  Clear the attr cache so we'll
976 				 * pick up the new file size and timestamps.
977 				 *
978 				 * We must still bzero the remaining buffer so
979 				 * uninitialized data doesn't get exposed by a
980 				 * future truncate that extends the file.
981 				 *
982 				 * To prevent lock order problems, we must
983 				 * truncate the file upstack, not here.
984 				 */
985 				SDT_PROBE2(fusefs, , io, trace, 1,
986 					"Short read of a clean file");
987 				fuse_vnode_clear_attr_cache(vp);
988 			} else {
989 				/*
990 				 * If dirty writes _are_ cached beyond EOF,
991 				 * that indicates a newly created hole that the
992 				 * server doesn't know about.  Those don't pose
993 				 * any problem.
994 				 * XXX: we don't currently track whether dirty
995 				 * writes are cached beyond EOF, before EOF, or
996 				 * both.
997 				 */
998 				SDT_PROBE2(fusefs, , io, trace, 1,
999 					"Short read of a dirty file");
1000 				uiop->uio_resid = 0;
1001 			}
1002 		}
1003 		if (error) {
1004 			bp->b_ioflags |= BIO_ERROR;
1005 			bp->b_error = error;
1006 		}
1007 	} else {
1008 		/*
1009 	         * Setup for actual write
1010 	         */
1011 		/*
1012 		 * If the file's size is cached, use that value, even if the
1013 		 * cache is expired.  At this point we're already committed to
1014 		 * writing something.  If the FUSE server has changed the
1015 		 * file's size behind our back, it's too late for us to do
1016 		 * anything about it.  In particular, we can't invalidate any
1017 		 * part of the file's buffers because VOP_STRATEGY is called
1018 		 * with them already locked.
1019 		 */
1020 		filesize = fvdat->cached_attrs.va_size;
1021 		/* filesize must've been cached by fuse_vnop_open.  */
1022 		KASSERT(filesize != VNOVAL, ("filesize should've been cached"));
1023 
1024 		if ((off_t)bp->b_lblkno * biosize + bp->b_dirtyend > filesize)
1025 			bp->b_dirtyend = filesize -
1026 				(off_t)bp->b_lblkno * biosize;
1027 
1028 		if (bp->b_dirtyend > bp->b_dirtyoff) {
1029 			io.iov_len = uiop->uio_resid = bp->b_dirtyend
1030 			    - bp->b_dirtyoff;
1031 			uiop->uio_offset = (off_t)bp->b_lblkno * biosize
1032 			    + bp->b_dirtyoff;
1033 			io.iov_base = (char *)bp->b_data + bp->b_dirtyoff;
1034 			uiop->uio_rw = UIO_WRITE;
1035 
1036 			bool pages = bp->b_flags & B_FUSEFS_WRITE_CACHE;
1037 			error = fuse_write_directbackend(vp, uiop, cred, fufh,
1038 				filesize, 0, pages);
1039 
1040 			if (error == EINTR || error == ETIMEDOUT) {
1041 				bp->b_flags &= ~(B_INVAL | B_NOCACHE);
1042 				if ((bp->b_flags & B_PAGING) == 0) {
1043 					bdirty(bp);
1044 					bp->b_flags &= ~B_DONE;
1045 				}
1046 				if ((error == EINTR || error == ETIMEDOUT) &&
1047 				    (bp->b_flags & B_ASYNC) == 0)
1048 					bp->b_flags |= B_EINTR;
1049 			} else {
1050 				if (error) {
1051 					bp->b_ioflags |= BIO_ERROR;
1052 					bp->b_flags |= B_INVAL;
1053 					bp->b_error = error;
1054 				}
1055 				bp->b_dirtyoff = bp->b_dirtyend = 0;
1056 			}
1057 		} else {
1058 			bp->b_resid = 0;
1059 			bufdone(bp);
1060 			return (0);
1061 		}
1062 	}
1063 	bp->b_resid = uiop->uio_resid;
1064 	bufdone(bp);
1065 	return (error);
1066 }
1067 
1068 int
1069 fuse_io_flushbuf(struct vnode *vp, int waitfor, struct thread *td)
1070 {
1071 
1072 	return (vn_fsync_buf(vp, waitfor));
1073 }
1074 
1075 /*
1076  * Flush and invalidate all dirty buffers. If another process is already
1077  * doing the flush, just wait for completion.
1078  */
1079 int
1080 fuse_io_invalbuf(struct vnode *vp, struct thread *td)
1081 {
1082 	struct fuse_vnode_data *fvdat = VTOFUD(vp);
1083 	int error = 0;
1084 
1085 	if (VN_IS_DOOMED(vp))
1086 		return 0;
1087 
1088 	ASSERT_VOP_ELOCKED(vp, "fuse_io_invalbuf");
1089 
1090 	while (fvdat->flag & FN_FLUSHINPROG) {
1091 		struct proc *p = td->td_proc;
1092 
1093 		if (vp->v_mount->mnt_kern_flag & MNTK_UNMOUNTF)
1094 			return EIO;
1095 		fvdat->flag |= FN_FLUSHWANT;
1096 		tsleep(&fvdat->flag, PRIBIO + 2, "fusevinv", 2 * hz);
1097 		error = 0;
1098 		if (p != NULL) {
1099 			PROC_LOCK(p);
1100 			if (SIGNOTEMPTY(p->p_siglist) ||
1101 			    SIGNOTEMPTY(td->td_siglist))
1102 				error = EINTR;
1103 			PROC_UNLOCK(p);
1104 		}
1105 		if (error == EINTR)
1106 			return EINTR;
1107 	}
1108 	fvdat->flag |= FN_FLUSHINPROG;
1109 
1110 	if (vp->v_bufobj.bo_object != NULL) {
1111 		VM_OBJECT_WLOCK(vp->v_bufobj.bo_object);
1112 		vm_object_page_clean(vp->v_bufobj.bo_object, 0, 0, OBJPC_SYNC);
1113 		VM_OBJECT_WUNLOCK(vp->v_bufobj.bo_object);
1114 	}
1115 	error = vinvalbuf(vp, V_SAVE, PCATCH, 0);
1116 	while (error) {
1117 		if (error == ERESTART || error == EINTR) {
1118 			fvdat->flag &= ~FN_FLUSHINPROG;
1119 			if (fvdat->flag & FN_FLUSHWANT) {
1120 				fvdat->flag &= ~FN_FLUSHWANT;
1121 				wakeup(&fvdat->flag);
1122 			}
1123 			return EINTR;
1124 		}
1125 		error = vinvalbuf(vp, V_SAVE, PCATCH, 0);
1126 	}
1127 	fvdat->flag &= ~FN_FLUSHINPROG;
1128 	if (fvdat->flag & FN_FLUSHWANT) {
1129 		fvdat->flag &= ~FN_FLUSHWANT;
1130 		wakeup(&fvdat->flag);
1131 	}
1132 	return (error);
1133 }
1134