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