xref: /freebsd/sys/fs/fuse/fuse_node.c (revision 6ef644f5889afbd0f681b08ed1a2f369524af83e)
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 #include <sys/types.h>
65 #include <sys/systm.h>
66 #include <sys/counter.h>
67 #include <sys/module.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/proc.h>
79 #include <sys/vnode.h>
80 #include <sys/namei.h>
81 #include <sys/mount.h>
82 #include <sys/sysctl.h>
83 #include <sys/fcntl.h>
84 #include <sys/priv.h>
85 #include <sys/buf.h>
86 #include <security/mac/mac_framework.h>
87 #include <vm/vm.h>
88 #include <vm/vm_extern.h>
89 
90 #include "fuse.h"
91 #include "fuse_node.h"
92 #include "fuse_internal.h"
93 #include "fuse_io.h"
94 #include "fuse_ipc.h"
95 
96 SDT_PROVIDER_DECLARE(fusefs);
97 /*
98  * Fuse trace probe:
99  * arg0: verbosity.  Higher numbers give more verbose messages
100  * arg1: Textual message
101  */
102 SDT_PROBE_DEFINE2(fusefs, , node, trace, "int", "char*");
103 
104 MALLOC_DEFINE(M_FUSEVN, "fuse_vnode", "fuse vnode private data");
105 
106 static int sysctl_fuse_cache_mode(SYSCTL_HANDLER_ARGS);
107 
108 static counter_u64_t fuse_node_count;
109 
110 SYSCTL_COUNTER_U64(_vfs_fusefs_stats, OID_AUTO, node_count, CTLFLAG_RD,
111     &fuse_node_count, "Count of FUSE vnodes");
112 
113 int	fuse_data_cache_mode = FUSE_CACHE_WT;
114 
115 /*
116  * DEPRECATED
117  * This sysctl is no longer needed as of fuse protocol 7.23.  Individual
118  * servers can select the cache behavior they need for each mountpoint:
119  * - writethrough: the default
120  * - writeback: set FUSE_WRITEBACK_CACHE in fuse_init_out.flags
121  * - uncached: set FOPEN_DIRECT_IO for every file
122  * The sysctl is retained primarily for use by jails supporting older FUSE
123  * protocols.  It may be removed entirely once FreeBSD 11.3 and 12.0 are EOL.
124  */
125 SYSCTL_PROC(_vfs_fusefs, OID_AUTO, data_cache_mode,
126     CTLTYPE_INT | CTLFLAG_MPSAFE | CTLFLAG_RW,
127     &fuse_data_cache_mode, 0, sysctl_fuse_cache_mode, "I",
128     "Zero: disable caching of FUSE file data; One: write-through caching "
129     "(default); Two: write-back caching (generally unsafe)");
130 
131 static int
132 sysctl_fuse_cache_mode(SYSCTL_HANDLER_ARGS)
133 {
134 	int val, error;
135 
136 	val = *(int *)arg1;
137 	error = sysctl_handle_int(oidp, &val, 0, req);
138 	if (error || !req->newptr)
139 		return (error);
140 
141 	switch (val) {
142 	case FUSE_CACHE_UC:
143 	case FUSE_CACHE_WT:
144 	case FUSE_CACHE_WB:
145 		*(int *)arg1 = val;
146 		break;
147 	default:
148 		return (EDOM);
149 	}
150 	return (0);
151 }
152 
153 static void
154 fuse_vnode_init(struct vnode *vp, struct fuse_vnode_data *fvdat,
155     uint64_t nodeid, __enum_uint8(vtype) vtyp)
156 {
157 	fvdat->nid = nodeid;
158 	LIST_INIT(&fvdat->handles);
159 	vattr_null(&fvdat->cached_attrs);
160 	if (nodeid == FUSE_ROOT_ID) {
161 		vp->v_vflag |= VV_ROOT;
162 	}
163 	vp->v_type = vtyp;
164 	vp->v_data = fvdat;
165 	cluster_init_vn(&fvdat->clusterw);
166 	timespecclear(&fvdat->last_local_modify);
167 
168 	counter_u64_add(fuse_node_count, 1);
169 }
170 
171 void
172 fuse_vnode_destroy(struct vnode *vp)
173 {
174 	struct fuse_vnode_data *fvdat = vp->v_data;
175 
176 	vp->v_data = NULL;
177 	KASSERT(LIST_EMPTY(&fvdat->handles),
178 		("Destroying fuse vnode with open files!"));
179 	free(fvdat, M_FUSEVN);
180 
181 	counter_u64_add(fuse_node_count, -1);
182 }
183 
184 int
185 fuse_vnode_cmp(struct vnode *vp, void *nidp)
186 {
187 	return (VTOI(vp) != *((uint64_t *)nidp));
188 }
189 
190 SDT_PROBE_DEFINE3(fusefs, , node, stale_vnode, "struct vnode*", "uint8_t",
191 		"uint64_t");
192 static int
193 fuse_vnode_alloc(struct mount *mp,
194     struct thread *td,
195     uint64_t nodeid,
196     __enum_uint8(vtype) vtyp,
197     struct vnode **vpp)
198 {
199 	struct fuse_data *data;
200 	struct fuse_vnode_data *fvdat;
201 	struct vnode *vp2;
202 	int err = 0;
203 
204 	data = fuse_get_mpdata(mp);
205 	if (vtyp == VNON) {
206 		return EINVAL;
207 	}
208 	*vpp = NULL;
209 	err = vfs_hash_get(mp, fuse_vnode_hash(nodeid), LK_EXCLUSIVE, td, vpp,
210 	    fuse_vnode_cmp, &nodeid);
211 	if (err)
212 		return (err);
213 
214 	if (*vpp) {
215 		if ((*vpp)->v_type == vtyp) {
216 			/* Reuse a vnode that hasn't yet been reclaimed */
217 			MPASS((*vpp)->v_data != NULL);
218 			MPASS(VTOFUD(*vpp)->nid == nodeid);
219 			SDT_PROBE2(fusefs, , node, trace, 1,
220 				"vnode taken from hash");
221 			return (0);
222 		} else {
223 			/*
224 			 * The inode changed types!  If we get here, we can't
225 			 * tell whether the inode's entry cache had expired
226 			 * yet.  So this could be the result of a buggy server,
227 			 * but more likely the server just reused an inode
228 			 * number following an entry cache expiration.
229 			 */
230 			SDT_PROBE3(fusefs, , node, stale_vnode, *vpp, vtyp,
231 				nodeid);
232 			fuse_internal_vnode_disappear(*vpp);
233 			vgone(*vpp);
234 			lockmgr((*vpp)->v_vnlock, LK_RELEASE, NULL);
235 		}
236 	}
237 	fvdat = malloc(sizeof(*fvdat), M_FUSEVN, M_WAITOK | M_ZERO);
238 	switch (vtyp) {
239 	case VFIFO:
240 		err = getnewvnode("fuse", mp, &fuse_fifoops, vpp);
241 		break;
242 	default:
243 		err = getnewvnode("fuse", mp, &fuse_vnops, vpp);
244 		break;
245 	}
246 	if (err) {
247 		free(fvdat, M_FUSEVN);
248 		return (err);
249 	}
250 	lockmgr((*vpp)->v_vnlock, LK_EXCLUSIVE, NULL);
251 	fuse_vnode_init(*vpp, fvdat, nodeid, vtyp);
252 	err = insmntque(*vpp, mp);
253 	ASSERT_VOP_ELOCKED(*vpp, "fuse_vnode_alloc");
254 	if (err) {
255 		lockmgr((*vpp)->v_vnlock, LK_RELEASE, NULL);
256 		free(fvdat, M_FUSEVN);
257 		*vpp = NULL;
258 		return (err);
259 	}
260 	/* Disallow async reads for fifos because UFS does.  I don't know why */
261 	if (data->dataflags & FSESS_ASYNC_READ && vtyp != VFIFO)
262 		VN_LOCK_ASHARE(*vpp);
263 
264 	vn_set_state(*vpp, VSTATE_CONSTRUCTED);
265 	err = vfs_hash_insert(*vpp, fuse_vnode_hash(nodeid), LK_EXCLUSIVE,
266 	    td, &vp2, fuse_vnode_cmp, &nodeid);
267 	if (err) {
268 		lockmgr((*vpp)->v_vnlock, LK_RELEASE, NULL);
269 		free(fvdat, M_FUSEVN);
270 		*vpp = NULL;
271 		return (err);
272 	}
273 	if (vp2 != NULL) {
274 		*vpp = vp2;
275 		return (0);
276 	}
277 
278 	ASSERT_VOP_ELOCKED(*vpp, "fuse_vnode_alloc");
279 
280 	return (0);
281 }
282 
283 int
284 fuse_vnode_get(struct mount *mp,
285     struct fuse_entry_out *feo,
286     uint64_t nodeid,
287     struct vnode *dvp,
288     struct vnode **vpp,
289     struct componentname *cnp,
290     __enum_uint8(vtype) vtyp)
291 {
292 	struct thread *td = curthread;
293 	/*
294 	 * feo should only be NULL for the root directory, which (when libfuse
295 	 * is used) always has generation 0
296 	 */
297 	uint64_t generation = feo ? feo->generation : 0;
298 	int err = 0;
299 
300 	if (dvp != NULL && VTOFUD(dvp)->nid == nodeid) {
301 		fuse_warn(fuse_get_mpdata(mp), FSESS_WARN_ILLEGAL_INODE,
302 			"Assigned same inode to both parent and child.");
303 		return EIO;
304 	}
305 
306 	err = fuse_vnode_alloc(mp, td, nodeid, vtyp, vpp);
307 	if (err) {
308 		return err;
309 	}
310 	if (dvp != NULL) {
311 		MPASS(cnp && (cnp->cn_flags & ISDOTDOT) == 0);
312 		MPASS(cnp &&
313 			!(cnp->cn_namelen == 1 && cnp->cn_nameptr[0] == '.'));
314 		fuse_vnode_setparent(*vpp, dvp);
315 	}
316 	if (dvp != NULL && cnp != NULL && (cnp->cn_flags & MAKEENTRY) != 0 &&
317 	    feo != NULL &&
318 	    (feo->entry_valid != 0 || feo->entry_valid_nsec != 0)) {
319 		struct timespec timeout;
320 
321 		ASSERT_VOP_LOCKED(*vpp, "fuse_vnode_get");
322 		ASSERT_VOP_LOCKED(dvp, "fuse_vnode_get");
323 
324 		fuse_validity_2_timespec(feo, &timeout);
325 		cache_enter_time(dvp, *vpp, cnp, &timeout, NULL);
326 	}
327 
328 	VTOFUD(*vpp)->generation = generation;
329 	/*
330 	 * In userland, libfuse uses cached lookups for dot and dotdot entries,
331 	 * thus it does not really bump the nlookup counter for forget.
332 	 * Follow the same semantic and avoid the bump in order to keep
333 	 * nlookup counters consistent.
334 	 */
335 	if (cnp == NULL || ((cnp->cn_flags & ISDOTDOT) == 0 &&
336 	    (cnp->cn_namelen != 1 || cnp->cn_nameptr[0] != '.')))
337 		VTOFUD(*vpp)->nlookup++;
338 
339 	return 0;
340 }
341 
342 /*
343  * Called for every fusefs vnode open to initialize the vnode (not
344  * fuse_filehandle) for use
345  */
346 void
347 fuse_vnode_open(struct vnode *vp, int32_t fuse_open_flags, struct thread *td)
348 {
349 	if (vnode_vtype(vp) == VREG)
350 		vnode_create_vobject(vp, 0, td);
351 }
352 
353 int
354 fuse_vnode_savesize(struct vnode *vp, struct ucred *cred, pid_t pid)
355 {
356 	struct fuse_vnode_data *fvdat = VTOFUD(vp);
357 	struct thread *td = curthread;
358 	struct fuse_filehandle *fufh = NULL;
359 	struct fuse_dispatcher fdi;
360 	struct fuse_setattr_in *fsai;
361 	int err = 0;
362 
363 	ASSERT_VOP_ELOCKED(vp, "fuse_io_extend");
364 
365 	if (fuse_isdeadfs(vp)) {
366 		return EBADF;
367 	}
368 	if (vnode_vtype(vp) == VDIR) {
369 		return EISDIR;
370 	}
371 	if (vfs_isrdonly(vnode_mount(vp))) {
372 		return EROFS;
373 	}
374 	if (cred == NULL) {
375 		cred = td->td_ucred;
376 	}
377 	fdisp_init(&fdi, sizeof(*fsai));
378 	fdisp_make_vp(&fdi, FUSE_SETATTR, vp, td, cred);
379 	fsai = fdi.indata;
380 	fsai->valid = 0;
381 
382 	/* Truncate to a new value. */
383 	MPASS((fvdat->flag & FN_SIZECHANGE) != 0);
384 	fsai->size = fvdat->cached_attrs.va_size;
385 	fsai->valid |= FATTR_SIZE;
386 
387 	fuse_filehandle_getrw(vp, FWRITE, &fufh, cred, pid);
388 	if (fufh) {
389 		fsai->fh = fufh->fh_id;
390 		fsai->valid |= FATTR_FH;
391 	}
392 	err = fdisp_wait_answ(&fdi);
393 	fdisp_destroy(&fdi);
394 	if (err == 0) {
395 		getnanouptime(&fvdat->last_local_modify);
396 		fvdat->flag &= ~FN_SIZECHANGE;
397 	}
398 
399 	return err;
400 }
401 
402 /*
403  * Adjust the vnode's size to a new value.
404  *
405  * If the new value came from the server, such as from a FUSE_GETATTR
406  * operation, set `from_server` true.  But if it came from a local operation,
407  * such as write(2) or truncate(2), set `from_server` false.
408  */
409 int
410 fuse_vnode_setsize(struct vnode *vp, off_t newsize, bool from_server)
411 {
412 	struct fuse_vnode_data *fvdat = VTOFUD(vp);
413 	struct vattr *attrs;
414 	off_t oldsize;
415 	size_t iosize;
416 	struct buf *bp = NULL;
417 	int err = 0;
418 
419 	ASSERT_VOP_ELOCKED(vp, "fuse_vnode_setsize");
420 
421 	iosize = fuse_iosize(vp);
422 	oldsize = fvdat->cached_attrs.va_size;
423 	fvdat->cached_attrs.va_size = newsize;
424 	if ((attrs = VTOVA(vp)) != NULL)
425 		attrs->va_size = newsize;
426 
427 	if (newsize < oldsize) {
428 		daddr_t lbn;
429 
430 		err = vtruncbuf(vp, newsize, fuse_iosize(vp));
431 		if (err)
432 			goto out;
433 		if (newsize % iosize == 0)
434 			goto out;
435 		/*
436 		 * Zero the contents of the last partial block.
437 		 * Sure seems like vtruncbuf should do this for us.
438 		 */
439 
440 		lbn = newsize / iosize;
441 		bp = getblk(vp, lbn, iosize, PCATCH, 0, 0);
442 		if (!bp) {
443 			err = EINTR;
444 			goto out;
445 		}
446 		if (!(bp->b_flags & B_CACHE))
447 			goto out;	/* Nothing to do */
448 		MPASS(bp->b_flags & B_VMIO);
449 		vfs_bio_clrbuf(bp);
450 		bp->b_dirtyend = MIN(bp->b_dirtyend, newsize - lbn * iosize);
451 	} else if (from_server && newsize > oldsize && oldsize != VNOVAL) {
452 		/*
453 		 * The FUSE server changed the file size behind our back.  We
454 		 * should invalidate the entire cache.
455 		 */
456 		daddr_t end_lbn;
457 
458 		end_lbn = howmany(newsize, iosize);
459 		v_inval_buf_range(vp, 0, end_lbn, iosize);
460 	}
461 out:
462 	if (bp)
463 		brelse(bp);
464 	vnode_pager_setsize(vp, newsize);
465 	return err;
466 }
467 
468 /* Get the current, possibly dirty, size of the file */
469 int
470 fuse_vnode_size(struct vnode *vp, off_t *filesize, struct ucred *cred,
471 	struct thread *td)
472 {
473 	struct fuse_vnode_data *fvdat = VTOFUD(vp);
474 	int error = 0;
475 
476 	if (!(fvdat->flag & FN_SIZECHANGE) &&
477 		(!fuse_vnode_attr_cache_valid(vp) ||
478 		  fvdat->cached_attrs.va_size == VNOVAL))
479 		error = fuse_internal_do_getattr(vp, NULL, cred, td);
480 
481 	if (!error)
482 		*filesize = fvdat->cached_attrs.va_size;
483 
484 	return error;
485 }
486 
487 void
488 fuse_vnode_undirty_cached_timestamps(struct vnode *vp, bool atime)
489 {
490 	struct fuse_vnode_data *fvdat = VTOFUD(vp);
491 
492 	fvdat->flag &= ~(FN_MTIMECHANGE | FN_CTIMECHANGE);
493 	if (atime)
494 		fvdat->flag &= ~FN_ATIMECHANGE;
495 }
496 
497 /* Update a fuse file's cached timestamps */
498 void
499 fuse_vnode_update(struct vnode *vp, int flags)
500 {
501 	struct fuse_vnode_data *fvdat = VTOFUD(vp);
502 	struct mount *mp = vnode_mount(vp);
503 	struct fuse_data *data = fuse_get_mpdata(mp);
504 	struct timespec ts;
505 
506 	vfs_timestamp(&ts);
507 
508 	if (data->time_gran > 1)
509 		ts.tv_nsec = rounddown(ts.tv_nsec, data->time_gran);
510 
511 	if (mp->mnt_flag & MNT_NOATIME)
512 		flags &= ~FN_ATIMECHANGE;
513 
514 	if (flags & FN_ATIMECHANGE)
515 		fvdat->cached_attrs.va_atime = ts;
516 	if (flags & FN_MTIMECHANGE)
517 		fvdat->cached_attrs.va_mtime = ts;
518 	if (flags & FN_CTIMECHANGE)
519 		fvdat->cached_attrs.va_ctime = ts;
520 
521 	fvdat->flag |= flags;
522 }
523 
524 void
525 fuse_node_init(void)
526 {
527 	fuse_node_count = counter_u64_alloc(M_WAITOK);
528 }
529 
530 void
531 fuse_node_destroy(void)
532 {
533 	counter_u64_free(fuse_node_count);
534 }
535