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