]> git.ipfire.org Git - thirdparty/qemu.git/blame - qemu-nbd.c
qemu-nbd: fix regression with qemu-nbd --fork run over ssh
[thirdparty/qemu.git] / qemu-nbd.c
CommitLineData
cd831bd7 1/*
7a5ca864
FB
2 * Copyright (C) 2005 Anthony Liguori <anthony@codemonkey.ws>
3 *
4 * Network Block Device
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 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
8167ee88 16 * along with this program; if not, see <http://www.gnu.org/licenses/>.
7a5ca864
FB
17 */
18
d38ea87a 19#include "qemu/osdep.h"
c2a3d7da
EB
20#include <getopt.h>
21#include <libgen.h>
22#include <pthread.h>
23
49f95221 24#include "qemu/help-texts.h"
da34e65c 25#include "qapi/error.h"
f348b6d1 26#include "qemu/cutils.h"
26f54e9a 27#include "sysemu/block-backend.h"
cbc20bfb 28#include "sysemu/runstate.h" /* for qemu_system_killed() prototype */
b3838a40 29#include "block/block_int.h"
737e150e 30#include "block/nbd.h"
6a1751b7 31#include "qemu/main-loop.h"
0b8fa32f 32#include "qemu/module.h"
922a01a0 33#include "qemu/option.h"
537b41f5 34#include "qemu/error-report.h"
0ab3b337 35#include "qemu/config-file.h"
58369e22 36#include "qemu/bswap.h"
39ca463e 37#include "qemu/log.h"
53fabd4b 38#include "qemu/systemd.h"
8c116b0e 39#include "block/snapshot.h"
452fcdbc 40#include "qapi/qmp/qdict.h"
d49b6836 41#include "qapi/qmp/qstring.h"
0ab3b337 42#include "qom/object_interfaces.h"
d0d6ff58 43#include "io/channel-socket.h"
e4849c1d 44#include "io/net-listener.h"
c2297088 45#include "crypto/init.h"
0279cd95 46#include "crypto/tlscreds.h"
39ca463e 47#include "trace/control.h"
be377133 48#include "qemu-version.h"
7a5ca864 49
3d212b41
RJ
50#ifdef CONFIG_SELINUX
51#include <selinux/selinux.h>
52#endif
53
3c1fa35d
EB
54#ifdef __linux__
55#define HAVE_NBD_DEVICE 1
56#else
57#define HAVE_NBD_DEVICE 0
58#endif
59
713cc671 60#define SOCKET_PATH "/var/lock/qemu-nbd-%s"
fa8b7ce2
DB
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
ffb31e1d 68#define QEMU_NBD_OPT_FORK 263
b25e12da 69#define QEMU_NBD_OPT_TLSAUTHZ 264
637bc5a5 70#define QEMU_NBD_OPT_PID_FILE 265
3d212b41 71#define QEMU_NBD_OPT_SELINUX_LABEL 266
003b2b25 72#define QEMU_NBD_OPT_TLSHOSTNAME 267
7a5ca864 73
bd31c214
EB
74#define MBR_SIZE 512
75
b1d8e52e 76static int verbose;
a517e88b 77static char *srcpath;
bd269ebc 78static SocketAddress *saddr;
7860a380 79static int persistent = 0;
d794f7f3 80static enum { RUNNING, TERMINATE, TERMINATED } state;
a61c6782
PB
81static int shared = 1;
82static int nb_fds;
e4849c1d 83static QIONetListener *server;
145614a1 84static QCryptoTLSCreds *tlscreds;
b25e12da 85static const char *tlsauthz;
7a5ca864
FB
86
87static void usage(const char *name)
88{
b033cd86 89 (printf) (
7a5ca864 90"Usage: %s [OPTIONS] FILE\n"
68b96f15
EB
91" or: %s -L [OPTIONS]\n"
92"QEMU Disk Network Block Device Utility\n"
7a5ca864 93"\n"
713cc671
PL
94" -h, --help display this help and exit\n"
95" -V, --version output version information and exit\n"
b033cd86
PB
96"\n"
97"Connection properties:\n"
713cc671
PL
98" -p, --port=PORT port to listen on (default `%d')\n"
99" -b, --bind=IFACE interface to bind to (default `0.0.0.0')\n"
100" -k, --socket=PATH path to the unix socket\n"
101" (default '"SOCKET_PATH"')\n"
102" -e, --shared=NUM device can be shared by NUM clients (default '1')\n"
103" -t, --persistent don't exit on the last connection\n"
104" -v, --verbose display extra debugging information\n"
f5cd0bb5
VSO
105" -x, --export-name=NAME expose export by name (default is empty string)\n"
106" -D, --description=TEXT export a human-readable description\n"
7a5ca864 107"\n"
b033cd86 108"Exposing part of the image:\n"
713cc671 109" -o, --offset=OFFSET offset into the image\n"
dbc7b014 110" -A, --allocation-depth expose the allocation depth\n"
636192c4 111" -B, --bitmap=NAME expose a persistent dirty bitmap\n"
b033cd86 112"\n"
0ab3b337 113"General purpose options:\n"
68b96f15 114" -L, --list list exports available from another NBD server\n"
0ab3b337
DB
115" --object type,id=ID,... define an object such as 'secret' for providing\n"
116" passwords and/or encryption keys\n"
f7812df7 117" --tls-creds=ID use id of an earlier --object to provide TLS\n"
b25e12da
DB
118" --tls-authz=ID use id of an earlier --object to provide\n"
119" authorization\n"
39ca463e
DL
120" -T, --trace [[enable=]<pattern>][,events=<file>][,file=<file>]\n"
121" specify tracing options\n"
ffb31e1d
HR
122" --fork fork off the server process and exit the parent\n"
123" once the server is running\n"
637bc5a5 124" --pid-file=PATH store the server's process ID in the given file\n"
3d212b41
RJ
125#ifdef CONFIG_SELINUX
126" --selinux-label=LABEL set SELinux process label on listening socket\n"
127#endif
3c1fa35d
EB
128#if HAVE_NBD_DEVICE
129"\n"
b033cd86 130"Kernel NBD client support:\n"
713cc671
PL
131" -c, --connect=DEV connect FILE to the local NBD device DEV\n"
132" -d, --disconnect disconnect the specified device\n"
b033cd86
PB
133#endif
134"\n"
135"Block device options:\n"
713cc671
PL
136" -f, --format=FORMAT set image format (raw, qcow2, ...)\n"
137" -r, --read-only export read-only\n"
138" -s, --snapshot use FILE as an external snapshot, create a temporary\n"
139" file with backing_file=FILE, redirect the write to\n"
140" the temporary one\n"
8c116b0e 141" -l, --load-snapshot=SNAPSHOT_PARAM\n"
713cc671
PL
142" load an internal snapshot inside FILE and export it\n"
143" as an read-only device, SNAPSHOT_PARAM format is\n"
144" 'snapshot.id=[ID],snapshot.name=[NAME]', or\n"
145" '[ID_OR_NAME]'\n"
146" -n, --nocache disable host cache\n"
09615257
NS
147" --cache=MODE set cache mode used to access the disk image, the\n"
148" valid options are: 'none', 'writeback' (default),\n"
149" 'writethrough', 'directsync' and 'unsafe'\n"
7680274d 150" --aio=MODE set AIO mode (native, io_uring or threads)\n"
b3838a40 151" --discard=MODE set discard mode (ignore, unmap)\n"
6883de6c 152" --detect-zeroes=MODE set detect-zeroes mode (off, on, unmap)\n"
77c9aaef 153" --image-opts treat FILE as a full set of image options\n"
b033cd86 154"\n"
f5048cb7 155QEMU_HELP_BOTTOM "\n"
68b96f15 156 , name, name, NBD_DEFAULT_PORT, "DEVICE");
7a5ca864
FB
157}
158
159static void version(const char *name)
160{
161 printf(
7e563bfb 162"%s " QEMU_FULL_VERSION "\n"
7a5ca864
FB
163"Written by Anthony Liguori.\n"
164"\n"
be377133 165QEMU_COPYRIGHT "\n"
7a5ca864
FB
166"This is free software; see the source for copying conditions. There is NO\n"
167"warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n"
315bc7aa 168 , name);
7a5ca864
FB
169}
170
029a88c9 171#ifdef CONFIG_POSIX
cbc20bfb
SH
172/*
173 * The client thread uses SIGTERM to interrupt the server. A signal
174 * handler ensures that "qemu-nbd -v -c" exits with a nice status code.
175 */
176void qemu_system_killed(int signum, pid_t pid)
bb345110 177{
d73415a3 178 qatomic_cmpxchg(&state, RUNNING, TERMINATE);
a61c6782 179 qemu_notify_event();
bb345110 180}
029a88c9 181#endif /* CONFIG_POSIX */
537b41f5 182
68b96f15
EB
183static int qemu_nbd_client_list(SocketAddress *saddr, QCryptoTLSCreds *tls,
184 const char *hostname)
185{
186 int ret = EXIT_FAILURE;
187 int rc;
188 Error *err = NULL;
189 QIOChannelSocket *sioc;
190 NBDExportInfo *list;
191 int i, j;
192
193 sioc = qio_channel_socket_new();
194 if (qio_channel_socket_connect_sync(sioc, saddr, &err) < 0) {
195 error_report_err(err);
992809bf 196 goto out;
68b96f15
EB
197 }
198 rc = nbd_receive_export_list(QIO_CHANNEL(sioc), tls, hostname, &list,
199 &err);
200 if (rc < 0) {
201 if (err) {
202 error_report_err(err);
203 }
204 goto out;
205 }
206 printf("exports available: %d\n", rc);
207 for (i = 0; i < rc; i++) {
208 printf(" export: '%s'\n", list[i].name);
209 if (list[i].description && *list[i].description) {
210 printf(" description: %s\n", list[i].description);
211 }
212 if (list[i].flags & NBD_FLAG_HAS_FLAGS) {
c4e2aff8
HR
213 static const char *const flag_names[] = {
214 [NBD_FLAG_READ_ONLY_BIT] = "readonly",
215 [NBD_FLAG_SEND_FLUSH_BIT] = "flush",
216 [NBD_FLAG_SEND_FUA_BIT] = "fua",
217 [NBD_FLAG_ROTATIONAL_BIT] = "rotational",
218 [NBD_FLAG_SEND_TRIM_BIT] = "trim",
219 [NBD_FLAG_SEND_WRITE_ZEROES_BIT] = "zeroes",
220 [NBD_FLAG_SEND_DF_BIT] = "df",
221 [NBD_FLAG_CAN_MULTI_CONN_BIT] = "multi",
222 [NBD_FLAG_SEND_RESIZE_BIT] = "resize",
223 [NBD_FLAG_SEND_CACHE_BIT] = "cache",
0a479545 224 [NBD_FLAG_SEND_FAST_ZERO_BIT] = "fast-zero",
c4e2aff8
HR
225 };
226
68b96f15
EB
227 printf(" size: %" PRIu64 "\n", list[i].size);
228 printf(" flags: 0x%x (", list[i].flags);
c4e2aff8
HR
229 for (size_t bit = 0; bit < ARRAY_SIZE(flag_names); bit++) {
230 if (flag_names[bit] && (list[i].flags & (1 << bit))) {
231 printf(" %s", flag_names[bit]);
232 }
68b96f15
EB
233 }
234 printf(" )\n");
235 }
236 if (list[i].min_block) {
237 printf(" min block: %u\n", list[i].min_block);
238 printf(" opt block: %u\n", list[i].opt_block);
239 printf(" max block: %u\n", list[i].max_block);
240 }
241 if (list[i].n_contexts) {
242 printf(" available meta contexts: %d\n", list[i].n_contexts);
243 for (j = 0; j < list[i].n_contexts; j++) {
244 printf(" %s\n", list[i].contexts[j]);
245 }
246 }
247 }
248 nbd_free_export_list(list, rc);
249
250 ret = EXIT_SUCCESS;
251 out:
252 object_unref(OBJECT(sioc));
253 return ret;
254}
255
256
3c1fa35d 257#if HAVE_NBD_DEVICE
a517e88b 258static void *show_parts(void *arg)
cd831bd7 259{
a6ac2313 260 char *device = arg;
a517e88b
PB
261 int nbd;
262
263 /* linux just needs an open() to trigger
264 * the partition table update
265 * but remember to load the module with max_part != 0 :
266 * modprobe nbd max_part=63
267 */
268 nbd = open(device, O_RDWR);
fc19f8a0 269 if (nbd >= 0) {
a517e88b
PB
270 close(nbd);
271 }
272 return NULL;
273}
cd831bd7 274
03b67621
DL
275struct NbdClientOpts {
276 char *device;
5c56dd27 277 bool fork_process;
03b67621
DL
278};
279
a517e88b
PB
280static void *nbd_client_thread(void *arg)
281{
03b67621 282 struct NbdClientOpts *opts = arg;
6dc1667d 283 NBDExportInfo info = { .request_sizes = false, .name = g_strdup("") };
d0d6ff58 284 QIOChannelSocket *sioc;
af74b550
AC
285 int fd = -1;
286 int ret = EXIT_FAILURE;
a517e88b 287 pthread_t show_parts_thread;
1ce52846 288 Error *local_error = NULL;
a517e88b 289
d0d6ff58
DB
290 sioc = qio_channel_socket_new();
291 if (qio_channel_socket_connect_sync(sioc,
292 saddr,
293 &local_error) < 0) {
48bec07e 294 error_report_err(local_error);
dc10e8b3
SH
295 goto out;
296 }
a517e88b 297
af74b550
AC
298 if (nbd_receive_negotiate(NULL, QIO_CHANNEL(sioc),
299 NULL, NULL, NULL, &info, &local_error) < 0) {
1ce52846 300 if (local_error) {
78288671 301 error_report_err(local_error);
1ce52846 302 }
af74b550 303 goto out;
a517e88b
PB
304 }
305
03b67621 306 fd = open(opts->device, O_RDWR);
fc19f8a0 307 if (fd < 0) {
a6ac2313 308 /* Linux-only, we can use %m in printf. */
03b67621 309 error_report("Failed to open %s: %m", opts->device);
af74b550 310 goto out;
a6ac2313
PB
311 }
312
af74b550 313 if (nbd_init(fd, sioc, &info, &local_error) < 0) {
be41c100 314 error_report_err(local_error);
af74b550 315 goto out;
a517e88b
PB
316 }
317
318 /* update partition table */
03b67621 319 pthread_create(&show_parts_thread, NULL, show_parts, opts->device);
a517e88b 320
5c56dd27 321 if (verbose && !opts->fork_process) {
c1f8fdc3 322 fprintf(stderr, "NBD device %s is now connected to %s\n",
03b67621 323 opts->device, srcpath);
c1f8fdc3
PB
324 } else {
325 /* Close stderr so that the qemu-nbd process exits. */
326 dup2(STDOUT_FILENO, STDERR_FILENO);
327 }
a517e88b 328
af74b550
AC
329 if (nbd_client(fd) < 0) {
330 goto out;
cd831bd7 331 }
a517e88b 332
af74b550
AC
333 ret = EXIT_SUCCESS;
334
335 out:
336 if (fd >= 0) {
337 close(fd);
338 }
d0d6ff58 339 object_unref(OBJECT(sioc));
6dc1667d 340 g_free(info.name);
a517e88b 341 kill(getpid(), SIGTERM);
af74b550 342 return (void *) (intptr_t) ret;
cd831bd7 343}
3c1fa35d 344#endif /* HAVE_NBD_DEVICE */
cd831bd7 345
e4afbf4f 346static int nbd_can_accept(void)
a61c6782 347{
3dcf56e6 348 return state == RUNNING && (shared == 0 || nb_fds < shared);
a61c6782
PB
349}
350
d0d6ff58 351static void nbd_update_server_watch(void);
e4afbf4f 352
0c9390d9 353static void nbd_client_closed(NBDClient *client, bool negotiated)
a61c6782 354{
1743b515 355 nb_fds--;
0c9390d9 356 if (negotiated && nb_fds == 0 && !persistent && state == RUNNING) {
7860a380
PB
357 state = TERMINATE;
358 }
d0d6ff58 359 nbd_update_server_watch();
7860a380 360 nbd_client_put(client);
a61c6782
PB
361}
362
e4849c1d
DB
363static void nbd_accept(QIONetListener *listener, QIOChannelSocket *cioc,
364 gpointer opaque)
a61c6782 365{
7860a380 366 if (state >= TERMINATE) {
e4849c1d 367 return;
7860a380
PB
368 }
369
ee7d7aab 370 nb_fds++;
d0d6ff58 371 nbd_update_server_watch();
b25e12da 372 nbd_client_new(cioc, tlscreds, tlsauthz, nbd_client_closed);
a61c6782
PB
373}
374
d0d6ff58 375static void nbd_update_server_watch(void)
e4afbf4f
FZ
376{
377 if (nbd_can_accept()) {
e4849c1d 378 qio_net_listener_set_client_func(server, nbd_accept, NULL, NULL);
e4afbf4f 379 } else {
e4849c1d 380 qio_net_listener_set_client_func(server, NULL, NULL, NULL);
e4afbf4f
FZ
381 }
382}
383
48bec07e 384
bd269ebc 385static SocketAddress *nbd_build_socket_address(const char *sockpath,
48bec07e
DB
386 const char *bindto,
387 const char *port)
388{
bd269ebc 389 SocketAddress *saddr;
48bec07e 390
bd269ebc 391 saddr = g_new0(SocketAddress, 1);
48bec07e 392 if (sockpath) {
bd269ebc
MA
393 saddr->type = SOCKET_ADDRESS_TYPE_UNIX;
394 saddr->u.q_unix.path = g_strdup(sockpath);
48bec07e 395 } else {
0399293e 396 InetSocketAddress *inet;
bd269ebc
MA
397 saddr->type = SOCKET_ADDRESS_TYPE_INET;
398 inet = &saddr->u.inet;
0399293e 399 inet->host = g_strdup(bindto);
48bec07e 400 if (port) {
0399293e 401 inet->port = g_strdup(port);
48bec07e 402 } else {
0399293e 403 inet->port = g_strdup_printf("%d", NBD_DEFAULT_PORT);
48bec07e
DB
404 }
405 }
406
407 return saddr;
408}
409
410
77c9aaef
DB
411static QemuOptsList file_opts = {
412 .name = "file",
413 .implied_opt_name = "file",
414 .head = QTAILQ_HEAD_INITIALIZER(file_opts.head),
415 .desc = {
416 /* no elements => accept any params */
417 { /* end of list */ }
418 },
419};
420
68b96f15
EB
421static QCryptoTLSCreds *nbd_get_tls_creds(const char *id, bool list,
422 Error **errp)
145614a1
DB
423{
424 Object *obj;
425 QCryptoTLSCreds *creds;
426
427 obj = object_resolve_path_component(
428 object_get_objects_root(), id);
429 if (!obj) {
430 error_setg(errp, "No TLS credentials with id '%s'",
431 id);
432 return NULL;
433 }
434 creds = (QCryptoTLSCreds *)
435 object_dynamic_cast(obj, TYPE_QCRYPTO_TLS_CREDS);
436 if (!creds) {
437 error_setg(errp, "Object with id '%s' is not TLS credentials",
438 id);
439 return NULL;
440 }
441
0279cd95
PMD
442 if (!qcrypto_tls_creds_check_endpoint(creds,
443 list
444 ? QCRYPTO_TLS_CREDS_ENDPOINT_CLIENT
445 : QCRYPTO_TLS_CREDS_ENDPOINT_SERVER,
446 errp)) {
447 return NULL;
145614a1
DB
448 }
449 object_ref(obj);
450 return creds;
451}
452
a721f53b
RJ
453static void setup_address_and_port(const char **address, const char **port)
454{
455 if (*address == NULL) {
456 *address = "0.0.0.0";
457 }
458
459 if (*port == NULL) {
460 *port = stringify(NBD_DEFAULT_PORT);
461 }
462}
463
a721f53b
RJ
464/*
465 * Check socket parameters compatibility when socket activation is used.
466 */
467static const char *socket_activation_validate_opts(const char *device,
468 const char *sockpath,
469 const char *address,
68b96f15 470 const char *port,
3d212b41 471 const char *selinux,
68b96f15 472 bool list)
a721f53b
RJ
473{
474 if (device != NULL) {
475 return "NBD device can't be set when using socket activation";
476 }
477
478 if (sockpath != NULL) {
479 return "Unix socket can't be set when using socket activation";
480 }
481
482 if (address != NULL) {
483 return "The interface can't be set when using socket activation";
484 }
485
486 if (port != NULL) {
487 return "TCP port number can't be set when using socket activation";
488 }
489
3d212b41
RJ
490 if (selinux != NULL) {
491 return "SELinux label can't be set when using socket activation";
492 }
493
68b96f15
EB
494 if (list) {
495 return "List mode is incompatible with socket activation";
496 }
497
a721f53b
RJ
498 return NULL;
499}
145614a1 500
b3b5299d
KW
501static void qemu_nbd_shutdown(void)
502{
503 job_cancel_sync_all();
1895b977 504 blk_exp_close_all();
b3b5299d
KW
505 bdrv_close_all();
506}
507
7a5ca864
FB
508int main(int argc, char **argv)
509{
26f54e9a 510 BlockBackend *blk;
7a5ca864 511 BlockDriverState *bs;
9d26dfcb 512 uint64_t dev_offset = 0;
dbb38caa 513 bool readonly = false;
cd831bd7 514 bool disconnect = false;
a721f53b 515 const char *bindto = NULL;
48bec07e
DB
516 const char *port = NULL;
517 char *sockpath = NULL;
a6ac2313 518 char *device = NULL;
8c116b0e
WX
519 QemuOpts *sn_opts = NULL;
520 const char *sn_id_or_name = NULL;
dbc7b014 521 const char *sopt = "hVb:o:p:rsnc:dvk:e:f:tl:x:T:D:AB:L";
7a5ca864 522 struct option lopt[] = {
aa6e546c
DB
523 { "help", no_argument, NULL, 'h' },
524 { "version", no_argument, NULL, 'V' },
525 { "bind", required_argument, NULL, 'b' },
526 { "port", required_argument, NULL, 'p' },
527 { "socket", required_argument, NULL, 'k' },
528 { "offset", required_argument, NULL, 'o' },
529 { "read-only", no_argument, NULL, 'r' },
dbc7b014 530 { "allocation-depth", no_argument, NULL, 'A' },
636192c4 531 { "bitmap", required_argument, NULL, 'B' },
aa6e546c
DB
532 { "connect", required_argument, NULL, 'c' },
533 { "disconnect", no_argument, NULL, 'd' },
68b96f15 534 { "list", no_argument, NULL, 'L' },
aa6e546c
DB
535 { "snapshot", no_argument, NULL, 's' },
536 { "load-snapshot", required_argument, NULL, 'l' },
537 { "nocache", no_argument, NULL, 'n' },
538 { "cache", required_argument, NULL, QEMU_NBD_OPT_CACHE },
539 { "aio", required_argument, NULL, QEMU_NBD_OPT_AIO },
540 { "discard", required_argument, NULL, QEMU_NBD_OPT_DISCARD },
541 { "detect-zeroes", required_argument, NULL,
542 QEMU_NBD_OPT_DETECT_ZEROES },
543 { "shared", required_argument, NULL, 'e' },
544 { "format", required_argument, NULL, 'f' },
545 { "persistent", no_argument, NULL, 't' },
546 { "verbose", no_argument, NULL, 'v' },
547 { "object", required_argument, NULL, QEMU_NBD_OPT_OBJECT },
548 { "export-name", required_argument, NULL, 'x' },
b1a75b33 549 { "description", required_argument, NULL, 'D' },
aa6e546c 550 { "tls-creds", required_argument, NULL, QEMU_NBD_OPT_TLSCREDS },
003b2b25 551 { "tls-hostname", required_argument, NULL, QEMU_NBD_OPT_TLSHOSTNAME },
b25e12da 552 { "tls-authz", required_argument, NULL, QEMU_NBD_OPT_TLSAUTHZ },
aa6e546c 553 { "image-opts", no_argument, NULL, QEMU_NBD_OPT_IMAGE_OPTS },
39ca463e 554 { "trace", required_argument, NULL, 'T' },
ffb31e1d 555 { "fork", no_argument, NULL, QEMU_NBD_OPT_FORK },
637bc5a5 556 { "pid-file", required_argument, NULL, QEMU_NBD_OPT_PID_FILE },
3d212b41
RJ
557 { "selinux-label", required_argument, NULL,
558 QEMU_NBD_OPT_SELINUX_LABEL },
660f11be 559 { NULL, 0, NULL, 0 }
7a5ca864
FB
560 };
561 int ch;
562 int opt_ind = 0;
f5edb014 563 int flags = BDRV_O_RDWR;
4fbec260 564 int ret = 0;
39a5235c 565 bool seen_cache = false;
ded9d2d5 566 bool seen_discard = false;
39a5235c 567 bool seen_aio = false;
a517e88b 568 pthread_t client_thread;
e6b63677 569 const char *fmt = NULL;
34b5d2c6 570 Error *local_err = NULL;
b3838a40 571 BlockdevDetectZeroesOptions detect_zeroes = BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF;
4fbec260 572 QDict *options = NULL;
68b96f15 573 const char *export_name = NULL; /* defaults to "" later for server mode */
b1a75b33 574 const char *export_description = NULL;
e5fb29d5 575 BlockDirtyBitmapOrStrList *bitmaps = NULL;
dbc7b014 576 bool alloc_depth = false;
145614a1 577 const char *tlscredsid = NULL;
003b2b25 578 const char *tlshostname = NULL;
77c9aaef 579 bool imageOpts = false;
09615257 580 bool writethrough = false; /* Client will flush as needed. */
ffb31e1d 581 bool fork_process = false;
68b96f15 582 bool list = false;
a721f53b 583 unsigned socket_activation;
637bc5a5 584 const char *pid_file_name = NULL;
3d212b41 585 const char *selinux_label = NULL;
00917172 586 BlockExportOptions *export_opts;
7a5ca864 587
029a88c9 588#ifdef CONFIG_POSIX
cbc20bfb
SH
589 os_setup_early_signal_handling();
590 os_setup_signal_handling();
041e32b8
HR
591#endif
592
98c5d2e7 593 socket_init();
f5852efa 594 error_init(argv[0]);
fe4db84d 595 module_call_init(MODULE_INIT_TRACE);
e8f2d272 596 qcrypto_init(&error_fatal);
c2297088 597
0ab3b337 598 module_call_init(MODULE_INIT_QOM);
39ca463e 599 qemu_add_opts(&qemu_trace_opts);
10f5bff6 600 qemu_init_exec_dir(argv[0]);
bb345110 601
7a5ca864
FB
602 while ((ch = getopt_long(argc, argv, sopt, lopt, &opt_ind)) != -1) {
603 switch (ch) {
604 case 's':
2f726488
TS
605 flags |= BDRV_O_SNAPSHOT;
606 break;
607 case 'n':
39a5235c
PB
608 optarg = (char *) "none";
609 /* fallthrough */
610 case QEMU_NBD_OPT_CACHE:
611 if (seen_cache) {
85b01e09
MA
612 error_report("-n and --cache can only be specified once");
613 exit(EXIT_FAILURE);
39a5235c
PB
614 }
615 seen_cache = true;
6effd5bf 616 if (bdrv_parse_cache_mode(optarg, &flags, &writethrough) == -1) {
85b01e09
MA
617 error_report("Invalid cache mode `%s'", optarg);
618 exit(EXIT_FAILURE);
39a5235c 619 }
7a5ca864 620 break;
39a5235c
PB
621 case QEMU_NBD_OPT_AIO:
622 if (seen_aio) {
85b01e09
MA
623 error_report("--aio can only be specified once");
624 exit(EXIT_FAILURE);
39a5235c
PB
625 }
626 seen_aio = true;
7680274d
AM
627 if (bdrv_parse_aio(optarg, &flags) < 0) {
628 error_report("Invalid aio mode '%s'", optarg);
629 exit(EXIT_FAILURE);
39a5235c
PB
630 }
631 break;
ded9d2d5
PB
632 case QEMU_NBD_OPT_DISCARD:
633 if (seen_discard) {
85b01e09
MA
634 error_report("--discard can only be specified once");
635 exit(EXIT_FAILURE);
ded9d2d5
PB
636 }
637 seen_discard = true;
638 if (bdrv_parse_discard_flags(optarg, &flags) == -1) {
85b01e09
MA
639 error_report("Invalid discard mode `%s'", optarg);
640 exit(EXIT_FAILURE);
ded9d2d5
PB
641 }
642 break;
b3838a40
PL
643 case QEMU_NBD_OPT_DETECT_ZEROES:
644 detect_zeroes =
f7abe0ec 645 qapi_enum_parse(&BlockdevDetectZeroesOptions_lookup,
b3838a40 646 optarg,
b3838a40
PL
647 BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF,
648 &local_err);
649 if (local_err) {
c29b77f9
MA
650 error_reportf_err(local_err,
651 "Failed to parse detect_zeroes mode: ");
85b01e09 652 exit(EXIT_FAILURE);
b3838a40
PL
653 }
654 if (detect_zeroes == BLOCKDEV_DETECT_ZEROES_OPTIONS_UNMAP &&
655 !(flags & BDRV_O_UNMAP)) {
85b01e09
MA
656 error_report("setting detect-zeroes to unmap is not allowed "
657 "without setting discard operation to unmap");
658 exit(EXIT_FAILURE);
b3838a40
PL
659 }
660 break;
7a5ca864
FB
661 case 'b':
662 bindto = optarg;
663 break;
664 case 'p':
48bec07e 665 port = optarg;
7a5ca864
FB
666 break;
667 case 'o':
43b51011
EB
668 if (qemu_strtou64(optarg, NULL, 0, &dev_offset) < 0) {
669 error_report("Invalid offset '%s'", optarg);
85b01e09 670 exit(EXIT_FAILURE);
7a5ca864 671 }
7a5ca864 672 break;
8c116b0e
WX
673 case 'l':
674 if (strstart(optarg, SNAPSHOT_OPT_BASE, NULL)) {
70b94331
MA
675 sn_opts = qemu_opts_parse_noisily(&internal_snapshot_opts,
676 optarg, false);
8c116b0e 677 if (!sn_opts) {
85b01e09
MA
678 error_report("Failed in parsing snapshot param `%s'",
679 optarg);
680 exit(EXIT_FAILURE);
8c116b0e
WX
681 }
682 } else {
683 sn_id_or_name = optarg;
684 }
685 /* fall through */
7a5ca864 686 case 'r':
dbb38caa 687 readonly = true;
07108b29 688 flags &= ~BDRV_O_RDWR;
7a5ca864 689 break;
dbc7b014
EB
690 case 'A':
691 alloc_depth = true;
692 break;
636192c4 693 case 'B':
e5fb29d5
VSO
694 {
695 BlockDirtyBitmapOrStr *el = g_new(BlockDirtyBitmapOrStr, 1);
696 *el = (BlockDirtyBitmapOrStr) {
697 .type = QTYPE_QSTRING,
698 .u.local = g_strdup(optarg),
699 };
700 QAPI_LIST_PREPEND(bitmaps, el);
701 }
636192c4 702 break;
cd831bd7 703 case 'k':
b32f6c28 704 sockpath = optarg;
713cc671 705 if (sockpath[0] != '/') {
9af9e0fe 706 error_report("socket path must be absolute");
85b01e09 707 exit(EXIT_FAILURE);
713cc671 708 }
cd831bd7
TS
709 break;
710 case 'd':
711 disconnect = true;
712 break;
713 case 'c':
714 device = optarg;
715 break;
3b05a8e9 716 case 'e':
43b51011 717 if (qemu_strtoi(optarg, NULL, 0, &shared) < 0 ||
3dcf56e6 718 shared < 0) {
85b01e09
MA
719 error_report("Invalid shared device number '%s'", optarg);
720 exit(EXIT_FAILURE);
3b05a8e9 721 }
3b05a8e9 722 break;
e6b63677
DB
723 case 'f':
724 fmt = optarg;
725 break;
713cc671
PL
726 case 't':
727 persistent = 1;
728 break;
3d4b2f9c
DB
729 case 'x':
730 export_name = optarg;
93676c88
EB
731 if (strlen(export_name) > NBD_MAX_STRING_SIZE) {
732 error_report("export name '%s' too long", export_name);
733 exit(EXIT_FAILURE);
734 }
3d4b2f9c 735 break;
b1a75b33
EB
736 case 'D':
737 export_description = optarg;
93676c88
EB
738 if (strlen(export_description) > NBD_MAX_STRING_SIZE) {
739 error_report("export description '%s' too long",
740 export_description);
741 exit(EXIT_FAILURE);
742 }
b1a75b33 743 break;
7a5ca864
FB
744 case 'v':
745 verbose = 1;
746 break;
747 case 'V':
748 version(argv[0]);
749 exit(0);
750 break;
751 case 'h':
752 usage(argv[0]);
753 exit(0);
754 break;
755 case '?':
85b01e09
MA
756 error_report("Try `%s --help' for more information.", argv[0]);
757 exit(EXIT_FAILURE);
fa40e43c
KW
758 case QEMU_NBD_OPT_OBJECT:
759 user_creatable_process_cmdline(optarg);
760 break;
145614a1
DB
761 case QEMU_NBD_OPT_TLSCREDS:
762 tlscredsid = optarg;
763 break;
003b2b25
DB
764 case QEMU_NBD_OPT_TLSHOSTNAME:
765 tlshostname = optarg;
766 break;
77c9aaef
DB
767 case QEMU_NBD_OPT_IMAGE_OPTS:
768 imageOpts = true;
769 break;
39ca463e 770 case 'T':
92eecfff 771 trace_opt_parse(optarg);
39ca463e 772 break;
b25e12da
DB
773 case QEMU_NBD_OPT_TLSAUTHZ:
774 tlsauthz = optarg;
775 break;
ffb31e1d
HR
776 case QEMU_NBD_OPT_FORK:
777 fork_process = true;
778 break;
68b96f15
EB
779 case 'L':
780 list = true;
781 break;
637bc5a5
HR
782 case QEMU_NBD_OPT_PID_FILE:
783 pid_file_name = optarg;
784 break;
3d212b41
RJ
785 case QEMU_NBD_OPT_SELINUX_LABEL:
786 selinux_label = optarg;
787 break;
7a5ca864
FB
788 }
789 }
790
68b96f15
EB
791 if (list) {
792 if (argc != optind) {
793 error_report("List mode is incompatible with a file name");
794 exit(EXIT_FAILURE);
795 }
0bc16997 796 if (export_name || export_description || dev_offset ||
cbad81ce 797 device || disconnect || fmt || sn_id_or_name || bitmaps ||
dbc7b014 798 alloc_depth || seen_aio || seen_discard || seen_cache) {
68b96f15
EB
799 error_report("List mode is incompatible with per-device settings");
800 exit(EXIT_FAILURE);
801 }
802 if (fork_process) {
803 error_report("List mode is incompatible with forking");
804 exit(EXIT_FAILURE);
805 }
806 } else if ((argc - optind) != 1) {
433672b0
MA
807 error_report("Invalid number of arguments");
808 error_printf("Try `%s --help' for more information.\n", argv[0]);
85b01e09 809 exit(EXIT_FAILURE);
68b96f15
EB
810 } else if (!export_name) {
811 export_name = "";
7a5ca864
FB
812 }
813
39ca463e
DL
814 if (!trace_init_backends()) {
815 exit(1);
816 }
92eecfff 817 trace_init_file();
c5955f4f 818 qemu_set_log(LOG_TRACE, &error_fatal);
39ca463e 819
a721f53b
RJ
820 socket_activation = check_socket_activation();
821 if (socket_activation == 0) {
e8ae8b1a
DB
822 if (!sockpath) {
823 setup_address_and_port(&bindto, &port);
824 }
a721f53b
RJ
825 } else {
826 /* Using socket activation - check user didn't use -p etc. */
827 const char *err_msg = socket_activation_validate_opts(device, sockpath,
68b96f15 828 bindto, port,
3d212b41 829 selinux_label,
68b96f15 830 list);
a721f53b
RJ
831 if (err_msg != NULL) {
832 error_report("%s", err_msg);
833 exit(EXIT_FAILURE);
834 }
53fabd4b
PB
835
836 /* qemu-nbd can only listen on a single socket. */
837 if (socket_activation > 1) {
838 error_report("qemu-nbd does not support socket activation with %s > 1",
839 "LISTEN_FDS");
840 exit(EXIT_FAILURE);
841 }
a721f53b
RJ
842 }
843
145614a1 844 if (tlscredsid) {
145614a1
DB
845 if (device) {
846 error_report("TLS is not supported with a host device");
847 exit(EXIT_FAILURE);
848 }
b25e12da
DB
849 if (tlsauthz && list) {
850 error_report("TLS authorization is incompatible with export list");
851 exit(EXIT_FAILURE);
852 }
003b2b25
DB
853 if (tlshostname && !list) {
854 error_report("TLS hostname is only supported with export list");
855 exit(EXIT_FAILURE);
856 }
68b96f15 857 tlscreds = nbd_get_tls_creds(tlscredsid, list, &local_err);
145614a1 858 if (local_err) {
5217f188 859 error_reportf_err(local_err, "Failed to get TLS creds: ");
145614a1
DB
860 exit(EXIT_FAILURE);
861 }
b25e12da
DB
862 } else {
863 if (tlsauthz) {
864 error_report("--tls-authz is not permitted without --tls-creds");
865 exit(EXIT_FAILURE);
866 }
003b2b25
DB
867 if (tlshostname) {
868 error_report("--tls-hostname is not permitted without --tls-creds");
869 exit(EXIT_FAILURE);
870 }
145614a1
DB
871 }
872
3d212b41
RJ
873 if (selinux_label) {
874#ifdef CONFIG_SELINUX
875 if (sockpath == NULL && device == NULL) {
876 error_report("--selinux-label is not permitted without --socket");
877 exit(EXIT_FAILURE);
878 }
879#else
880 error_report("SELinux support not enabled in this binary");
881 exit(EXIT_FAILURE);
882#endif
883 }
884
68b96f15
EB
885 if (list) {
886 saddr = nbd_build_socket_address(sockpath, bindto, port);
003b2b25
DB
887 return qemu_nbd_client_list(saddr, tlscreds,
888 tlshostname ? tlshostname : bindto);
68b96f15
EB
889 }
890
3c1fa35d
EB
891#if !HAVE_NBD_DEVICE
892 if (disconnect || device) {
893 error_report("Kernel /dev/nbdN support not available");
894 exit(EXIT_FAILURE);
895 }
896#else /* HAVE_NBD_DEVICE */
cd831bd7 897 if (disconnect) {
d0d6ff58
DB
898 int nbdfd = open(argv[optind], O_RDWR);
899 if (nbdfd < 0) {
85b01e09
MA
900 error_report("Cannot open %s: %s", argv[optind],
901 strerror(errno));
902 exit(EXIT_FAILURE);
fc19f8a0 903 }
d0d6ff58 904 nbd_disconnect(nbdfd);
cd831bd7 905
d0d6ff58 906 close(nbdfd);
cd831bd7
TS
907
908 printf("%s disconnected\n", argv[optind]);
909
713cc671 910 return 0;
cd831bd7 911 }
3c1fa35d 912#endif
cd831bd7 913
ffb31e1d 914 if ((device && !verbose) || fork_process) {
eb705985 915#ifndef WIN32
a7241974 916 g_autoptr(GError) err = NULL;
c1f8fdc3
PB
917 int stderr_fd[2];
918 pid_t pid;
919 int ret;
920
a7241974 921 if (!g_unix_open_pipe(stderr_fd, FD_CLOEXEC, &err)) {
85b01e09 922 error_report("Error setting up communication pipe: %s",
a7241974 923 err->message);
85b01e09 924 exit(EXIT_FAILURE);
c1f8fdc3
PB
925 }
926
927 /* Now daemonize, but keep a communication channel open to
928 * print errors and exit with the proper status code.
929 */
930 pid = fork();
70d4739e 931 if (pid < 0) {
85b01e09
MA
932 error_report("Failed to fork: %s", strerror(errno));
933 exit(EXIT_FAILURE);
70d4739e 934 } else if (pid == 0) {
c1f8fdc3 935 close(stderr_fd[0]);
e6df58a5 936
9faf31b6 937 ret = qemu_daemon(1, 0);
c1f8fdc3
PB
938
939 /* Temporarily redirect stderr to the parent's pipe... */
940 dup2(stderr_fd[1], STDERR_FILENO);
fc19f8a0 941 if (ret < 0) {
85b01e09
MA
942 error_report("Failed to daemonize: %s", strerror(errno));
943 exit(EXIT_FAILURE);
c1f8fdc3
PB
944 }
945
946 /* ... close the descriptor we inherited and go on. */
947 close(stderr_fd[1]);
948 } else {
949 bool errors = false;
950 char *buf;
951
952 /* In the parent. Print error messages from the child until
953 * it closes the pipe.
954 */
955 close(stderr_fd[1]);
956 buf = g_malloc(1024);
957 while ((ret = read(stderr_fd[0], buf, 1024)) > 0) {
958 errors = true;
959 ret = qemu_write_full(STDERR_FILENO, buf, ret);
fc19f8a0 960 if (ret < 0) {
c1f8fdc3
PB
961 exit(EXIT_FAILURE);
962 }
963 }
fc19f8a0 964 if (ret < 0) {
85b01e09
MA
965 error_report("Cannot read from daemon: %s",
966 strerror(errno));
967 exit(EXIT_FAILURE);
c1f8fdc3
PB
968 }
969
970 /* Usually the daemon should not print any message.
971 * Exit with zero status in that case.
972 */
973 exit(errors);
974 }
eb705985
DB
975#else /* WIN32 */
976 error_report("Unable to fork into background on Windows hosts");
977 exit(EXIT_FAILURE);
978#endif /* WIN32 */
c1f8fdc3
PB
979 }
980
a6ac2313
PB
981 if (device != NULL && sockpath == NULL) {
982 sockpath = g_malloc(128);
983 snprintf(sockpath, 128, SOCKET_PATH, basename(device));
cd831bd7
TS
984 }
985
e4849c1d 986 server = qio_net_listener_new();
a721f53b 987 if (socket_activation == 0) {
582d4210
EB
988 int backlog;
989
3dcf56e6 990 if (persistent || shared == 0) {
582d4210
EB
991 backlog = SOMAXCONN;
992 } else {
993 backlog = MIN(shared, SOMAXCONN);
994 }
3d212b41
RJ
995#ifdef CONFIG_SELINUX
996 if (selinux_label && setsockcreatecon_raw(selinux_label) == -1) {
997 error_report("Cannot set SELinux socket create context to %s: %s",
998 selinux_label, strerror(errno));
999 exit(EXIT_FAILURE);
1000 }
1001#endif
a721f53b 1002 saddr = nbd_build_socket_address(sockpath, bindto, port);
582d4210
EB
1003 if (qio_net_listener_open_sync(server, saddr, backlog,
1004 &local_err) < 0) {
e4849c1d 1005 object_unref(OBJECT(server));
a721f53b 1006 error_report_err(local_err);
e4849c1d 1007 exit(EXIT_FAILURE);
a721f53b 1008 }
3d212b41
RJ
1009#ifdef CONFIG_SELINUX
1010 if (selinux_label && setsockcreatecon_raw(NULL) == -1) {
1011 error_report("Cannot clear SELinux socket create context: %s",
1012 strerror(errno));
1013 exit(EXIT_FAILURE);
1014 }
1015#endif
a721f53b 1016 } else {
e4849c1d 1017 size_t i;
a721f53b 1018 /* See comment in check_socket_activation above. */
e4849c1d
DB
1019 for (i = 0; i < socket_activation; i++) {
1020 QIOChannelSocket *sioc;
1021 sioc = qio_channel_socket_new_fd(FIRST_SOCKET_ACTIVATION_FD + i,
1022 &local_err);
1023 if (sioc == NULL) {
1024 object_unref(OBJECT(server));
5217f188
MA
1025 error_reportf_err(local_err,
1026 "Failed to use socket activation: ");
e4849c1d
DB
1027 exit(EXIT_FAILURE);
1028 }
1029 qio_net_listener_add(server, sioc);
1030 object_unref(OBJECT(sioc));
a721f53b
RJ
1031 }
1032 }
48bec07e 1033
f9734d5d 1034 qemu_init_main_loop(&error_fatal);
802ddc37 1035 bdrv_init();
b3b5299d 1036 atexit(qemu_nbd_shutdown);
802ddc37 1037
77c9aaef
DB
1038 srcpath = argv[optind];
1039 if (imageOpts) {
1040 QemuOpts *opts;
1041 if (fmt) {
1042 error_report("--image-opts and -f are mutually exclusive");
1043 exit(EXIT_FAILURE);
1044 }
1045 opts = qemu_opts_parse_noisily(&file_opts, srcpath, true);
1046 if (!opts) {
1047 qemu_opts_reset(&file_opts);
1048 exit(EXIT_FAILURE);
1049 }
1050 options = qemu_opts_to_qdict(opts, NULL);
1051 qemu_opts_reset(&file_opts);
efaa7c4e 1052 blk = blk_new_open(NULL, NULL, options, flags, &local_err);
77c9aaef
DB
1053 } else {
1054 if (fmt) {
1055 options = qdict_new();
46f5ac20 1056 qdict_put_str(options, "driver", fmt);
77c9aaef 1057 }
efaa7c4e 1058 blk = blk_new_open(srcpath, NULL, options, flags, &local_err);
e6b63677
DB
1059 }
1060
4fbec260 1061 if (!blk) {
c29b77f9
MA
1062 error_reportf_err(local_err, "Failed to blk_new_open '%s': ",
1063 argv[optind]);
85b01e09 1064 exit(EXIT_FAILURE);
802ddc37 1065 }
4fbec260 1066 bs = blk_bs(blk);
802ddc37 1067
b57e4de0
KW
1068 if (dev_offset) {
1069 QDict *raw_opts = qdict_new();
1070 qdict_put_str(raw_opts, "driver", "raw");
1071 qdict_put_str(raw_opts, "file", bs->node_name);
1072 qdict_put_int(raw_opts, "offset", dev_offset);
c6e0a6de
KW
1073
1074 aio_context_acquire(qemu_get_aio_context());
b57e4de0 1075 bs = bdrv_open(NULL, NULL, raw_opts, flags, &error_fatal);
c6e0a6de
KW
1076 aio_context_release(qemu_get_aio_context());
1077
b57e4de0
KW
1078 blk_remove_bs(blk);
1079 blk_insert_bs(blk, bs, &error_fatal);
1080 bdrv_unref(bs);
1081 }
1082
6effd5bf
KW
1083 blk_set_enable_write_cache(blk, !writethrough);
1084
8c116b0e
WX
1085 if (sn_opts) {
1086 ret = bdrv_snapshot_load_tmp(bs,
1087 qemu_opt_get(sn_opts, SNAPSHOT_OPT_ID),
1088 qemu_opt_get(sn_opts, SNAPSHOT_OPT_NAME),
1089 &local_err);
1090 } else if (sn_id_or_name) {
1091 ret = bdrv_snapshot_load_tmp_by_id_or_name(bs, sn_id_or_name,
1092 &local_err);
1093 }
1094 if (ret < 0) {
c29b77f9 1095 error_reportf_err(local_err, "Failed to load snapshot: ");
85b01e09 1096 exit(EXIT_FAILURE);
8c116b0e
WX
1097 }
1098
b3838a40 1099 bs->detect_zeroes = detect_zeroes;
e424b655 1100
a5fced40 1101 nbd_server_is_qemu_nbd(shared);
00917172
KW
1102
1103 export_opts = g_new(BlockExportOptions, 1);
1104 *export_opts = (BlockExportOptions) {
1105 .type = BLOCK_EXPORT_TYPE_NBD,
d53be9ce 1106 .id = g_strdup("qemu-nbd-export"),
b6076afc 1107 .node_name = g_strdup(bdrv_get_node_name(bs)),
00917172
KW
1108 .has_writethrough = true,
1109 .writethrough = writethrough,
30dbc81d
KW
1110 .has_writable = true,
1111 .writable = !readonly,
00917172 1112 .u.nbd = {
cbad81ce 1113 .name = g_strdup(export_name),
cbad81ce
EB
1114 .description = g_strdup(export_description),
1115 .has_bitmaps = !!bitmaps,
1116 .bitmaps = bitmaps,
dbc7b014
EB
1117 .has_allocation_depth = alloc_depth,
1118 .allocation_depth = alloc_depth,
00917172
KW
1119 },
1120 };
1121 blk_exp_add(export_opts, &error_fatal);
1122 qapi_free_BlockExportOptions(export_opts);
3b05a8e9 1123
f1ef5555 1124 if (device) {
3c1fa35d 1125#if HAVE_NBD_DEVICE
f1ef5555 1126 int ret;
03b67621
DL
1127 struct NbdClientOpts opts = {
1128 .device = device,
5c56dd27 1129 .fork_process = fork_process,
03b67621 1130 };
f1ef5555 1131
03b67621 1132 ret = pthread_create(&client_thread, NULL, nbd_client_thread, &opts);
f1ef5555 1133 if (ret != 0) {
85b01e09
MA
1134 error_report("Failed to create client thread: %s", strerror(ret));
1135 exit(EXIT_FAILURE);
f1ef5555 1136 }
3c1fa35d 1137#endif
f1ef5555
PB
1138 } else {
1139 /* Shut up GCC warnings. */
1140 memset(&client_thread, 0, sizeof(client_thread));
1141 }
1142
d0d6ff58 1143 nbd_update_server_watch();
7a5ca864 1144
637bc5a5
HR
1145 if (pid_file_name) {
1146 qemu_write_pidfile(pid_file_name, &error_fatal);
1147 }
1148
9faf31b6
MT
1149 /* now when the initialization is (almost) complete, chdir("/")
1150 * to free any busy filesystems */
1151 if (chdir("/") < 0) {
85b01e09
MA
1152 error_report("Could not chdir to root directory: %s",
1153 strerror(errno));
1154 exit(EXIT_FAILURE);
9faf31b6
MT
1155 }
1156
ffb31e1d 1157 if (fork_process) {
5c56dd27 1158 dup2(STDOUT_FILENO, STDERR_FILENO);
ffb31e1d
HR
1159 }
1160
7860a380 1161 state = RUNNING;
3b05a8e9 1162 do {
a61c6782 1163 main_loop_wait(false);
7860a380 1164 if (state == TERMINATE) {
bc4ee65b 1165 blk_exp_close_all();
d794f7f3 1166 state = TERMINATED;
7860a380
PB
1167 }
1168 } while (state != TERMINATED);
7a5ca864 1169
26f54e9a 1170 blk_unref(blk);
b32f6c28
PB
1171 if (sockpath) {
1172 unlink(sockpath);
1173 }
7a5ca864 1174
fbf28a43 1175 qemu_opts_del(sn_opts);
8c116b0e 1176
a517e88b
PB
1177 if (device) {
1178 void *ret;
1179 pthread_join(client_thread, &ret);
1180 exit(ret != NULL);
1181 } else {
1182 exit(EXIT_SUCCESS);
1183 }
7a5ca864 1184}