xref: /freebsd/sys/fs/fuse/fuse_internal.c (revision e92ffd9b626833ebdbf2742c8ffddc6cd94b963e)
1 /*-
2  * SPDX-License-Identifier: BSD-3-Clause
3  *
4  * Copyright (c) 2007-2009 Google Inc. and Amit Singh
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/param.h>
67 #include <sys/systm.h>
68 #include <sys/counter.h>
69 #include <sys/module.h>
70 #include <sys/errno.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/mutex.h>
78 #include <sys/sdt.h>
79 #include <sys/sx.h>
80 #include <sys/proc.h>
81 #include <sys/mount.h>
82 #include <sys/vnode.h>
83 #include <sys/namei.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/dirent.h>
90 #include <sys/bio.h>
91 #include <sys/buf.h>
92 #include <sys/sysctl.h>
93 #include <sys/priv.h>
94 
95 #include "fuse.h"
96 #include "fuse_file.h"
97 #include "fuse_internal.h"
98 #include "fuse_io.h"
99 #include "fuse_ipc.h"
100 #include "fuse_node.h"
101 #include "fuse_file.h"
102 
103 SDT_PROVIDER_DECLARE(fusefs);
104 /*
105  * Fuse trace probe:
106  * arg0: verbosity.  Higher numbers give more verbose messages
107  * arg1: Textual message
108  */
109 SDT_PROBE_DEFINE2(fusefs, , internal, trace, "int", "char*");
110 
111 #ifdef ZERO_PAD_INCOMPLETE_BUFS
112 static int isbzero(void *buf, size_t len);
113 
114 #endif
115 
116 counter_u64_t fuse_lookup_cache_hits;
117 counter_u64_t fuse_lookup_cache_misses;
118 
119 SYSCTL_COUNTER_U64(_vfs_fusefs_stats, OID_AUTO, lookup_cache_hits, CTLFLAG_RD,
120     &fuse_lookup_cache_hits, "number of positive cache hits in lookup");
121 
122 SYSCTL_COUNTER_U64(_vfs_fusefs_stats, OID_AUTO, lookup_cache_misses, CTLFLAG_RD,
123     &fuse_lookup_cache_misses, "number of cache misses in lookup");
124 
125 int
126 fuse_internal_get_cached_vnode(struct mount* mp, ino_t ino, int flags,
127 	struct vnode **vpp)
128 {
129 	struct bintime now;
130 	struct thread *td = curthread;
131 	uint64_t nodeid = ino;
132 	int error;
133 
134 	*vpp = NULL;
135 
136 	error = vfs_hash_get(mp, fuse_vnode_hash(nodeid), flags, td, vpp,
137 	    fuse_vnode_cmp, &nodeid);
138 	if (error)
139 		return error;
140 	/*
141 	 * Check the entry cache timeout.  We have to do this within fusefs
142 	 * instead of by using cache_enter_time/cache_lookup because those
143 	 * routines are only intended to work with pathnames, not inodes
144 	 */
145 	if (*vpp != NULL) {
146 		getbinuptime(&now);
147 		if (bintime_cmp(&(VTOFUD(*vpp)->entry_cache_timeout), &now, >)){
148 			counter_u64_add(fuse_lookup_cache_hits, 1);
149 			return 0;
150 		} else {
151 			/* Entry cache timeout */
152 			counter_u64_add(fuse_lookup_cache_misses, 1);
153 			cache_purge(*vpp);
154 			vput(*vpp);
155 			*vpp = NULL;
156 		}
157 	}
158 	return 0;
159 }
160 
161 SDT_PROBE_DEFINE0(fusefs, , internal, access_vadmin);
162 /* Synchronously send a FUSE_ACCESS operation */
163 int
164 fuse_internal_access(struct vnode *vp,
165     accmode_t mode,
166     struct thread *td,
167     struct ucred *cred)
168 {
169 	int err = 0;
170 	uint32_t mask = F_OK;
171 	int dataflags;
172 	struct mount *mp;
173 	struct fuse_dispatcher fdi;
174 	struct fuse_access_in *fai;
175 	struct fuse_data *data;
176 
177 	mp = vnode_mount(vp);
178 
179 	data = fuse_get_mpdata(mp);
180 	dataflags = data->dataflags;
181 
182 	if (mode == 0)
183 		return 0;
184 
185 	if (mode & VMODIFY_PERMS && vfs_isrdonly(mp)) {
186 		switch (vp->v_type) {
187 		case VDIR:
188 			/* FALLTHROUGH */
189 		case VLNK:
190 			/* FALLTHROUGH */
191 		case VREG:
192 			return EROFS;
193 		default:
194 			break;
195 		}
196 	}
197 
198 	/* Unless explicitly permitted, deny everyone except the fs owner. */
199 	if (!(dataflags & FSESS_DAEMON_CAN_SPY)) {
200 		if (fuse_match_cred(data->daemoncred, cred))
201 			return EPERM;
202 	}
203 
204 	if (dataflags & FSESS_DEFAULT_PERMISSIONS) {
205 		struct vattr va;
206 
207 		fuse_internal_getattr(vp, &va, cred, td);
208 		return vaccess(vp->v_type, va.va_mode, va.va_uid,
209 		    va.va_gid, mode, cred);
210 	}
211 
212 	if (mode & VADMIN) {
213 		/*
214 		 * The FUSE protocol doesn't have an equivalent of VADMIN, so
215 		 * it's a bug if we ever reach this point with that bit set.
216 		 */
217 		SDT_PROBE0(fusefs, , internal, access_vadmin);
218 	}
219 
220 	if (fsess_not_impl(mp, FUSE_ACCESS))
221 		return 0;
222 
223 	if ((mode & (VWRITE | VAPPEND)) != 0)
224 		mask |= W_OK;
225 	if ((mode & VREAD) != 0)
226 		mask |= R_OK;
227 	if ((mode & VEXEC) != 0)
228 		mask |= X_OK;
229 
230 	fdisp_init(&fdi, sizeof(*fai));
231 	fdisp_make_vp(&fdi, FUSE_ACCESS, vp, td, cred);
232 
233 	fai = fdi.indata;
234 	fai->mask = mask;
235 
236 	err = fdisp_wait_answ(&fdi);
237 	fdisp_destroy(&fdi);
238 
239 	if (err == ENOSYS) {
240 		fsess_set_notimpl(mp, FUSE_ACCESS);
241 		err = 0;
242 	}
243 	return err;
244 }
245 
246 /*
247  * Cache FUSE attributes from attr, in attribute cache associated with vnode
248  * 'vp'.  Optionally, if argument 'vap' is not NULL, store a copy of the
249  * converted attributes there as well.
250  *
251  * If the nominal attribute cache TTL is zero, do not cache on the 'vp' (but do
252  * return the result to the caller).
253  */
254 void
255 fuse_internal_cache_attrs(struct vnode *vp, struct fuse_attr *attr,
256 	uint64_t attr_valid, uint32_t attr_valid_nsec, struct vattr *vap,
257 	bool from_server)
258 {
259 	struct mount *mp;
260 	struct fuse_vnode_data *fvdat;
261 	struct fuse_data *data;
262 	struct vattr *vp_cache_at;
263 
264 	mp = vnode_mount(vp);
265 	fvdat = VTOFUD(vp);
266 	data = fuse_get_mpdata(mp);
267 
268 	ASSERT_VOP_ELOCKED(vp, "fuse_internal_cache_attrs");
269 
270 	fuse_validity_2_bintime(attr_valid, attr_valid_nsec,
271 		&fvdat->attr_cache_timeout);
272 
273 	if (vnode_isreg(vp) &&
274 	    fvdat->cached_attrs.va_size != VNOVAL &&
275 	    attr->size != fvdat->cached_attrs.va_size)
276 	{
277 		if ( data->cache_mode == FUSE_CACHE_WB &&
278 		    fvdat->flag & FN_SIZECHANGE)
279 		{
280 			const char *msg;
281 
282 			/*
283 			 * The server changed the file's size even though we're
284 			 * using writeback cacheing and and we have outstanding
285 			 * dirty writes!  That's a server bug.
286 			 */
287 			if (fuse_libabi_geq(data, 7, 23)) {
288 				msg = "writeback cache incoherent!."
289 				    "To prevent data corruption, disable "
290 				    "the writeback cache according to your "
291 				    "FUSE server's documentation.";
292 			} else {
293 				msg = "writeback cache incoherent!."
294 				    "To prevent data corruption, disable "
295 				    "the writeback cache by setting "
296 				    "vfs.fusefs.data_cache_mode to 0 or 1.";
297 			}
298 			fuse_warn(data, FSESS_WARN_WB_CACHE_INCOHERENT, msg);
299 		}
300 		if (fuse_vnode_attr_cache_valid(vp) &&
301 		    data->cache_mode != FUSE_CACHE_UC)
302 		{
303 			/*
304 			 * The server changed the file's size even though we
305 			 * have it cached and our cache has not yet expired.
306 			 * That's a bug.
307 			 */
308 			fuse_warn(data, FSESS_WARN_CACHE_INCOHERENT,
309 			    "cache incoherent!  "
310 			    "To prevent "
311 			    "data corruption, disable the data cache "
312 			    "by mounting with -o direct_io, or as "
313 			    "directed otherwise by your FUSE server's "
314 			    "documentation.");
315 		}
316 	}
317 
318 	/* Fix our buffers if the filesize changed without us knowing */
319 	if (vnode_isreg(vp) && attr->size != fvdat->cached_attrs.va_size) {
320 		(void)fuse_vnode_setsize(vp, attr->size, from_server);
321 		fvdat->cached_attrs.va_size = attr->size;
322 	}
323 
324 	if (attr_valid > 0 || attr_valid_nsec > 0)
325 		vp_cache_at = &(fvdat->cached_attrs);
326 	else if (vap != NULL)
327 		vp_cache_at = vap;
328 	else
329 		return;
330 
331 	vattr_null(vp_cache_at);
332 	vp_cache_at->va_fsid = mp->mnt_stat.f_fsid.val[0];
333 	vp_cache_at->va_fileid = attr->ino;
334 	vp_cache_at->va_mode = attr->mode & ~S_IFMT;
335 	vp_cache_at->va_nlink     = attr->nlink;
336 	vp_cache_at->va_uid       = attr->uid;
337 	vp_cache_at->va_gid       = attr->gid;
338 	vp_cache_at->va_rdev      = attr->rdev;
339 	vp_cache_at->va_size      = attr->size;
340 	/* XXX on i386, seconds are truncated to 32 bits */
341 	vp_cache_at->va_atime.tv_sec  = attr->atime;
342 	vp_cache_at->va_atime.tv_nsec = attr->atimensec;
343 	vp_cache_at->va_mtime.tv_sec  = attr->mtime;
344 	vp_cache_at->va_mtime.tv_nsec = attr->mtimensec;
345 	vp_cache_at->va_ctime.tv_sec  = attr->ctime;
346 	vp_cache_at->va_ctime.tv_nsec = attr->ctimensec;
347 	if (fuse_libabi_geq(data, 7, 9) && attr->blksize > 0)
348 		vp_cache_at->va_blocksize = attr->blksize;
349 	else
350 		vp_cache_at->va_blocksize = PAGE_SIZE;
351 	vp_cache_at->va_type = IFTOVT(attr->mode);
352 	vp_cache_at->va_bytes = attr->blocks * S_BLKSIZE;
353 	vp_cache_at->va_flags = 0;
354 
355 	if (vap != vp_cache_at && vap != NULL)
356 		memcpy(vap, vp_cache_at, sizeof(*vap));
357 }
358 
359 /* fsync */
360 
361 int
362 fuse_internal_fsync_callback(struct fuse_ticket *tick, struct uio *uio)
363 {
364 	if (tick->tk_aw_ohead.error == ENOSYS) {
365 		fsess_set_notimpl(tick->tk_data->mp, fticket_opcode(tick));
366 	}
367 	return 0;
368 }
369 
370 int
371 fuse_internal_fsync(struct vnode *vp,
372     struct thread *td,
373     int waitfor,
374     bool datasync)
375 {
376 	struct fuse_fsync_in *ffsi = NULL;
377 	struct fuse_dispatcher fdi;
378 	struct fuse_filehandle *fufh;
379 	struct fuse_vnode_data *fvdat = VTOFUD(vp);
380 	struct mount *mp = vnode_mount(vp);
381 	int op = FUSE_FSYNC;
382 	int err = 0;
383 
384 	if (fsess_not_impl(vnode_mount(vp),
385 	    (vnode_vtype(vp) == VDIR ? FUSE_FSYNCDIR : FUSE_FSYNC))) {
386 		return 0;
387 	}
388 	if (vnode_isdir(vp))
389 		op = FUSE_FSYNCDIR;
390 
391 	if (fsess_not_impl(mp, op))
392 		return 0;
393 
394 	fdisp_init(&fdi, sizeof(*ffsi));
395 	/*
396 	 * fsync every open file handle for this file, because we can't be sure
397 	 * which file handle the caller is really referring to.
398 	 */
399 	LIST_FOREACH(fufh, &fvdat->handles, next) {
400 		fdi.iosize = sizeof(*ffsi);
401 		if (ffsi == NULL)
402 			fdisp_make_vp(&fdi, op, vp, td, NULL);
403 		else
404 			fdisp_refresh_vp(&fdi, op, vp, td, NULL);
405 		ffsi = fdi.indata;
406 		ffsi->fh = fufh->fh_id;
407 		ffsi->fsync_flags = 0;
408 
409 		if (datasync)
410 			ffsi->fsync_flags = FUSE_FSYNC_FDATASYNC;
411 
412 		if (waitfor == MNT_WAIT) {
413 			err = fdisp_wait_answ(&fdi);
414 		} else {
415 			fuse_insert_callback(fdi.tick,
416 				fuse_internal_fsync_callback);
417 			fuse_insert_message(fdi.tick, false);
418 		}
419 		if (err == ENOSYS) {
420 			/* ENOSYS means "success, and don't call again" */
421 			fsess_set_notimpl(mp, op);
422 			err = 0;
423 			break;
424 		}
425 	}
426 	fdisp_destroy(&fdi);
427 
428 	return err;
429 }
430 
431 /* Asynchronous invalidation */
432 SDT_PROBE_DEFINE3(fusefs, , internal, invalidate_entry,
433 	"struct vnode*", "struct fuse_notify_inval_entry_out*", "char*");
434 int
435 fuse_internal_invalidate_entry(struct mount *mp, struct uio *uio)
436 {
437 	struct fuse_notify_inval_entry_out fnieo;
438 	struct componentname cn;
439 	struct vnode *dvp, *vp;
440 	char name[PATH_MAX];
441 	int err;
442 
443 	if ((err = uiomove(&fnieo, sizeof(fnieo), uio)) != 0)
444 		return (err);
445 
446 	if (fnieo.namelen >= sizeof(name))
447 		return (EINVAL);
448 
449 	if ((err = uiomove(name, fnieo.namelen, uio)) != 0)
450 		return (err);
451 	name[fnieo.namelen] = '\0';
452 	/* fusefs does not cache "." or ".." entries */
453 	if (strncmp(name, ".", sizeof(".")) == 0 ||
454 	    strncmp(name, "..", sizeof("..")) == 0)
455 		return (0);
456 
457 	if (fnieo.parent == FUSE_ROOT_ID)
458 		err = VFS_ROOT(mp, LK_SHARED, &dvp);
459 	else
460 		err = fuse_internal_get_cached_vnode( mp, fnieo.parent,
461 			LK_SHARED, &dvp);
462 	SDT_PROBE3(fusefs, , internal, invalidate_entry, dvp, &fnieo, name);
463 	/*
464 	 * If dvp is not in the cache, then it must've been reclaimed.  And
465 	 * since fuse_vnop_reclaim does a cache_purge, name's entry must've
466 	 * been invalidated already.  So we can safely return if dvp == NULL
467 	 */
468 	if (err != 0 || dvp == NULL)
469 		return (err);
470 	/*
471 	 * XXX we can't check dvp's generation because the FUSE invalidate
472 	 * entry message doesn't include it.  Worse case is that we invalidate
473 	 * an entry that didn't need to be invalidated.
474 	 */
475 
476 	cn.cn_nameiop = LOOKUP;
477 	cn.cn_flags = 0;	/* !MAKEENTRY means free cached entry */
478 	cn.cn_cred = curthread->td_ucred;
479 	cn.cn_lkflags = LK_SHARED;
480 	cn.cn_pnbuf = NULL;
481 	cn.cn_nameptr = name;
482 	cn.cn_namelen = fnieo.namelen;
483 	err = cache_lookup(dvp, &vp, &cn, NULL, NULL);
484 	MPASS(err == 0);
485 	fuse_vnode_clear_attr_cache(dvp);
486 	vput(dvp);
487 	return (0);
488 }
489 
490 SDT_PROBE_DEFINE2(fusefs, , internal, invalidate_inode,
491 	"struct vnode*", "struct fuse_notify_inval_inode_out *");
492 int
493 fuse_internal_invalidate_inode(struct mount *mp, struct uio *uio)
494 {
495 	struct fuse_notify_inval_inode_out fniio;
496 	struct vnode *vp;
497 	int err;
498 
499 	if ((err = uiomove(&fniio, sizeof(fniio), uio)) != 0)
500 		return (err);
501 
502 	if (fniio.ino == FUSE_ROOT_ID)
503 		err = VFS_ROOT(mp, LK_EXCLUSIVE, &vp);
504 	else
505 		err = fuse_internal_get_cached_vnode(mp, fniio.ino, LK_SHARED,
506 			&vp);
507 	SDT_PROBE2(fusefs, , internal, invalidate_inode, vp, &fniio);
508 	if (err != 0 || vp == NULL)
509 		return (err);
510 	/*
511 	 * XXX we can't check vp's generation because the FUSE invalidate
512 	 * entry message doesn't include it.  Worse case is that we invalidate
513 	 * an inode that didn't need to be invalidated.
514 	 */
515 
516 	/*
517 	 * Flush and invalidate buffers if off >= 0.  Technically we only need
518 	 * to flush and invalidate the range of offsets [off, off + len), but
519 	 * for simplicity's sake we do everything.
520 	 */
521 	if (fniio.off >= 0)
522 		fuse_io_invalbuf(vp, curthread);
523 	fuse_vnode_clear_attr_cache(vp);
524 	vput(vp);
525 	return (0);
526 }
527 
528 /* mknod */
529 int
530 fuse_internal_mknod(struct vnode *dvp, struct vnode **vpp,
531 	struct componentname *cnp, struct vattr *vap)
532 {
533 	struct fuse_data *data;
534 	struct fuse_mknod_in fmni;
535 	size_t insize;
536 
537 	data = fuse_get_mpdata(dvp->v_mount);
538 
539 	fmni.mode = MAKEIMODE(vap->va_type, vap->va_mode);
540 	fmni.rdev = vap->va_rdev;
541 	if (fuse_libabi_geq(data, 7, 12)) {
542 		insize = sizeof(fmni);
543 		fmni.umask = curthread->td_proc->p_pd->pd_cmask;
544 	} else {
545 		insize = FUSE_COMPAT_MKNOD_IN_SIZE;
546 	}
547 	return (fuse_internal_newentry(dvp, vpp, cnp, FUSE_MKNOD, &fmni,
548 	    insize, vap->va_type));
549 }
550 
551 /* readdir */
552 
553 int
554 fuse_internal_readdir(struct vnode *vp,
555     struct uio *uio,
556     off_t startoff,
557     struct fuse_filehandle *fufh,
558     struct fuse_iov *cookediov,
559     int *ncookies,
560     uint64_t *cookies)
561 {
562 	int err = 0;
563 	struct fuse_dispatcher fdi;
564 	struct fuse_read_in *fri = NULL;
565 	int fnd_start;
566 
567 	if (uio_resid(uio) == 0)
568 		return 0;
569 	fdisp_init(&fdi, 0);
570 
571 	/*
572 	 * Note that we DO NOT have a UIO_SYSSPACE here (so no need for p2p
573 	 * I/O).
574 	 */
575 
576 	/*
577 	 * fnd_start is set non-zero once the offset in the directory gets
578 	 * to the startoff.  This is done because directories must be read
579 	 * from the beginning (offset == 0) when fuse_vnop_readdir() needs
580 	 * to do an open of the directory.
581 	 * If it is not set non-zero here, it will be set non-zero in
582 	 * fuse_internal_readdir_processdata() when uio_offset == startoff.
583 	 */
584 	fnd_start = 0;
585 	if (uio->uio_offset == startoff)
586 		fnd_start = 1;
587 	while (uio_resid(uio) > 0) {
588 		fdi.iosize = sizeof(*fri);
589 		if (fri == NULL)
590 			fdisp_make_vp(&fdi, FUSE_READDIR, vp, NULL, NULL);
591 		else
592 			fdisp_refresh_vp(&fdi, FUSE_READDIR, vp, NULL, NULL);
593 
594 		fri = fdi.indata;
595 		fri->fh = fufh->fh_id;
596 		fri->offset = uio_offset(uio);
597 		fri->size = MIN(uio->uio_resid,
598 		    fuse_get_mpdata(vp->v_mount)->max_read);
599 
600 		if ((err = fdisp_wait_answ(&fdi)))
601 			break;
602 		if ((err = fuse_internal_readdir_processdata(uio, startoff,
603 		    &fnd_start, fri->size, fdi.answ, fdi.iosize, cookediov,
604 		    ncookies, &cookies)))
605 			break;
606 	}
607 
608 	fdisp_destroy(&fdi);
609 	return ((err == -1) ? 0 : err);
610 }
611 
612 /*
613  * Return -1 to indicate that this readdir is finished, 0 if it copied
614  * all the directory data read in and it may be possible to read more
615  * and greater than 0 for a failure.
616  */
617 int
618 fuse_internal_readdir_processdata(struct uio *uio,
619     off_t startoff,
620     int *fnd_start,
621     size_t reqsize,
622     void *buf,
623     size_t bufsize,
624     struct fuse_iov *cookediov,
625     int *ncookies,
626     uint64_t **cookiesp)
627 {
628 	int err = 0;
629 	int oreclen;
630 	size_t freclen;
631 
632 	struct dirent *de;
633 	struct fuse_dirent *fudge;
634 	uint64_t *cookies;
635 
636 	cookies = *cookiesp;
637 	if (bufsize < FUSE_NAME_OFFSET)
638 		return -1;
639 	for (;;) {
640 		if (bufsize < FUSE_NAME_OFFSET) {
641 			err = -1;
642 			break;
643 		}
644 		fudge = (struct fuse_dirent *)buf;
645 		freclen = FUSE_DIRENT_SIZE(fudge);
646 
647 		if (bufsize < freclen) {
648 			/*
649 			 * This indicates a partial directory entry at the
650 			 * end of the directory data.
651 			 */
652 			err = -1;
653 			break;
654 		}
655 #ifdef ZERO_PAD_INCOMPLETE_BUFS
656 		if (isbzero(buf, FUSE_NAME_OFFSET)) {
657 			err = -1;
658 			break;
659 		}
660 #endif
661 
662 		if (!fudge->namelen || fudge->namelen > MAXNAMLEN) {
663 			err = EINVAL;
664 			break;
665 		}
666 		oreclen = GENERIC_DIRSIZ((struct pseudo_dirent *)
667 					    &fudge->namelen);
668 
669 		if (oreclen > uio_resid(uio)) {
670 			/* Out of space for the dir so we are done. */
671 			err = -1;
672 			break;
673 		}
674 		/*
675 		 * Don't start to copy the directory entries out until
676 		 * the requested offset in the directory is found.
677 		 */
678 		if (*fnd_start != 0) {
679 			fiov_adjust(cookediov, oreclen);
680 			bzero(cookediov->base, oreclen);
681 
682 			de = (struct dirent *)cookediov->base;
683 			de->d_fileno = fudge->ino;
684 			de->d_off = fudge->off;
685 			de->d_reclen = oreclen;
686 			de->d_type = fudge->type;
687 			de->d_namlen = fudge->namelen;
688 			memcpy((char *)cookediov->base + sizeof(struct dirent) -
689 			       MAXNAMLEN - 1,
690 			       (char *)buf + FUSE_NAME_OFFSET, fudge->namelen);
691 			dirent_terminate(de);
692 
693 			err = uiomove(cookediov->base, cookediov->len, uio);
694 			if (err)
695 				break;
696 			if (cookies != NULL) {
697 				if (*ncookies == 0) {
698 					err = -1;
699 					break;
700 				}
701 				*cookies = fudge->off;
702 				cookies++;
703 				(*ncookies)--;
704 			}
705 		} else if (startoff == fudge->off)
706 			*fnd_start = 1;
707 		buf = (char *)buf + freclen;
708 		bufsize -= freclen;
709 		uio_setoffset(uio, fudge->off);
710 	}
711 	*cookiesp = cookies;
712 
713 	return err;
714 }
715 
716 /* remove */
717 
718 int
719 fuse_internal_remove(struct vnode *dvp,
720     struct vnode *vp,
721     struct componentname *cnp,
722     enum fuse_opcode op)
723 {
724 	struct fuse_dispatcher fdi;
725 	nlink_t nlink;
726 	int err = 0;
727 
728 	fdisp_init(&fdi, cnp->cn_namelen + 1);
729 	fdisp_make_vp(&fdi, op, dvp, curthread, cnp->cn_cred);
730 
731 	memcpy(fdi.indata, cnp->cn_nameptr, cnp->cn_namelen);
732 	((char *)fdi.indata)[cnp->cn_namelen] = '\0';
733 
734 	err = fdisp_wait_answ(&fdi);
735 	fdisp_destroy(&fdi);
736 
737 	if (err)
738 		return (err);
739 
740 	/*
741 	 * Access the cached nlink even if the attr cached has expired.  If
742 	 * it's inaccurate, the worst that will happen is:
743 	 * 1) We'll recycle the vnode even though the file has another link we
744 	 *    don't know about, costing a bit of cpu time, or
745 	 * 2) We won't recycle the vnode even though all of its links are gone.
746 	 *    It will linger around until vnlru reclaims it, costing a bit of
747 	 *    temporary memory.
748 	 */
749 	nlink = VTOFUD(vp)->cached_attrs.va_nlink--;
750 
751 	/*
752 	 * Purge the parent's attribute cache because the daemon
753 	 * should've updated its mtime and ctime.
754 	 */
755 	fuse_vnode_clear_attr_cache(dvp);
756 
757 	/* NB: nlink could be zero if it was never cached */
758 	if (nlink <= 1 || vnode_vtype(vp) == VDIR) {
759 		fuse_internal_vnode_disappear(vp);
760 	} else {
761 		cache_purge(vp);
762 		fuse_vnode_update(vp, FN_CTIMECHANGE);
763 	}
764 
765 	return err;
766 }
767 
768 /* rename */
769 
770 int
771 fuse_internal_rename(struct vnode *fdvp,
772     struct componentname *fcnp,
773     struct vnode *tdvp,
774     struct componentname *tcnp)
775 {
776 	struct fuse_dispatcher fdi;
777 	struct fuse_rename_in *fri;
778 	int err = 0;
779 
780 	fdisp_init(&fdi, sizeof(*fri) + fcnp->cn_namelen + tcnp->cn_namelen + 2);
781 	fdisp_make_vp(&fdi, FUSE_RENAME, fdvp, curthread, tcnp->cn_cred);
782 
783 	fri = fdi.indata;
784 	fri->newdir = VTOI(tdvp);
785 	memcpy((char *)fdi.indata + sizeof(*fri), fcnp->cn_nameptr,
786 	    fcnp->cn_namelen);
787 	((char *)fdi.indata)[sizeof(*fri) + fcnp->cn_namelen] = '\0';
788 	memcpy((char *)fdi.indata + sizeof(*fri) + fcnp->cn_namelen + 1,
789 	    tcnp->cn_nameptr, tcnp->cn_namelen);
790 	((char *)fdi.indata)[sizeof(*fri) + fcnp->cn_namelen +
791 	    tcnp->cn_namelen + 1] = '\0';
792 
793 	err = fdisp_wait_answ(&fdi);
794 	fdisp_destroy(&fdi);
795 	return err;
796 }
797 
798 /* strategy */
799 
800 /* entity creation */
801 
802 void
803 fuse_internal_newentry_makerequest(struct mount *mp,
804     uint64_t dnid,
805     struct componentname *cnp,
806     enum fuse_opcode op,
807     void *buf,
808     size_t bufsize,
809     struct fuse_dispatcher *fdip)
810 {
811 	fdip->iosize = bufsize + cnp->cn_namelen + 1;
812 
813 	fdisp_make(fdip, op, mp, dnid, curthread, cnp->cn_cred);
814 	memcpy(fdip->indata, buf, bufsize);
815 	memcpy((char *)fdip->indata + bufsize, cnp->cn_nameptr, cnp->cn_namelen);
816 	((char *)fdip->indata)[bufsize + cnp->cn_namelen] = '\0';
817 }
818 
819 int
820 fuse_internal_newentry_core(struct vnode *dvp,
821     struct vnode **vpp,
822     struct componentname *cnp,
823     enum vtype vtyp,
824     struct fuse_dispatcher *fdip)
825 {
826 	int err = 0;
827 	struct fuse_entry_out *feo;
828 	struct mount *mp = vnode_mount(dvp);
829 
830 	if ((err = fdisp_wait_answ(fdip))) {
831 		return err;
832 	}
833 	feo = fdip->answ;
834 
835 	if ((err = fuse_internal_checkentry(feo, vtyp))) {
836 		return err;
837 	}
838 	err = fuse_vnode_get(mp, feo, feo->nodeid, dvp, vpp, cnp, vtyp);
839 	if (err) {
840 		fuse_internal_forget_send(mp, curthread, cnp->cn_cred,
841 		    feo->nodeid, 1);
842 		return err;
843 	}
844 
845 	/*
846 	 * Purge the parent's attribute cache because the daemon should've
847 	 * updated its mtime and ctime
848 	 */
849 	fuse_vnode_clear_attr_cache(dvp);
850 
851 	fuse_internal_cache_attrs(*vpp, &feo->attr, feo->attr_valid,
852 		feo->attr_valid_nsec, NULL, true);
853 
854 	return err;
855 }
856 
857 int
858 fuse_internal_newentry(struct vnode *dvp,
859     struct vnode **vpp,
860     struct componentname *cnp,
861     enum fuse_opcode op,
862     void *buf,
863     size_t bufsize,
864     enum vtype vtype)
865 {
866 	int err;
867 	struct fuse_dispatcher fdi;
868 	struct mount *mp = vnode_mount(dvp);
869 
870 	fdisp_init(&fdi, 0);
871 	fuse_internal_newentry_makerequest(mp, VTOI(dvp), cnp, op, buf,
872 	    bufsize, &fdi);
873 	err = fuse_internal_newentry_core(dvp, vpp, cnp, vtype, &fdi);
874 	fdisp_destroy(&fdi);
875 
876 	return err;
877 }
878 
879 /* entity destruction */
880 
881 int
882 fuse_internal_forget_callback(struct fuse_ticket *ftick, struct uio *uio)
883 {
884 	fuse_internal_forget_send(ftick->tk_data->mp, curthread, NULL,
885 	    ((struct fuse_in_header *)ftick->tk_ms_fiov.base)->nodeid, 1);
886 
887 	return 0;
888 }
889 
890 void
891 fuse_internal_forget_send(struct mount *mp,
892     struct thread *td,
893     struct ucred *cred,
894     uint64_t nodeid,
895     uint64_t nlookup)
896 {
897 
898 	struct fuse_dispatcher fdi;
899 	struct fuse_forget_in *ffi;
900 
901 	/*
902          * KASSERT(nlookup > 0, ("zero-times forget for vp #%llu",
903          *         (long long unsigned) nodeid));
904          */
905 
906 	fdisp_init(&fdi, sizeof(*ffi));
907 	fdisp_make(&fdi, FUSE_FORGET, mp, nodeid, td, cred);
908 
909 	ffi = fdi.indata;
910 	ffi->nlookup = nlookup;
911 
912 	fuse_insert_message(fdi.tick, false);
913 	fdisp_destroy(&fdi);
914 }
915 
916 /* Fetch the vnode's attributes from the daemon*/
917 int
918 fuse_internal_do_getattr(struct vnode *vp, struct vattr *vap,
919 	struct ucred *cred, struct thread *td)
920 {
921 	struct fuse_dispatcher fdi;
922 	struct fuse_vnode_data *fvdat = VTOFUD(vp);
923 	struct fuse_getattr_in *fgai;
924 	struct fuse_attr_out *fao;
925 	off_t old_filesize = fvdat->cached_attrs.va_size;
926 	struct timespec old_atime = fvdat->cached_attrs.va_atime;
927 	struct timespec old_ctime = fvdat->cached_attrs.va_ctime;
928 	struct timespec old_mtime = fvdat->cached_attrs.va_mtime;
929 	enum vtype vtyp;
930 	int err;
931 
932 	ASSERT_VOP_LOCKED(vp, __func__);
933 
934 	fdisp_init(&fdi, sizeof(*fgai));
935 	fdisp_make_vp(&fdi, FUSE_GETATTR, vp, td, cred);
936 	fgai = fdi.indata;
937 	/*
938 	 * We could look up a file handle and set it in fgai->fh, but that
939 	 * involves extra runtime work and I'm unaware of any file systems that
940 	 * care.
941 	 */
942 	fgai->getattr_flags = 0;
943 	if ((err = fdisp_wait_answ(&fdi))) {
944 		if (err == ENOENT)
945 			fuse_internal_vnode_disappear(vp);
946 		goto out;
947 	}
948 
949 	fao = (struct fuse_attr_out *)fdi.answ;
950 	vtyp = IFTOVT(fao->attr.mode);
951 	if (fvdat->flag & FN_SIZECHANGE)
952 		fao->attr.size = old_filesize;
953 	if (fvdat->flag & FN_ATIMECHANGE) {
954 		fao->attr.atime = old_atime.tv_sec;
955 		fao->attr.atimensec = old_atime.tv_nsec;
956 	}
957 	if (fvdat->flag & FN_CTIMECHANGE) {
958 		fao->attr.ctime = old_ctime.tv_sec;
959 		fao->attr.ctimensec = old_ctime.tv_nsec;
960 	}
961 	if (fvdat->flag & FN_MTIMECHANGE) {
962 		fao->attr.mtime = old_mtime.tv_sec;
963 		fao->attr.mtimensec = old_mtime.tv_nsec;
964 	}
965 	fuse_internal_cache_attrs(vp, &fao->attr, fao->attr_valid,
966 		fao->attr_valid_nsec, vap, true);
967 	if (vtyp != vnode_vtype(vp)) {
968 		fuse_internal_vnode_disappear(vp);
969 		err = ENOENT;
970 	}
971 
972 out:
973 	fdisp_destroy(&fdi);
974 	return err;
975 }
976 
977 /* Read a vnode's attributes from cache or fetch them from the fuse daemon */
978 int
979 fuse_internal_getattr(struct vnode *vp, struct vattr *vap, struct ucred *cred,
980 	struct thread *td)
981 {
982 	struct vattr *attrs;
983 
984 	if ((attrs = VTOVA(vp)) != NULL) {
985 		*vap = *attrs;	/* struct copy */
986 		return 0;
987 	}
988 
989 	return fuse_internal_do_getattr(vp, vap, cred, td);
990 }
991 
992 void
993 fuse_internal_vnode_disappear(struct vnode *vp)
994 {
995 	struct fuse_vnode_data *fvdat = VTOFUD(vp);
996 
997 	ASSERT_VOP_ELOCKED(vp, "fuse_internal_vnode_disappear");
998 	fvdat->flag |= FN_REVOKED;
999 	cache_purge(vp);
1000 }
1001 
1002 /* fuse start/stop */
1003 
1004 SDT_PROBE_DEFINE2(fusefs, , internal, init_done,
1005 	"struct fuse_data*", "struct fuse_init_out*");
1006 int
1007 fuse_internal_init_callback(struct fuse_ticket *tick, struct uio *uio)
1008 {
1009 	int err = 0;
1010 	struct fuse_data *data = tick->tk_data;
1011 	struct fuse_init_out *fiio;
1012 
1013 	if ((err = tick->tk_aw_ohead.error)) {
1014 		goto out;
1015 	}
1016 	if ((err = fticket_pull(tick, uio))) {
1017 		goto out;
1018 	}
1019 	fiio = fticket_resp(tick)->base;
1020 
1021 	data->fuse_libabi_major = fiio->major;
1022 	data->fuse_libabi_minor = fiio->minor;
1023 	if (!fuse_libabi_geq(data, 7, 4)) {
1024 		/*
1025 		 * With a little work we could support servers as old as 7.1.
1026 		 * But there would be little payoff.
1027 		 */
1028 		SDT_PROBE2(fusefs, , internal, trace, 1,
1029 			"userpace version too low");
1030 		err = EPROTONOSUPPORT;
1031 		goto out;
1032 	}
1033 
1034 	if (fuse_libabi_geq(data, 7, 5)) {
1035 		if (fticket_resp(tick)->len == sizeof(struct fuse_init_out) ||
1036 		    fticket_resp(tick)->len == FUSE_COMPAT_22_INIT_OUT_SIZE) {
1037 			data->max_write = fiio->max_write;
1038 			if (fiio->flags & FUSE_ASYNC_READ)
1039 				data->dataflags |= FSESS_ASYNC_READ;
1040 			if (fiio->flags & FUSE_POSIX_LOCKS)
1041 				data->dataflags |= FSESS_POSIX_LOCKS;
1042 			if (fiio->flags & FUSE_EXPORT_SUPPORT)
1043 				data->dataflags |= FSESS_EXPORT_SUPPORT;
1044 			if (fiio->flags & FUSE_NO_OPEN_SUPPORT)
1045 				data->dataflags |= FSESS_NO_OPEN_SUPPORT;
1046 			if (fiio->flags & FUSE_NO_OPENDIR_SUPPORT)
1047 				data->dataflags |= FSESS_NO_OPENDIR_SUPPORT;
1048 			/*
1049 			 * Don't bother to check FUSE_BIG_WRITES, because it's
1050 			 * redundant with max_write
1051 			 */
1052 			/*
1053 			 * max_background and congestion_threshold are not
1054 			 * implemented
1055 			 */
1056 		} else {
1057 			err = EINVAL;
1058 		}
1059 	} else {
1060 		/* Old fixed values */
1061 		data->max_write = 4096;
1062 	}
1063 
1064 	if (fuse_libabi_geq(data, 7, 6))
1065 		data->max_readahead_blocks = fiio->max_readahead / maxbcachebuf;
1066 
1067 	if (!fuse_libabi_geq(data, 7, 7))
1068 		fsess_set_notimpl(data->mp, FUSE_INTERRUPT);
1069 
1070 	if (!fuse_libabi_geq(data, 7, 8)) {
1071 		fsess_set_notimpl(data->mp, FUSE_BMAP);
1072 		fsess_set_notimpl(data->mp, FUSE_DESTROY);
1073 	}
1074 
1075 	if (!fuse_libabi_geq(data, 7, 19)) {
1076 		fsess_set_notimpl(data->mp, FUSE_FALLOCATE);
1077 	}
1078 
1079 	if (fuse_libabi_geq(data, 7, 23) && fiio->time_gran >= 1 &&
1080 	    fiio->time_gran <= 1000000000)
1081 		data->time_gran = fiio->time_gran;
1082 	else
1083 		data->time_gran = 1;
1084 
1085 	if (!fuse_libabi_geq(data, 7, 23))
1086 		data->cache_mode = fuse_data_cache_mode;
1087 	else if (fiio->flags & FUSE_WRITEBACK_CACHE)
1088 		data->cache_mode = FUSE_CACHE_WB;
1089 	else
1090 		data->cache_mode = FUSE_CACHE_WT;
1091 
1092 	if (!fuse_libabi_geq(data, 7, 24))
1093 		fsess_set_notimpl(data->mp, FUSE_LSEEK);
1094 
1095 	if (!fuse_libabi_geq(data, 7, 28))
1096 		fsess_set_notimpl(data->mp, FUSE_COPY_FILE_RANGE);
1097 
1098 out:
1099 	if (err) {
1100 		fdata_set_dead(data);
1101 	}
1102 	FUSE_LOCK();
1103 	data->dataflags |= FSESS_INITED;
1104 	SDT_PROBE2(fusefs, , internal, init_done, data, fiio);
1105 	wakeup(&data->ticketer);
1106 	FUSE_UNLOCK();
1107 
1108 	return 0;
1109 }
1110 
1111 void
1112 fuse_internal_send_init(struct fuse_data *data, struct thread *td)
1113 {
1114 	struct fuse_init_in *fiii;
1115 	struct fuse_dispatcher fdi;
1116 
1117 	fdisp_init(&fdi, sizeof(*fiii));
1118 	fdisp_make(&fdi, FUSE_INIT, data->mp, 0, td, NULL);
1119 	fiii = fdi.indata;
1120 	fiii->major = FUSE_KERNEL_VERSION;
1121 	fiii->minor = FUSE_KERNEL_MINOR_VERSION;
1122 	/*
1123 	 * fusefs currently reads ahead no more than one cache block at a time.
1124 	 * See fuse_read_biobackend
1125 	 */
1126 	fiii->max_readahead = maxbcachebuf;
1127 	/*
1128 	 * Unsupported features:
1129 	 * FUSE_FILE_OPS: No known FUSE server or client supports it
1130 	 * FUSE_ATOMIC_O_TRUNC: our VFS cannot support it
1131 	 * FUSE_DONT_MASK: unlike Linux, FreeBSD always applies the umask, even
1132 	 *	when default ACLs are in use.
1133 	 * FUSE_SPLICE_WRITE, FUSE_SPLICE_MOVE, FUSE_SPLICE_READ: FreeBSD
1134 	 *	doesn't have splice(2).
1135 	 * FUSE_FLOCK_LOCKS: not yet implemented
1136 	 * FUSE_HAS_IOCTL_DIR: not yet implemented
1137 	 * FUSE_AUTO_INVAL_DATA: not yet implemented
1138 	 * FUSE_DO_READDIRPLUS: not yet implemented
1139 	 * FUSE_READDIRPLUS_AUTO: not yet implemented
1140 	 * FUSE_ASYNC_DIO: not yet implemented
1141 	 * FUSE_PARALLEL_DIROPS: not yet implemented
1142 	 * FUSE_HANDLE_KILLPRIV: not yet implemented
1143 	 * FUSE_POSIX_ACL: not yet implemented
1144 	 * FUSE_ABORT_ERROR: not yet implemented
1145 	 * FUSE_CACHE_SYMLINKS: not yet implemented
1146 	 * FUSE_MAX_PAGES: not yet implemented
1147 	 */
1148 	fiii->flags = FUSE_ASYNC_READ | FUSE_POSIX_LOCKS | FUSE_EXPORT_SUPPORT
1149 		| FUSE_BIG_WRITES | FUSE_WRITEBACK_CACHE
1150 		| FUSE_NO_OPEN_SUPPORT | FUSE_NO_OPENDIR_SUPPORT;
1151 
1152 	fuse_insert_callback(fdi.tick, fuse_internal_init_callback);
1153 	fuse_insert_message(fdi.tick, false);
1154 	fdisp_destroy(&fdi);
1155 }
1156 
1157 /*
1158  * Send a FUSE_SETATTR operation with no permissions checks.  If cred is NULL,
1159  * send the request with root credentials
1160  */
1161 int fuse_internal_setattr(struct vnode *vp, struct vattr *vap,
1162 	struct thread *td, struct ucred *cred)
1163 {
1164 	struct fuse_vnode_data *fvdat;
1165 	struct fuse_dispatcher fdi;
1166 	struct fuse_setattr_in *fsai;
1167 	struct mount *mp;
1168 	pid_t pid = td->td_proc->p_pid;
1169 	struct fuse_data *data;
1170 	int err = 0;
1171 	enum vtype vtyp;
1172 
1173 	ASSERT_VOP_ELOCKED(vp, __func__);
1174 
1175 	mp = vnode_mount(vp);
1176 	fvdat = VTOFUD(vp);
1177 	data = fuse_get_mpdata(mp);
1178 
1179 	fdisp_init(&fdi, sizeof(*fsai));
1180 	fdisp_make_vp(&fdi, FUSE_SETATTR, vp, td, cred);
1181 	if (!cred) {
1182 		fdi.finh->uid = 0;
1183 		fdi.finh->gid = 0;
1184 	}
1185 	fsai = fdi.indata;
1186 	fsai->valid = 0;
1187 
1188 	if (vap->va_uid != (uid_t)VNOVAL) {
1189 		fsai->uid = vap->va_uid;
1190 		fsai->valid |= FATTR_UID;
1191 	}
1192 	if (vap->va_gid != (gid_t)VNOVAL) {
1193 		fsai->gid = vap->va_gid;
1194 		fsai->valid |= FATTR_GID;
1195 	}
1196 	if (vap->va_size != VNOVAL) {
1197 		struct fuse_filehandle *fufh = NULL;
1198 
1199 		/*Truncate to a new value. */
1200 		fsai->size = vap->va_size;
1201 		fsai->valid |= FATTR_SIZE;
1202 
1203 		fuse_filehandle_getrw(vp, FWRITE, &fufh, cred, pid);
1204 		if (fufh) {
1205 			fsai->fh = fufh->fh_id;
1206 			fsai->valid |= FATTR_FH;
1207 		}
1208 		VTOFUD(vp)->flag &= ~FN_SIZECHANGE;
1209 	}
1210 	if (vap->va_atime.tv_sec != VNOVAL) {
1211 		fsai->atime = vap->va_atime.tv_sec;
1212 		fsai->atimensec = vap->va_atime.tv_nsec;
1213 		fsai->valid |= FATTR_ATIME;
1214 		if (vap->va_vaflags & VA_UTIMES_NULL)
1215 			fsai->valid |= FATTR_ATIME_NOW;
1216 	} else if (fvdat->flag & FN_ATIMECHANGE) {
1217 		fsai->atime = fvdat->cached_attrs.va_atime.tv_sec;
1218 		fsai->atimensec = fvdat->cached_attrs.va_atime.tv_nsec;
1219 		fsai->valid |= FATTR_ATIME;
1220 	}
1221 	if (vap->va_mtime.tv_sec != VNOVAL) {
1222 		fsai->mtime = vap->va_mtime.tv_sec;
1223 		fsai->mtimensec = vap->va_mtime.tv_nsec;
1224 		fsai->valid |= FATTR_MTIME;
1225 		if (vap->va_vaflags & VA_UTIMES_NULL)
1226 			fsai->valid |= FATTR_MTIME_NOW;
1227 	} else if (fvdat->flag & FN_MTIMECHANGE) {
1228 		fsai->mtime = fvdat->cached_attrs.va_mtime.tv_sec;
1229 		fsai->mtimensec = fvdat->cached_attrs.va_mtime.tv_nsec;
1230 		fsai->valid |= FATTR_MTIME;
1231 	}
1232 	if (fuse_libabi_geq(data, 7, 23) && fvdat->flag & FN_CTIMECHANGE) {
1233 		fsai->ctime = fvdat->cached_attrs.va_ctime.tv_sec;
1234 		fsai->ctimensec = fvdat->cached_attrs.va_ctime.tv_nsec;
1235 		fsai->valid |= FATTR_CTIME;
1236 	}
1237 	if (vap->va_mode != (mode_t)VNOVAL) {
1238 		fsai->mode = vap->va_mode & ALLPERMS;
1239 		fsai->valid |= FATTR_MODE;
1240 	}
1241 	if (!fsai->valid) {
1242 		goto out;
1243 	}
1244 
1245 	if ((err = fdisp_wait_answ(&fdi)))
1246 		goto out;
1247 	vtyp = IFTOVT(((struct fuse_attr_out *)fdi.answ)->attr.mode);
1248 
1249 	if (vnode_vtype(vp) != vtyp) {
1250 		if (vnode_vtype(vp) == VNON && vtyp != VNON) {
1251 			SDT_PROBE2(fusefs, , internal, trace, 1, "FUSE: Dang! "
1252 				"vnode_vtype is VNON and vtype isn't.");
1253 		} else {
1254 			/*
1255 	                 * STALE vnode, ditch
1256 	                 *
1257 			 * The vnode has changed its type "behind our back".
1258 			 * This probably means that the file got deleted and
1259 			 * recreated on the server, with the same inode.
1260 			 * There's nothing really we can do, so let us just
1261 			 * return ENOENT.  After all, the entry must not have
1262 			 * existed in the recent past.  If the user tries
1263 			 * again, it will work.
1264 	                 */
1265 			fuse_internal_vnode_disappear(vp);
1266 			err = ENOENT;
1267 		}
1268 	}
1269 	if (err == 0) {
1270 		struct fuse_attr_out *fao = (struct fuse_attr_out*)fdi.answ;
1271 		fuse_vnode_undirty_cached_timestamps(vp, true);
1272 		fuse_internal_cache_attrs(vp, &fao->attr, fao->attr_valid,
1273 			fao->attr_valid_nsec, NULL, false);
1274 		getnanouptime(&fvdat->last_local_modify);
1275 	}
1276 
1277 out:
1278 	fdisp_destroy(&fdi);
1279 	return err;
1280 }
1281 
1282 /*
1283  * FreeBSD clears the SUID and SGID bits on any write by a non-root user.
1284  */
1285 void
1286 fuse_internal_clear_suid_on_write(struct vnode *vp, struct ucred *cred,
1287 	struct thread *td)
1288 {
1289 	struct fuse_data *data;
1290 	struct mount *mp;
1291 	struct vattr va;
1292 	int dataflags;
1293 
1294 	mp = vnode_mount(vp);
1295 	data = fuse_get_mpdata(mp);
1296 	dataflags = data->dataflags;
1297 
1298 	ASSERT_VOP_LOCKED(vp, __func__);
1299 
1300 	if (dataflags & FSESS_DEFAULT_PERMISSIONS) {
1301 		if (priv_check_cred(cred, PRIV_VFS_RETAINSUGID)) {
1302 			fuse_internal_getattr(vp, &va, cred, td);
1303 			if (va.va_mode & (S_ISUID | S_ISGID)) {
1304 				mode_t mode = va.va_mode & ~(S_ISUID | S_ISGID);
1305 				/* Clear all vattr fields except mode */
1306 				vattr_null(&va);
1307 				va.va_mode = mode;
1308 
1309 				/*
1310 				 * Ignore fuse_internal_setattr's return value,
1311 				 * because at this point the write operation has
1312 				 * already succeeded and we don't want to return
1313 				 * failing status for that.
1314 				 */
1315 				(void)fuse_internal_setattr(vp, &va, td, NULL);
1316 			}
1317 		}
1318 	}
1319 }
1320 
1321 #ifdef ZERO_PAD_INCOMPLETE_BUFS
1322 static int
1323 isbzero(void *buf, size_t len)
1324 {
1325 	int i;
1326 
1327 	for (i = 0; i < len; i++) {
1328 		if (((char *)buf)[i])
1329 			return (0);
1330 	}
1331 
1332 	return (1);
1333 }
1334 
1335 #endif
1336 
1337 void
1338 fuse_internal_init(void)
1339 {
1340 	fuse_lookup_cache_misses = counter_u64_alloc(M_WAITOK);
1341 	fuse_lookup_cache_hits = counter_u64_alloc(M_WAITOK);
1342 }
1343 
1344 void
1345 fuse_internal_destroy(void)
1346 {
1347 	counter_u64_free(fuse_lookup_cache_hits);
1348 	counter_u64_free(fuse_lookup_cache_misses);
1349 }
1350