xref: /freebsd/sys/fs/fuse/fuse_device.c (revision 105fd928b0b5b35ab529e5f6914788dc49582901)
1 /*-
2  * SPDX-License-Identifier: BSD-3-Clause
3  *
4  * Copyright (c) 2007-2009 Google Inc.
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions are
9  * met:
10  *
11  * * Redistributions of source code must retain the above copyright
12  *   notice, this list of conditions and the following disclaimer.
13  * * Redistributions in binary form must reproduce the above
14  *   copyright notice, this list of conditions and the following disclaimer
15  *   in the documentation and/or other materials provided with the
16  *   distribution.
17  * * Neither the name of Google Inc. nor the names of its
18  *   contributors may be used to endorse or promote products derived from
19  *   this software without specific prior written permission.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
22  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
23  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
24  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
25  * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
26  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
27  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
28  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
29  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
30  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
31  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
32  *
33  * Copyright (C) 2005 Csaba Henk.
34  * All rights reserved.
35  *
36  * Copyright (c) 2019 The FreeBSD Foundation
37  *
38  * Portions of this software were developed by BFF Storage Systems, LLC under
39  * sponsorship from the FreeBSD Foundation.
40  *
41  * Redistribution and use in source and binary forms, with or without
42  * modification, are permitted provided that the following conditions
43  * are met:
44  * 1. Redistributions of source code must retain the above copyright
45  *    notice, this list of conditions and the following disclaimer.
46  * 2. Redistributions in binary form must reproduce the above copyright
47  *    notice, this list of conditions and the following disclaimer in the
48  *    documentation and/or other materials provided with the distribution.
49  *
50  * THIS SOFTWARE IS PROVIDED BY AUTHOR AND CONTRIBUTORS ``AS IS'' AND
51  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
52  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
53  * ARE DISCLAIMED.  IN NO EVENT SHALL AUTHOR OR CONTRIBUTORS BE LIABLE
54  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
55  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
56  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
57  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
58  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
59  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
60  * SUCH DAMAGE.
61  */
62 
63 #include <sys/cdefs.h>
64 __FBSDID("$FreeBSD$");
65 
66 #include <sys/types.h>
67 #include <sys/module.h>
68 #include <sys/systm.h>
69 #include <sys/errno.h>
70 #include <sys/param.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/sx.h>
78 #include <sys/mutex.h>
79 #include <sys/proc.h>
80 #include <sys/mount.h>
81 #include <sys/sdt.h>
82 #include <sys/stat.h>
83 #include <sys/fcntl.h>
84 #include <sys/sysctl.h>
85 #include <sys/poll.h>
86 #include <sys/selinfo.h>
87 
88 #include "fuse.h"
89 #include "fuse_internal.h"
90 #include "fuse_ipc.h"
91 
92 #include <compat/linux/linux_errno.h>
93 #include <compat/linux/linux_errno.inc>
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, , device, trace, "int", "char*");
102 
103 static struct cdev *fuse_dev;
104 
105 static d_kqfilter_t fuse_device_filter;
106 static d_open_t fuse_device_open;
107 static d_poll_t fuse_device_poll;
108 static d_read_t fuse_device_read;
109 static d_write_t fuse_device_write;
110 
111 static struct cdevsw fuse_device_cdevsw = {
112 	.d_kqfilter = fuse_device_filter,
113 	.d_open = fuse_device_open,
114 	.d_name = "fuse",
115 	.d_poll = fuse_device_poll,
116 	.d_read = fuse_device_read,
117 	.d_write = fuse_device_write,
118 	.d_version = D_VERSION,
119 };
120 
121 static int fuse_device_filt_read(struct knote *kn, long hint);
122 static int fuse_device_filt_write(struct knote *kn, long hint);
123 static void fuse_device_filt_detach(struct knote *kn);
124 
125 struct filterops fuse_device_rfiltops = {
126 	.f_isfd = 1,
127 	.f_detach = fuse_device_filt_detach,
128 	.f_event = fuse_device_filt_read,
129 };
130 
131 struct filterops fuse_device_wfiltops = {
132 	.f_isfd = 1,
133 	.f_event = fuse_device_filt_write,
134 };
135 
136 /****************************
137  *
138  * >>> Fuse device op defs
139  *
140  ****************************/
141 
142 static void
143 fdata_dtor(void *arg)
144 {
145 	struct fuse_data *fdata;
146 	struct fuse_ticket *tick;
147 
148 	fdata = arg;
149 	if (fdata == NULL)
150 		return;
151 
152 	fdata_set_dead(fdata);
153 
154 	FUSE_LOCK();
155 	fuse_lck_mtx_lock(fdata->aw_mtx);
156 	/* wakup poll()ers */
157 	selwakeuppri(&fdata->ks_rsel, PZERO + 1);
158 	/* Don't let syscall handlers wait in vain */
159 	while ((tick = fuse_aw_pop(fdata))) {
160 		fuse_lck_mtx_lock(tick->tk_aw_mtx);
161 		fticket_set_answered(tick);
162 		tick->tk_aw_errno = ENOTCONN;
163 		wakeup(tick);
164 		fuse_lck_mtx_unlock(tick->tk_aw_mtx);
165 		FUSE_ASSERT_AW_DONE(tick);
166 		fuse_ticket_drop(tick);
167 	}
168 	fuse_lck_mtx_unlock(fdata->aw_mtx);
169 
170 	/* Cleanup unsent operations */
171 	fuse_lck_mtx_lock(fdata->ms_mtx);
172 	while ((tick = fuse_ms_pop(fdata))) {
173 		fuse_ticket_drop(tick);
174 	}
175 	fuse_lck_mtx_unlock(fdata->ms_mtx);
176 	FUSE_UNLOCK();
177 
178 	fdata_trydestroy(fdata);
179 }
180 
181 static int
182 fuse_device_filter(struct cdev *dev, struct knote *kn)
183 {
184 	struct fuse_data *data;
185 	int error;
186 
187 	error = devfs_get_cdevpriv((void **)&data);
188 
189 	if (error == 0 && kn->kn_filter == EVFILT_READ) {
190 		kn->kn_fop = &fuse_device_rfiltops;
191 		kn->kn_hook = data;
192 		knlist_add(&data->ks_rsel.si_note, kn, 0);
193 		error = 0;
194 	} else if (error == 0 && kn->kn_filter == EVFILT_WRITE) {
195 		kn->kn_fop = &fuse_device_wfiltops;
196 		error = 0;
197 	} else if (error == 0) {
198 		error = EINVAL;
199 		kn->kn_data = error;
200 	}
201 
202 	return (error);
203 }
204 
205 static void
206 fuse_device_filt_detach(struct knote *kn)
207 {
208 	struct fuse_data *data;
209 
210 	data = (struct fuse_data*)kn->kn_hook;
211 	MPASS(data != NULL);
212 	knlist_remove(&data->ks_rsel.si_note, kn, 0);
213 	kn->kn_hook = NULL;
214 }
215 
216 static int
217 fuse_device_filt_read(struct knote *kn, long hint)
218 {
219 	struct fuse_data *data;
220 	int ready;
221 
222 	data = (struct fuse_data*)kn->kn_hook;
223 	MPASS(data != NULL);
224 
225 	mtx_assert(&data->ms_mtx, MA_OWNED);
226 	if (fdata_get_dead(data)) {
227 		kn->kn_flags |= EV_EOF;
228 		kn->kn_fflags = ENODEV;
229 		kn->kn_data = 1;
230 		ready = 1;
231 	} else if (STAILQ_FIRST(&data->ms_head)) {
232 		MPASS(data->ms_count >= 1);
233 		kn->kn_data = data->ms_count;
234 		ready = 1;
235 	} else {
236 		ready = 0;
237 	}
238 
239 	return (ready);
240 }
241 
242 static int
243 fuse_device_filt_write(struct knote *kn, long hint)
244 {
245 
246 	kn->kn_data = 0;
247 
248 	/* The device is always ready to write, so we return 1*/
249 	return (1);
250 }
251 
252 /*
253  * Resources are set up on a per-open basis
254  */
255 static int
256 fuse_device_open(struct cdev *dev, int oflags, int devtype, struct thread *td)
257 {
258 	struct fuse_data *fdata;
259 	int error;
260 
261 	SDT_PROBE2(fusefs, , device, trace, 1, "device open");
262 
263 	fdata = fdata_alloc(dev, td->td_ucred);
264 	error = devfs_set_cdevpriv(fdata, fdata_dtor);
265 	if (error != 0)
266 		fdata_trydestroy(fdata);
267 	else
268 		SDT_PROBE2(fusefs, , device, trace, 1, "device open success");
269 	return (error);
270 }
271 
272 int
273 fuse_device_poll(struct cdev *dev, int events, struct thread *td)
274 {
275 	struct fuse_data *data;
276 	int error, revents = 0;
277 
278 	error = devfs_get_cdevpriv((void **)&data);
279 	if (error != 0)
280 		return (events &
281 		    (POLLHUP|POLLIN|POLLRDNORM|POLLOUT|POLLWRNORM));
282 
283 	if (events & (POLLIN | POLLRDNORM)) {
284 		fuse_lck_mtx_lock(data->ms_mtx);
285 		if (fdata_get_dead(data) || STAILQ_FIRST(&data->ms_head))
286 			revents |= events & (POLLIN | POLLRDNORM);
287 		else
288 			selrecord(td, &data->ks_rsel);
289 		fuse_lck_mtx_unlock(data->ms_mtx);
290 	}
291 	if (events & (POLLOUT | POLLWRNORM)) {
292 		revents |= events & (POLLOUT | POLLWRNORM);
293 	}
294 	return (revents);
295 }
296 
297 /*
298  * fuse_device_read hangs on the queue of VFS messages.
299  * When it's notified that there is a new one, it picks that and
300  * passes up to the daemon
301  */
302 int
303 fuse_device_read(struct cdev *dev, struct uio *uio, int ioflag)
304 {
305 	int err;
306 	struct fuse_data *data;
307 	struct fuse_ticket *tick;
308 	void *buf;
309 	int buflen;
310 
311 	SDT_PROBE2(fusefs, , device, trace, 1, "fuse device read");
312 
313 	err = devfs_get_cdevpriv((void **)&data);
314 	if (err != 0)
315 		return (err);
316 
317 	fuse_lck_mtx_lock(data->ms_mtx);
318 again:
319 	if (fdata_get_dead(data)) {
320 		SDT_PROBE2(fusefs, , device, trace, 2,
321 			"we know early on that reader should be kicked so we "
322 			"don't wait for news");
323 		fuse_lck_mtx_unlock(data->ms_mtx);
324 		return (ENODEV);
325 	}
326 	if (!(tick = fuse_ms_pop(data))) {
327 		/* check if we may block */
328 		if (ioflag & O_NONBLOCK) {
329 			/* get outa here soon */
330 			fuse_lck_mtx_unlock(data->ms_mtx);
331 			return (EAGAIN);
332 		} else {
333 			err = msleep(data, &data->ms_mtx, PCATCH, "fu_msg", 0);
334 			if (err != 0) {
335 				fuse_lck_mtx_unlock(data->ms_mtx);
336 				return (fdata_get_dead(data) ? ENODEV : err);
337 			}
338 			tick = fuse_ms_pop(data);
339 		}
340 	}
341 	if (!tick) {
342 		/*
343 		 * We can get here if fuse daemon suddenly terminates,
344 		 * eg, by being hit by a SIGKILL
345 		 * -- and some other cases, too, tho not totally clear, when
346 		 * (cv_signal/wakeup_one signals the whole process ?)
347 		 */
348 		SDT_PROBE2(fusefs, , device, trace, 1, "no message on thread");
349 		goto again;
350 	}
351 	fuse_lck_mtx_unlock(data->ms_mtx);
352 
353 	if (fdata_get_dead(data)) {
354 		/*
355 		 * somebody somewhere -- eg., umount routine --
356 		 * wants this liaison finished off
357 		 */
358 		SDT_PROBE2(fusefs, , device, trace, 2,
359 			"reader is to be sacked");
360 		if (tick) {
361 			SDT_PROBE2(fusefs, , device, trace, 2, "weird -- "
362 				"\"kick\" is set tho there is message");
363 			FUSE_ASSERT_MS_DONE(tick);
364 			fuse_ticket_drop(tick);
365 		}
366 		return (ENODEV);	/* This should make the daemon get off
367 					 * of us */
368 	}
369 	SDT_PROBE2(fusefs, , device, trace, 1,
370 		"fuse device read message successfully");
371 
372 	buf = tick->tk_ms_fiov.base;
373 	buflen = tick->tk_ms_fiov.len;
374 
375 	/*
376 	 * Why not ban mercilessly stupid daemons who can't keep up
377 	 * with us? (There is no much use of a partial read here...)
378 	 */
379 	/*
380 	 * XXX note that in such cases Linux FUSE throws EIO at the
381 	 * syscall invoker and stands back to the message queue. The
382 	 * rationale should be made clear (and possibly adopt that
383 	 * behaviour). Keeping the current scheme at least makes
384 	 * fallacy as loud as possible...
385 	 */
386 	if (uio->uio_resid < buflen) {
387 		fdata_set_dead(data);
388 		SDT_PROBE2(fusefs, , device, trace, 2,
389 		    "daemon is stupid, kick it off...");
390 		err = ENODEV;
391 	} else {
392 		err = uiomove(buf, buflen, uio);
393 	}
394 
395 	FUSE_ASSERT_MS_DONE(tick);
396 	fuse_ticket_drop(tick);
397 
398 	return (err);
399 }
400 
401 static inline int
402 fuse_ohead_audit(struct fuse_out_header *ohead, struct uio *uio)
403 {
404 	if (uio->uio_resid + sizeof(struct fuse_out_header) != ohead->len) {
405 		SDT_PROBE2(fusefs, , device, trace, 1,
406 			"Format error: body size "
407 			"differs from size claimed by header");
408 		return (EINVAL);
409 	}
410 	if (uio->uio_resid && ohead->unique != 0 && ohead->error) {
411 		SDT_PROBE2(fusefs, , device, trace, 1,
412 			"Format error: non zero error but message had a body");
413 		return (EINVAL);
414 	}
415 
416 	return (0);
417 }
418 
419 SDT_PROBE_DEFINE1(fusefs, , device, fuse_device_write_notify,
420 	"struct fuse_out_header*");
421 SDT_PROBE_DEFINE1(fusefs, , device, fuse_device_write_missing_ticket,
422 	"uint64_t");
423 SDT_PROBE_DEFINE1(fusefs, , device, fuse_device_write_found,
424 	"struct fuse_ticket*");
425 /*
426  * fuse_device_write first reads the header sent by the daemon.
427  * If that's OK, looks up ticket/callback node by the unique id seen in header.
428  * If the callback node contains a handler function, the uio is passed over
429  * that.
430  */
431 static int
432 fuse_device_write(struct cdev *dev, struct uio *uio, int ioflag)
433 {
434 	struct fuse_out_header ohead;
435 	int err = 0;
436 	struct fuse_data *data;
437 	struct mount *mp;
438 	struct fuse_ticket *tick, *itick, *x_tick;
439 	int found = 0;
440 
441 	err = devfs_get_cdevpriv((void **)&data);
442 	if (err != 0)
443 		return (err);
444 	mp = data->mp;
445 
446 	if (uio->uio_resid < sizeof(struct fuse_out_header)) {
447 		SDT_PROBE2(fusefs, , device, trace, 1,
448 			"fuse_device_write got less than a header!");
449 		fdata_set_dead(data);
450 		return (EINVAL);
451 	}
452 	if ((err = uiomove(&ohead, sizeof(struct fuse_out_header), uio)) != 0)
453 		return (err);
454 
455 	if (data->linux_errnos != 0 && ohead.error != 0) {
456 		err = -ohead.error;
457 		if (err < 0 || err >= nitems(linux_to_bsd_errtbl))
458 			return (EINVAL);
459 
460 		/* '-', because it will get flipped again below */
461 		ohead.error = -linux_to_bsd_errtbl[err];
462 	}
463 
464 	/*
465 	 * We check header information (which is redundant) and compare it
466 	 * with what we see. If we see some inconsistency we discard the
467 	 * whole answer and proceed on as if it had never existed. In
468 	 * particular, no pretender will be woken up, regardless the
469 	 * "unique" value in the header.
470 	 */
471 	if ((err = fuse_ohead_audit(&ohead, uio))) {
472 		fdata_set_dead(data);
473 		return (err);
474 	}
475 	/* Pass stuff over to callback if there is one installed */
476 
477 	/* Looking for ticket with the unique id of header */
478 	fuse_lck_mtx_lock(data->aw_mtx);
479 	TAILQ_FOREACH_SAFE(tick, &data->aw_head, tk_aw_link,
480 	    x_tick) {
481 		if (tick->tk_unique == ohead.unique) {
482 			SDT_PROBE1(fusefs, , device, fuse_device_write_found,
483 				tick);
484 			found = 1;
485 			fuse_aw_remove(tick);
486 			break;
487 		}
488 	}
489 	if (found && tick->irq_unique > 0) {
490 		/*
491 		 * Discard the FUSE_INTERRUPT ticket that tried to interrupt
492 		 * this operation
493 		 */
494 		TAILQ_FOREACH_SAFE(itick, &data->aw_head, tk_aw_link,
495 		    x_tick) {
496 			if (itick->tk_unique == tick->irq_unique) {
497 				fuse_aw_remove(itick);
498 				fuse_ticket_drop(itick);
499 				break;
500 			}
501 		}
502 		tick->irq_unique = 0;
503 	}
504 	fuse_lck_mtx_unlock(data->aw_mtx);
505 
506 	if (found) {
507 		if (tick->tk_aw_handler) {
508 			/*
509 			 * We found a callback with proper handler. In this
510 			 * case the out header will be 0wnd by the callback,
511 			 * so the fun of freeing that is left for her.
512 			 * (Then, by all chance, she'll just get that's done
513 			 * via ticket_drop(), so no manual mucking
514 			 * around...)
515 			 */
516 			SDT_PROBE2(fusefs, , device, trace, 1,
517 				"pass ticket to a callback");
518 			/* Sanitize the linuxism of negative errnos */
519 			ohead.error *= -1;
520 			memcpy(&tick->tk_aw_ohead, &ohead, sizeof(ohead));
521 			err = tick->tk_aw_handler(tick, uio);
522 		} else {
523 			/* pretender doesn't wanna do anything with answer */
524 			SDT_PROBE2(fusefs, , device, trace, 1,
525 				"stuff devalidated, so we drop it");
526 		}
527 
528 		/*
529 		 * As aw_mtx was not held during the callback execution the
530 		 * ticket may have been inserted again.  However, this is safe
531 		 * because fuse_ticket_drop() will deal with refcount anyway.
532 		 */
533 		fuse_ticket_drop(tick);
534 	} else if (ohead.unique == 0){
535 		/* unique == 0 means asynchronous notification */
536 		SDT_PROBE1(fusefs, , device, fuse_device_write_notify, &ohead);
537 		switch (ohead.error) {
538 		case FUSE_NOTIFY_INVAL_ENTRY:
539 			err = fuse_internal_invalidate_entry(mp, uio);
540 			break;
541 		case FUSE_NOTIFY_INVAL_INODE:
542 			err = fuse_internal_invalidate_inode(mp, uio);
543 			break;
544 		case FUSE_NOTIFY_RETRIEVE:
545 		case FUSE_NOTIFY_STORE:
546 			/*
547 			 * Unimplemented.  I don't know of any file systems
548 			 * that use them, and the protocol isn't sound anyway,
549 			 * since the notification messages don't include the
550 			 * inode's generation number.  Without that, it's
551 			 * possible to manipulate the cache of the wrong vnode.
552 			 * Finally, it's not defined what this message should
553 			 * do for a file with dirty cache.
554 			 */
555 		case FUSE_NOTIFY_POLL:
556 			/* Unimplemented.  See comments in fuse_vnops */
557 		default:
558 			/* Not implemented */
559 			err = ENOSYS;
560 		}
561 	} else {
562 		/* no callback at all! */
563 		SDT_PROBE1(fusefs, , device, fuse_device_write_missing_ticket,
564 			ohead.unique);
565 		if (ohead.error == -EAGAIN) {
566 			/*
567 			 * This was probably a response to a FUSE_INTERRUPT
568 			 * operation whose original operation is already
569 			 * complete.  We can't store FUSE_INTERRUPT tickets
570 			 * indefinitely because their responses are optional.
571 			 * So we delete them when the original operation
572 			 * completes.  And sadly the fuse_header_out doesn't
573 			 * identify the opcode, so we have to guess.
574 			 */
575 			err = 0;
576 		} else {
577 			err = EINVAL;
578 		}
579 	}
580 
581 	return (err);
582 }
583 
584 int
585 fuse_device_init(void)
586 {
587 
588 	fuse_dev = make_dev(&fuse_device_cdevsw, 0, UID_ROOT, GID_OPERATOR,
589 	    S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH, "fuse");
590 	if (fuse_dev == NULL)
591 		return (ENOMEM);
592 	return (0);
593 }
594 
595 void
596 fuse_device_destroy(void)
597 {
598 
599 	MPASS(fuse_dev != NULL);
600 	destroy_dev(fuse_dev);
601 }
602