master
c 1,649 lines 48 KB
Raw
1 /*
2 * Present a block device as a raw image through FUSE
3 *
4 * Copyright (c) 2020, 2025 Hanna Czenczek <hreitz@redhat.com>
5 *
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; under version 2 or later of the License.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License
16 * along with this program; if not, see <http://www.gnu.org/licenses/>.
17 */
18
19 #define FUSE_USE_VERSION 31
20
21 #include "qemu/osdep.h"
22 #include "qemu/memalign.h"
23 #include "qemu/aio.h"
24 #include "block/block_int-common.h"
25 #include "block/export.h"
26 #include "block/fuse.h"
27 #include "block/qapi.h"
28 #include "qapi/error.h"
29 #include "qapi/qapi-commands-block.h"
30 #include "qemu/coroutine.h"
31 #include "qemu/error-report.h"
32 #include "qemu/main-loop.h"
33 #include "system/block-backend.h"
34 #include "system/iothread.h"
35
36 #include <fuse.h>
37 #include <fuse_lowlevel.h>
38
39 #include "standard-headers/linux/fuse.h"
40 #include <sys/ioctl.h>
41
42 #if defined(CONFIG_FALLOCATE_ZERO_RANGE)
43 #include <linux/falloc.h>
44 #endif
45
46 #ifdef __linux__
47 #include <linux/fs.h>
48 #endif
49
50 /* Prevent overly long bounce buffer allocations */
51 #define FUSE_MAX_READ_BYTES (MIN(BDRV_REQUEST_MAX_BYTES, 1 * 1024 * 1024))
52 #define FUSE_MAX_WRITE_BYTES (64 * 1024)
53
54 typedef struct FuseRequestInHeader {
55 struct fuse_in_header common;
56 /* All supported requests */
57 union {
58 /*
59 * When using_old_fuse_init_in() is true, then the smaller older struct
60 * is used by the kernel. The flags2 member and other new members must
61 * be treated as absent then.
62 */
63 struct fuse_init_in init;
64 struct fuse_open_in open;
65 struct fuse_setattr_in setattr;
66 struct fuse_read_in read;
67 struct fuse_write_in write;
68 struct fuse_fallocate_in fallocate;
69 #ifdef CONFIG_FUSE_LSEEK
70 struct fuse_lseek_in lseek;
71 #endif
72 };
73 } FuseRequestInHeader;
74
75 typedef struct FuseRequestOutHeader {
76 struct fuse_out_header common;
77 /* All supported requests */
78 union {
79 struct fuse_init_out init;
80 struct fuse_statfs_out statfs;
81 struct fuse_open_out open;
82 struct fuse_attr_out attr;
83 struct fuse_write_out write;
84 #ifdef CONFIG_FUSE_LSEEK
85 struct fuse_lseek_out lseek;
86 #endif
87 };
88 } FuseRequestOutHeader;
89
90 typedef union FuseRequestInHeaderBuf {
91 struct FuseRequestInHeader structured;
92 struct {
93 /*
94 * Part of the request header that is filled for write requests
95 * (Needed because we want the data to go into a different buffer, to
96 * avoid having to use a bounce buffer)
97 */
98 char head[sizeof(struct fuse_in_header) +
99 sizeof(struct fuse_write_in)];
100 /*
101 * Rest of the request header for requests that have a longer header
102 * than write requests
103 */
104 char tail[sizeof(FuseRequestInHeader) -
105 (sizeof(struct fuse_in_header) +
106 sizeof(struct fuse_write_in))];
107 };
108 } FuseRequestInHeaderBuf;
109
110 QEMU_BUILD_BUG_ON(sizeof(FuseRequestInHeaderBuf) !=
111 sizeof(FuseRequestInHeader));
112 QEMU_BUILD_BUG_ON(sizeof(((FuseRequestInHeaderBuf *)0)->head) +
113 sizeof(((FuseRequestInHeaderBuf *)0)->tail) !=
114 sizeof(FuseRequestInHeader));
115
116 typedef struct FuseExport FuseExport;
117
118 /*
119 * One FUSE "queue", representing one FUSE FD from which requests are fetched
120 * and processed. Each queue is tied to an AioContext.
121 */
122 typedef struct FuseQueue {
123 FuseExport *exp;
124
125 AioContext *ctx;
126 int fuse_fd;
127
128 /*
129 * Cached buffer to receive the data of WRITE requests. Cached because:
130 * To read requests, we put a FuseRequestInHeaderBuf (FRIHB) object on the
131 * stack, and a (WRITE data) buffer on the heap. We pass FRIHB.head and the
132 * data buffer to readv(). This way, for WRITE requests, we get exactly
133 * their data in the data buffer and can avoid bounce buffering.
134 * However, for non-WRITE requests, some of the header may end up in the
135 * data buffer, so we will need to copy that back into the FRIHB object, and
136 * then we don't need the heap buffer anymore. That is why we cache it, so
137 * we can trivially reuse it between non-WRITE requests.
138 *
139 * Note that these data buffers and thus req_write_data_cached are allocated
140 * via blk_blockalign() and thus need to be freed via qemu_vfree().
141 */
142 void *req_write_data_cached;
143 } FuseQueue;
144
145 struct FuseExport {
146 BlockExport common;
147
148 struct fuse_session *fuse_session;
149 unsigned int in_flight; /* atomic */
150 bool mounted, fd_handler_set_up;
151
152 /*
153 * Set when there was an unrecoverable error and no requests should be read
154 * from the device anymore (basically only in case of something we would
155 * consider a kernel bug). Access atomically.
156 */
157 bool halted;
158
159 int num_queues;
160 FuseQueue *queues;
161 /*
162 * True if this export should follow the generic export's AioContext.
163 * Will be false if the queues' AioContexts have been explicitly set by the
164 * user, i.e. are expected to stay in those contexts.
165 * (I.e. is always false if there is more than one queue.)
166 */
167 bool follow_aio_context;
168
169 char *mountpoint;
170 bool writable;
171 bool growable;
172 /* Whether allow_other was used as a mount option or not */
173 bool allow_other;
174
175 /* All atomic */
176 mode_t st_mode;
177 uid_t st_uid;
178 gid_t st_gid;
179 };
180
181 /*
182 * Verify that the size of FuseRequestInHeaderBuf.head plus the data
183 * buffer are big enough to be accepted by the FUSE kernel driver.
184 */
185 QEMU_BUILD_BUG_ON(sizeof(((FuseRequestInHeaderBuf *)0)->head) +
186 FUSE_MAX_WRITE_BYTES <
187 FUSE_MIN_READ_BUFFER);
188
189 static GHashTable *exports;
190
191 static void fuse_export_shutdown(BlockExport *exp);
192 static void fuse_export_delete(BlockExport *exp);
193 static void fuse_export_halt(FuseExport *exp);
194
195 static void init_exports_table(void);
196
197 static int mount_fuse_export(FuseExport *exp, Error **errp);
198 static int clone_fuse_fd(int fd, Error **errp);
199
200 static bool is_regular_file(const char *path, Error **errp);
201
202 static void read_from_fuse_fd(void *opaque);
203 static void coroutine_fn
204 fuse_co_process_request(FuseQueue *q, const FuseRequestInHeader *in_hdr,
205 const void *data_buffer);
206 static int fuse_write_err(int fd, const struct fuse_in_header *in_hdr, int err);
207
208 static void fuse_inc_in_flight(FuseExport *exp)
209 {
210 if (qatomic_fetch_inc(&exp->in_flight) == 0) {
211 /* Prevent export from being deleted */
212 blk_exp_ref(&exp->common);
213 }
214 }
215
216 static void fuse_dec_in_flight(FuseExport *exp)
217 {
218 if (qatomic_fetch_dec(&exp->in_flight) == 1) {
219 /* Wake AIO_WAIT_WHILE() */
220 aio_wait_kick();
221
222 /* Now the export can be deleted */
223 blk_exp_unref(&exp->common);
224 }
225 }
226
227 /**
228 * Attach FUSE FD read handler.
229 */
230 static void fuse_attach_handlers(FuseExport *exp)
231 {
232 if (qatomic_read(&exp->halted)) {
233 return;
234 }
235
236 for (int i = 0; i < exp->num_queues; i++) {
237 aio_set_fd_handler(exp->queues[i].ctx, exp->queues[i].fuse_fd,
238 read_from_fuse_fd, NULL, NULL, NULL,
239 &exp->queues[i]);
240 }
241 exp->fd_handler_set_up = true;
242 }
243
244 /**
245 * Detach FUSE FD read handler.
246 */
247 static void fuse_detach_handlers(FuseExport *exp)
248 {
249 for (int i = 0; i < exp->num_queues; i++) {
250 aio_set_fd_handler(exp->queues[i].ctx, exp->queues[i].fuse_fd,
251 NULL, NULL, NULL, NULL, NULL);
252 }
253 exp->fd_handler_set_up = false;
254 }
255
256 static void fuse_export_drained_begin(void *opaque)
257 {
258 fuse_detach_handlers(opaque);
259 }
260
261 static void fuse_export_drained_end(void *opaque)
262 {
263 FuseExport *exp = opaque;
264
265 /* Refresh AioContext in case it changed */
266 exp->common.ctx = blk_get_aio_context(exp->common.blk);
267 if (exp->follow_aio_context) {
268 assert(exp->num_queues == 1);
269 exp->queues[0].ctx = exp->common.ctx;
270 }
271
272 fuse_attach_handlers(exp);
273 }
274
275 static bool fuse_export_drained_poll(void *opaque)
276 {
277 FuseExport *exp = opaque;
278
279 return qatomic_read(&exp->in_flight) > 0;
280 }
281
282 static const BlockDevOps fuse_export_blk_dev_ops = {
283 .drained_begin = fuse_export_drained_begin,
284 .drained_end = fuse_export_drained_end,
285 .drained_poll = fuse_export_drained_poll,
286 };
287
288 static int fuse_export_create(BlockExport *blk_exp,
289 BlockExportOptions *blk_exp_args,
290 AioContext *const *multithread,
291 size_t mt_count,
292 Error **errp)
293 {
294 ERRP_GUARD(); /* ensure clean-up even with error_fatal */
295 FuseExport *exp = container_of(blk_exp, FuseExport, common);
296 BlockExportOptionsFuse *args = &blk_exp_args->u.fuse;
297 uint32_t st_mode;
298 int ret;
299
300 assert(blk_exp_args->type == BLOCK_EXPORT_TYPE_FUSE);
301
302 if (multithread) {
303 /* Guaranteed by common export code */
304 assert(mt_count >= 1);
305
306 exp->follow_aio_context = false;
307 exp->num_queues = mt_count;
308 exp->queues = g_new(FuseQueue, mt_count);
309
310 for (size_t i = 0; i < mt_count; i++) {
311 exp->queues[i] = (FuseQueue) {
312 .exp = exp,
313 .ctx = multithread[i],
314 .fuse_fd = -1,
315 };
316 }
317 } else {
318 /* Guaranteed by common export code */
319 assert(mt_count == 0);
320
321 exp->follow_aio_context = true;
322 exp->num_queues = 1;
323 exp->queues = g_new(FuseQueue, 1);
324 exp->queues[0] = (FuseQueue) {
325 .exp = exp,
326 .ctx = exp->common.ctx,
327 .fuse_fd = -1,
328 };
329 }
330
331 /* For growable and writable exports, take the RESIZE permission */
332 if (args->growable || blk_exp_args->writable) {
333 uint64_t blk_perm, blk_shared_perm;
334
335 blk_get_perm(exp->common.blk, &blk_perm, &blk_shared_perm);
336
337 ret = blk_set_perm(exp->common.blk, blk_perm | BLK_PERM_RESIZE,
338 blk_shared_perm, errp);
339 if (ret < 0) {
340 goto fail;
341 }
342 }
343
344 blk_set_dev_ops(exp->common.blk, &fuse_export_blk_dev_ops, exp);
345
346 /*
347 * We handle draining ourselves using an in-flight counter and by disabling
348 * the FUSE fd handler. Do not queue BlockBackend requests, they need to
349 * complete so the in-flight counter reaches zero.
350 */
351 blk_set_disable_request_queuing(exp->common.blk, true);
352
353 init_exports_table();
354
355 /*
356 * It is important to do this check before calling is_regular_file() --
357 * that function will do a stat(), which we would have to handle if we
358 * already exported something on @mountpoint. But we cannot, because
359 * we are currently caught up here.
360 * (Note that ideally we would want to resolve relative paths here,
361 * but bdrv_make_absolute_filename() might do the wrong thing for
362 * paths that contain colons, and realpath() would resolve symlinks,
363 * which we do not want: The mount point is not going to be the
364 * symlink's destination, but the link itself.)
365 * So this will not catch all potential clashes, but hopefully at
366 * least the most common one of specifying exactly the same path
367 * string twice.
368 */
369 if (g_hash_table_contains(exports, args->mountpoint)) {
370 error_setg(errp, "There already is a FUSE export on '%s'",
371 args->mountpoint);
372 ret = -EEXIST;
373 goto fail;
374 }
375
376 if (!is_regular_file(args->mountpoint, errp)) {
377 ret = -EINVAL;
378 goto fail;
379 }
380
381 exp->mountpoint = g_strdup(args->mountpoint);
382 exp->writable = blk_exp_args->writable;
383 exp->growable = args->growable;
384
385 /* set default */
386 if (!args->has_allow_other) {
387 args->allow_other = FUSE_EXPORT_ALLOW_OTHER_AUTO;
388 }
389
390 st_mode = S_IFREG | S_IRUSR;
391 if (exp->writable) {
392 st_mode |= S_IWUSR;
393 }
394 qatomic_set(&exp->st_mode, st_mode);
395 qatomic_set(&exp->st_uid, getuid());
396 qatomic_set(&exp->st_gid, getgid());
397
398 if (args->allow_other == FUSE_EXPORT_ALLOW_OTHER_AUTO) {
399 /* Try allow_other == true first, ignore errors */
400 exp->allow_other = true;
401 ret = mount_fuse_export(exp, NULL);
402 if (ret < 0) {
403 exp->allow_other = false;
404 ret = mount_fuse_export(exp, errp);
405 }
406 } else {
407 exp->allow_other = args->allow_other == FUSE_EXPORT_ALLOW_OTHER_ON;
408 ret = mount_fuse_export(exp, errp);
409 }
410 if (ret < 0) {
411 goto fail;
412 }
413
414 g_hash_table_insert(exports, g_strdup(exp->mountpoint), NULL);
415
416 assert(exp->num_queues >= 1);
417 exp->queues[0].fuse_fd = fuse_session_fd(exp->fuse_session);
418 ret = qemu_fcntl_addfl(exp->queues[0].fuse_fd, O_NONBLOCK);
419 if (ret < 0) {
420 error_setg_errno(errp, -ret, "Failed to make FUSE FD non-blocking");
421 goto fail;
422 }
423
424 for (int i = 1; i < exp->num_queues; i++) {
425 int fd = clone_fuse_fd(exp->queues[0].fuse_fd, errp);
426 if (fd < 0) {
427 ret = fd;
428 goto fail;
429 }
430 exp->queues[i].fuse_fd = fd;
431 }
432
433 fuse_attach_handlers(exp);
434 return 0;
435
436 fail:
437 fuse_export_shutdown(blk_exp);
438 fuse_export_delete(blk_exp);
439 return ret;
440 }
441
442 /**
443 * Allocates the global @exports hash table.
444 */
445 static void init_exports_table(void)
446 {
447 if (exports) {
448 return;
449 }
450
451 exports = g_hash_table_new_full(g_str_hash, g_str_equal, g_free, NULL);
452 }
453
454 /**
455 * Create exp->fuse_session and mount it. Expects exp->mountpoint,
456 * exp->writable, and exp->allow_other to be set as intended for the mount.
457 */
458 static int mount_fuse_export(FuseExport *exp, Error **errp)
459 {
460 const char *fuse_argv[4];
461 char *mount_opts;
462 struct fuse_args fuse_args;
463 int ret;
464 /*
465 * We just create the session for mounting/unmounting, no need to provide
466 * any operations. However, since libfuse commit 52a633a5d, we have to
467 * provide some op struct and cannot just pass NULL (even though the commit
468 * message ("allow passing ops as NULL") seems to imply the exact opposite,
469 * as does the comment added to fuse_session_new_fn() ("To create a no-op
470 * session just for mounting pass op as NULL.").
471 * This is how said libfuse commit implements a no-op session internally, so
472 * do it the same way.
473 */
474 static const struct fuse_lowlevel_ops null_ops = { 0 };
475
476 /*
477 * Note that these mount options differ from what we would pass to a direct
478 * mount() call:
479 * - nosuid, nodev, and noatime are not understood by the kernel; libfuse
480 * uses those options to construct the mount flags (MS_*)
481 * - The FUSE kernel driver requires additional options (fd, rootmode,
482 * user_id, group_id); these will be set by libfuse.
483 * Note that max_read is set here, while max_write is set via the FUSE INIT
484 * operation.
485 */
486 mount_opts = g_strdup_printf("%s,nosuid,nodev,noatime,max_read=%zu,"
487 "default_permissions%s",
488 exp->writable ? "rw" : "ro",
489 FUSE_MAX_READ_BYTES,
490 exp->allow_other ? ",allow_other" : "");
491
492 fuse_argv[0] = ""; /* Dummy program name */
493 fuse_argv[1] = "-o";
494 fuse_argv[2] = mount_opts;
495 fuse_argv[3] = NULL;
496 fuse_args = (struct fuse_args)FUSE_ARGS_INIT(3, (char **)fuse_argv);
497
498 exp->fuse_session = fuse_session_new(&fuse_args, &null_ops,
499 sizeof(null_ops), NULL);
500 g_free(mount_opts);
501 if (!exp->fuse_session) {
502 error_setg(errp, "Failed to set up FUSE session");
503 return -EIO;
504 }
505
506 ret = fuse_session_mount(exp->fuse_session, exp->mountpoint);
507 if (ret < 0) {
508 error_setg(errp, "Failed to mount FUSE session to export");
509 ret = -EIO;
510 goto fail;
511 }
512 exp->mounted = true;
513
514 return 0;
515
516 fail:
517 fuse_session_destroy(exp->fuse_session);
518 exp->fuse_session = NULL;
519 return ret;
520 }
521
522 /**
523 * Allocate a buffer to receive WRITE data, or take the cached one.
524 */
525 static void *get_write_data_buffer(FuseQueue *q)
526 {
527 if (q->req_write_data_cached) {
528 void *cached = q->req_write_data_cached;
529 q->req_write_data_cached = NULL;
530 return cached;
531 } else {
532 return blk_blockalign(q->exp->common.blk, FUSE_MAX_WRITE_BYTES);
533 }
534 }
535
536 /**
537 * Release a WRITE data buffer, possibly reusing it for a subsequent request.
538 */
539 static void release_write_data_buffer(FuseQueue *q, void **buffer)
540 {
541 if (!*buffer) {
542 return;
543 }
544
545 if (!q->req_write_data_cached) {
546 q->req_write_data_cached = *buffer;
547 } else {
548 qemu_vfree(*buffer);
549 }
550 *buffer = NULL;
551 }
552
553 /**
554 * Return the length of the specific operation's own in_header.
555 * Return -ENOSYS if the operation is not supported.
556 */
557 static ssize_t req_op_hdr_len(const FuseRequestInHeader *in_hdr)
558 {
559 switch (in_hdr->common.opcode) {
560 case FUSE_INIT:
561 return sizeof(in_hdr->init);
562 case FUSE_OPEN:
563 return sizeof(in_hdr->open);
564 case FUSE_SETATTR:
565 return sizeof(in_hdr->setattr);
566 case FUSE_READ:
567 return sizeof(in_hdr->read);
568 case FUSE_WRITE:
569 return sizeof(in_hdr->write);
570 case FUSE_FALLOCATE:
571 return sizeof(in_hdr->fallocate);
572 #ifdef CONFIG_FUSE_LSEEK
573 case FUSE_LSEEK:
574 return sizeof(in_hdr->lseek);
575 #endif
576 case FUSE_DESTROY:
577 case FUSE_STATFS:
578 case FUSE_RELEASE:
579 case FUSE_LOOKUP:
580 case FUSE_FORGET:
581 case FUSE_BATCH_FORGET:
582 case FUSE_GETATTR:
583 case FUSE_FSYNC:
584 case FUSE_FLUSH:
585 /* These requests don't have their own header or we don't care */
586 return 0;
587 default:
588 return -ENOSYS;
589 }
590 }
591
592 /**
593 * Clone the given /dev/fuse file descriptor, yielding a second FD from which
594 * requests can be pulled for the associated filesystem. Returns an FD on
595 * success, and -errno on error.
596 */
597 static int clone_fuse_fd(int fd, Error **errp)
598 {
599 uint32_t src_fd = fd;
600 int new_fd;
601 int ret;
602
603 /*
604 * The name "/dev/fuse" is fixed, see libfuse's lib/fuse_loop_mt.c
605 * (fuse_clone_chan()).
606 */
607 new_fd = open("/dev/fuse", O_RDWR | O_CLOEXEC | O_NONBLOCK);
608 if (new_fd < 0) {
609 ret = -errno;
610 error_setg_errno(errp, errno, "Failed to open /dev/fuse");
611 return ret;
612 }
613
614 ret = ioctl(new_fd, FUSE_DEV_IOC_CLONE, &src_fd);
615 if (ret < 0) {
616 ret = -errno;
617 error_setg_errno(errp, errno, "Failed to clone FUSE FD");
618 close(new_fd);
619 return ret;
620 }
621
622 return new_fd;
623 }
624
625 /**
626 * Check whether the smaller older fuse_init_in structure from before protocol
627 * version 7.36 is used. The flags2 member and other new members must be treated
628 * as absent then.
629 */
630 static bool using_old_fuse_init_in(const struct fuse_init_in *in)
631 {
632 return in->major < 7 || (in->major == 7 && in->minor < 36);
633 }
634
635 /**
636 * Try to read a single request from the FUSE FD.
637 * Takes a FuseQueue pointer in `opaque`.
638 *
639 * Assumes the export's in-flight counter has already been incremented.
640 *
641 * If a request is available, process it.
642 */
643 static void coroutine_fn co_read_from_fuse_fd(void *opaque)
644 {
645 FuseQueue *q = opaque;
646 int fuse_fd = q->fuse_fd;
647 FuseExport *exp = q->exp;
648 ssize_t ret;
649 FuseRequestInHeaderBuf in_hdr_buf;
650 const FuseRequestInHeader *in_hdr;
651 void *data_buffer = NULL;
652 struct iovec iov[2];
653 ssize_t op_hdr_len;
654
655 if (unlikely(qatomic_read(&exp->halted))) {
656 goto no_request;
657 }
658
659 data_buffer = get_write_data_buffer(q);
660
661 /* Construct the I/O vector to hold the FUSE request */
662 iov[0] = (struct iovec) { &in_hdr_buf.head, sizeof(in_hdr_buf.head) };
663 iov[1] = (struct iovec) { data_buffer, FUSE_MAX_WRITE_BYTES };
664 ret = RETRY_ON_EINTR(readv(fuse_fd, iov, ARRAY_SIZE(iov)));
665 if (ret < 0 && errno == EAGAIN) {
666 /* No request available */
667 goto no_request;
668 } else if (unlikely(ret < 0)) {
669 error_report("Failed to read from FUSE device: %s", strerror(errno));
670 goto no_request;
671 }
672
673 if (unlikely(ret < sizeof(in_hdr->common))) {
674 error_report("Incomplete read from FUSE device, expected at least %zu "
675 "bytes, read %zi bytes; cannot trust subsequent "
676 "requests, halting the export",
677 sizeof(in_hdr->common), ret);
678 fuse_export_halt(exp);
679 goto no_request;
680 }
681 in_hdr = &in_hdr_buf.structured;
682
683 if (unlikely(ret != in_hdr->common.len)) {
684 error_report("Number of bytes read from FUSE device does not match "
685 "request size, expected %" PRIu32 " bytes, read %zi "
686 "bytes; cannot trust subsequent requests, halting the "
687 "export",
688 in_hdr->common.len, ret);
689 fuse_export_halt(exp);
690 goto no_request;
691 }
692
693 op_hdr_len = req_op_hdr_len(in_hdr);
694 if (op_hdr_len < 0) {
695 fuse_write_err(fuse_fd, &in_hdr->common, op_hdr_len);
696 goto no_request;
697 }
698
699 /*
700 * If the request is of type FUSE_INIT, need to check the version to
701 * actually determine the length of the fuse_init_in structure used by the
702 * kernel. In protocol version 7.36, the structure was extended.
703 */
704 if (in_hdr->common.opcode == FUSE_INIT) {
705 /* Length of the fuse_init_in structure before 7.36. */
706 size_t old_init_hdr_len = 16;
707
708 /*
709 * Expect at least the size of the smaller older structure to ensure the
710 * version can be checked.
711 */
712 if (unlikely(ret < sizeof(in_hdr->common) + old_init_hdr_len)) {
713 error_report("FUSE_INIT request truncated, read only %zi bytes",
714 ret);
715 fuse_write_err(fuse_fd, &in_hdr->common, -EINVAL);
716 goto no_request;
717 }
718
719 if (using_old_fuse_init_in(&in_hdr->init)) {
720 op_hdr_len = old_init_hdr_len;
721 }
722 }
723
724 if (unlikely(ret < sizeof(in_hdr->common) + op_hdr_len)) {
725 error_report("FUSE request truncated, expected %zu bytes, read %zi "
726 "bytes",
727 sizeof(in_hdr->common) + op_hdr_len, ret);
728 fuse_write_err(fuse_fd, &in_hdr->common, -EINVAL);
729 goto no_request;
730 }
731
732 /*
733 * Only WRITE uses the write data buffer, so for non-WRITE requests longer
734 * than .head, we need to copy any data that spilled into data_buffer into
735 * .tail. Then we can release the write data buffer.
736 */
737 if (in_hdr->common.opcode != FUSE_WRITE) {
738 if (ret > sizeof(in_hdr_buf.head)) {
739 size_t len;
740 /* Limit size to prevent overflow */
741 len = MIN(ret - sizeof(in_hdr_buf.head), sizeof(in_hdr_buf.tail));
742 memcpy(in_hdr_buf.tail, data_buffer, len);
743 }
744
745 release_write_data_buffer(q, &data_buffer);
746 }
747
748 fuse_co_process_request(q, in_hdr, data_buffer);
749
750 no_request:
751 release_write_data_buffer(q, &data_buffer);
752 fuse_dec_in_flight(exp);
753 }
754
755 /**
756 * Try to read and process a single request from the FUSE FD.
757 * (To be used as a handler for when the FUSE FD becomes readable.)
758 * Takes a FuseQueue pointer in `opaque`.
759 */
760 static void read_from_fuse_fd(void *opaque)
761 {
762 FuseQueue *q = opaque;
763 Coroutine *co;
764
765 co = qemu_coroutine_create(co_read_from_fuse_fd, q);
766 /* Decremented by co_read_from_fuse_fd() */
767 fuse_inc_in_flight(q->exp);
768 qemu_coroutine_enter(co);
769 }
770
771 static void fuse_export_shutdown(BlockExport *blk_exp)
772 {
773 FuseExport *exp = container_of(blk_exp, FuseExport, common);
774
775 if (exp->fd_handler_set_up) {
776 fuse_detach_handlers(exp);
777 }
778
779 if (exp->mountpoint) {
780 /*
781 * Safe to drop now, because we will not handle any requests for this
782 * export anymore anyway (at least not from the main thread).
783 */
784 g_hash_table_remove(exports, exp->mountpoint);
785 }
786 }
787
788 static void fuse_export_delete(BlockExport *blk_exp)
789 {
790 FuseExport *exp = container_of(blk_exp, FuseExport, common);
791
792 for (int i = 0; i < exp->num_queues; i++) {
793 FuseQueue *q = &exp->queues[i];
794
795 /* Queue 0's FD belongs to the FUSE session */
796 if (i > 0 && q->fuse_fd >= 0) {
797 close(q->fuse_fd);
798 }
799 qemu_vfree(q->req_write_data_cached);
800 }
801 g_free(exp->queues);
802
803 if (exp->fuse_session) {
804 if (exp->mounted) {
805 fuse_session_unmount(exp->fuse_session);
806 }
807
808 fuse_session_destroy(exp->fuse_session);
809 }
810
811 g_free(exp->mountpoint);
812 }
813
814 /**
815 * Halt the export: Detach FD handlers, and set exp->halted to true, preventing
816 * fuse_attach_handlers() from re-attaching them, therefore stopping all further
817 * request processing.
818 *
819 * Call this function when an unrecoverable error happens that makes processing
820 * all future requests unreliable.
821 */
822 static void fuse_export_halt(FuseExport *exp)
823 {
824 qatomic_set(&exp->halted, true);
825 fuse_detach_handlers(exp);
826 }
827
828 /**
829 * Check whether @path points to a regular file. If not, put an
830 * appropriate message into *errp.
831 */
832 static bool is_regular_file(const char *path, Error **errp)
833 {
834 struct stat statbuf;
835 int ret;
836
837 ret = stat(path, &statbuf);
838 if (ret < 0) {
839 error_setg_errno(errp, errno, "Failed to stat '%s'", path);
840 return false;
841 }
842
843 if (!S_ISREG(statbuf.st_mode)) {
844 error_setg(errp, "'%s' is not a regular file", path);
845 return false;
846 }
847
848 return true;
849 }
850
851 /**
852 * Process FUSE INIT.
853 * Return the number of bytes written to *out on success, and -errno on error.
854 */
855 static ssize_t coroutine_fn GRAPH_RDLOCK
856 fuse_co_init(FuseExport *exp, struct fuse_init_out *out,
857 const struct fuse_init_in *in)
858 {
859 uint32_t supported_flags = FUSE_ASYNC_READ | FUSE_ASYNC_DIO;
860 uint32_t flags2 = 0;
861
862 if (!exp->growable) {
863 /*
864 * Back when libfuse was used, it would always set this flag and thus
865 * the kernel did not execute a truncate itself and passed along O_TRUNC
866 * to user space. Continue setting the flag for backwards compatibility
867 * when the export is not growable to avoid issues with O_TRUNC, i.e.
868 * blockdev-based exports running into ENOTSUP and file-based exports
869 * with growable=off to be truncated and then stuck with size 0.
870 */
871 supported_flags = FUSE_ATOMIC_O_TRUNC;
872 }
873
874 if (in->major != 7) {
875 error_report("FUSE major version mismatch: We have 7, but kernel has %"
876 PRIu32, in->major);
877 return -EINVAL;
878 }
879
880 /* 2007's 7.9 added fuse_attr.blksize; working around that would be hard */
881 if (in->minor < 9) {
882 error_report("FUSE minor version too old: 9 required, but kernel has %"
883 PRIu32, in->minor);
884 return -EINVAL;
885 }
886
887 if (!using_old_fuse_init_in(in)) {
888 /* The flags2 flags must be shifted down by 32 bits. */
889 const uint32_t supported_flags2 = FUSE_DIRECT_IO_ALLOW_MMAP >> 32;
890 /* flags2 is only considered if FUSE_INIT_EXT is set. */
891 supported_flags = supported_flags | FUSE_INIT_EXT;
892 flags2 = in->flags2 & supported_flags2;
893 }
894
895 *out = (struct fuse_init_out) {
896 .major = 7,
897 .minor = MIN(FUSE_KERNEL_MINOR_VERSION, in->minor),
898 .max_readahead = in->max_readahead,
899 .max_write = FUSE_MAX_WRITE_BYTES,
900 .flags = in->flags & supported_flags,
901 .flags2 = flags2,
902
903 /* libfuse maximum: 2^16 - 1 */
904 .max_background = UINT16_MAX,
905
906 /* libfuse default: max_background * 3 / 4 */
907 .congestion_threshold = (int)UINT16_MAX * 3 / 4,
908
909 /* libfuse default: 1 */
910 .time_gran = 1,
911
912 /*
913 * probably unneeded without FUSE_MAX_PAGES, but this would be the
914 * libfuse default
915 */
916 .max_pages = DIV_ROUND_UP(FUSE_MAX_WRITE_BYTES,
917 qemu_real_host_page_size()),
918
919 /* Only needed for mappings (i.e. DAX) */
920 .map_alignment = 0,
921 };
922
923 /*
924 * Before 7.23, fuse_init_out is shorter.
925 * Drop the tail (time_gran, max_pages, map_alignment).
926 */
927 return out->minor >= 23 ? sizeof(*out) : FUSE_COMPAT_22_INIT_OUT_SIZE;
928 }
929
930 /**
931 * Return some filesystem information, just to not break e.g. `df`.
932 */
933 static ssize_t coroutine_fn GRAPH_RDLOCK
934 fuse_co_statfs(FuseExport *exp, struct fuse_statfs_out *out)
935 {
936 BlockDriverState *root_bs;
937 uint32_t opt_transfer = 512;
938
939 root_bs = blk_bs(exp->common.blk);
940 if (root_bs) {
941 opt_transfer = root_bs->bl.opt_transfer;
942 if (!opt_transfer) {
943 opt_transfer = root_bs->bl.request_alignment;
944 }
945 opt_transfer = MAX(opt_transfer, 512);
946 }
947
948 *out = (struct fuse_statfs_out) {
949 /* These are the fields libfuse sets by default */
950 .st = {
951 .namelen = 255,
952 .bsize = opt_transfer,
953 },
954 };
955 return sizeof(*out);
956 }
957
958 /**
959 * Let clients get file attributes (i.e., stat() the file).
960 * Return the number of bytes written to *out on success, and -errno on error.
961 */
962 static ssize_t coroutine_fn GRAPH_RDLOCK
963 fuse_co_getattr(FuseExport *exp, struct fuse_attr_out *out)
964 {
965 int64_t length, allocated_blocks;
966 time_t now = time(NULL);
967
968 length = blk_co_getlength(exp->common.blk);
969 if (length < 0) {
970 return length;
971 }
972
973 allocated_blocks = bdrv_co_get_allocated_file_size(blk_bs(exp->common.blk));
974 if (allocated_blocks <= 0) {
975 allocated_blocks = DIV_ROUND_UP(length, 512);
976 } else {
977 allocated_blocks = DIV_ROUND_UP(allocated_blocks, 512);
978 }
979
980 *out = (struct fuse_attr_out) {
981 .attr_valid = 1,
982 .attr = {
983 .ino = 1,
984 .mode = qatomic_read(&exp->st_mode),
985 .nlink = 1,
986 .uid = qatomic_read(&exp->st_uid),
987 .gid = qatomic_read(&exp->st_gid),
988 .size = length,
989 .blksize = blk_bs(exp->common.blk)->bl.request_alignment,
990 .blocks = allocated_blocks,
991 .atime = now,
992 .mtime = now,
993 .ctime = now,
994 },
995 };
996
997 return sizeof(*out);
998 }
999
1000 static int coroutine_fn GRAPH_RDLOCK
1001 fuse_co_do_truncate(const FuseExport *exp, int64_t size, bool req_zero_write,
1002 PreallocMode prealloc)
1003 {
1004 BdrvRequestFlags truncate_flags = 0;
1005
1006 if (req_zero_write) {
1007 truncate_flags |= BDRV_REQ_ZERO_WRITE;
1008 }
1009
1010 return blk_co_truncate(exp->common.blk, size, true, prealloc,
1011 truncate_flags, NULL);
1012 }
1013
1014 /**
1015 * Let clients set file attributes. Only resizing and changing
1016 * permissions (st_mode, st_uid, st_gid) is allowed.
1017 * Changing permissions is only allowed as far as it will actually
1018 * permit access: Read-only exports cannot be given +w, and exports
1019 * without allow_other cannot be given a different UID or GID, and
1020 * they cannot be given non-owner access.
1021 * Return the number of bytes written to *out on success, and -errno on error.
1022 */
1023 static ssize_t coroutine_fn GRAPH_RDLOCK
1024 fuse_co_setattr(FuseExport *exp, struct fuse_attr_out *out, uint32_t to_set,
1025 uint64_t size, uint32_t mode, uint32_t uid, uint32_t gid)
1026 {
1027 int supported_attrs;
1028 int ret;
1029
1030 /* SIZE and MODE are actually supported, the others can be safely ignored */
1031 supported_attrs = FATTR_SIZE | FATTR_MODE |
1032 FATTR_FH | FATTR_LOCKOWNER | FATTR_KILL_SUIDGID;
1033 if (exp->allow_other) {
1034 supported_attrs |= FATTR_UID | FATTR_GID;
1035 }
1036
1037 if (to_set & ~supported_attrs) {
1038 return -ENOTSUP;
1039 }
1040
1041 /* Do some argument checks first before committing to anything */
1042 if (to_set & FATTR_MODE) {
1043 /*
1044 * Without allow_other, non-owners can never access the export, so do
1045 * not allow setting permissions for them
1046 */
1047 if (!exp->allow_other && (mode & (S_IRWXG | S_IRWXO)) != 0) {
1048 return -EPERM;
1049 }
1050
1051 /* +w for read-only exports makes no sense, disallow it */
1052 if (!exp->writable && (mode & (S_IWUSR | S_IWGRP | S_IWOTH)) != 0) {
1053 return -EROFS;
1054 }
1055 }
1056
1057 if (to_set & FATTR_SIZE) {
1058 if (!exp->writable) {
1059 return -EACCES;
1060 }
1061
1062 ret = fuse_co_do_truncate(exp, size, true, PREALLOC_MODE_OFF);
1063 if (ret < 0) {
1064 return ret;
1065 }
1066 }
1067
1068 if (to_set & FATTR_MODE) {
1069 /* Ignore FUSE-supplied file type, only change the mode */
1070 qatomic_set(&exp->st_mode, (mode & 07777) | S_IFREG);
1071 }
1072
1073 if (to_set & FATTR_UID) {
1074 qatomic_set(&exp->st_uid, uid);
1075 }
1076
1077 if (to_set & FATTR_GID) {
1078 qatomic_set(&exp->st_gid, gid);
1079 }
1080
1081 return fuse_co_getattr(exp, out);
1082 }
1083
1084 /**
1085 * Open an inode. We only have a single inode in our exported filesystem, so we
1086 * just acknowledge the request.
1087 * Return the number of bytes written to *out on success, and -errno on error.
1088 */
1089 static ssize_t coroutine_fn GRAPH_RDLOCK
1090 fuse_co_open(FuseExport *exp, struct fuse_open_out *out)
1091 {
1092 *out = (struct fuse_open_out) {
1093 .open_flags = FOPEN_DIRECT_IO | FOPEN_PARALLEL_DIRECT_WRITES,
1094 };
1095 return sizeof(*out);
1096 }
1097
1098 /**
1099 * Handle client reads from the exported image. Allocates *bufptr and reads
1100 * data from the block device into that buffer.
1101 * Returns the buffer (read) size on success, and -errno on error.
1102 * Note: If the returned size is 0, *bufptr will be set to NULL.
1103 * After use, *bufptr must be freed via qemu_vfree().
1104 */
1105 static ssize_t coroutine_fn GRAPH_RDLOCK
1106 fuse_co_read(FuseExport *exp, void **bufptr, uint64_t offset, uint32_t size)
1107 {
1108 int64_t blk_len;
1109 void *buf;
1110 int ret;
1111
1112 /* Limited by max_read, should not happen */
1113 if (size > FUSE_MAX_READ_BYTES) {
1114 return -EINVAL;
1115 }
1116
1117 /**
1118 * Clients will expect short reads at EOF, so we have to limit
1119 * offset+size to the image length.
1120 */
1121 blk_len = blk_co_getlength(exp->common.blk);
1122 if (blk_len < 0) {
1123 return blk_len;
1124 }
1125
1126 if (offset >= blk_len) {
1127 /* Explicitly set to NULL because we return success here */
1128 *bufptr = NULL;
1129 return 0;
1130 }
1131
1132 if (offset + size > blk_len) {
1133 size = blk_len - offset;
1134 }
1135
1136 buf = qemu_try_blockalign(blk_bs(exp->common.blk), size);
1137 if (!buf) {
1138 return -ENOMEM;
1139 }
1140
1141 ret = blk_co_pread(exp->common.blk, offset, size, buf, 0);
1142 if (ret < 0) {
1143 qemu_vfree(buf);
1144 return ret;
1145 }
1146
1147 *bufptr = buf;
1148 return size;
1149 }
1150
1151 /**
1152 * Handle client writes to the exported image. @buf has the data to be written.
1153 * Return the number of bytes written to *out on success, and -errno on error.
1154 */
1155 static ssize_t coroutine_fn GRAPH_RDLOCK
1156 fuse_co_write(FuseExport *exp, struct fuse_write_out *out,
1157 uint64_t offset, uint32_t size, const void *buf)
1158 {
1159 int64_t blk_len;
1160 int ret;
1161
1162 QEMU_BUILD_BUG_ON(FUSE_MAX_WRITE_BYTES > BDRV_REQUEST_MAX_BYTES);
1163 /* Limited by max_write, should not happen */
1164 if (size > FUSE_MAX_WRITE_BYTES) {
1165 return -EINVAL;
1166 }
1167
1168 if (!exp->writable) {
1169 return -EACCES;
1170 }
1171
1172 /**
1173 * Clients will expect short writes at EOF, so we have to limit
1174 * offset+size to the image length.
1175 */
1176 blk_len = blk_co_getlength(exp->common.blk);
1177 if (blk_len < 0) {
1178 return blk_len;
1179 }
1180
1181 if (offset >= blk_len && !exp->growable) {
1182 *out = (struct fuse_write_out) {
1183 .size = 0,
1184 };
1185 return sizeof(*out);
1186 }
1187
1188 if (offset + size < offset) {
1189 return -EINVAL;
1190 } else if (offset + size > blk_len) {
1191 if (exp->growable) {
1192 ret = fuse_co_do_truncate(exp, offset + size, true,
1193 PREALLOC_MODE_OFF);
1194 if (ret < 0) {
1195 return ret;
1196 }
1197 } else {
1198 size = blk_len - offset;
1199 }
1200 }
1201
1202 ret = blk_co_pwrite(exp->common.blk, offset, size, buf, 0);
1203 if (ret < 0) {
1204 return ret;
1205 }
1206
1207 *out = (struct fuse_write_out) {
1208 .size = size,
1209 };
1210 return sizeof(*out);
1211 }
1212
1213 /**
1214 * Let clients perform various fallocate() operations.
1215 * Return 0 on success (no 'out' object), and -errno on error.
1216 */
1217 static ssize_t coroutine_fn GRAPH_RDLOCK
1218 fuse_co_fallocate(FuseExport *exp,
1219 uint64_t offset, uint64_t length, uint32_t mode)
1220 {
1221 int64_t blk_len;
1222 int ret;
1223
1224 if (!exp->writable) {
1225 return -EACCES;
1226 }
1227
1228 blk_len = blk_co_getlength(exp->common.blk);
1229 if (blk_len < 0) {
1230 return blk_len;
1231 }
1232
1233 #ifdef CONFIG_FALLOCATE_PUNCH_HOLE
1234 if (mode & FALLOC_FL_KEEP_SIZE) {
1235 length = MIN(length, blk_len - offset);
1236 }
1237 #endif /* CONFIG_FALLOCATE_PUNCH_HOLE */
1238
1239 if (!mode) {
1240 /* We can only fallocate at the EOF with a truncate */
1241 if (offset < blk_len) {
1242 return -EOPNOTSUPP;
1243 }
1244
1245 if (offset > blk_len) {
1246 /* No preallocation needed here */
1247 ret = fuse_co_do_truncate(exp, offset, true, PREALLOC_MODE_OFF);
1248 if (ret < 0) {
1249 return ret;
1250 }
1251 }
1252
1253 ret = fuse_co_do_truncate(exp, offset + length, true,
1254 PREALLOC_MODE_FALLOC);
1255 }
1256 #ifdef CONFIG_FALLOCATE_PUNCH_HOLE
1257 else if (mode & FALLOC_FL_PUNCH_HOLE) {
1258 if (!(mode & FALLOC_FL_KEEP_SIZE)) {
1259 return -EINVAL;
1260 }
1261
1262 do {
1263 int size = MIN(length, BDRV_REQUEST_MAX_BYTES);
1264
1265 ret = blk_co_pwrite_zeroes(exp->common.blk, offset, size,
1266 BDRV_REQ_MAY_UNMAP |
1267 BDRV_REQ_NO_FALLBACK);
1268 if (ret == -ENOTSUP) {
1269 /*
1270 * fallocate() specifies to return EOPNOTSUPP for unsupported
1271 * operations
1272 */
1273 ret = -EOPNOTSUPP;
1274 }
1275
1276 offset += size;
1277 length -= size;
1278 } while (ret == 0 && length > 0);
1279 }
1280 #endif /* CONFIG_FALLOCATE_PUNCH_HOLE */
1281 #ifdef CONFIG_FALLOCATE_ZERO_RANGE
1282 else if (mode & FALLOC_FL_ZERO_RANGE) {
1283 if (!(mode & FALLOC_FL_KEEP_SIZE) && offset + length > blk_len) {
1284 /* No need for zeroes, we are going to write them ourselves */
1285 ret = fuse_co_do_truncate(exp, offset + length, false,
1286 PREALLOC_MODE_OFF);
1287 if (ret < 0) {
1288 return ret;
1289 }
1290 }
1291
1292 do {
1293 int size = MIN(length, BDRV_REQUEST_MAX_BYTES);
1294
1295 ret = blk_co_pwrite_zeroes(exp->common.blk,
1296 offset, size, 0);
1297 offset += size;
1298 length -= size;
1299 } while (ret == 0 && length > 0);
1300 }
1301 #endif /* CONFIG_FALLOCATE_ZERO_RANGE */
1302 else {
1303 ret = -EOPNOTSUPP;
1304 }
1305
1306 return ret < 0 ? ret : 0;
1307 }
1308
1309 /**
1310 * Let clients fsync the exported image.
1311 * Return 0 on success (no 'out' object), and -errno on error.
1312 */
1313 static ssize_t coroutine_fn GRAPH_RDLOCK fuse_co_fsync(FuseExport *exp)
1314 {
1315 return blk_co_flush(exp->common.blk);
1316 }
1317
1318 /**
1319 * Called before an FD to the exported image is closed. (libfuse
1320 * notes this to be a way to return last-minute errors.)
1321 * Return 0 on success (no 'out' object), and -errno on error.
1322 */
1323 static ssize_t coroutine_fn GRAPH_RDLOCK fuse_co_flush(FuseExport *exp)
1324 {
1325 return blk_co_flush(exp->common.blk);
1326 }
1327
1328 #ifdef CONFIG_FUSE_LSEEK
1329 /**
1330 * Let clients inquire allocation status.
1331 * Return the number of bytes written to *out on success, and -errno on error.
1332 */
1333 static ssize_t coroutine_fn GRAPH_RDLOCK
1334 fuse_co_lseek(FuseExport *exp, struct fuse_lseek_out *out,
1335 uint64_t offset, uint32_t whence)
1336 {
1337 if (whence != SEEK_HOLE && whence != SEEK_DATA) {
1338 return -EINVAL;
1339 }
1340
1341 while (true) {
1342 int64_t pnum;
1343 int ret;
1344
1345 ret = bdrv_co_block_status_above(blk_bs(exp->common.blk), NULL,
1346 offset, INT64_MAX, &pnum, NULL, NULL);
1347 if (ret < 0) {
1348 return ret;
1349 }
1350
1351 if (!pnum && (ret & BDRV_BLOCK_EOF)) {
1352 int64_t blk_len;
1353
1354 /*
1355 * If blk_getlength() rounds (e.g. by sectors), then the
1356 * export length will be rounded, too. However,
1357 * bdrv_block_status_above() may return EOF at unaligned
1358 * offsets. We must not let this become visible and thus
1359 * always simulate a hole between @offset (the real EOF)
1360 * and @blk_len (the client-visible EOF).
1361 */
1362
1363 blk_len = blk_co_getlength(exp->common.blk);
1364 if (blk_len < 0) {
1365 return blk_len;
1366 }
1367
1368 if (offset > blk_len || whence == SEEK_DATA) {
1369 return -ENXIO;
1370 }
1371
1372 *out = (struct fuse_lseek_out) {
1373 .offset = offset,
1374 };
1375 return sizeof(*out);
1376 }
1377
1378 if (ret & BDRV_BLOCK_DATA) {
1379 if (whence == SEEK_DATA) {
1380 *out = (struct fuse_lseek_out) {
1381 .offset = offset,
1382 };
1383 return sizeof(*out);
1384 }
1385 } else {
1386 if (whence == SEEK_HOLE) {
1387 *out = (struct fuse_lseek_out) {
1388 .offset = offset,
1389 };
1390 return sizeof(*out);
1391 }
1392 }
1393
1394 /* Safety check against infinite loops */
1395 if (!pnum) {
1396 return -ENXIO;
1397 }
1398
1399 offset += pnum;
1400 }
1401 }
1402 #endif
1403
1404 /**
1405 * Write a FUSE response to the given @fd.
1406 *
1407 * Effectively, writes out_hdr->common.len bytes of the buffer that is *out_hdr.
1408 *
1409 * @fd: FUSE file descriptor
1410 * @out_hdr: Request response header and request-specific response data
1411 */
1412 static int fuse_write_response(int fd, FuseRequestOutHeader *out_hdr)
1413 {
1414 size_t to_write = out_hdr->common.len;
1415 ssize_t ret;
1416
1417 /* Must at least write fuse_out_header */
1418 assert(to_write >= sizeof(out_hdr->common));
1419
1420 ret = RETRY_ON_EINTR(write(fd, out_hdr, to_write));
1421 if (ret < 0) {
1422 ret = -errno;
1423 error_report("Failed to write to FUSE device: %s", strerror(-ret));
1424 return ret;
1425 }
1426
1427 /* Short writes are unexpected, treat them as errors */
1428 if (ret != to_write) {
1429 error_report("Short write to FUSE device, wrote %zi of %zu bytes",
1430 ret, to_write);
1431 return -EIO;
1432 }
1433
1434 return 0;
1435 }
1436
1437 /**
1438 * Write a FUSE error response to @fd.
1439 *
1440 * @fd: FUSE file descriptor
1441 * @in_hdr: Incoming request header to which to respond
1442 * @err: Error code (-errno, must be negative!)
1443 */
1444 static int fuse_write_err(int fd, const struct fuse_in_header *in_hdr, int err)
1445 {
1446 FuseRequestOutHeader out_hdr = {
1447 .common = {
1448 .len = sizeof(out_hdr.common),
1449 /* FUSE expects negative error values */
1450 .error = err,
1451 .unique = in_hdr->unique,
1452 },
1453 };
1454
1455 return fuse_write_response(fd, &out_hdr);
1456 }
1457
1458 /**
1459 * Write a FUSE response to the given @fd, using separate buffers for the
1460 * response header and data.
1461 *
1462 * In contrast to fuse_write_response(), this function cannot return a full
1463 * FuseRequestOutHeader (i.e. including request-specific response structs),
1464 * but only FuseRequestOutHeader.common. The remaining data must be in
1465 * *buf.
1466 *
1467 * (Total length must be set in out_hdr->len.)
1468 *
1469 * @fd: FUSE file descriptor
1470 * @out_hdr: Request response header
1471 * @buf: Pointer to response data
1472 */
1473 static int fuse_write_buf_response(int fd,
1474 const struct fuse_out_header *out_hdr,
1475 const void *buf)
1476 {
1477 size_t to_write = out_hdr->len;
1478 struct iovec iov[2] = {
1479 { (void *)out_hdr, sizeof(*out_hdr) },
1480 { (void *)buf, to_write - sizeof(*out_hdr) },
1481 };
1482 ssize_t ret;
1483
1484 /* *buf length must not be negative */
1485 assert(to_write >= sizeof(*out_hdr));
1486
1487 ret = RETRY_ON_EINTR(writev(fd, iov, ARRAY_SIZE(iov)));
1488 if (ret < 0) {
1489 ret = -errno;
1490 error_report("Failed to write to FUSE device: %s", strerror(-ret));
1491 return ret;
1492 }
1493
1494 /* Short writes are unexpected, treat them as errors */
1495 if (ret != to_write) {
1496 error_report("Short write to FUSE device, wrote %zi of %zu bytes",
1497 ret, to_write);
1498 return -EIO;
1499 }
1500
1501 return 0;
1502 }
1503
1504 /**
1505 * Process a FUSE request, incl. writing the response.
1506 */
1507 static void coroutine_fn
1508 fuse_co_process_request(FuseQueue *q, const FuseRequestInHeader *in_hdr,
1509 const void *data_buffer)
1510 {
1511 FuseRequestOutHeader out_hdr;
1512 FuseExport *exp = q->exp;
1513 /* For read requests: Data to be returned */
1514 void *out_data_buffer = NULL;
1515 ssize_t ret;
1516
1517 GRAPH_RDLOCK_GUARD();
1518
1519 switch (in_hdr->common.opcode) {
1520 case FUSE_INIT:
1521 ret = fuse_co_init(exp, &out_hdr.init, &in_hdr->init);
1522 break;
1523
1524 case FUSE_DESTROY:
1525 ret = 0;
1526 break;
1527
1528 case FUSE_STATFS:
1529 ret = fuse_co_statfs(exp, &out_hdr.statfs);
1530 break;
1531
1532 case FUSE_OPEN:
1533 ret = fuse_co_open(exp, &out_hdr.open);
1534 break;
1535
1536 case FUSE_RELEASE:
1537 ret = 0;
1538 break;
1539
1540 case FUSE_LOOKUP:
1541 ret = -ENOENT; /* There is no node but the root node */
1542 break;
1543
1544 case FUSE_FORGET:
1545 case FUSE_BATCH_FORGET:
1546 /* These have no response, and there is nothing we need to do */
1547 return;
1548
1549 case FUSE_GETATTR:
1550 ret = fuse_co_getattr(exp, &out_hdr.attr);
1551 break;
1552
1553 case FUSE_SETATTR: {
1554 const struct fuse_setattr_in *in = &in_hdr->setattr;
1555 ret = fuse_co_setattr(exp, &out_hdr.attr,
1556 in->valid, in->size, in->mode, in->uid, in->gid);
1557 break;
1558 }
1559
1560 case FUSE_READ: {
1561 const struct fuse_read_in *in = &in_hdr->read;
1562 ret = fuse_co_read(exp, &out_data_buffer, in->offset, in->size);
1563 break;
1564 }
1565
1566 case FUSE_WRITE: {
1567 const struct fuse_write_in *in = &in_hdr->write;
1568 uint32_t req_len = in_hdr->common.len;
1569
1570 if (unlikely(req_len < sizeof(in_hdr->common) + sizeof(*in) +
1571 in->size)) {
1572 warn_report("FUSE WRITE truncated; received %zu bytes of %" PRIu32,
1573 req_len - sizeof(in_hdr->common) - sizeof(*in),
1574 in->size);
1575 ret = -EINVAL;
1576 break;
1577 }
1578
1579 /*
1580 * co_read_from_fuse_fd() has checked that in_hdr->len matches the
1581 * number of bytes read, which cannot exceed the max_write value we set
1582 * (FUSE_MAX_WRITE_BYTES). So we know that FUSE_MAX_WRITE_BYTES >=
1583 * in_hdr->len >= in->size + X, so this assertion must hold.
1584 */
1585 assert(in->size <= FUSE_MAX_WRITE_BYTES);
1586
1587 ret = fuse_co_write(exp, &out_hdr.write,
1588 in->offset, in->size, data_buffer);
1589 break;
1590 }
1591
1592 case FUSE_FALLOCATE: {
1593 const struct fuse_fallocate_in *in = &in_hdr->fallocate;
1594 ret = fuse_co_fallocate(exp, in->offset, in->length, in->mode);
1595 break;
1596 }
1597
1598 case FUSE_FSYNC:
1599 ret = fuse_co_fsync(exp);
1600 break;
1601
1602 case FUSE_FLUSH:
1603 ret = fuse_co_flush(exp);
1604 break;
1605
1606 #ifdef CONFIG_FUSE_LSEEK
1607 case FUSE_LSEEK: {
1608 const struct fuse_lseek_in *in = &in_hdr->lseek;
1609 ret = fuse_co_lseek(exp, &out_hdr.lseek, in->offset, in->whence);
1610 break;
1611 }
1612 #endif
1613
1614 default:
1615 ret = -ENOSYS;
1616 }
1617
1618 if (ret >= 0) {
1619 out_hdr.common = (struct fuse_out_header) {
1620 .len = sizeof(out_hdr.common) + ret,
1621 .unique = in_hdr->common.unique,
1622 };
1623 } else {
1624 /* fuse_read() must not return a buffer in case of error */
1625 assert(out_data_buffer == NULL);
1626
1627 out_hdr.common = (struct fuse_out_header) {
1628 .len = sizeof(out_hdr.common),
1629 /* FUSE expects negative errno values */
1630 .error = ret,
1631 .unique = in_hdr->common.unique,
1632 };
1633 }
1634
1635 if (out_data_buffer) {
1636 fuse_write_buf_response(q->fuse_fd, &out_hdr.common, out_data_buffer);
1637 qemu_vfree(out_data_buffer);
1638 } else {
1639 fuse_write_response(q->fuse_fd, &out_hdr);
1640 }
1641 }
1642
1643 const BlockExportDriver blk_exp_fuse = {
1644 .type = BLOCK_EXPORT_TYPE_FUSE,
1645 .instance_size = sizeof(FuseExport),
1646 .create = fuse_export_create,
1647 .delete = fuse_export_delete,
1648 .request_shutdown = fuse_export_shutdown,
1649 };