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