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