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-common.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 #define HAVE_NBD_DEVICE 1
53 #define HAVE_NBD_DEVICE 0
56 #define SOCKET_PATH "/var/lock/qemu-nbd-%s"
57 #define QEMU_NBD_OPT_CACHE 256
58 #define QEMU_NBD_OPT_AIO 257
59 #define QEMU_NBD_OPT_DISCARD 258
60 #define QEMU_NBD_OPT_DETECT_ZEROES 259
61 #define QEMU_NBD_OPT_OBJECT 260
62 #define QEMU_NBD_OPT_TLSCREDS 261
63 #define QEMU_NBD_OPT_IMAGE_OPTS 262
64 #define QEMU_NBD_OPT_FORK 263
65 #define QEMU_NBD_OPT_TLSAUTHZ 264
66 #define QEMU_NBD_OPT_PID_FILE 265
72 static SocketAddress
*saddr
;
73 static int persistent
= 0;
74 static enum { RUNNING
, TERMINATE
, TERMINATED
} state
;
75 static int shared
= 1;
77 static QIONetListener
*server
;
78 static QCryptoTLSCreds
*tlscreds
;
79 static const char *tlsauthz
;
81 static void usage(const char *name
)
84 "Usage: %s [OPTIONS] FILE\n"
85 " or: %s -L [OPTIONS]\n"
86 "QEMU Disk Network Block Device Utility\n"
88 " -h, --help display this help and exit\n"
89 " -V, --version output version information and exit\n"
91 "Connection properties:\n"
92 " -p, --port=PORT port to listen on (default `%d')\n"
93 " -b, --bind=IFACE interface to bind to (default `0.0.0.0')\n"
94 " -k, --socket=PATH path to the unix socket\n"
95 " (default '"SOCKET_PATH
"')\n"
96 " -e, --shared=NUM device can be shared by NUM clients (default '1')\n"
97 " -t, --persistent don't exit on the last connection\n"
98 " -v, --verbose display extra debugging information\n"
99 " -x, --export-name=NAME expose export by name (default is empty string)\n"
100 " -D, --description=TEXT export a human-readable description\n"
102 "Exposing part of the image:\n"
103 " -o, --offset=OFFSET offset into the image\n"
104 " -A, --allocation-depth expose the allocation depth\n"
105 " -B, --bitmap=NAME expose a persistent dirty bitmap\n"
107 "General purpose options:\n"
108 " -L, --list list exports available from another NBD server\n"
109 " --object type,id=ID,... define an object such as 'secret' for providing\n"
110 " passwords and/or encryption keys\n"
111 " --tls-creds=ID use id of an earlier --object to provide TLS\n"
112 " --tls-authz=ID use id of an earlier --object to provide\n"
114 " -T, --trace [[enable=]<pattern>][,events=<file>][,file=<file>]\n"
115 " specify tracing options\n"
116 " --fork fork off the server process and exit the parent\n"
117 " once the server is running\n"
118 " --pid-file=PATH store the server's process ID in the given file\n"
121 "Kernel NBD client support:\n"
122 " -c, --connect=DEV connect FILE to the local NBD device DEV\n"
123 " -d, --disconnect disconnect the specified device\n"
126 "Block device options:\n"
127 " -f, --format=FORMAT set image format (raw, qcow2, ...)\n"
128 " -r, --read-only export read-only\n"
129 " -s, --snapshot use FILE as an external snapshot, create a temporary\n"
130 " file with backing_file=FILE, redirect the write to\n"
131 " the temporary one\n"
132 " -l, --load-snapshot=SNAPSHOT_PARAM\n"
133 " load an internal snapshot inside FILE and export it\n"
134 " as an read-only device, SNAPSHOT_PARAM format is\n"
135 " 'snapshot.id=[ID],snapshot.name=[NAME]', or\n"
137 " -n, --nocache disable host cache\n"
138 " --cache=MODE set cache mode (none, writeback, ...)\n"
139 " --aio=MODE set AIO mode (native, io_uring or threads)\n"
140 " --discard=MODE set discard mode (ignore, unmap)\n"
141 " --detect-zeroes=MODE set detect-zeroes mode (off, on, unmap)\n"
142 " --image-opts treat FILE as a full set of image options\n"
144 QEMU_HELP_BOTTOM
"\n"
145 , name
, name
, NBD_DEFAULT_PORT
, "DEVICE");
148 static void version(const char *name
)
151 "%s " QEMU_FULL_VERSION
"\n"
152 "Written by Anthony Liguori.\n"
155 "This is free software; see the source for copying conditions. There is NO\n"
156 "warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n"
162 * The client thread uses SIGTERM to interrupt the server. A signal
163 * handler ensures that "qemu-nbd -v -c" exits with a nice status code.
165 void qemu_system_killed(int signum
, pid_t pid
)
167 qatomic_cmpxchg(&state
, RUNNING
, TERMINATE
);
170 #endif /* CONFIG_POSIX */
172 static int qemu_nbd_client_list(SocketAddress
*saddr
, QCryptoTLSCreds
*tls
,
173 const char *hostname
)
175 int ret
= EXIT_FAILURE
;
178 QIOChannelSocket
*sioc
;
182 sioc
= qio_channel_socket_new();
183 if (qio_channel_socket_connect_sync(sioc
, saddr
, &err
) < 0) {
184 error_report_err(err
);
187 rc
= nbd_receive_export_list(QIO_CHANNEL(sioc
), tls
, hostname
, &list
,
191 error_report_err(err
);
195 printf("exports available: %d\n", rc
);
196 for (i
= 0; i
< rc
; i
++) {
197 printf(" export: '%s'\n", list
[i
].name
);
198 if (list
[i
].description
&& *list
[i
].description
) {
199 printf(" description: %s\n", list
[i
].description
);
201 if (list
[i
].flags
& NBD_FLAG_HAS_FLAGS
) {
202 static const char *const flag_names
[] = {
203 [NBD_FLAG_READ_ONLY_BIT
] = "readonly",
204 [NBD_FLAG_SEND_FLUSH_BIT
] = "flush",
205 [NBD_FLAG_SEND_FUA_BIT
] = "fua",
206 [NBD_FLAG_ROTATIONAL_BIT
] = "rotational",
207 [NBD_FLAG_SEND_TRIM_BIT
] = "trim",
208 [NBD_FLAG_SEND_WRITE_ZEROES_BIT
] = "zeroes",
209 [NBD_FLAG_SEND_DF_BIT
] = "df",
210 [NBD_FLAG_CAN_MULTI_CONN_BIT
] = "multi",
211 [NBD_FLAG_SEND_RESIZE_BIT
] = "resize",
212 [NBD_FLAG_SEND_CACHE_BIT
] = "cache",
213 [NBD_FLAG_SEND_FAST_ZERO_BIT
] = "fast-zero",
216 printf(" size: %" PRIu64
"\n", list
[i
].size
);
217 printf(" flags: 0x%x (", list
[i
].flags
);
218 for (size_t bit
= 0; bit
< ARRAY_SIZE(flag_names
); bit
++) {
219 if (flag_names
[bit
] && (list
[i
].flags
& (1 << bit
))) {
220 printf(" %s", flag_names
[bit
]);
225 if (list
[i
].min_block
) {
226 printf(" min block: %u\n", list
[i
].min_block
);
227 printf(" opt block: %u\n", list
[i
].opt_block
);
228 printf(" max block: %u\n", list
[i
].max_block
);
230 if (list
[i
].n_contexts
) {
231 printf(" available meta contexts: %d\n", list
[i
].n_contexts
);
232 for (j
= 0; j
< list
[i
].n_contexts
; j
++) {
233 printf(" %s\n", list
[i
].contexts
[j
]);
237 nbd_free_export_list(list
, rc
);
241 object_unref(OBJECT(sioc
));
247 static void *show_parts(void *arg
)
252 /* linux just needs an open() to trigger
253 * the partition table update
254 * but remember to load the module with max_part != 0 :
255 * modprobe nbd max_part=63
257 nbd
= open(device
, O_RDWR
);
264 static void *nbd_client_thread(void *arg
)
267 NBDExportInfo info
= { .request_sizes
= false, .name
= g_strdup("") };
268 QIOChannelSocket
*sioc
;
270 int ret
= EXIT_FAILURE
;
271 pthread_t show_parts_thread
;
272 Error
*local_error
= NULL
;
274 sioc
= qio_channel_socket_new();
275 if (qio_channel_socket_connect_sync(sioc
,
278 error_report_err(local_error
);
282 if (nbd_receive_negotiate(NULL
, QIO_CHANNEL(sioc
),
283 NULL
, NULL
, NULL
, &info
, &local_error
) < 0) {
285 error_report_err(local_error
);
290 fd
= open(device
, O_RDWR
);
292 /* Linux-only, we can use %m in printf. */
293 error_report("Failed to open %s: %m", device
);
297 if (nbd_init(fd
, sioc
, &info
, &local_error
) < 0) {
298 error_report_err(local_error
);
302 /* update partition table */
303 pthread_create(&show_parts_thread
, NULL
, show_parts
, device
);
306 fprintf(stderr
, "NBD device %s is now connected to %s\n",
309 /* Close stderr so that the qemu-nbd process exits. */
310 dup2(STDOUT_FILENO
, STDERR_FILENO
);
313 if (nbd_client(fd
) < 0) {
323 object_unref(OBJECT(sioc
));
325 kill(getpid(), SIGTERM
);
326 return (void *) (intptr_t) ret
;
328 #endif /* HAVE_NBD_DEVICE */
330 static int nbd_can_accept(void)
332 return state
== RUNNING
&& (shared
== 0 || nb_fds
< shared
);
335 static void nbd_update_server_watch(void);
337 static void nbd_client_closed(NBDClient
*client
, bool negotiated
)
340 if (negotiated
&& nb_fds
== 0 && !persistent
&& state
== RUNNING
) {
343 nbd_update_server_watch();
344 nbd_client_put(client
);
347 static void nbd_accept(QIONetListener
*listener
, QIOChannelSocket
*cioc
,
350 if (state
>= TERMINATE
) {
355 nbd_update_server_watch();
356 nbd_client_new(cioc
, tlscreds
, tlsauthz
, nbd_client_closed
);
359 static void nbd_update_server_watch(void)
361 if (nbd_can_accept()) {
362 qio_net_listener_set_client_func(server
, nbd_accept
, NULL
, NULL
);
364 qio_net_listener_set_client_func(server
, NULL
, NULL
, NULL
);
369 static SocketAddress
*nbd_build_socket_address(const char *sockpath
,
373 SocketAddress
*saddr
;
375 saddr
= g_new0(SocketAddress
, 1);
377 saddr
->type
= SOCKET_ADDRESS_TYPE_UNIX
;
378 saddr
->u
.q_unix
.path
= g_strdup(sockpath
);
380 InetSocketAddress
*inet
;
381 saddr
->type
= SOCKET_ADDRESS_TYPE_INET
;
382 inet
= &saddr
->u
.inet
;
383 inet
->host
= g_strdup(bindto
);
385 inet
->port
= g_strdup(port
);
387 inet
->port
= g_strdup_printf("%d", NBD_DEFAULT_PORT
);
395 static QemuOptsList file_opts
= {
397 .implied_opt_name
= "file",
398 .head
= QTAILQ_HEAD_INITIALIZER(file_opts
.head
),
400 /* no elements => accept any params */
401 { /* end of list */ }
405 static QCryptoTLSCreds
*nbd_get_tls_creds(const char *id
, bool list
,
409 QCryptoTLSCreds
*creds
;
411 obj
= object_resolve_path_component(
412 object_get_objects_root(), id
);
414 error_setg(errp
, "No TLS credentials with id '%s'",
418 creds
= (QCryptoTLSCreds
*)
419 object_dynamic_cast(obj
, TYPE_QCRYPTO_TLS_CREDS
);
421 error_setg(errp
, "Object with id '%s' is not TLS credentials",
426 if (!qcrypto_tls_creds_check_endpoint(creds
,
428 ? QCRYPTO_TLS_CREDS_ENDPOINT_CLIENT
429 : QCRYPTO_TLS_CREDS_ENDPOINT_SERVER
,
437 static void setup_address_and_port(const char **address
, const char **port
)
439 if (*address
== NULL
) {
440 *address
= "0.0.0.0";
444 *port
= stringify(NBD_DEFAULT_PORT
);
449 * Check socket parameters compatibility when socket activation is used.
451 static const char *socket_activation_validate_opts(const char *device
,
452 const char *sockpath
,
457 if (device
!= NULL
) {
458 return "NBD device can't be set when using socket activation";
461 if (sockpath
!= NULL
) {
462 return "Unix socket can't be set when using socket activation";
465 if (address
!= NULL
) {
466 return "The interface can't be set when using socket activation";
470 return "TCP port number can't be set when using socket activation";
474 return "List mode is incompatible with socket activation";
480 static void qemu_nbd_shutdown(void)
482 job_cancel_sync_all();
487 int main(int argc
, char **argv
)
490 BlockDriverState
*bs
;
491 uint64_t dev_offset
= 0;
492 bool readonly
= false;
493 bool disconnect
= false;
494 const char *bindto
= NULL
;
495 const char *port
= NULL
;
496 char *sockpath
= NULL
;
498 QemuOpts
*sn_opts
= NULL
;
499 const char *sn_id_or_name
= NULL
;
500 const char *sopt
= "hVb:o:p:rsnc:dvk:e:f:tl:x:T:D:AB:L";
501 struct option lopt
[] = {
502 { "help", no_argument
, NULL
, 'h' },
503 { "version", no_argument
, NULL
, 'V' },
504 { "bind", required_argument
, NULL
, 'b' },
505 { "port", required_argument
, NULL
, 'p' },
506 { "socket", required_argument
, NULL
, 'k' },
507 { "offset", required_argument
, NULL
, 'o' },
508 { "read-only", no_argument
, NULL
, 'r' },
509 { "allocation-depth", no_argument
, NULL
, 'A' },
510 { "bitmap", required_argument
, NULL
, 'B' },
511 { "connect", required_argument
, NULL
, 'c' },
512 { "disconnect", no_argument
, NULL
, 'd' },
513 { "list", no_argument
, NULL
, 'L' },
514 { "snapshot", no_argument
, NULL
, 's' },
515 { "load-snapshot", required_argument
, NULL
, 'l' },
516 { "nocache", no_argument
, NULL
, 'n' },
517 { "cache", required_argument
, NULL
, QEMU_NBD_OPT_CACHE
},
518 { "aio", required_argument
, NULL
, QEMU_NBD_OPT_AIO
},
519 { "discard", required_argument
, NULL
, QEMU_NBD_OPT_DISCARD
},
520 { "detect-zeroes", required_argument
, NULL
,
521 QEMU_NBD_OPT_DETECT_ZEROES
},
522 { "shared", required_argument
, NULL
, 'e' },
523 { "format", required_argument
, NULL
, 'f' },
524 { "persistent", no_argument
, NULL
, 't' },
525 { "verbose", no_argument
, NULL
, 'v' },
526 { "object", required_argument
, NULL
, QEMU_NBD_OPT_OBJECT
},
527 { "export-name", required_argument
, NULL
, 'x' },
528 { "description", required_argument
, NULL
, 'D' },
529 { "tls-creds", required_argument
, NULL
, QEMU_NBD_OPT_TLSCREDS
},
530 { "tls-authz", required_argument
, NULL
, QEMU_NBD_OPT_TLSAUTHZ
},
531 { "image-opts", no_argument
, NULL
, QEMU_NBD_OPT_IMAGE_OPTS
},
532 { "trace", required_argument
, NULL
, 'T' },
533 { "fork", no_argument
, NULL
, QEMU_NBD_OPT_FORK
},
534 { "pid-file", required_argument
, NULL
, QEMU_NBD_OPT_PID_FILE
},
539 int flags
= BDRV_O_RDWR
;
541 bool seen_cache
= false;
542 bool seen_discard
= false;
543 bool seen_aio
= false;
544 pthread_t client_thread
;
545 const char *fmt
= NULL
;
546 Error
*local_err
= NULL
;
547 BlockdevDetectZeroesOptions detect_zeroes
= BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF
;
548 QDict
*options
= NULL
;
549 const char *export_name
= NULL
; /* defaults to "" later for server mode */
550 const char *export_description
= NULL
;
551 strList
*bitmaps
= NULL
;
552 bool alloc_depth
= false;
553 const char *tlscredsid
= NULL
;
554 bool imageOpts
= false;
555 bool writethrough
= true;
556 bool fork_process
= false;
559 unsigned socket_activation
;
560 const char *pid_file_name
= NULL
;
561 BlockExportOptions
*export_opts
;
564 os_setup_early_signal_handling();
565 os_setup_signal_handling();
570 module_call_init(MODULE_INIT_TRACE
);
571 qcrypto_init(&error_fatal
);
573 module_call_init(MODULE_INIT_QOM
);
574 qemu_add_opts(&qemu_trace_opts
);
575 qemu_init_exec_dir(argv
[0]);
577 while ((ch
= getopt_long(argc
, argv
, sopt
, lopt
, &opt_ind
)) != -1) {
580 flags
|= BDRV_O_SNAPSHOT
;
583 optarg
= (char *) "none";
585 case QEMU_NBD_OPT_CACHE
:
587 error_report("-n and --cache can only be specified once");
591 if (bdrv_parse_cache_mode(optarg
, &flags
, &writethrough
) == -1) {
592 error_report("Invalid cache mode `%s'", optarg
);
596 case QEMU_NBD_OPT_AIO
:
598 error_report("--aio can only be specified once");
602 if (bdrv_parse_aio(optarg
, &flags
) < 0) {
603 error_report("Invalid aio mode '%s'", optarg
);
607 case QEMU_NBD_OPT_DISCARD
:
609 error_report("--discard can only be specified once");
613 if (bdrv_parse_discard_flags(optarg
, &flags
) == -1) {
614 error_report("Invalid discard mode `%s'", optarg
);
618 case QEMU_NBD_OPT_DETECT_ZEROES
:
620 qapi_enum_parse(&BlockdevDetectZeroesOptions_lookup
,
622 BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF
,
625 error_reportf_err(local_err
,
626 "Failed to parse detect_zeroes mode: ");
629 if (detect_zeroes
== BLOCKDEV_DETECT_ZEROES_OPTIONS_UNMAP
&&
630 !(flags
& BDRV_O_UNMAP
)) {
631 error_report("setting detect-zeroes to unmap is not allowed "
632 "without setting discard operation to unmap");
643 if (qemu_strtou64(optarg
, NULL
, 0, &dev_offset
) < 0) {
644 error_report("Invalid offset '%s'", optarg
);
649 if (strstart(optarg
, SNAPSHOT_OPT_BASE
, NULL
)) {
650 sn_opts
= qemu_opts_parse_noisily(&internal_snapshot_opts
,
653 error_report("Failed in parsing snapshot param `%s'",
658 sn_id_or_name
= optarg
;
663 flags
&= ~BDRV_O_RDWR
;
669 QAPI_LIST_PREPEND(bitmaps
, g_strdup(optarg
));
673 if (sockpath
[0] != '/') {
674 error_report("socket path must be absolute");
685 if (qemu_strtoi(optarg
, NULL
, 0, &shared
) < 0 ||
687 error_report("Invalid shared device number '%s'", optarg
);
698 export_name
= optarg
;
699 if (strlen(export_name
) > NBD_MAX_STRING_SIZE
) {
700 error_report("export name '%s' too long", export_name
);
705 export_description
= optarg
;
706 if (strlen(export_description
) > NBD_MAX_STRING_SIZE
) {
707 error_report("export description '%s' too long",
724 error_report("Try `%s --help' for more information.", argv
[0]);
726 case QEMU_NBD_OPT_OBJECT
:
727 user_creatable_process_cmdline(optarg
);
729 case QEMU_NBD_OPT_TLSCREDS
:
732 case QEMU_NBD_OPT_IMAGE_OPTS
:
736 trace_opt_parse(optarg
);
738 case QEMU_NBD_OPT_TLSAUTHZ
:
741 case QEMU_NBD_OPT_FORK
:
747 case QEMU_NBD_OPT_PID_FILE
:
748 pid_file_name
= optarg
;
754 if (argc
!= optind
) {
755 error_report("List mode is incompatible with a file name");
758 if (export_name
|| export_description
|| dev_offset
||
759 device
|| disconnect
|| fmt
|| sn_id_or_name
|| bitmaps
||
760 alloc_depth
|| seen_aio
|| seen_discard
|| seen_cache
) {
761 error_report("List mode is incompatible with per-device settings");
765 error_report("List mode is incompatible with forking");
768 } else if ((argc
- optind
) != 1) {
769 error_report("Invalid number of arguments");
770 error_printf("Try `%s --help' for more information.\n", argv
[0]);
772 } else if (!export_name
) {
776 if (!trace_init_backends()) {
780 qemu_set_log(LOG_TRACE
);
782 socket_activation
= check_socket_activation();
783 if (socket_activation
== 0) {
784 setup_address_and_port(&bindto
, &port
);
786 /* Using socket activation - check user didn't use -p etc. */
787 const char *err_msg
= socket_activation_validate_opts(device
, sockpath
,
790 if (err_msg
!= NULL
) {
791 error_report("%s", err_msg
);
795 /* qemu-nbd can only listen on a single socket. */
796 if (socket_activation
> 1) {
797 error_report("qemu-nbd does not support socket activation with %s > 1",
805 error_report("TLS is only supported with IPv4/IPv6");
809 error_report("TLS is not supported with a host device");
812 if (tlsauthz
&& list
) {
813 error_report("TLS authorization is incompatible with export list");
816 tlscreds
= nbd_get_tls_creds(tlscredsid
, list
, &local_err
);
818 error_reportf_err(local_err
, "Failed to get TLS creds: ");
823 error_report("--tls-authz is not permitted without --tls-creds");
829 saddr
= nbd_build_socket_address(sockpath
, bindto
, port
);
830 return qemu_nbd_client_list(saddr
, tlscreds
, bindto
);
834 if (disconnect
|| device
) {
835 error_report("Kernel /dev/nbdN support not available");
838 #else /* HAVE_NBD_DEVICE */
840 int nbdfd
= open(argv
[optind
], O_RDWR
);
842 error_report("Cannot open %s: %s", argv
[optind
],
846 nbd_disconnect(nbdfd
);
850 printf("%s disconnected\n", argv
[optind
]);
856 if ((device
&& !verbose
) || fork_process
) {
862 if (qemu_pipe(stderr_fd
) < 0) {
863 error_report("Error setting up communication pipe: %s",
868 /* Now daemonize, but keep a communication channel open to
869 * print errors and exit with the proper status code.
873 error_report("Failed to fork: %s", strerror(errno
));
875 } else if (pid
== 0) {
878 /* Remember parent's stderr if we will be restoring it. */
880 old_stderr
= dup(STDERR_FILENO
);
883 ret
= qemu_daemon(1, 0);
885 /* Temporarily redirect stderr to the parent's pipe... */
886 dup2(stderr_fd
[1], STDERR_FILENO
);
888 error_report("Failed to daemonize: %s", strerror(errno
));
892 /* ... close the descriptor we inherited and go on. */
898 /* In the parent. Print error messages from the child until
899 * it closes the pipe.
902 buf
= g_malloc(1024);
903 while ((ret
= read(stderr_fd
[0], buf
, 1024)) > 0) {
905 ret
= qemu_write_full(STDERR_FILENO
, buf
, ret
);
911 error_report("Cannot read from daemon: %s",
916 /* Usually the daemon should not print any message.
917 * Exit with zero status in that case.
922 error_report("Unable to fork into background on Windows hosts");
927 if (device
!= NULL
&& sockpath
== NULL
) {
928 sockpath
= g_malloc(128);
929 snprintf(sockpath
, 128, SOCKET_PATH
, basename(device
));
932 server
= qio_net_listener_new();
933 if (socket_activation
== 0) {
936 if (persistent
|| shared
== 0) {
939 backlog
= MIN(shared
, SOMAXCONN
);
941 saddr
= nbd_build_socket_address(sockpath
, bindto
, port
);
942 if (qio_net_listener_open_sync(server
, saddr
, backlog
,
944 object_unref(OBJECT(server
));
945 error_report_err(local_err
);
950 /* See comment in check_socket_activation above. */
951 for (i
= 0; i
< socket_activation
; i
++) {
952 QIOChannelSocket
*sioc
;
953 sioc
= qio_channel_socket_new_fd(FIRST_SOCKET_ACTIVATION_FD
+ i
,
956 object_unref(OBJECT(server
));
957 error_reportf_err(local_err
,
958 "Failed to use socket activation: ");
961 qio_net_listener_add(server
, sioc
);
962 object_unref(OBJECT(sioc
));
966 qemu_init_main_loop(&error_fatal
);
968 atexit(qemu_nbd_shutdown
);
970 srcpath
= argv
[optind
];
974 error_report("--image-opts and -f are mutually exclusive");
977 opts
= qemu_opts_parse_noisily(&file_opts
, srcpath
, true);
979 qemu_opts_reset(&file_opts
);
982 options
= qemu_opts_to_qdict(opts
, NULL
);
983 qemu_opts_reset(&file_opts
);
984 blk
= blk_new_open(NULL
, NULL
, options
, flags
, &local_err
);
987 options
= qdict_new();
988 qdict_put_str(options
, "driver", fmt
);
990 blk
= blk_new_open(srcpath
, NULL
, options
, flags
, &local_err
);
994 error_reportf_err(local_err
, "Failed to blk_new_open '%s': ",
1001 QDict
*raw_opts
= qdict_new();
1002 qdict_put_str(raw_opts
, "driver", "raw");
1003 qdict_put_str(raw_opts
, "file", bs
->node_name
);
1004 qdict_put_int(raw_opts
, "offset", dev_offset
);
1005 bs
= bdrv_open(NULL
, NULL
, raw_opts
, flags
, &error_fatal
);
1007 blk_insert_bs(blk
, bs
, &error_fatal
);
1011 blk_set_enable_write_cache(blk
, !writethrough
);
1014 ret
= bdrv_snapshot_load_tmp(bs
,
1015 qemu_opt_get(sn_opts
, SNAPSHOT_OPT_ID
),
1016 qemu_opt_get(sn_opts
, SNAPSHOT_OPT_NAME
),
1018 } else if (sn_id_or_name
) {
1019 ret
= bdrv_snapshot_load_tmp_by_id_or_name(bs
, sn_id_or_name
,
1023 error_reportf_err(local_err
, "Failed to load snapshot: ");
1027 bs
->detect_zeroes
= detect_zeroes
;
1029 nbd_server_is_qemu_nbd(true);
1031 export_opts
= g_new(BlockExportOptions
, 1);
1032 *export_opts
= (BlockExportOptions
) {
1033 .type
= BLOCK_EXPORT_TYPE_NBD
,
1034 .id
= g_strdup("qemu-nbd-export"),
1035 .node_name
= g_strdup(bdrv_get_node_name(bs
)),
1036 .has_writethrough
= true,
1037 .writethrough
= writethrough
,
1038 .has_writable
= true,
1039 .writable
= !readonly
,
1042 .name
= g_strdup(export_name
),
1043 .has_description
= !!export_description
,
1044 .description
= g_strdup(export_description
),
1045 .has_bitmaps
= !!bitmaps
,
1047 .has_allocation_depth
= alloc_depth
,
1048 .allocation_depth
= alloc_depth
,
1051 blk_exp_add(export_opts
, &error_fatal
);
1052 qapi_free_BlockExportOptions(export_opts
);
1058 ret
= pthread_create(&client_thread
, NULL
, nbd_client_thread
, device
);
1060 error_report("Failed to create client thread: %s", strerror(ret
));
1065 /* Shut up GCC warnings. */
1066 memset(&client_thread
, 0, sizeof(client_thread
));
1069 nbd_update_server_watch();
1071 if (pid_file_name
) {
1072 qemu_write_pidfile(pid_file_name
, &error_fatal
);
1075 /* now when the initialization is (almost) complete, chdir("/")
1076 * to free any busy filesystems */
1077 if (chdir("/") < 0) {
1078 error_report("Could not chdir to root directory: %s",
1084 dup2(old_stderr
, STDERR_FILENO
);
1090 main_loop_wait(false);
1091 if (state
== TERMINATE
) {
1092 blk_exp_close_all();
1095 } while (state
!= TERMINATED
);
1102 qemu_opts_del(sn_opts
);
1106 pthread_join(client_thread
, &ret
);