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