2 * Copyright (C) 2005 Anthony Liguori <anthony@codemonkey.ws>
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 of the License.
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.
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/>.
19 #include "qemu/osdep.h"
24 #include "qemu/help-texts.h"
25 #include "qapi/error.h"
26 #include "qemu/cutils.h"
27 #include "sysemu/block-backend.h"
28 #include "sysemu/runstate.h" /* for qemu_system_killed() prototype */
29 #include "block/block_int.h"
30 #include "block/nbd.h"
31 #include "qemu/main-loop.h"
32 #include "qemu/module.h"
33 #include "qemu/option.h"
34 #include "qemu/error-report.h"
35 #include "qemu/config-file.h"
36 #include "qemu/bswap.h"
38 #include "qemu/systemd.h"
39 #include "block/snapshot.h"
40 #include "qapi/qmp/qdict.h"
41 #include "qapi/qmp/qstring.h"
42 #include "qom/object_interfaces.h"
43 #include "io/channel-socket.h"
44 #include "io/net-listener.h"
45 #include "crypto/init.h"
46 #include "crypto/tlscreds.h"
47 #include "trace/control.h"
48 #include "qemu-version.h"
51 #include <selinux/selinux.h>
55 #define HAVE_NBD_DEVICE 1
57 #define HAVE_NBD_DEVICE 0
60 #define SOCKET_PATH "/var/lock/qemu-nbd-%s"
61 #define QEMU_NBD_OPT_CACHE 256
62 #define QEMU_NBD_OPT_AIO 257
63 #define QEMU_NBD_OPT_DISCARD 258
64 #define QEMU_NBD_OPT_DETECT_ZEROES 259
65 #define QEMU_NBD_OPT_OBJECT 260
66 #define QEMU_NBD_OPT_TLSCREDS 261
67 #define QEMU_NBD_OPT_IMAGE_OPTS 262
68 #define QEMU_NBD_OPT_FORK 263
69 #define QEMU_NBD_OPT_TLSAUTHZ 264
70 #define QEMU_NBD_OPT_PID_FILE 265
71 #define QEMU_NBD_OPT_SELINUX_LABEL 266
72 #define QEMU_NBD_OPT_TLSHOSTNAME 267
76 static int persistent = 0;
77 static enum { RUNNING, TERMINATE, TERMINATED } state;
78 static int shared = 1;
80 static QIONetListener *server;
81 static QCryptoTLSCreds *tlscreds;
82 static const char *tlsauthz;
84 static void usage(const char *name)
87 "Usage: %s [OPTIONS] FILE\n"
88 " or: %s -L [OPTIONS]\n"
89 "QEMU Disk Network Block Device Utility\n"
91 " -h, --help display this help and exit\n"
92 " -V, --version output version information and exit\n"
94 "Connection properties:\n"
95 " -p, --port=PORT port to listen on (default `%d')\n"
96 " -b, --bind=IFACE interface to bind to (default `0.0.0.0')\n"
97 " -k, --socket=PATH path to the unix socket\n"
98 " (default '"SOCKET_PATH"')\n"
99 " -e, --shared=NUM device can be shared by NUM clients (default '1')\n"
100 " -t, --persistent don't exit on the last connection\n"
101 " -v, --verbose display extra debugging information\n"
102 " -x, --export-name=NAME expose export by name (default is empty string)\n"
103 " -D, --description=TEXT export a human-readable description\n"
105 "Exposing part of the image:\n"
106 " -o, --offset=OFFSET offset into the image\n"
107 " -A, --allocation-depth expose the allocation depth\n"
108 " -B, --bitmap=NAME expose a persistent dirty bitmap\n"
110 "General purpose options:\n"
111 " -L, --list list exports available from another NBD server\n"
112 " --object type,id=ID,... define an object such as 'secret' for providing\n"
113 " passwords and/or encryption keys\n"
114 " --tls-creds=ID use id of an earlier --object to provide TLS\n"
115 " --tls-authz=ID use id of an earlier --object to provide\n"
117 " -T, --trace [[enable=]<pattern>][,events=<file>][,file=<file>]\n"
118 " specify tracing options\n"
119 " --fork fork off the server process and exit the parent\n"
120 " once the server is running\n"
121 " --pid-file=PATH store the server's process ID in the given file\n"
122 #ifdef CONFIG_SELINUX
123 " --selinux-label=LABEL set SELinux process label on listening socket\n"
127 "Kernel NBD client support:\n"
128 " -c, --connect=DEV connect FILE to the local NBD device DEV\n"
129 " -d, --disconnect disconnect the specified device\n"
132 "Block device options:\n"
133 " -f, --format=FORMAT set image format (raw, qcow2, ...)\n"
134 " -r, --read-only export read-only\n"
135 " -s, --snapshot use FILE as an external snapshot, create a temporary\n"
136 " file with backing_file=FILE, redirect the write to\n"
137 " the temporary one\n"
138 " -l, --load-snapshot=SNAPSHOT_PARAM\n"
139 " load an internal snapshot inside FILE and export it\n"
140 " as an read-only device, SNAPSHOT_PARAM format is\n"
141 " 'snapshot.id=[ID],snapshot.name=[NAME]', or\n"
143 " -n, --nocache disable host cache\n"
144 " --cache=MODE set cache mode used to access the disk image, the\n"
145 " valid options are: 'none', 'writeback' (default),\n"
146 " 'writethrough', 'directsync' and 'unsafe'\n"
147 " --aio=MODE set AIO mode (native, io_uring or threads)\n"
148 " --discard=MODE set discard mode (ignore, unmap)\n"
149 " --detect-zeroes=MODE set detect-zeroes mode (off, on, unmap)\n"
150 " --image-opts treat FILE as a full set of image options\n"
152 QEMU_HELP_BOTTOM "\n"
153 , name, name, NBD_DEFAULT_PORT, "DEVICE");
156 static void version(const char *name)
159 "%s " QEMU_FULL_VERSION "\n"
160 "Written by Anthony Liguori.\n"
163 "This is free software; see the source for copying conditions. There is NO\n"
164 "warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n"
170 * The client thread uses SIGTERM to interrupt the server. A signal
171 * handler ensures that "qemu-nbd -v -c" exits with a nice status code.
173 void qemu_system_killed(int signum, pid_t pid)
175 qatomic_cmpxchg(&state, RUNNING, TERMINATE);
178 #endif /* CONFIG_POSIX */
180 static int qemu_nbd_client_list(SocketAddress *saddr, QCryptoTLSCreds *tls,
181 const char *hostname)
183 int ret = EXIT_FAILURE;
186 QIOChannelSocket *sioc;
190 sioc = qio_channel_socket_new();
191 if (qio_channel_socket_connect_sync(sioc, saddr, &err) < 0) {
192 error_report_err(err);
195 rc = nbd_receive_export_list(QIO_CHANNEL(sioc), tls, hostname, &list,
199 error_report_err(err);
203 printf("exports available: %d\n", rc);
204 for (i = 0; i < rc; i++) {
205 printf(" export: '%s'\n", list[i].name);
206 if (list[i].description && *list[i].description) {
207 printf(" description: %s\n", list[i].description);
209 if (list[i].flags & NBD_FLAG_HAS_FLAGS) {
210 static const char *const flag_names[] = {
211 [NBD_FLAG_READ_ONLY_BIT] = "readonly",
212 [NBD_FLAG_SEND_FLUSH_BIT] = "flush",
213 [NBD_FLAG_SEND_FUA_BIT] = "fua",
214 [NBD_FLAG_ROTATIONAL_BIT] = "rotational",
215 [NBD_FLAG_SEND_TRIM_BIT] = "trim",
216 [NBD_FLAG_SEND_WRITE_ZEROES_BIT] = "zeroes",
217 [NBD_FLAG_SEND_DF_BIT] = "df",
218 [NBD_FLAG_CAN_MULTI_CONN_BIT] = "multi",
219 [NBD_FLAG_SEND_RESIZE_BIT] = "resize",
220 [NBD_FLAG_SEND_CACHE_BIT] = "cache",
221 [NBD_FLAG_SEND_FAST_ZERO_BIT] = "fast-zero",
224 printf(" size: %" PRIu64 "\n", list[i].size);
225 printf(" flags: 0x%x (", list[i].flags);
226 for (size_t bit = 0; bit < ARRAY_SIZE(flag_names); bit++) {
227 if (flag_names[bit] && (list[i].flags & (1 << bit))) {
228 printf(" %s", flag_names[bit]);
233 if (list[i].min_block) {
234 printf(" min block: %u\n", list[i].min_block);
235 printf(" opt block: %u\n", list[i].opt_block);
236 printf(" max block: %u\n", list[i].max_block);
238 if (list[i].n_contexts) {
239 printf(" available meta contexts: %d\n", list[i].n_contexts);
240 for (j = 0; j < list[i].n_contexts; j++) {
241 printf(" %s\n", list[i].contexts[j]);
245 nbd_free_export_list(list, rc);
249 object_unref(OBJECT(sioc));
254 struct NbdClientOpts {
257 SocketAddress *saddr;
263 static void nbd_client_release_pipe(int old_stderr)
265 /* Close stderr so that the qemu-nbd process exits. */
266 if (dup2(old_stderr, STDERR_FILENO) < 0) {
267 error_report("Could not release pipe to parent: %s",
271 if (old_stderr != STDOUT_FILENO && close(old_stderr) < 0) {
272 error_report("Could not release qemu-nbd: %s", strerror(errno));
278 static void *show_parts(void *arg)
283 /* linux just needs an open() to trigger
284 * the partition table update
285 * but remember to load the module with max_part != 0 :
286 * modprobe nbd max_part=63
288 nbd = open(device, O_RDWR);
295 static void *nbd_client_thread(void *arg)
297 struct NbdClientOpts *opts = arg;
298 NBDExportInfo info = { .request_sizes = false, .name = g_strdup("") };
299 QIOChannelSocket *sioc;
301 int ret = EXIT_FAILURE;
302 pthread_t show_parts_thread;
303 Error *local_error = NULL;
305 sioc = qio_channel_socket_new();
306 if (qio_channel_socket_connect_sync(sioc,
309 error_report_err(local_error);
313 if (nbd_receive_negotiate(QIO_CHANNEL(sioc), NULL, NULL, NULL,
314 &info, &local_error) < 0) {
316 error_report_err(local_error);
321 fd = open(opts->device, O_RDWR);
323 /* Linux-only, we can use %m in printf. */
324 error_report("Failed to open %s: %m", opts->device);
328 if (nbd_init(fd, sioc, &info, &local_error) < 0) {
329 error_report_err(local_error);
333 /* update partition table */
334 pthread_create(&show_parts_thread, NULL, show_parts, opts->device);
336 if (opts->verbose && !opts->fork_process) {
337 fprintf(stderr, "NBD device %s is now connected to %s\n",
338 opts->device, opts->srcpath);
340 nbd_client_release_pipe(opts->old_stderr);
343 if (nbd_client(fd) < 0) {
353 object_unref(OBJECT(sioc));
355 kill(getpid(), SIGTERM);
356 return (void *) (intptr_t) ret;
358 #endif /* HAVE_NBD_DEVICE */
360 static int nbd_can_accept(void)
362 return state == RUNNING && (shared == 0 || nb_fds < shared);
365 static void nbd_update_server_watch(void);
367 static void nbd_client_closed(NBDClient *client, bool negotiated)
370 if (negotiated && nb_fds == 0 && !persistent && state == RUNNING) {
373 nbd_update_server_watch();
374 nbd_client_put(client);
377 static void nbd_accept(QIONetListener *listener, QIOChannelSocket *cioc,
380 if (state >= TERMINATE) {
385 nbd_update_server_watch();
386 nbd_client_new(cioc, tlscreds, tlsauthz, nbd_client_closed);
389 static void nbd_update_server_watch(void)
391 if (nbd_can_accept()) {
392 qio_net_listener_set_client_func(server, nbd_accept, NULL, NULL);
394 qio_net_listener_set_client_func(server, NULL, NULL, NULL);
399 static SocketAddress *nbd_build_socket_address(const char *sockpath,
403 SocketAddress *saddr;
405 saddr = g_new0(SocketAddress, 1);
407 saddr->type = SOCKET_ADDRESS_TYPE_UNIX;
408 saddr->u.q_unix.path = g_strdup(sockpath);
410 InetSocketAddress *inet;
411 saddr->type = SOCKET_ADDRESS_TYPE_INET;
412 inet = &saddr->u.inet;
413 inet->host = g_strdup(bindto);
415 inet->port = g_strdup(port);
417 inet->port = g_strdup_printf("%d", NBD_DEFAULT_PORT);
425 static QemuOptsList file_opts = {
427 .implied_opt_name = "file",
428 .head = QTAILQ_HEAD_INITIALIZER(file_opts.head),
430 /* no elements => accept any params */
431 { /* end of list */ }
435 static QCryptoTLSCreds *nbd_get_tls_creds(const char *id, bool list,
439 QCryptoTLSCreds *creds;
441 obj = object_resolve_path_component(
442 object_get_objects_root(), id);
444 error_setg(errp, "No TLS credentials with id '%s'",
448 creds = (QCryptoTLSCreds *)
449 object_dynamic_cast(obj, TYPE_QCRYPTO_TLS_CREDS);
451 error_setg(errp, "Object with id '%s' is not TLS credentials",
456 if (!qcrypto_tls_creds_check_endpoint(creds,
458 ? QCRYPTO_TLS_CREDS_ENDPOINT_CLIENT
459 : QCRYPTO_TLS_CREDS_ENDPOINT_SERVER,
467 static void setup_address_and_port(const char **address, const char **port)
469 if (*address == NULL) {
470 *address = "0.0.0.0";
474 *port = stringify(NBD_DEFAULT_PORT);
479 * Check socket parameters compatibility when socket activation is used.
481 static const char *socket_activation_validate_opts(const char *device,
482 const char *sockpath,
488 if (device != NULL) {
489 return "NBD device can't be set when using socket activation";
492 if (sockpath != NULL) {
493 return "Unix socket can't be set when using socket activation";
496 if (address != NULL) {
497 return "The interface can't be set when using socket activation";
501 return "TCP port number can't be set when using socket activation";
504 if (selinux != NULL) {
505 return "SELinux label can't be set when using socket activation";
509 return "List mode is incompatible with socket activation";
515 static void qemu_nbd_shutdown(void)
517 job_cancel_sync_all();
522 int main(int argc, char **argv)
525 BlockDriverState *bs;
526 uint64_t dev_offset = 0;
527 bool readonly = false;
528 bool disconnect = false;
529 const char *bindto = NULL;
530 const char *port = NULL;
531 char *sockpath = NULL;
532 QemuOpts *sn_opts = NULL;
533 const char *sn_id_or_name = NULL;
534 const char *sopt = "hVb:o:p:rsnc:dvk:e:f:tl:x:T:D:AB:L";
535 struct option lopt[] = {
536 { "help", no_argument, NULL, 'h' },
537 { "version", no_argument, NULL, 'V' },
538 { "bind", required_argument, NULL, 'b' },
539 { "port", required_argument, NULL, 'p' },
540 { "socket", required_argument, NULL, 'k' },
541 { "offset", required_argument, NULL, 'o' },
542 { "read-only", no_argument, NULL, 'r' },
543 { "allocation-depth", no_argument, NULL, 'A' },
544 { "bitmap", required_argument, NULL, 'B' },
545 { "connect", required_argument, NULL, 'c' },
546 { "disconnect", no_argument, NULL, 'd' },
547 { "list", no_argument, NULL, 'L' },
548 { "snapshot", no_argument, NULL, 's' },
549 { "load-snapshot", required_argument, NULL, 'l' },
550 { "nocache", no_argument, NULL, 'n' },
551 { "cache", required_argument, NULL, QEMU_NBD_OPT_CACHE },
552 { "aio", required_argument, NULL, QEMU_NBD_OPT_AIO },
553 { "discard", required_argument, NULL, QEMU_NBD_OPT_DISCARD },
554 { "detect-zeroes", required_argument, NULL,
555 QEMU_NBD_OPT_DETECT_ZEROES },
556 { "shared", required_argument, NULL, 'e' },
557 { "format", required_argument, NULL, 'f' },
558 { "persistent", no_argument, NULL, 't' },
559 { "verbose", no_argument, NULL, 'v' },
560 { "object", required_argument, NULL, QEMU_NBD_OPT_OBJECT },
561 { "export-name", required_argument, NULL, 'x' },
562 { "description", required_argument, NULL, 'D' },
563 { "tls-creds", required_argument, NULL, QEMU_NBD_OPT_TLSCREDS },
564 { "tls-hostname", required_argument, NULL, QEMU_NBD_OPT_TLSHOSTNAME },
565 { "tls-authz", required_argument, NULL, QEMU_NBD_OPT_TLSAUTHZ },
566 { "image-opts", no_argument, NULL, QEMU_NBD_OPT_IMAGE_OPTS },
567 { "trace", required_argument, NULL, 'T' },
568 { "fork", no_argument, NULL, QEMU_NBD_OPT_FORK },
569 { "pid-file", required_argument, NULL, QEMU_NBD_OPT_PID_FILE },
570 { "selinux-label", required_argument, NULL,
571 QEMU_NBD_OPT_SELINUX_LABEL },
576 int flags = BDRV_O_RDWR;
578 bool seen_cache = false;
579 bool seen_discard = false;
580 bool seen_aio = false;
581 pthread_t client_thread;
582 const char *fmt = NULL;
583 Error *local_err = NULL;
584 BlockdevDetectZeroesOptions detect_zeroes = BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF;
585 QDict *options = NULL;
586 const char *export_name = NULL; /* defaults to "" later for server mode */
587 const char *export_description = NULL;
588 BlockDirtyBitmapOrStrList *bitmaps = NULL;
589 bool alloc_depth = false;
590 const char *tlscredsid = NULL;
591 const char *tlshostname = NULL;
592 bool imageOpts = false;
593 bool writethrough = false; /* Client will flush as needed. */
595 unsigned socket_activation;
596 const char *pid_file_name = NULL;
597 const char *selinux_label = NULL;
598 BlockExportOptions *export_opts;
599 struct NbdClientOpts opts = {
600 .fork_process = false,
605 .old_stderr = STDOUT_FILENO,
609 os_setup_early_signal_handling();
610 os_setup_signal_handling();
615 module_call_init(MODULE_INIT_TRACE);
616 qcrypto_init(&error_fatal);
618 module_call_init(MODULE_INIT_QOM);
619 qemu_add_opts(&qemu_trace_opts);
620 qemu_init_exec_dir(argv[0]);
622 while ((ch = getopt_long(argc, argv, sopt, lopt, &opt_ind)) != -1) {
625 flags |= BDRV_O_SNAPSHOT;
628 optarg = (char *) "none";
630 case QEMU_NBD_OPT_CACHE:
632 error_report("-n and --cache can only be specified once");
636 if (bdrv_parse_cache_mode(optarg, &flags, &writethrough) == -1) {
637 error_report("Invalid cache mode `%s'", optarg);
641 case QEMU_NBD_OPT_AIO:
643 error_report("--aio can only be specified once");
647 if (bdrv_parse_aio(optarg, &flags) < 0) {
648 error_report("Invalid aio mode '%s'", optarg);
652 case QEMU_NBD_OPT_DISCARD:
654 error_report("--discard can only be specified once");
658 if (bdrv_parse_discard_flags(optarg, &flags) == -1) {
659 error_report("Invalid discard mode `%s'", optarg);
663 case QEMU_NBD_OPT_DETECT_ZEROES:
665 qapi_enum_parse(&BlockdevDetectZeroesOptions_lookup,
667 BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF,
670 error_reportf_err(local_err,
671 "Failed to parse detect_zeroes mode: ");
674 if (detect_zeroes == BLOCKDEV_DETECT_ZEROES_OPTIONS_UNMAP &&
675 !(flags & BDRV_O_UNMAP)) {
676 error_report("setting detect-zeroes to unmap is not allowed "
677 "without setting discard operation to unmap");
688 if (qemu_strtou64(optarg, NULL, 0, &dev_offset) < 0) {
689 error_report("Invalid offset '%s'", optarg);
694 if (strstart(optarg, SNAPSHOT_OPT_BASE, NULL)) {
695 sn_opts = qemu_opts_parse_noisily(&internal_snapshot_opts,
698 error_report("Failed in parsing snapshot param `%s'",
703 sn_id_or_name = optarg;
708 flags &= ~BDRV_O_RDWR;
715 BlockDirtyBitmapOrStr *el = g_new(BlockDirtyBitmapOrStr, 1);
716 *el = (BlockDirtyBitmapOrStr) {
717 .type = QTYPE_QSTRING,
718 .u.local = g_strdup(optarg),
720 QAPI_LIST_PREPEND(bitmaps, el);
725 if (sockpath[0] != '/') {
726 error_report("socket path must be absolute");
734 opts.device = optarg;
737 if (qemu_strtoi(optarg, NULL, 0, &shared) < 0 ||
739 error_report("Invalid shared device number '%s'", optarg);
750 export_name = optarg;
751 if (strlen(export_name) > NBD_MAX_STRING_SIZE) {
752 error_report("export name '%s' too long", export_name);
757 export_description = optarg;
758 if (strlen(export_description) > NBD_MAX_STRING_SIZE) {
759 error_report("export description '%s' too long",
776 error_report("Try `%s --help' for more information.", argv[0]);
778 case QEMU_NBD_OPT_OBJECT:
779 user_creatable_process_cmdline(optarg);
781 case QEMU_NBD_OPT_TLSCREDS:
784 case QEMU_NBD_OPT_TLSHOSTNAME:
785 tlshostname = optarg;
787 case QEMU_NBD_OPT_IMAGE_OPTS:
791 trace_opt_parse(optarg);
793 case QEMU_NBD_OPT_TLSAUTHZ:
796 case QEMU_NBD_OPT_FORK:
797 opts.fork_process = true;
802 case QEMU_NBD_OPT_PID_FILE:
803 pid_file_name = optarg;
805 case QEMU_NBD_OPT_SELINUX_LABEL:
806 selinux_label = optarg;
812 if (argc != optind) {
813 error_report("List mode is incompatible with a file name");
816 if (export_name || export_description || dev_offset ||
817 opts.device || disconnect || fmt || sn_id_or_name || bitmaps ||
818 alloc_depth || seen_aio || seen_discard || seen_cache) {
819 error_report("List mode is incompatible with per-device settings");
822 if (opts.fork_process) {
823 error_report("List mode is incompatible with forking");
826 } else if ((argc - optind) != 1) {
827 error_report("Invalid number of arguments");
828 error_printf("Try `%s --help' for more information.\n", argv[0]);
830 } else if (!export_name) {
834 if (!trace_init_backends()) {
838 qemu_set_log(LOG_TRACE, &error_fatal);
840 socket_activation = check_socket_activation();
841 if (socket_activation == 0) {
843 setup_address_and_port(&bindto, &port);
846 /* Using socket activation - check user didn't use -p etc. */
847 const char *err_msg = socket_activation_validate_opts(opts.device,
852 if (err_msg != NULL) {
853 error_report("%s", err_msg);
857 /* qemu-nbd can only listen on a single socket. */
858 if (socket_activation > 1) {
859 error_report("qemu-nbd does not support socket activation with %s > 1",
867 error_report("TLS is not supported with a host device");
870 if (tlsauthz && list) {
871 error_report("TLS authorization is incompatible with export list");
874 if (tlshostname && !list) {
875 error_report("TLS hostname is only supported with export list");
878 tlscreds = nbd_get_tls_creds(tlscredsid, list, &local_err);
880 error_reportf_err(local_err, "Failed to get TLS creds: ");
885 error_report("--tls-authz is not permitted without --tls-creds");
889 error_report("--tls-hostname is not permitted without --tls-creds");
895 #ifdef CONFIG_SELINUX
896 if (sockpath == NULL && opts.device == NULL) {
897 error_report("--selinux-label is not permitted without --socket");
901 error_report("SELinux support not enabled in this binary");
907 opts.saddr = nbd_build_socket_address(sockpath, bindto, port);
908 return qemu_nbd_client_list(opts.saddr, tlscreds,
909 tlshostname ? tlshostname : bindto);
913 if (disconnect || opts.device) {
914 error_report("Kernel /dev/nbdN support not available");
917 #else /* HAVE_NBD_DEVICE */
919 int nbdfd = open(argv[optind], O_RDWR);
921 error_report("Cannot open %s: %s", argv[optind],
925 nbd_disconnect(nbdfd);
929 printf("%s disconnected\n", argv[optind]);
935 if ((opts.device && !opts.verbose) || opts.fork_process) {
937 g_autoptr(GError) err = NULL;
942 if (!g_unix_open_pipe(stderr_fd, FD_CLOEXEC, &err)) {
943 error_report("Error setting up communication pipe: %s",
948 /* Now daemonize, but keep a communication channel open to
949 * print errors and exit with the proper status code.
953 error_report("Failed to fork: %s", strerror(errno));
955 } else if (pid == 0) {
960 /* Remember parent's stderr if we will be restoring it. */
961 if (opts.verbose /* fork_process is set */) {
962 opts.old_stderr = dup(STDERR_FILENO);
963 if (opts.old_stderr < 0) {
964 error_report("Could not dup original stderr: %s",
970 ret = qemu_daemon(1, 0);
971 saved_errno = errno; /* dup2 will overwrite error below */
973 /* Temporarily redirect stderr to the parent's pipe... */
974 if (dup2(stderr_fd[1], STDERR_FILENO) < 0) {
976 snprintf(str, sizeof(str),
977 "%s: Failed to link stderr to the pipe: %s\n",
978 g_get_prgname(), strerror(errno));
980 * We are unable to use error_report() here as we need to get
981 * stderr pointed to the parent's pipe. Write to that pipe
984 ret = write(stderr_fd[1], str, strlen(str));
989 error_report("Failed to daemonize: %s", strerror(saved_errno));
993 /* ... close the descriptor we inherited and go on. */
999 /* In the parent. Print error messages from the child until
1000 * it closes the pipe.
1002 close(stderr_fd[1]);
1003 buf = g_malloc(1024);
1004 while ((ret = read(stderr_fd[0], buf, 1024)) > 0) {
1006 ret = qemu_write_full(STDERR_FILENO, buf, ret);
1012 error_report("Cannot read from daemon: %s",
1017 /* Usually the daemon should not print any message.
1018 * Exit with zero status in that case.
1023 error_report("Unable to fork into background on Windows hosts");
1028 if (opts.device != NULL && sockpath == NULL) {
1029 sockpath = g_malloc(128);
1030 snprintf(sockpath, 128, SOCKET_PATH, basename(opts.device));
1033 server = qio_net_listener_new();
1034 if (socket_activation == 0) {
1037 if (persistent || shared == 0) {
1038 backlog = SOMAXCONN;
1040 backlog = MIN(shared, SOMAXCONN);
1042 #ifdef CONFIG_SELINUX
1043 if (selinux_label && setsockcreatecon_raw(selinux_label) == -1) {
1044 error_report("Cannot set SELinux socket create context to %s: %s",
1045 selinux_label, strerror(errno));
1049 opts.saddr = nbd_build_socket_address(sockpath, bindto, port);
1050 if (qio_net_listener_open_sync(server, opts.saddr, backlog,
1052 object_unref(OBJECT(server));
1053 error_report_err(local_err);
1056 #ifdef CONFIG_SELINUX
1057 if (selinux_label && setsockcreatecon_raw(NULL) == -1) {
1058 error_report("Cannot clear SELinux socket create context: %s",
1065 /* See comment in check_socket_activation above. */
1066 for (i = 0; i < socket_activation; i++) {
1067 QIOChannelSocket *sioc;
1068 sioc = qio_channel_socket_new_fd(FIRST_SOCKET_ACTIVATION_FD + i,
1071 object_unref(OBJECT(server));
1072 error_reportf_err(local_err,
1073 "Failed to use socket activation: ");
1076 qio_net_listener_add(server, sioc);
1077 object_unref(OBJECT(sioc));
1081 qemu_init_main_loop(&error_fatal);
1083 atexit(qemu_nbd_shutdown);
1085 opts.srcpath = argv[optind];
1089 error_report("--image-opts and -f are mutually exclusive");
1092 o = qemu_opts_parse_noisily(&file_opts, opts.srcpath, true);
1094 qemu_opts_reset(&file_opts);
1097 options = qemu_opts_to_qdict(o, NULL);
1098 qemu_opts_reset(&file_opts);
1099 blk = blk_new_open(NULL, NULL, options, flags, &local_err);
1102 options = qdict_new();
1103 qdict_put_str(options, "driver", fmt);
1105 blk = blk_new_open(opts.srcpath, NULL, options, flags, &local_err);
1109 error_reportf_err(local_err, "Failed to blk_new_open '%s': ",
1116 QDict *raw_opts = qdict_new();
1117 qdict_put_str(raw_opts, "driver", "raw");
1118 qdict_put_str(raw_opts, "file", bs->node_name);
1119 qdict_put_int(raw_opts, "offset", dev_offset);
1121 aio_context_acquire(qemu_get_aio_context());
1122 bs = bdrv_open(NULL, NULL, raw_opts, flags, &error_fatal);
1123 aio_context_release(qemu_get_aio_context());
1126 blk_insert_bs(blk, bs, &error_fatal);
1130 blk_set_enable_write_cache(blk, !writethrough);
1133 ret = bdrv_snapshot_load_tmp(bs,
1134 qemu_opt_get(sn_opts, SNAPSHOT_OPT_ID),
1135 qemu_opt_get(sn_opts, SNAPSHOT_OPT_NAME),
1137 } else if (sn_id_or_name) {
1138 ret = bdrv_snapshot_load_tmp_by_id_or_name(bs, sn_id_or_name,
1142 error_reportf_err(local_err, "Failed to load snapshot: ");
1146 bs->detect_zeroes = detect_zeroes;
1148 nbd_server_is_qemu_nbd(shared);
1150 export_opts = g_new(BlockExportOptions, 1);
1151 *export_opts = (BlockExportOptions) {
1152 .type = BLOCK_EXPORT_TYPE_NBD,
1153 .id = g_strdup("qemu-nbd-export"),
1154 .node_name = g_strdup(bdrv_get_node_name(bs)),
1155 .has_writethrough = true,
1156 .writethrough = writethrough,
1157 .has_writable = true,
1158 .writable = !readonly,
1160 .name = g_strdup(export_name),
1161 .description = g_strdup(export_description),
1162 .has_bitmaps = !!bitmaps,
1164 .has_allocation_depth = alloc_depth,
1165 .allocation_depth = alloc_depth,
1168 blk_exp_add(export_opts, &error_fatal);
1169 qapi_free_BlockExportOptions(export_opts);
1174 ret = pthread_create(&client_thread, NULL, nbd_client_thread, &opts);
1176 error_report("Failed to create client thread: %s", strerror(ret));
1181 /* Shut up GCC warnings. */
1182 memset(&client_thread, 0, sizeof(client_thread));
1185 nbd_update_server_watch();
1187 if (pid_file_name) {
1188 qemu_write_pidfile(pid_file_name, &error_fatal);
1191 /* now when the initialization is (almost) complete, chdir("/")
1192 * to free any busy filesystems */
1193 if (chdir("/") < 0) {
1194 error_report("Could not chdir to root directory: %s",
1199 if (opts.fork_process) {
1200 nbd_client_release_pipe(opts.old_stderr);
1205 main_loop_wait(false);
1206 if (state == TERMINATE) {
1207 blk_exp_close_all();
1210 } while (state != TERMINATED);
1217 qemu_opts_del(sn_opts);
1221 pthread_join(client_thread, &ret);