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