xref: /freebsd/sys/fs/fuse/fuse_io.c (revision eac7052fdebb90caf2f653e06187bdbca837b9c7)
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 		size_t sizeof_fwi;
559 
560 		if (fuse_libabi_geq(data, 7, 9)) {
561 			sizeof_fwi = sizeof(*fwi);
562 		} else {
563 			sizeof_fwi = FUSE_COMPAT_WRITE_IN_SIZE;
564 		}
565 
566 		chunksize = MIN(uio->uio_resid, data->max_write);
567 
568 		fdi.iosize = sizeof_fwi + chunksize;
569 		fdisp_make_vp(&fdi, FUSE_WRITE, vp, uio->uio_td, cred);
570 
571 		fwi = fdi.indata;
572 		fwi->fh = fufh->fh_id;
573 		fwi->offset = uio->uio_offset;
574 		fwi->size = chunksize;
575 		fwi->write_flags = write_flags;
576 		if (fuse_libabi_geq(data, 7, 9)) {
577 			fwi->flags = fufh_type_2_fflags(fufh->fufh_type);
578 		}
579 		fwi_data = (char *)fdi.indata + sizeof_fwi;
580 
581 		if ((err = uiomove(fwi_data, chunksize, uio)))
582 			break;
583 
584 retry:
585 		err = fdisp_wait_answ(&fdi);
586 		if (err == ERESTART || err == EINTR || err == EWOULDBLOCK) {
587 			/*
588 			 * Rewind the uio so dofilewrite will know it's
589 			 * incomplete
590 			 */
591 			uio->uio_resid += fwi->size;
592 			uio->uio_offset -= fwi->size;
593 			/*
594 			 * Change ERESTART into EINTR because we can't rewind
595 			 * uio->uio_iov.  Basically, once uiomove(9) has been
596 			 * called, it's impossible to restart a syscall.
597 			 */
598 			if (err == ERESTART)
599 				err = EINTR;
600 			break;
601 		} else if (err) {
602 			break;
603 		} else {
604 			wrote_anything = true;
605 		}
606 
607 		fwo = ((struct fuse_write_out *)fdi.answ);
608 
609 		/* Adjust the uio in the case of short writes */
610 		diff = fwi->size - fwo->size;
611 		as_written_offset = uio->uio_offset - diff;
612 
613 		if (as_written_offset - diff > filesize)
614 			fuse_vnode_setsize(vp, as_written_offset);
615 		if (as_written_offset - diff >= filesize)
616 			fvdat->flag &= ~FN_SIZECHANGE;
617 
618 		if (diff < 0) {
619 			printf("WARNING: misbehaving FUSE filesystem "
620 				"wrote more data than we provided it\n");
621 			err = EINVAL;
622 			break;
623 		} else if (diff > 0) {
624 			/* Short write */
625 			if (!direct_io) {
626 				printf("WARNING: misbehaving FUSE filesystem: "
627 					"short writes are only allowed with "
628 					"direct_io\n");
629 			}
630 			if (ioflag & IO_DIRECT) {
631 				/* Return early */
632 				uio->uio_resid += diff;
633 				uio->uio_offset -= diff;
634 				break;
635 			} else {
636 				/* Resend the unwritten portion of data */
637 				fdi.iosize = sizeof_fwi + diff;
638 				/* Refresh fdi without clearing data buffer */
639 				fdisp_refresh_vp(&fdi, FUSE_WRITE, vp,
640 					uio->uio_td, cred);
641 				fwi = fdi.indata;
642 				MPASS2(fwi == fdi.indata, "FUSE dispatcher "
643 					"reallocated despite no increase in "
644 					"size?");
645 				void *src = (char*)fwi_data + fwo->size;
646 				memmove(fwi_data, src, diff);
647 				fwi->fh = fufh->fh_id;
648 				fwi->offset = as_written_offset;
649 				fwi->size = diff;
650 				fwi->write_flags = write_flags;
651 				goto retry;
652 			}
653 		}
654 	}
655 
656 	fdisp_destroy(&fdi);
657 
658 	if (wrote_anything)
659 		fuse_vnode_undirty_cached_timestamps(vp);
660 
661 	return (err);
662 }
663 
664 SDT_PROBE_DEFINE6(fusefs, , io, write_biobackend_start, "int64_t", "int", "int",
665 		"struct uio*", "int", "bool");
666 SDT_PROBE_DEFINE2(fusefs, , io, write_biobackend_append_race, "long", "int");
667 SDT_PROBE_DEFINE2(fusefs, , io, write_biobackend_issue, "int", "struct buf*");
668 
669 static int
670 fuse_write_biobackend(struct vnode *vp, struct uio *uio,
671     struct ucred *cred, struct fuse_filehandle *fufh, int ioflag, pid_t pid)
672 {
673 	struct fuse_vnode_data *fvdat = VTOFUD(vp);
674 	struct buf *bp;
675 	daddr_t lbn;
676 	off_t filesize;
677 	int bcount;
678 	int n, on, seqcount, err = 0;
679 	bool last_page;
680 
681 	const int biosize = fuse_iosize(vp);
682 
683 	seqcount = ioflag >> IO_SEQSHIFT;
684 
685 	KASSERT(uio->uio_rw == UIO_WRITE, ("fuse_write_biobackend mode"));
686 	if (vp->v_type != VREG)
687 		return (EIO);
688 	if (uio->uio_offset < 0)
689 		return (EINVAL);
690 	if (uio->uio_resid == 0)
691 		return (0);
692 
693 	err = fuse_vnode_size(vp, &filesize, cred, curthread);
694 	if (err)
695 		return err;
696 
697 	if (ioflag & IO_APPEND)
698 		uio_setoffset(uio, filesize);
699 
700 	if (vn_rlimit_fsize(vp, uio, uio->uio_td))
701 		return (EFBIG);
702 
703 	do {
704 		bool direct_append, extending;
705 
706 		if (fuse_isdeadfs(vp)) {
707 			err = ENXIO;
708 			break;
709 		}
710 		lbn = uio->uio_offset / biosize;
711 		on = uio->uio_offset & (biosize - 1);
712 		n = MIN((unsigned)(biosize - on), uio->uio_resid);
713 
714 again:
715 		/* Get or create a buffer for the write */
716 		direct_append = uio->uio_offset == filesize && n;
717 		if (uio->uio_offset + n < filesize) {
718 			extending = false;
719 			if ((off_t)(lbn + 1) * biosize < filesize) {
720 				/* Not the file's last block */
721 				bcount = biosize;
722 			} else {
723 				/* The file's last block */
724 				bcount = filesize - (off_t)lbn * biosize;
725 			}
726 		} else {
727 			extending = true;
728 			bcount = on + n;
729 		}
730 		if (howmany(((off_t)lbn * biosize + on + n - 1), PAGE_SIZE) >=
731 		    howmany(filesize, PAGE_SIZE))
732 			last_page = true;
733 		else
734 			last_page = false;
735 		if (direct_append) {
736 			/*
737 			 * Take care to preserve the buffer's B_CACHE state so
738 			 * as not to cause an unnecessary read.
739 			 */
740 			bp = getblk(vp, lbn, on, PCATCH, 0, 0);
741 			if (bp != NULL) {
742 				uint32_t save = bp->b_flags & B_CACHE;
743 				allocbuf(bp, bcount);
744 				bp->b_flags |= save;
745 			}
746 		} else {
747 			bp = getblk(vp, lbn, bcount, PCATCH, 0, 0);
748 		}
749 		if (!bp) {
750 			err = EINTR;
751 			break;
752 		}
753 		if (extending) {
754 			/*
755 			 * Extend file _after_ locking buffer so we won't race
756 			 * with other readers
757 			 */
758 			err = fuse_vnode_setsize(vp, uio->uio_offset + n);
759 			filesize = uio->uio_offset + n;
760 			fvdat->flag |= FN_SIZECHANGE;
761 			if (err) {
762 				brelse(bp);
763 				break;
764 			}
765 		}
766 
767 		SDT_PROBE6(fusefs, , io, write_biobackend_start,
768 			lbn, on, n, uio, bcount, direct_append);
769 		/*
770 	         * Issue a READ if B_CACHE is not set.  In special-append
771 	         * mode, B_CACHE is based on the buffer prior to the write
772 	         * op and is typically set, avoiding the read.  If a read
773 	         * is required in special append mode, the server will
774 	         * probably send us a short-read since we extended the file
775 	         * on our end, resulting in b_resid == 0 and, thusly,
776 	         * B_CACHE getting set.
777 	         *
778 	         * We can also avoid issuing the read if the write covers
779 	         * the entire buffer.  We have to make sure the buffer state
780 	         * is reasonable in this case since we will not be initiating
781 	         * I/O.  See the comments in kern/vfs_bio.c's getblk() for
782 	         * more information.
783 	         *
784 	         * B_CACHE may also be set due to the buffer being cached
785 	         * normally.
786 	         */
787 
788 		if (on == 0 && n == bcount) {
789 			bp->b_flags |= B_CACHE;
790 			bp->b_flags &= ~B_INVAL;
791 			bp->b_ioflags &= ~BIO_ERROR;
792 		}
793 		if ((bp->b_flags & B_CACHE) == 0) {
794 			bp->b_iocmd = BIO_READ;
795 			vfs_busy_pages(bp, 0);
796 			fuse_io_strategy(vp, bp);
797 			if ((err = bp->b_error)) {
798 				brelse(bp);
799 				break;
800 			}
801 			if (bp->b_resid > 0) {
802 				/*
803 				 * Short read indicates EOF.  Update file size
804 				 * from the server and try again.
805 				 */
806 				SDT_PROBE2(fusefs, , io, trace, 1,
807 					"Short read during a RMW");
808 				brelse(bp);
809 				err = fuse_vnode_size(vp, &filesize, cred,
810 				    curthread);
811 				if (err)
812 					break;
813 				else
814 					goto again;
815 			}
816 		}
817 		if (bp->b_wcred == NOCRED)
818 			bp->b_wcred = crhold(cred);
819 
820 		/*
821 	         * If dirtyend exceeds file size, chop it down.  This should
822 	         * not normally occur but there is an append race where it
823 	         * might occur XXX, so we log it.
824 	         *
825 	         * If the chopping creates a reverse-indexed or degenerate
826 	         * situation with dirtyoff/end, we 0 both of them.
827 	         */
828 		if (bp->b_dirtyend > bcount) {
829 			SDT_PROBE2(fusefs, , io, write_biobackend_append_race,
830 			    (long)bp->b_blkno * biosize,
831 			    bp->b_dirtyend - bcount);
832 			bp->b_dirtyend = bcount;
833 		}
834 		if (bp->b_dirtyoff >= bp->b_dirtyend)
835 			bp->b_dirtyoff = bp->b_dirtyend = 0;
836 
837 		/*
838 	         * If the new write will leave a contiguous dirty
839 	         * area, just update the b_dirtyoff and b_dirtyend,
840 	         * otherwise force a write rpc of the old dirty area.
841 	         *
842 	         * While it is possible to merge discontiguous writes due to
843 	         * our having a B_CACHE buffer ( and thus valid read data
844 	         * for the hole), we don't because it could lead to
845 	         * significant cache coherency problems with multiple clients,
846 	         * especially if locking is implemented later on.
847 	         *
848 	         * as an optimization we could theoretically maintain
849 	         * a linked list of discontinuous areas, but we would still
850 	         * have to commit them separately so there isn't much
851 	         * advantage to it except perhaps a bit of asynchronization.
852 	         */
853 
854 		if (bp->b_dirtyend > 0 &&
855 		    (on > bp->b_dirtyend || (on + n) < bp->b_dirtyoff)) {
856 			/*
857 	                 * Yes, we mean it. Write out everything to "storage"
858 	                 * immediately, without hesitation. (Apart from other
859 	                 * reasons: the only way to know if a write is valid
860 	                 * if its actually written out.)
861 	                 */
862 			SDT_PROBE2(fusefs, , io, write_biobackend_issue, 0, bp);
863 			bwrite(bp);
864 			if (bp->b_error == EINTR) {
865 				err = EINTR;
866 				break;
867 			}
868 			goto again;
869 		}
870 		err = uiomove((char *)bp->b_data + on, n, uio);
871 
872 		if (err) {
873 			bp->b_ioflags |= BIO_ERROR;
874 			bp->b_error = err;
875 			brelse(bp);
876 			break;
877 			/* TODO: vfs_bio_clrbuf like ffs_write does? */
878 		}
879 		/*
880 	         * Only update dirtyoff/dirtyend if not a degenerate
881 	         * condition.
882 	         */
883 		if (n) {
884 			if (bp->b_dirtyend > 0) {
885 				bp->b_dirtyoff = MIN(on, bp->b_dirtyoff);
886 				bp->b_dirtyend = MAX((on + n), bp->b_dirtyend);
887 			} else {
888 				bp->b_dirtyoff = on;
889 				bp->b_dirtyend = on + n;
890 			}
891 			vfs_bio_set_valid(bp, on, n);
892 		}
893 
894 		vfs_bio_set_flags(bp, ioflag);
895 
896 		bp->b_flags |= B_FUSEFS_WRITE_CACHE;
897 		if (ioflag & IO_SYNC) {
898 			SDT_PROBE2(fusefs, , io, write_biobackend_issue, 2, bp);
899 			if (!(ioflag & IO_VMIO))
900 				bp->b_flags &= ~B_FUSEFS_WRITE_CACHE;
901 			err = bwrite(bp);
902 		} else if (vm_page_count_severe() ||
903 			    buf_dirty_count_severe() ||
904 			    (ioflag & IO_ASYNC)) {
905 			bp->b_flags |= B_CLUSTEROK;
906 			SDT_PROBE2(fusefs, , io, write_biobackend_issue, 3, bp);
907 			bawrite(bp);
908 		} else if (on == 0 && n == bcount) {
909 			if ((vp->v_mount->mnt_flag & MNT_NOCLUSTERW) == 0) {
910 				bp->b_flags |= B_CLUSTEROK;
911 				SDT_PROBE2(fusefs, , io, write_biobackend_issue,
912 					4, bp);
913 				cluster_write(vp, bp, filesize, seqcount, 0);
914 			} else {
915 				SDT_PROBE2(fusefs, , io, write_biobackend_issue,
916 					5, bp);
917 				bawrite(bp);
918 			}
919 		} else if (ioflag & IO_DIRECT) {
920 			bp->b_flags |= B_CLUSTEROK;
921 			SDT_PROBE2(fusefs, , io, write_biobackend_issue, 6, bp);
922 			bawrite(bp);
923 		} else {
924 			bp->b_flags &= ~B_CLUSTEROK;
925 			SDT_PROBE2(fusefs, , io, write_biobackend_issue, 7, bp);
926 			bdwrite(bp);
927 		}
928 		if (err)
929 			break;
930 	} while (uio->uio_resid > 0 && n > 0);
931 
932 	return (err);
933 }
934 
935 int
936 fuse_io_strategy(struct vnode *vp, struct buf *bp)
937 {
938 	struct fuse_vnode_data *fvdat = VTOFUD(vp);
939 	struct fuse_filehandle *fufh;
940 	struct ucred *cred;
941 	struct uio *uiop;
942 	struct uio uio;
943 	struct iovec io;
944 	off_t filesize;
945 	int error = 0;
946 	int fflag;
947 	/* We don't know the true pid when we're dealing with the cache */
948 	pid_t pid = 0;
949 
950 	const int biosize = fuse_iosize(vp);
951 
952 	MPASS(vp->v_type == VREG || vp->v_type == VDIR);
953 	MPASS(bp->b_iocmd == BIO_READ || bp->b_iocmd == BIO_WRITE);
954 
955 	fflag = bp->b_iocmd == BIO_READ ? FREAD : FWRITE;
956 	cred = bp->b_iocmd == BIO_READ ? bp->b_rcred : bp->b_wcred;
957 	error = fuse_filehandle_getrw(vp, fflag, &fufh, cred, pid);
958 	if (bp->b_iocmd == BIO_READ && error == EBADF) {
959 		/*
960 		 * This may be a read-modify-write operation on a cached file
961 		 * opened O_WRONLY.  The FUSE protocol allows this.
962 		 */
963 		error = fuse_filehandle_get(vp, FWRITE, &fufh, cred, pid);
964 	}
965 	if (error) {
966 		printf("FUSE: strategy: filehandles are closed\n");
967 		bp->b_ioflags |= BIO_ERROR;
968 		bp->b_error = error;
969 		bufdone(bp);
970 		return (error);
971 	}
972 
973 	uiop = &uio;
974 	uiop->uio_iov = &io;
975 	uiop->uio_iovcnt = 1;
976 	uiop->uio_segflg = UIO_SYSSPACE;
977 	uiop->uio_td = curthread;
978 
979 	/*
980          * clear BIO_ERROR and B_INVAL state prior to initiating the I/O.  We
981          * do this here so we do not have to do it in all the code that
982          * calls us.
983          */
984 	bp->b_flags &= ~B_INVAL;
985 	bp->b_ioflags &= ~BIO_ERROR;
986 
987 	KASSERT(!(bp->b_flags & B_DONE),
988 	    ("fuse_io_strategy: bp %p already marked done", bp));
989 	if (bp->b_iocmd == BIO_READ) {
990 		ssize_t left;
991 
992 		io.iov_len = uiop->uio_resid = bp->b_bcount;
993 		io.iov_base = bp->b_data;
994 		uiop->uio_rw = UIO_READ;
995 
996 		uiop->uio_offset = ((off_t)bp->b_lblkno) * biosize;
997 		error = fuse_read_directbackend(vp, uiop, cred, fufh);
998 		/*
999 		 * Store the amount we failed to read in the buffer's private
1000 		 * field, so callers can truncate the file if necessary'
1001 		 */
1002 
1003 		if (!error && uiop->uio_resid) {
1004 			int nread = bp->b_bcount - uiop->uio_resid;
1005 			left = uiop->uio_resid;
1006 			bzero((char *)bp->b_data + nread, left);
1007 
1008 			if ((fvdat->flag & FN_SIZECHANGE) == 0) {
1009 				/*
1010 				 * A short read with no error, when not using
1011 				 * direct io, and when no writes are cached,
1012 				 * indicates EOF caused by a server-side
1013 				 * truncation.  Clear the attr cache so we'll
1014 				 * pick up the new file size and timestamps.
1015 				 *
1016 				 * We must still bzero the remaining buffer so
1017 				 * uninitialized data doesn't get exposed by a
1018 				 * future truncate that extends the file.
1019 				 *
1020 				 * To prevent lock order problems, we must
1021 				 * truncate the file upstack, not here.
1022 				 */
1023 				SDT_PROBE2(fusefs, , io, trace, 1,
1024 					"Short read of a clean file");
1025 				fuse_vnode_clear_attr_cache(vp);
1026 			} else {
1027 				/*
1028 				 * If dirty writes _are_ cached beyond EOF,
1029 				 * that indicates a newly created hole that the
1030 				 * server doesn't know about.  Those don't pose
1031 				 * any problem.
1032 				 * XXX: we don't currently track whether dirty
1033 				 * writes are cached beyond EOF, before EOF, or
1034 				 * both.
1035 				 */
1036 				SDT_PROBE2(fusefs, , io, trace, 1,
1037 					"Short read of a dirty file");
1038 				uiop->uio_resid = 0;
1039 			}
1040 		}
1041 		if (error) {
1042 			bp->b_ioflags |= BIO_ERROR;
1043 			bp->b_error = error;
1044 		}
1045 	} else {
1046 		/*
1047 	         * Setup for actual write
1048 	         */
1049 		error = fuse_vnode_size(vp, &filesize, cred, curthread);
1050 		if (error) {
1051 			bp->b_ioflags |= BIO_ERROR;
1052 			bp->b_error = error;
1053 			bufdone(bp);
1054 			return (error);
1055 		}
1056 
1057 		if ((off_t)bp->b_lblkno * biosize + bp->b_dirtyend > filesize)
1058 			bp->b_dirtyend = filesize -
1059 				(off_t)bp->b_lblkno * biosize;
1060 
1061 		if (bp->b_dirtyend > bp->b_dirtyoff) {
1062 			io.iov_len = uiop->uio_resid = bp->b_dirtyend
1063 			    - bp->b_dirtyoff;
1064 			uiop->uio_offset = (off_t)bp->b_lblkno * biosize
1065 			    + bp->b_dirtyoff;
1066 			io.iov_base = (char *)bp->b_data + bp->b_dirtyoff;
1067 			uiop->uio_rw = UIO_WRITE;
1068 
1069 			bool pages = bp->b_flags & B_FUSEFS_WRITE_CACHE;
1070 			error = fuse_write_directbackend(vp, uiop, cred, fufh,
1071 				filesize, 0, pages);
1072 
1073 			if (error == EINTR || error == ETIMEDOUT) {
1074 				bp->b_flags &= ~(B_INVAL | B_NOCACHE);
1075 				if ((bp->b_flags & B_PAGING) == 0) {
1076 					bdirty(bp);
1077 					bp->b_flags &= ~B_DONE;
1078 				}
1079 				if ((error == EINTR || error == ETIMEDOUT) &&
1080 				    (bp->b_flags & B_ASYNC) == 0)
1081 					bp->b_flags |= B_EINTR;
1082 			} else {
1083 				if (error) {
1084 					bp->b_ioflags |= BIO_ERROR;
1085 					bp->b_flags |= B_INVAL;
1086 					bp->b_error = error;
1087 				}
1088 				bp->b_dirtyoff = bp->b_dirtyend = 0;
1089 			}
1090 		} else {
1091 			bp->b_resid = 0;
1092 			bufdone(bp);
1093 			return (0);
1094 		}
1095 	}
1096 	bp->b_resid = uiop->uio_resid;
1097 	bufdone(bp);
1098 	return (error);
1099 }
1100 
1101 int
1102 fuse_io_flushbuf(struct vnode *vp, int waitfor, struct thread *td)
1103 {
1104 
1105 	return (vn_fsync_buf(vp, waitfor));
1106 }
1107 
1108 /*
1109  * Flush and invalidate all dirty buffers. If another process is already
1110  * doing the flush, just wait for completion.
1111  */
1112 int
1113 fuse_io_invalbuf(struct vnode *vp, struct thread *td)
1114 {
1115 	struct fuse_vnode_data *fvdat = VTOFUD(vp);
1116 	int error = 0;
1117 
1118 	if (VN_IS_DOOMED(vp))
1119 		return 0;
1120 
1121 	ASSERT_VOP_ELOCKED(vp, "fuse_io_invalbuf");
1122 
1123 	while (fvdat->flag & FN_FLUSHINPROG) {
1124 		struct proc *p = td->td_proc;
1125 
1126 		if (vp->v_mount->mnt_kern_flag & MNTK_UNMOUNTF)
1127 			return EIO;
1128 		fvdat->flag |= FN_FLUSHWANT;
1129 		tsleep(&fvdat->flag, PRIBIO + 2, "fusevinv", 2 * hz);
1130 		error = 0;
1131 		if (p != NULL) {
1132 			PROC_LOCK(p);
1133 			if (SIGNOTEMPTY(p->p_siglist) ||
1134 			    SIGNOTEMPTY(td->td_siglist))
1135 				error = EINTR;
1136 			PROC_UNLOCK(p);
1137 		}
1138 		if (error == EINTR)
1139 			return EINTR;
1140 	}
1141 	fvdat->flag |= FN_FLUSHINPROG;
1142 
1143 	if (vp->v_bufobj.bo_object != NULL) {
1144 		VM_OBJECT_WLOCK(vp->v_bufobj.bo_object);
1145 		vm_object_page_clean(vp->v_bufobj.bo_object, 0, 0, OBJPC_SYNC);
1146 		VM_OBJECT_WUNLOCK(vp->v_bufobj.bo_object);
1147 	}
1148 	error = vinvalbuf(vp, V_SAVE, PCATCH, 0);
1149 	while (error) {
1150 		if (error == ERESTART || error == EINTR) {
1151 			fvdat->flag &= ~FN_FLUSHINPROG;
1152 			if (fvdat->flag & FN_FLUSHWANT) {
1153 				fvdat->flag &= ~FN_FLUSHWANT;
1154 				wakeup(&fvdat->flag);
1155 			}
1156 			return EINTR;
1157 		}
1158 		error = vinvalbuf(vp, V_SAVE, PCATCH, 0);
1159 	}
1160 	fvdat->flag &= ~FN_FLUSHINPROG;
1161 	if (fvdat->flag & FN_FLUSHWANT) {
1162 		fvdat->flag &= ~FN_FLUSHWANT;
1163 		wakeup(&fvdat->flag);
1164 	}
1165 	return (error);
1166 }
1167