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 used to access the disk image, the\n"
139 " valid options are: 'none', 'writeback' (default),\n"
140 " 'writethrough', 'directsync' and 'unsafe'\n"
141 " --aio=MODE set AIO mode (native, io_uring or threads)\n"
142 " --discard=MODE set discard mode (ignore, unmap)\n"
143 " --detect-zeroes=MODE set detect-zeroes mode (off, on, unmap)\n"
144 " --image-opts treat FILE as a full set of image options\n"
146 QEMU_HELP_BOTTOM
"\n"
147 , name
, name
, NBD_DEFAULT_PORT
, "DEVICE");
150 static void version(const char *name
)
153 "%s " QEMU_FULL_VERSION
"\n"
154 "Written by Anthony Liguori.\n"
157 "This is free software; see the source for copying conditions. There is NO\n"
158 "warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n"
164 * The client thread uses SIGTERM to interrupt the server. A signal
165 * handler ensures that "qemu-nbd -v -c" exits with a nice status code.
167 void qemu_system_killed(int signum
, pid_t pid
)
169 qatomic_cmpxchg(&state
, RUNNING
, TERMINATE
);
172 #endif /* CONFIG_POSIX */
174 static int qemu_nbd_client_list(SocketAddress
*saddr
, QCryptoTLSCreds
*tls
,
175 const char *hostname
)
177 int ret
= EXIT_FAILURE
;
180 QIOChannelSocket
*sioc
;
184 sioc
= qio_channel_socket_new();
185 if (qio_channel_socket_connect_sync(sioc
, saddr
, &err
) < 0) {
186 error_report_err(err
);
189 rc
= nbd_receive_export_list(QIO_CHANNEL(sioc
), tls
, hostname
, &list
,
193 error_report_err(err
);
197 printf("exports available: %d\n", rc
);
198 for (i
= 0; i
< rc
; i
++) {
199 printf(" export: '%s'\n", list
[i
].name
);
200 if (list
[i
].description
&& *list
[i
].description
) {
201 printf(" description: %s\n", list
[i
].description
);
203 if (list
[i
].flags
& NBD_FLAG_HAS_FLAGS
) {
204 static const char *const flag_names
[] = {
205 [NBD_FLAG_READ_ONLY_BIT
] = "readonly",
206 [NBD_FLAG_SEND_FLUSH_BIT
] = "flush",
207 [NBD_FLAG_SEND_FUA_BIT
] = "fua",
208 [NBD_FLAG_ROTATIONAL_BIT
] = "rotational",
209 [NBD_FLAG_SEND_TRIM_BIT
] = "trim",
210 [NBD_FLAG_SEND_WRITE_ZEROES_BIT
] = "zeroes",
211 [NBD_FLAG_SEND_DF_BIT
] = "df",
212 [NBD_FLAG_CAN_MULTI_CONN_BIT
] = "multi",
213 [NBD_FLAG_SEND_RESIZE_BIT
] = "resize",
214 [NBD_FLAG_SEND_CACHE_BIT
] = "cache",
215 [NBD_FLAG_SEND_FAST_ZERO_BIT
] = "fast-zero",
218 printf(" size: %" PRIu64
"\n", list
[i
].size
);
219 printf(" flags: 0x%x (", list
[i
].flags
);
220 for (size_t bit
= 0; bit
< ARRAY_SIZE(flag_names
); bit
++) {
221 if (flag_names
[bit
] && (list
[i
].flags
& (1 << bit
))) {
222 printf(" %s", flag_names
[bit
]);
227 if (list
[i
].min_block
) {
228 printf(" min block: %u\n", list
[i
].min_block
);
229 printf(" opt block: %u\n", list
[i
].opt_block
);
230 printf(" max block: %u\n", list
[i
].max_block
);
232 if (list
[i
].n_contexts
) {
233 printf(" available meta contexts: %d\n", list
[i
].n_contexts
);
234 for (j
= 0; j
< list
[i
].n_contexts
; j
++) {
235 printf(" %s\n", list
[i
].contexts
[j
]);
239 nbd_free_export_list(list
, rc
);
243 object_unref(OBJECT(sioc
));
249 static void *show_parts(void *arg
)
254 /* linux just needs an open() to trigger
255 * the partition table update
256 * but remember to load the module with max_part != 0 :
257 * modprobe nbd max_part=63
259 nbd
= open(device
, O_RDWR
);
266 static void *nbd_client_thread(void *arg
)
269 NBDExportInfo info
= { .request_sizes
= false, .name
= g_strdup("") };
270 QIOChannelSocket
*sioc
;
272 int ret
= EXIT_FAILURE
;
273 pthread_t show_parts_thread
;
274 Error
*local_error
= NULL
;
276 sioc
= qio_channel_socket_new();
277 if (qio_channel_socket_connect_sync(sioc
,
280 error_report_err(local_error
);
284 if (nbd_receive_negotiate(NULL
, QIO_CHANNEL(sioc
),
285 NULL
, NULL
, NULL
, &info
, &local_error
) < 0) {
287 error_report_err(local_error
);
292 fd
= open(device
, O_RDWR
);
294 /* Linux-only, we can use %m in printf. */
295 error_report("Failed to open %s: %m", device
);
299 if (nbd_init(fd
, sioc
, &info
, &local_error
) < 0) {
300 error_report_err(local_error
);
304 /* update partition table */
305 pthread_create(&show_parts_thread
, NULL
, show_parts
, device
);
308 fprintf(stderr
, "NBD device %s is now connected to %s\n",
311 /* Close stderr so that the qemu-nbd process exits. */
312 dup2(STDOUT_FILENO
, STDERR_FILENO
);
315 if (nbd_client(fd
) < 0) {
325 object_unref(OBJECT(sioc
));
327 kill(getpid(), SIGTERM
);
328 return (void *) (intptr_t) ret
;
330 #endif /* HAVE_NBD_DEVICE */
332 static int nbd_can_accept(void)
334 return state
== RUNNING
&& (shared
== 0 || nb_fds
< shared
);
337 static void nbd_update_server_watch(void);
339 static void nbd_client_closed(NBDClient
*client
, bool negotiated
)
342 if (negotiated
&& nb_fds
== 0 && !persistent
&& state
== RUNNING
) {
345 nbd_update_server_watch();
346 nbd_client_put(client
);
349 static void nbd_accept(QIONetListener
*listener
, QIOChannelSocket
*cioc
,
352 if (state
>= TERMINATE
) {
357 nbd_update_server_watch();
358 nbd_client_new(cioc
, tlscreds
, tlsauthz
, nbd_client_closed
);
361 static void nbd_update_server_watch(void)
363 if (nbd_can_accept()) {
364 qio_net_listener_set_client_func(server
, nbd_accept
, NULL
, NULL
);
366 qio_net_listener_set_client_func(server
, NULL
, NULL
, NULL
);
371 static SocketAddress
*nbd_build_socket_address(const char *sockpath
,
375 SocketAddress
*saddr
;
377 saddr
= g_new0(SocketAddress
, 1);
379 saddr
->type
= SOCKET_ADDRESS_TYPE_UNIX
;
380 saddr
->u
.q_unix
.path
= g_strdup(sockpath
);
382 InetSocketAddress
*inet
;
383 saddr
->type
= SOCKET_ADDRESS_TYPE_INET
;
384 inet
= &saddr
->u
.inet
;
385 inet
->host
= g_strdup(bindto
);
387 inet
->port
= g_strdup(port
);
389 inet
->port
= g_strdup_printf("%d", NBD_DEFAULT_PORT
);
397 static QemuOptsList file_opts
= {
399 .implied_opt_name
= "file",
400 .head
= QTAILQ_HEAD_INITIALIZER(file_opts
.head
),
402 /* no elements => accept any params */
403 { /* end of list */ }
407 static QCryptoTLSCreds
*nbd_get_tls_creds(const char *id
, bool list
,
411 QCryptoTLSCreds
*creds
;
413 obj
= object_resolve_path_component(
414 object_get_objects_root(), id
);
416 error_setg(errp
, "No TLS credentials with id '%s'",
420 creds
= (QCryptoTLSCreds
*)
421 object_dynamic_cast(obj
, TYPE_QCRYPTO_TLS_CREDS
);
423 error_setg(errp
, "Object with id '%s' is not TLS credentials",
428 if (!qcrypto_tls_creds_check_endpoint(creds
,
430 ? QCRYPTO_TLS_CREDS_ENDPOINT_CLIENT
431 : QCRYPTO_TLS_CREDS_ENDPOINT_SERVER
,
439 static void setup_address_and_port(const char **address
, const char **port
)
441 if (*address
== NULL
) {
442 *address
= "0.0.0.0";
446 *port
= stringify(NBD_DEFAULT_PORT
);
451 * Check socket parameters compatibility when socket activation is used.
453 static const char *socket_activation_validate_opts(const char *device
,
454 const char *sockpath
,
459 if (device
!= NULL
) {
460 return "NBD device can't be set when using socket activation";
463 if (sockpath
!= NULL
) {
464 return "Unix socket can't be set when using socket activation";
467 if (address
!= NULL
) {
468 return "The interface can't be set when using socket activation";
472 return "TCP port number can't be set when using socket activation";
476 return "List mode is incompatible with socket activation";
482 static void qemu_nbd_shutdown(void)
484 job_cancel_sync_all();
489 int main(int argc
, char **argv
)
492 BlockDriverState
*bs
;
493 uint64_t dev_offset
= 0;
494 bool readonly
= false;
495 bool disconnect
= false;
496 const char *bindto
= NULL
;
497 const char *port
= NULL
;
498 char *sockpath
= NULL
;
500 QemuOpts
*sn_opts
= NULL
;
501 const char *sn_id_or_name
= NULL
;
502 const char *sopt
= "hVb:o:p:rsnc:dvk:e:f:tl:x:T:D:AB:L";
503 struct option lopt
[] = {
504 { "help", no_argument
, NULL
, 'h' },
505 { "version", no_argument
, NULL
, 'V' },
506 { "bind", required_argument
, NULL
, 'b' },
507 { "port", required_argument
, NULL
, 'p' },
508 { "socket", required_argument
, NULL
, 'k' },
509 { "offset", required_argument
, NULL
, 'o' },
510 { "read-only", no_argument
, NULL
, 'r' },
511 { "allocation-depth", no_argument
, NULL
, 'A' },
512 { "bitmap", required_argument
, NULL
, 'B' },
513 { "connect", required_argument
, NULL
, 'c' },
514 { "disconnect", no_argument
, NULL
, 'd' },
515 { "list", no_argument
, NULL
, 'L' },
516 { "snapshot", no_argument
, NULL
, 's' },
517 { "load-snapshot", required_argument
, NULL
, 'l' },
518 { "nocache", no_argument
, NULL
, 'n' },
519 { "cache", required_argument
, NULL
, QEMU_NBD_OPT_CACHE
},
520 { "aio", required_argument
, NULL
, QEMU_NBD_OPT_AIO
},
521 { "discard", required_argument
, NULL
, QEMU_NBD_OPT_DISCARD
},
522 { "detect-zeroes", required_argument
, NULL
,
523 QEMU_NBD_OPT_DETECT_ZEROES
},
524 { "shared", required_argument
, NULL
, 'e' },
525 { "format", required_argument
, NULL
, 'f' },
526 { "persistent", no_argument
, NULL
, 't' },
527 { "verbose", no_argument
, NULL
, 'v' },
528 { "object", required_argument
, NULL
, QEMU_NBD_OPT_OBJECT
},
529 { "export-name", required_argument
, NULL
, 'x' },
530 { "description", required_argument
, NULL
, 'D' },
531 { "tls-creds", required_argument
, NULL
, QEMU_NBD_OPT_TLSCREDS
},
532 { "tls-authz", required_argument
, NULL
, QEMU_NBD_OPT_TLSAUTHZ
},
533 { "image-opts", no_argument
, NULL
, QEMU_NBD_OPT_IMAGE_OPTS
},
534 { "trace", required_argument
, NULL
, 'T' },
535 { "fork", no_argument
, NULL
, QEMU_NBD_OPT_FORK
},
536 { "pid-file", required_argument
, NULL
, QEMU_NBD_OPT_PID_FILE
},
541 int flags
= BDRV_O_RDWR
;
543 bool seen_cache
= false;
544 bool seen_discard
= false;
545 bool seen_aio
= false;
546 pthread_t client_thread
;
547 const char *fmt
= NULL
;
548 Error
*local_err
= NULL
;
549 BlockdevDetectZeroesOptions detect_zeroes
= BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF
;
550 QDict
*options
= NULL
;
551 const char *export_name
= NULL
; /* defaults to "" later for server mode */
552 const char *export_description
= NULL
;
553 strList
*bitmaps
= NULL
;
554 bool alloc_depth
= false;
555 const char *tlscredsid
= NULL
;
556 bool imageOpts
= false;
557 bool writethrough
= false; /* Client will flush as needed. */
558 bool fork_process
= false;
561 unsigned socket_activation
;
562 const char *pid_file_name
= NULL
;
563 BlockExportOptions
*export_opts
;
566 os_setup_early_signal_handling();
567 os_setup_signal_handling();
572 module_call_init(MODULE_INIT_TRACE
);
573 qcrypto_init(&error_fatal
);
575 module_call_init(MODULE_INIT_QOM
);
576 qemu_add_opts(&qemu_trace_opts
);
577 qemu_init_exec_dir(argv
[0]);
579 while ((ch
= getopt_long(argc
, argv
, sopt
, lopt
, &opt_ind
)) != -1) {
582 flags
|= BDRV_O_SNAPSHOT
;
585 optarg
= (char *) "none";
587 case QEMU_NBD_OPT_CACHE
:
589 error_report("-n and --cache can only be specified once");
593 if (bdrv_parse_cache_mode(optarg
, &flags
, &writethrough
) == -1) {
594 error_report("Invalid cache mode `%s'", optarg
);
598 case QEMU_NBD_OPT_AIO
:
600 error_report("--aio can only be specified once");
604 if (bdrv_parse_aio(optarg
, &flags
) < 0) {
605 error_report("Invalid aio mode '%s'", optarg
);
609 case QEMU_NBD_OPT_DISCARD
:
611 error_report("--discard can only be specified once");
615 if (bdrv_parse_discard_flags(optarg
, &flags
) == -1) {
616 error_report("Invalid discard mode `%s'", optarg
);
620 case QEMU_NBD_OPT_DETECT_ZEROES
:
622 qapi_enum_parse(&BlockdevDetectZeroesOptions_lookup
,
624 BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF
,
627 error_reportf_err(local_err
,
628 "Failed to parse detect_zeroes mode: ");
631 if (detect_zeroes
== BLOCKDEV_DETECT_ZEROES_OPTIONS_UNMAP
&&
632 !(flags
& BDRV_O_UNMAP
)) {
633 error_report("setting detect-zeroes to unmap is not allowed "
634 "without setting discard operation to unmap");
645 if (qemu_strtou64(optarg
, NULL
, 0, &dev_offset
) < 0) {
646 error_report("Invalid offset '%s'", optarg
);
651 if (strstart(optarg
, SNAPSHOT_OPT_BASE
, NULL
)) {
652 sn_opts
= qemu_opts_parse_noisily(&internal_snapshot_opts
,
655 error_report("Failed in parsing snapshot param `%s'",
660 sn_id_or_name
= optarg
;
665 flags
&= ~BDRV_O_RDWR
;
671 QAPI_LIST_PREPEND(bitmaps
, g_strdup(optarg
));
675 if (sockpath
[0] != '/') {
676 error_report("socket path must be absolute");
687 if (qemu_strtoi(optarg
, NULL
, 0, &shared
) < 0 ||
689 error_report("Invalid shared device number '%s'", optarg
);
700 export_name
= optarg
;
701 if (strlen(export_name
) > NBD_MAX_STRING_SIZE
) {
702 error_report("export name '%s' too long", export_name
);
707 export_description
= optarg
;
708 if (strlen(export_description
) > NBD_MAX_STRING_SIZE
) {
709 error_report("export description '%s' too long",
726 error_report("Try `%s --help' for more information.", argv
[0]);
728 case QEMU_NBD_OPT_OBJECT
:
729 user_creatable_process_cmdline(optarg
);
731 case QEMU_NBD_OPT_TLSCREDS
:
734 case QEMU_NBD_OPT_IMAGE_OPTS
:
738 trace_opt_parse(optarg
);
740 case QEMU_NBD_OPT_TLSAUTHZ
:
743 case QEMU_NBD_OPT_FORK
:
749 case QEMU_NBD_OPT_PID_FILE
:
750 pid_file_name
= optarg
;
756 if (argc
!= optind
) {
757 error_report("List mode is incompatible with a file name");
760 if (export_name
|| export_description
|| dev_offset
||
761 device
|| disconnect
|| fmt
|| sn_id_or_name
|| bitmaps
||
762 alloc_depth
|| seen_aio
|| seen_discard
|| seen_cache
) {
763 error_report("List mode is incompatible with per-device settings");
767 error_report("List mode is incompatible with forking");
770 } else if ((argc
- optind
) != 1) {
771 error_report("Invalid number of arguments");
772 error_printf("Try `%s --help' for more information.\n", argv
[0]);
774 } else if (!export_name
) {
778 if (!trace_init_backends()) {
782 qemu_set_log(LOG_TRACE
);
784 socket_activation
= check_socket_activation();
785 if (socket_activation
== 0) {
786 setup_address_and_port(&bindto
, &port
);
788 /* Using socket activation - check user didn't use -p etc. */
789 const char *err_msg
= socket_activation_validate_opts(device
, sockpath
,
792 if (err_msg
!= NULL
) {
793 error_report("%s", err_msg
);
797 /* qemu-nbd can only listen on a single socket. */
798 if (socket_activation
> 1) {
799 error_report("qemu-nbd does not support socket activation with %s > 1",
807 error_report("TLS is only supported with IPv4/IPv6");
811 error_report("TLS is not supported with a host device");
814 if (tlsauthz
&& list
) {
815 error_report("TLS authorization is incompatible with export list");
818 tlscreds
= nbd_get_tls_creds(tlscredsid
, list
, &local_err
);
820 error_reportf_err(local_err
, "Failed to get TLS creds: ");
825 error_report("--tls-authz is not permitted without --tls-creds");
831 saddr
= nbd_build_socket_address(sockpath
, bindto
, port
);
832 return qemu_nbd_client_list(saddr
, tlscreds
, bindto
);
836 if (disconnect
|| device
) {
837 error_report("Kernel /dev/nbdN support not available");
840 #else /* HAVE_NBD_DEVICE */
842 int nbdfd
= open(argv
[optind
], O_RDWR
);
844 error_report("Cannot open %s: %s", argv
[optind
],
848 nbd_disconnect(nbdfd
);
852 printf("%s disconnected\n", argv
[optind
]);
858 if ((device
&& !verbose
) || fork_process
) {
864 if (qemu_pipe(stderr_fd
) < 0) {
865 error_report("Error setting up communication pipe: %s",
870 /* Now daemonize, but keep a communication channel open to
871 * print errors and exit with the proper status code.
875 error_report("Failed to fork: %s", strerror(errno
));
877 } else if (pid
== 0) {
880 /* Remember parent's stderr if we will be restoring it. */
882 old_stderr
= dup(STDERR_FILENO
);
885 ret
= qemu_daemon(1, 0);
887 /* Temporarily redirect stderr to the parent's pipe... */
888 dup2(stderr_fd
[1], STDERR_FILENO
);
890 error_report("Failed to daemonize: %s", strerror(errno
));
894 /* ... close the descriptor we inherited and go on. */
900 /* In the parent. Print error messages from the child until
901 * it closes the pipe.
904 buf
= g_malloc(1024);
905 while ((ret
= read(stderr_fd
[0], buf
, 1024)) > 0) {
907 ret
= qemu_write_full(STDERR_FILENO
, buf
, ret
);
913 error_report("Cannot read from daemon: %s",
918 /* Usually the daemon should not print any message.
919 * Exit with zero status in that case.
924 error_report("Unable to fork into background on Windows hosts");
929 if (device
!= NULL
&& sockpath
== NULL
) {
930 sockpath
= g_malloc(128);
931 snprintf(sockpath
, 128, SOCKET_PATH
, basename(device
));
934 server
= qio_net_listener_new();
935 if (socket_activation
== 0) {
938 if (persistent
|| shared
== 0) {
941 backlog
= MIN(shared
, SOMAXCONN
);
943 saddr
= nbd_build_socket_address(sockpath
, bindto
, port
);
944 if (qio_net_listener_open_sync(server
, saddr
, backlog
,
946 object_unref(OBJECT(server
));
947 error_report_err(local_err
);
952 /* See comment in check_socket_activation above. */
953 for (i
= 0; i
< socket_activation
; i
++) {
954 QIOChannelSocket
*sioc
;
955 sioc
= qio_channel_socket_new_fd(FIRST_SOCKET_ACTIVATION_FD
+ i
,
958 object_unref(OBJECT(server
));
959 error_reportf_err(local_err
,
960 "Failed to use socket activation: ");
963 qio_net_listener_add(server
, sioc
);
964 object_unref(OBJECT(sioc
));
968 qemu_init_main_loop(&error_fatal
);
970 atexit(qemu_nbd_shutdown
);
972 srcpath
= argv
[optind
];
976 error_report("--image-opts and -f are mutually exclusive");
979 opts
= qemu_opts_parse_noisily(&file_opts
, srcpath
, true);
981 qemu_opts_reset(&file_opts
);
984 options
= qemu_opts_to_qdict(opts
, NULL
);
985 qemu_opts_reset(&file_opts
);
986 blk
= blk_new_open(NULL
, NULL
, options
, flags
, &local_err
);
989 options
= qdict_new();
990 qdict_put_str(options
, "driver", fmt
);
992 blk
= blk_new_open(srcpath
, NULL
, options
, flags
, &local_err
);
996 error_reportf_err(local_err
, "Failed to blk_new_open '%s': ",
1003 QDict
*raw_opts
= qdict_new();
1004 qdict_put_str(raw_opts
, "driver", "raw");
1005 qdict_put_str(raw_opts
, "file", bs
->node_name
);
1006 qdict_put_int(raw_opts
, "offset", dev_offset
);
1007 bs
= bdrv_open(NULL
, NULL
, raw_opts
, flags
, &error_fatal
);
1009 blk_insert_bs(blk
, bs
, &error_fatal
);
1013 blk_set_enable_write_cache(blk
, !writethrough
);
1016 ret
= bdrv_snapshot_load_tmp(bs
,
1017 qemu_opt_get(sn_opts
, SNAPSHOT_OPT_ID
),
1018 qemu_opt_get(sn_opts
, SNAPSHOT_OPT_NAME
),
1020 } else if (sn_id_or_name
) {
1021 ret
= bdrv_snapshot_load_tmp_by_id_or_name(bs
, sn_id_or_name
,
1025 error_reportf_err(local_err
, "Failed to load snapshot: ");
1029 bs
->detect_zeroes
= detect_zeroes
;
1031 nbd_server_is_qemu_nbd(true);
1033 export_opts
= g_new(BlockExportOptions
, 1);
1034 *export_opts
= (BlockExportOptions
) {
1035 .type
= BLOCK_EXPORT_TYPE_NBD
,
1036 .id
= g_strdup("qemu-nbd-export"),
1037 .node_name
= g_strdup(bdrv_get_node_name(bs
)),
1038 .has_writethrough
= true,
1039 .writethrough
= writethrough
,
1040 .has_writable
= true,
1041 .writable
= !readonly
,
1044 .name
= g_strdup(export_name
),
1045 .has_description
= !!export_description
,
1046 .description
= g_strdup(export_description
),
1047 .has_bitmaps
= !!bitmaps
,
1049 .has_allocation_depth
= alloc_depth
,
1050 .allocation_depth
= alloc_depth
,
1053 blk_exp_add(export_opts
, &error_fatal
);
1054 qapi_free_BlockExportOptions(export_opts
);
1060 ret
= pthread_create(&client_thread
, NULL
, nbd_client_thread
, device
);
1062 error_report("Failed to create client thread: %s", strerror(ret
));
1067 /* Shut up GCC warnings. */
1068 memset(&client_thread
, 0, sizeof(client_thread
));
1071 nbd_update_server_watch();
1073 if (pid_file_name
) {
1074 qemu_write_pidfile(pid_file_name
, &error_fatal
);
1077 /* now when the initialization is (almost) complete, chdir("/")
1078 * to free any busy filesystems */
1079 if (chdir("/") < 0) {
1080 error_report("Could not chdir to root directory: %s",
1086 dup2(old_stderr
, STDERR_FILENO
);
1092 main_loop_wait(false);
1093 if (state
== TERMINATE
) {
1094 blk_exp_close_all();
1097 } while (state
!= TERMINATED
);
1104 qemu_opts_del(sn_opts
);
1108 pthread_join(client_thread
, &ret
);