]> git.proxmox.com Git - mirror_qemu.git/blame - qemu-nbd.c
migration: Fix operator type
[mirror_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
a517e88b
PB
275static void *nbd_client_thread(void *arg)
276{
a6ac2313 277 char *device = arg;
6dc1667d 278 NBDExportInfo info = { .request_sizes = false, .name = g_strdup("") };
d0d6ff58 279 QIOChannelSocket *sioc;
af74b550
AC
280 int fd = -1;
281 int ret = EXIT_FAILURE;
a517e88b 282 pthread_t show_parts_thread;
1ce52846 283 Error *local_error = NULL;
a517e88b 284
d0d6ff58
DB
285 sioc = qio_channel_socket_new();
286 if (qio_channel_socket_connect_sync(sioc,
287 saddr,
288 &local_error) < 0) {
48bec07e 289 error_report_err(local_error);
dc10e8b3
SH
290 goto out;
291 }
a517e88b 292
af74b550
AC
293 if (nbd_receive_negotiate(NULL, QIO_CHANNEL(sioc),
294 NULL, NULL, NULL, &info, &local_error) < 0) {
1ce52846 295 if (local_error) {
78288671 296 error_report_err(local_error);
1ce52846 297 }
af74b550 298 goto out;
a517e88b
PB
299 }
300
a6ac2313 301 fd = open(device, O_RDWR);
fc19f8a0 302 if (fd < 0) {
a6ac2313 303 /* Linux-only, we can use %m in printf. */
b9884681 304 error_report("Failed to open %s: %m", device);
af74b550 305 goto out;
a6ac2313
PB
306 }
307
af74b550 308 if (nbd_init(fd, sioc, &info, &local_error) < 0) {
be41c100 309 error_report_err(local_error);
af74b550 310 goto out;
a517e88b
PB
311 }
312
313 /* update partition table */
a6ac2313 314 pthread_create(&show_parts_thread, NULL, show_parts, device);
a517e88b 315
c1f8fdc3
PB
316 if (verbose) {
317 fprintf(stderr, "NBD device %s is now connected to %s\n",
318 device, srcpath);
319 } else {
320 /* Close stderr so that the qemu-nbd process exits. */
321 dup2(STDOUT_FILENO, STDERR_FILENO);
322 }
a517e88b 323
af74b550
AC
324 if (nbd_client(fd) < 0) {
325 goto out;
cd831bd7 326 }
a517e88b 327
af74b550
AC
328 ret = EXIT_SUCCESS;
329
330 out:
331 if (fd >= 0) {
332 close(fd);
333 }
d0d6ff58 334 object_unref(OBJECT(sioc));
6dc1667d 335 g_free(info.name);
a517e88b 336 kill(getpid(), SIGTERM);
af74b550 337 return (void *) (intptr_t) ret;
cd831bd7 338}
3c1fa35d 339#endif /* HAVE_NBD_DEVICE */
cd831bd7 340
e4afbf4f 341static int nbd_can_accept(void)
a61c6782 342{
3dcf56e6 343 return state == RUNNING && (shared == 0 || nb_fds < shared);
a61c6782
PB
344}
345
d0d6ff58 346static void nbd_update_server_watch(void);
e4afbf4f 347
0c9390d9 348static void nbd_client_closed(NBDClient *client, bool negotiated)
a61c6782 349{
1743b515 350 nb_fds--;
0c9390d9 351 if (negotiated && nb_fds == 0 && !persistent && state == RUNNING) {
7860a380
PB
352 state = TERMINATE;
353 }
d0d6ff58 354 nbd_update_server_watch();
7860a380 355 nbd_client_put(client);
a61c6782
PB
356}
357
e4849c1d
DB
358static void nbd_accept(QIONetListener *listener, QIOChannelSocket *cioc,
359 gpointer opaque)
a61c6782 360{
7860a380 361 if (state >= TERMINATE) {
e4849c1d 362 return;
7860a380
PB
363 }
364
ee7d7aab 365 nb_fds++;
d0d6ff58 366 nbd_update_server_watch();
b25e12da 367 nbd_client_new(cioc, tlscreds, tlsauthz, nbd_client_closed);
a61c6782
PB
368}
369
d0d6ff58 370static void nbd_update_server_watch(void)
e4afbf4f
FZ
371{
372 if (nbd_can_accept()) {
e4849c1d 373 qio_net_listener_set_client_func(server, nbd_accept, NULL, NULL);
e4afbf4f 374 } else {
e4849c1d 375 qio_net_listener_set_client_func(server, NULL, NULL, NULL);
e4afbf4f
FZ
376 }
377}
378
48bec07e 379
bd269ebc 380static SocketAddress *nbd_build_socket_address(const char *sockpath,
48bec07e
DB
381 const char *bindto,
382 const char *port)
383{
bd269ebc 384 SocketAddress *saddr;
48bec07e 385
bd269ebc 386 saddr = g_new0(SocketAddress, 1);
48bec07e 387 if (sockpath) {
bd269ebc
MA
388 saddr->type = SOCKET_ADDRESS_TYPE_UNIX;
389 saddr->u.q_unix.path = g_strdup(sockpath);
48bec07e 390 } else {
0399293e 391 InetSocketAddress *inet;
bd269ebc
MA
392 saddr->type = SOCKET_ADDRESS_TYPE_INET;
393 inet = &saddr->u.inet;
0399293e 394 inet->host = g_strdup(bindto);
48bec07e 395 if (port) {
0399293e 396 inet->port = g_strdup(port);
48bec07e 397 } else {
0399293e 398 inet->port = g_strdup_printf("%d", NBD_DEFAULT_PORT);
48bec07e
DB
399 }
400 }
401
402 return saddr;
403}
404
405
77c9aaef
DB
406static QemuOptsList file_opts = {
407 .name = "file",
408 .implied_opt_name = "file",
409 .head = QTAILQ_HEAD_INITIALIZER(file_opts.head),
410 .desc = {
411 /* no elements => accept any params */
412 { /* end of list */ }
413 },
414};
415
68b96f15
EB
416static QCryptoTLSCreds *nbd_get_tls_creds(const char *id, bool list,
417 Error **errp)
145614a1
DB
418{
419 Object *obj;
420 QCryptoTLSCreds *creds;
421
422 obj = object_resolve_path_component(
423 object_get_objects_root(), id);
424 if (!obj) {
425 error_setg(errp, "No TLS credentials with id '%s'",
426 id);
427 return NULL;
428 }
429 creds = (QCryptoTLSCreds *)
430 object_dynamic_cast(obj, TYPE_QCRYPTO_TLS_CREDS);
431 if (!creds) {
432 error_setg(errp, "Object with id '%s' is not TLS credentials",
433 id);
434 return NULL;
435 }
436
0279cd95
PMD
437 if (!qcrypto_tls_creds_check_endpoint(creds,
438 list
439 ? QCRYPTO_TLS_CREDS_ENDPOINT_CLIENT
440 : QCRYPTO_TLS_CREDS_ENDPOINT_SERVER,
441 errp)) {
442 return NULL;
145614a1
DB
443 }
444 object_ref(obj);
445 return creds;
446}
447
a721f53b
RJ
448static void setup_address_and_port(const char **address, const char **port)
449{
450 if (*address == NULL) {
451 *address = "0.0.0.0";
452 }
453
454 if (*port == NULL) {
455 *port = stringify(NBD_DEFAULT_PORT);
456 }
457}
458
a721f53b
RJ
459/*
460 * Check socket parameters compatibility when socket activation is used.
461 */
462static const char *socket_activation_validate_opts(const char *device,
463 const char *sockpath,
464 const char *address,
68b96f15 465 const char *port,
3d212b41 466 const char *selinux,
68b96f15 467 bool list)
a721f53b
RJ
468{
469 if (device != NULL) {
470 return "NBD device can't be set when using socket activation";
471 }
472
473 if (sockpath != NULL) {
474 return "Unix socket can't be set when using socket activation";
475 }
476
477 if (address != NULL) {
478 return "The interface can't be set when using socket activation";
479 }
480
481 if (port != NULL) {
482 return "TCP port number can't be set when using socket activation";
483 }
484
3d212b41
RJ
485 if (selinux != NULL) {
486 return "SELinux label can't be set when using socket activation";
487 }
488
68b96f15
EB
489 if (list) {
490 return "List mode is incompatible with socket activation";
491 }
492
a721f53b
RJ
493 return NULL;
494}
145614a1 495
b3b5299d
KW
496static void qemu_nbd_shutdown(void)
497{
498 job_cancel_sync_all();
1895b977 499 blk_exp_close_all();
b3b5299d
KW
500 bdrv_close_all();
501}
502
7a5ca864
FB
503int main(int argc, char **argv)
504{
26f54e9a 505 BlockBackend *blk;
7a5ca864 506 BlockDriverState *bs;
9d26dfcb 507 uint64_t dev_offset = 0;
dbb38caa 508 bool readonly = false;
cd831bd7 509 bool disconnect = false;
a721f53b 510 const char *bindto = NULL;
48bec07e
DB
511 const char *port = NULL;
512 char *sockpath = NULL;
a6ac2313 513 char *device = NULL;
8c116b0e
WX
514 QemuOpts *sn_opts = NULL;
515 const char *sn_id_or_name = NULL;
dbc7b014 516 const char *sopt = "hVb:o:p:rsnc:dvk:e:f:tl:x:T:D:AB:L";
7a5ca864 517 struct option lopt[] = {
aa6e546c
DB
518 { "help", no_argument, NULL, 'h' },
519 { "version", no_argument, NULL, 'V' },
520 { "bind", required_argument, NULL, 'b' },
521 { "port", required_argument, NULL, 'p' },
522 { "socket", required_argument, NULL, 'k' },
523 { "offset", required_argument, NULL, 'o' },
524 { "read-only", no_argument, NULL, 'r' },
dbc7b014 525 { "allocation-depth", no_argument, NULL, 'A' },
636192c4 526 { "bitmap", required_argument, NULL, 'B' },
aa6e546c
DB
527 { "connect", required_argument, NULL, 'c' },
528 { "disconnect", no_argument, NULL, 'd' },
68b96f15 529 { "list", no_argument, NULL, 'L' },
aa6e546c
DB
530 { "snapshot", no_argument, NULL, 's' },
531 { "load-snapshot", required_argument, NULL, 'l' },
532 { "nocache", no_argument, NULL, 'n' },
533 { "cache", required_argument, NULL, QEMU_NBD_OPT_CACHE },
534 { "aio", required_argument, NULL, QEMU_NBD_OPT_AIO },
535 { "discard", required_argument, NULL, QEMU_NBD_OPT_DISCARD },
536 { "detect-zeroes", required_argument, NULL,
537 QEMU_NBD_OPT_DETECT_ZEROES },
538 { "shared", required_argument, NULL, 'e' },
539 { "format", required_argument, NULL, 'f' },
540 { "persistent", no_argument, NULL, 't' },
541 { "verbose", no_argument, NULL, 'v' },
542 { "object", required_argument, NULL, QEMU_NBD_OPT_OBJECT },
543 { "export-name", required_argument, NULL, 'x' },
b1a75b33 544 { "description", required_argument, NULL, 'D' },
aa6e546c 545 { "tls-creds", required_argument, NULL, QEMU_NBD_OPT_TLSCREDS },
003b2b25 546 { "tls-hostname", required_argument, NULL, QEMU_NBD_OPT_TLSHOSTNAME },
b25e12da 547 { "tls-authz", required_argument, NULL, QEMU_NBD_OPT_TLSAUTHZ },
aa6e546c 548 { "image-opts", no_argument, NULL, QEMU_NBD_OPT_IMAGE_OPTS },
39ca463e 549 { "trace", required_argument, NULL, 'T' },
ffb31e1d 550 { "fork", no_argument, NULL, QEMU_NBD_OPT_FORK },
637bc5a5 551 { "pid-file", required_argument, NULL, QEMU_NBD_OPT_PID_FILE },
3d212b41
RJ
552 { "selinux-label", required_argument, NULL,
553 QEMU_NBD_OPT_SELINUX_LABEL },
660f11be 554 { NULL, 0, NULL, 0 }
7a5ca864
FB
555 };
556 int ch;
557 int opt_ind = 0;
f5edb014 558 int flags = BDRV_O_RDWR;
4fbec260 559 int ret = 0;
39a5235c 560 bool seen_cache = false;
ded9d2d5 561 bool seen_discard = false;
39a5235c 562 bool seen_aio = false;
a517e88b 563 pthread_t client_thread;
e6b63677 564 const char *fmt = NULL;
34b5d2c6 565 Error *local_err = NULL;
b3838a40 566 BlockdevDetectZeroesOptions detect_zeroes = BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF;
4fbec260 567 QDict *options = NULL;
68b96f15 568 const char *export_name = NULL; /* defaults to "" later for server mode */
b1a75b33 569 const char *export_description = NULL;
cbad81ce 570 strList *bitmaps = NULL;
dbc7b014 571 bool alloc_depth = false;
145614a1 572 const char *tlscredsid = NULL;
003b2b25 573 const char *tlshostname = NULL;
77c9aaef 574 bool imageOpts = false;
09615257 575 bool writethrough = false; /* Client will flush as needed. */
ffb31e1d 576 bool fork_process = false;
68b96f15 577 bool list = false;
ffb31e1d 578 int old_stderr = -1;
a721f53b 579 unsigned socket_activation;
637bc5a5 580 const char *pid_file_name = NULL;
3d212b41 581 const char *selinux_label = NULL;
00917172 582 BlockExportOptions *export_opts;
7a5ca864 583
029a88c9 584#ifdef CONFIG_POSIX
cbc20bfb
SH
585 os_setup_early_signal_handling();
586 os_setup_signal_handling();
041e32b8
HR
587#endif
588
98c5d2e7 589 socket_init();
f5852efa 590 error_init(argv[0]);
fe4db84d 591 module_call_init(MODULE_INIT_TRACE);
e8f2d272 592 qcrypto_init(&error_fatal);
c2297088 593
0ab3b337 594 module_call_init(MODULE_INIT_QOM);
39ca463e 595 qemu_add_opts(&qemu_trace_opts);
10f5bff6 596 qemu_init_exec_dir(argv[0]);
bb345110 597
7a5ca864
FB
598 while ((ch = getopt_long(argc, argv, sopt, lopt, &opt_ind)) != -1) {
599 switch (ch) {
600 case 's':
2f726488
TS
601 flags |= BDRV_O_SNAPSHOT;
602 break;
603 case 'n':
39a5235c
PB
604 optarg = (char *) "none";
605 /* fallthrough */
606 case QEMU_NBD_OPT_CACHE:
607 if (seen_cache) {
85b01e09
MA
608 error_report("-n and --cache can only be specified once");
609 exit(EXIT_FAILURE);
39a5235c
PB
610 }
611 seen_cache = true;
6effd5bf 612 if (bdrv_parse_cache_mode(optarg, &flags, &writethrough) == -1) {
85b01e09
MA
613 error_report("Invalid cache mode `%s'", optarg);
614 exit(EXIT_FAILURE);
39a5235c 615 }
7a5ca864 616 break;
39a5235c
PB
617 case QEMU_NBD_OPT_AIO:
618 if (seen_aio) {
85b01e09
MA
619 error_report("--aio can only be specified once");
620 exit(EXIT_FAILURE);
39a5235c
PB
621 }
622 seen_aio = true;
7680274d
AM
623 if (bdrv_parse_aio(optarg, &flags) < 0) {
624 error_report("Invalid aio mode '%s'", optarg);
625 exit(EXIT_FAILURE);
39a5235c
PB
626 }
627 break;
ded9d2d5
PB
628 case QEMU_NBD_OPT_DISCARD:
629 if (seen_discard) {
85b01e09
MA
630 error_report("--discard can only be specified once");
631 exit(EXIT_FAILURE);
ded9d2d5
PB
632 }
633 seen_discard = true;
634 if (bdrv_parse_discard_flags(optarg, &flags) == -1) {
85b01e09
MA
635 error_report("Invalid discard mode `%s'", optarg);
636 exit(EXIT_FAILURE);
ded9d2d5
PB
637 }
638 break;
b3838a40
PL
639 case QEMU_NBD_OPT_DETECT_ZEROES:
640 detect_zeroes =
f7abe0ec 641 qapi_enum_parse(&BlockdevDetectZeroesOptions_lookup,
b3838a40 642 optarg,
b3838a40
PL
643 BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF,
644 &local_err);
645 if (local_err) {
c29b77f9
MA
646 error_reportf_err(local_err,
647 "Failed to parse detect_zeroes mode: ");
85b01e09 648 exit(EXIT_FAILURE);
b3838a40
PL
649 }
650 if (detect_zeroes == BLOCKDEV_DETECT_ZEROES_OPTIONS_UNMAP &&
651 !(flags & BDRV_O_UNMAP)) {
85b01e09
MA
652 error_report("setting detect-zeroes to unmap is not allowed "
653 "without setting discard operation to unmap");
654 exit(EXIT_FAILURE);
b3838a40
PL
655 }
656 break;
7a5ca864
FB
657 case 'b':
658 bindto = optarg;
659 break;
660 case 'p':
48bec07e 661 port = optarg;
7a5ca864
FB
662 break;
663 case 'o':
43b51011
EB
664 if (qemu_strtou64(optarg, NULL, 0, &dev_offset) < 0) {
665 error_report("Invalid offset '%s'", optarg);
85b01e09 666 exit(EXIT_FAILURE);
7a5ca864 667 }
7a5ca864 668 break;
8c116b0e
WX
669 case 'l':
670 if (strstart(optarg, SNAPSHOT_OPT_BASE, NULL)) {
70b94331
MA
671 sn_opts = qemu_opts_parse_noisily(&internal_snapshot_opts,
672 optarg, false);
8c116b0e 673 if (!sn_opts) {
85b01e09
MA
674 error_report("Failed in parsing snapshot param `%s'",
675 optarg);
676 exit(EXIT_FAILURE);
8c116b0e
WX
677 }
678 } else {
679 sn_id_or_name = optarg;
680 }
681 /* fall through */
7a5ca864 682 case 'r':
dbb38caa 683 readonly = true;
07108b29 684 flags &= ~BDRV_O_RDWR;
7a5ca864 685 break;
dbc7b014
EB
686 case 'A':
687 alloc_depth = true;
688 break;
636192c4 689 case 'B':
cbad81ce 690 QAPI_LIST_PREPEND(bitmaps, g_strdup(optarg));
636192c4 691 break;
cd831bd7 692 case 'k':
b32f6c28 693 sockpath = optarg;
713cc671 694 if (sockpath[0] != '/') {
9af9e0fe 695 error_report("socket path must be absolute");
85b01e09 696 exit(EXIT_FAILURE);
713cc671 697 }
cd831bd7
TS
698 break;
699 case 'd':
700 disconnect = true;
701 break;
702 case 'c':
703 device = optarg;
704 break;
3b05a8e9 705 case 'e':
43b51011 706 if (qemu_strtoi(optarg, NULL, 0, &shared) < 0 ||
3dcf56e6 707 shared < 0) {
85b01e09
MA
708 error_report("Invalid shared device number '%s'", optarg);
709 exit(EXIT_FAILURE);
3b05a8e9 710 }
3b05a8e9 711 break;
e6b63677
DB
712 case 'f':
713 fmt = optarg;
714 break;
713cc671
PL
715 case 't':
716 persistent = 1;
717 break;
3d4b2f9c
DB
718 case 'x':
719 export_name = optarg;
93676c88
EB
720 if (strlen(export_name) > NBD_MAX_STRING_SIZE) {
721 error_report("export name '%s' too long", export_name);
722 exit(EXIT_FAILURE);
723 }
3d4b2f9c 724 break;
b1a75b33
EB
725 case 'D':
726 export_description = optarg;
93676c88
EB
727 if (strlen(export_description) > NBD_MAX_STRING_SIZE) {
728 error_report("export description '%s' too long",
729 export_description);
730 exit(EXIT_FAILURE);
731 }
b1a75b33 732 break;
7a5ca864
FB
733 case 'v':
734 verbose = 1;
735 break;
736 case 'V':
737 version(argv[0]);
738 exit(0);
739 break;
740 case 'h':
741 usage(argv[0]);
742 exit(0);
743 break;
744 case '?':
85b01e09
MA
745 error_report("Try `%s --help' for more information.", argv[0]);
746 exit(EXIT_FAILURE);
fa40e43c
KW
747 case QEMU_NBD_OPT_OBJECT:
748 user_creatable_process_cmdline(optarg);
749 break;
145614a1
DB
750 case QEMU_NBD_OPT_TLSCREDS:
751 tlscredsid = optarg;
752 break;
003b2b25
DB
753 case QEMU_NBD_OPT_TLSHOSTNAME:
754 tlshostname = optarg;
755 break;
77c9aaef
DB
756 case QEMU_NBD_OPT_IMAGE_OPTS:
757 imageOpts = true;
758 break;
39ca463e 759 case 'T':
92eecfff 760 trace_opt_parse(optarg);
39ca463e 761 break;
b25e12da
DB
762 case QEMU_NBD_OPT_TLSAUTHZ:
763 tlsauthz = optarg;
764 break;
ffb31e1d
HR
765 case QEMU_NBD_OPT_FORK:
766 fork_process = true;
767 break;
68b96f15
EB
768 case 'L':
769 list = true;
770 break;
637bc5a5
HR
771 case QEMU_NBD_OPT_PID_FILE:
772 pid_file_name = optarg;
773 break;
3d212b41
RJ
774 case QEMU_NBD_OPT_SELINUX_LABEL:
775 selinux_label = optarg;
776 break;
7a5ca864
FB
777 }
778 }
779
68b96f15
EB
780 if (list) {
781 if (argc != optind) {
782 error_report("List mode is incompatible with a file name");
783 exit(EXIT_FAILURE);
784 }
0bc16997 785 if (export_name || export_description || dev_offset ||
cbad81ce 786 device || disconnect || fmt || sn_id_or_name || bitmaps ||
dbc7b014 787 alloc_depth || seen_aio || seen_discard || seen_cache) {
68b96f15
EB
788 error_report("List mode is incompatible with per-device settings");
789 exit(EXIT_FAILURE);
790 }
791 if (fork_process) {
792 error_report("List mode is incompatible with forking");
793 exit(EXIT_FAILURE);
794 }
795 } else if ((argc - optind) != 1) {
433672b0
MA
796 error_report("Invalid number of arguments");
797 error_printf("Try `%s --help' for more information.\n", argv[0]);
85b01e09 798 exit(EXIT_FAILURE);
68b96f15
EB
799 } else if (!export_name) {
800 export_name = "";
7a5ca864
FB
801 }
802
39ca463e
DL
803 if (!trace_init_backends()) {
804 exit(1);
805 }
92eecfff 806 trace_init_file();
c5955f4f 807 qemu_set_log(LOG_TRACE, &error_fatal);
39ca463e 808
a721f53b
RJ
809 socket_activation = check_socket_activation();
810 if (socket_activation == 0) {
e8ae8b1a
DB
811 if (!sockpath) {
812 setup_address_and_port(&bindto, &port);
813 }
a721f53b
RJ
814 } else {
815 /* Using socket activation - check user didn't use -p etc. */
816 const char *err_msg = socket_activation_validate_opts(device, sockpath,
68b96f15 817 bindto, port,
3d212b41 818 selinux_label,
68b96f15 819 list);
a721f53b
RJ
820 if (err_msg != NULL) {
821 error_report("%s", err_msg);
822 exit(EXIT_FAILURE);
823 }
53fabd4b
PB
824
825 /* qemu-nbd can only listen on a single socket. */
826 if (socket_activation > 1) {
827 error_report("qemu-nbd does not support socket activation with %s > 1",
828 "LISTEN_FDS");
829 exit(EXIT_FAILURE);
830 }
a721f53b
RJ
831 }
832
145614a1 833 if (tlscredsid) {
145614a1
DB
834 if (device) {
835 error_report("TLS is not supported with a host device");
836 exit(EXIT_FAILURE);
837 }
b25e12da
DB
838 if (tlsauthz && list) {
839 error_report("TLS authorization is incompatible with export list");
840 exit(EXIT_FAILURE);
841 }
003b2b25
DB
842 if (tlshostname && !list) {
843 error_report("TLS hostname is only supported with export list");
844 exit(EXIT_FAILURE);
845 }
68b96f15 846 tlscreds = nbd_get_tls_creds(tlscredsid, list, &local_err);
145614a1 847 if (local_err) {
5217f188 848 error_reportf_err(local_err, "Failed to get TLS creds: ");
145614a1
DB
849 exit(EXIT_FAILURE);
850 }
b25e12da
DB
851 } else {
852 if (tlsauthz) {
853 error_report("--tls-authz is not permitted without --tls-creds");
854 exit(EXIT_FAILURE);
855 }
003b2b25
DB
856 if (tlshostname) {
857 error_report("--tls-hostname is not permitted without --tls-creds");
858 exit(EXIT_FAILURE);
859 }
145614a1
DB
860 }
861
3d212b41
RJ
862 if (selinux_label) {
863#ifdef CONFIG_SELINUX
864 if (sockpath == NULL && device == NULL) {
865 error_report("--selinux-label is not permitted without --socket");
866 exit(EXIT_FAILURE);
867 }
868#else
869 error_report("SELinux support not enabled in this binary");
870 exit(EXIT_FAILURE);
871#endif
872 }
873
68b96f15
EB
874 if (list) {
875 saddr = nbd_build_socket_address(sockpath, bindto, port);
003b2b25
DB
876 return qemu_nbd_client_list(saddr, tlscreds,
877 tlshostname ? tlshostname : bindto);
68b96f15
EB
878 }
879
3c1fa35d
EB
880#if !HAVE_NBD_DEVICE
881 if (disconnect || device) {
882 error_report("Kernel /dev/nbdN support not available");
883 exit(EXIT_FAILURE);
884 }
885#else /* HAVE_NBD_DEVICE */
cd831bd7 886 if (disconnect) {
d0d6ff58
DB
887 int nbdfd = open(argv[optind], O_RDWR);
888 if (nbdfd < 0) {
85b01e09
MA
889 error_report("Cannot open %s: %s", argv[optind],
890 strerror(errno));
891 exit(EXIT_FAILURE);
fc19f8a0 892 }
d0d6ff58 893 nbd_disconnect(nbdfd);
cd831bd7 894
d0d6ff58 895 close(nbdfd);
cd831bd7
TS
896
897 printf("%s disconnected\n", argv[optind]);
898
713cc671 899 return 0;
cd831bd7 900 }
3c1fa35d 901#endif
cd831bd7 902
ffb31e1d 903 if ((device && !verbose) || fork_process) {
eb705985 904#ifndef WIN32
c1f8fdc3
PB
905 int stderr_fd[2];
906 pid_t pid;
907 int ret;
908
fc19f8a0 909 if (qemu_pipe(stderr_fd) < 0) {
85b01e09
MA
910 error_report("Error setting up communication pipe: %s",
911 strerror(errno));
912 exit(EXIT_FAILURE);
c1f8fdc3
PB
913 }
914
915 /* Now daemonize, but keep a communication channel open to
916 * print errors and exit with the proper status code.
917 */
918 pid = fork();
70d4739e 919 if (pid < 0) {
85b01e09
MA
920 error_report("Failed to fork: %s", strerror(errno));
921 exit(EXIT_FAILURE);
70d4739e 922 } else if (pid == 0) {
c1f8fdc3 923 close(stderr_fd[0]);
e6df58a5 924
0eaf453e
RP
925 /* Remember parent's stderr if we will be restoring it. */
926 if (fork_process) {
927 old_stderr = dup(STDERR_FILENO);
928 }
929
9faf31b6 930 ret = qemu_daemon(1, 0);
c1f8fdc3
PB
931
932 /* Temporarily redirect stderr to the parent's pipe... */
933 dup2(stderr_fd[1], STDERR_FILENO);
fc19f8a0 934 if (ret < 0) {
85b01e09
MA
935 error_report("Failed to daemonize: %s", strerror(errno));
936 exit(EXIT_FAILURE);
c1f8fdc3
PB
937 }
938
939 /* ... close the descriptor we inherited and go on. */
940 close(stderr_fd[1]);
941 } else {
942 bool errors = false;
943 char *buf;
944
945 /* In the parent. Print error messages from the child until
946 * it closes the pipe.
947 */
948 close(stderr_fd[1]);
949 buf = g_malloc(1024);
950 while ((ret = read(stderr_fd[0], buf, 1024)) > 0) {
951 errors = true;
952 ret = qemu_write_full(STDERR_FILENO, buf, ret);
fc19f8a0 953 if (ret < 0) {
c1f8fdc3
PB
954 exit(EXIT_FAILURE);
955 }
956 }
fc19f8a0 957 if (ret < 0) {
85b01e09
MA
958 error_report("Cannot read from daemon: %s",
959 strerror(errno));
960 exit(EXIT_FAILURE);
c1f8fdc3
PB
961 }
962
963 /* Usually the daemon should not print any message.
964 * Exit with zero status in that case.
965 */
966 exit(errors);
967 }
eb705985
DB
968#else /* WIN32 */
969 error_report("Unable to fork into background on Windows hosts");
970 exit(EXIT_FAILURE);
971#endif /* WIN32 */
c1f8fdc3
PB
972 }
973
a6ac2313
PB
974 if (device != NULL && sockpath == NULL) {
975 sockpath = g_malloc(128);
976 snprintf(sockpath, 128, SOCKET_PATH, basename(device));
cd831bd7
TS
977 }
978
e4849c1d 979 server = qio_net_listener_new();
a721f53b 980 if (socket_activation == 0) {
582d4210
EB
981 int backlog;
982
3dcf56e6 983 if (persistent || shared == 0) {
582d4210
EB
984 backlog = SOMAXCONN;
985 } else {
986 backlog = MIN(shared, SOMAXCONN);
987 }
3d212b41
RJ
988#ifdef CONFIG_SELINUX
989 if (selinux_label && setsockcreatecon_raw(selinux_label) == -1) {
990 error_report("Cannot set SELinux socket create context to %s: %s",
991 selinux_label, strerror(errno));
992 exit(EXIT_FAILURE);
993 }
994#endif
a721f53b 995 saddr = nbd_build_socket_address(sockpath, bindto, port);
582d4210
EB
996 if (qio_net_listener_open_sync(server, saddr, backlog,
997 &local_err) < 0) {
e4849c1d 998 object_unref(OBJECT(server));
a721f53b 999 error_report_err(local_err);
e4849c1d 1000 exit(EXIT_FAILURE);
a721f53b 1001 }
3d212b41
RJ
1002#ifdef CONFIG_SELINUX
1003 if (selinux_label && setsockcreatecon_raw(NULL) == -1) {
1004 error_report("Cannot clear SELinux socket create context: %s",
1005 strerror(errno));
1006 exit(EXIT_FAILURE);
1007 }
1008#endif
a721f53b 1009 } else {
e4849c1d 1010 size_t i;
a721f53b 1011 /* See comment in check_socket_activation above. */
e4849c1d
DB
1012 for (i = 0; i < socket_activation; i++) {
1013 QIOChannelSocket *sioc;
1014 sioc = qio_channel_socket_new_fd(FIRST_SOCKET_ACTIVATION_FD + i,
1015 &local_err);
1016 if (sioc == NULL) {
1017 object_unref(OBJECT(server));
5217f188
MA
1018 error_reportf_err(local_err,
1019 "Failed to use socket activation: ");
e4849c1d
DB
1020 exit(EXIT_FAILURE);
1021 }
1022 qio_net_listener_add(server, sioc);
1023 object_unref(OBJECT(sioc));
a721f53b
RJ
1024 }
1025 }
48bec07e 1026
f9734d5d 1027 qemu_init_main_loop(&error_fatal);
802ddc37 1028 bdrv_init();
b3b5299d 1029 atexit(qemu_nbd_shutdown);
802ddc37 1030
77c9aaef
DB
1031 srcpath = argv[optind];
1032 if (imageOpts) {
1033 QemuOpts *opts;
1034 if (fmt) {
1035 error_report("--image-opts and -f are mutually exclusive");
1036 exit(EXIT_FAILURE);
1037 }
1038 opts = qemu_opts_parse_noisily(&file_opts, srcpath, true);
1039 if (!opts) {
1040 qemu_opts_reset(&file_opts);
1041 exit(EXIT_FAILURE);
1042 }
1043 options = qemu_opts_to_qdict(opts, NULL);
1044 qemu_opts_reset(&file_opts);
efaa7c4e 1045 blk = blk_new_open(NULL, NULL, options, flags, &local_err);
77c9aaef
DB
1046 } else {
1047 if (fmt) {
1048 options = qdict_new();
46f5ac20 1049 qdict_put_str(options, "driver", fmt);
77c9aaef 1050 }
efaa7c4e 1051 blk = blk_new_open(srcpath, NULL, options, flags, &local_err);
e6b63677
DB
1052 }
1053
4fbec260 1054 if (!blk) {
c29b77f9
MA
1055 error_reportf_err(local_err, "Failed to blk_new_open '%s': ",
1056 argv[optind]);
85b01e09 1057 exit(EXIT_FAILURE);
802ddc37 1058 }
4fbec260 1059 bs = blk_bs(blk);
802ddc37 1060
b57e4de0
KW
1061 if (dev_offset) {
1062 QDict *raw_opts = qdict_new();
1063 qdict_put_str(raw_opts, "driver", "raw");
1064 qdict_put_str(raw_opts, "file", bs->node_name);
1065 qdict_put_int(raw_opts, "offset", dev_offset);
1066 bs = bdrv_open(NULL, NULL, raw_opts, flags, &error_fatal);
1067 blk_remove_bs(blk);
1068 blk_insert_bs(blk, bs, &error_fatal);
1069 bdrv_unref(bs);
1070 }
1071
6effd5bf
KW
1072 blk_set_enable_write_cache(blk, !writethrough);
1073
8c116b0e
WX
1074 if (sn_opts) {
1075 ret = bdrv_snapshot_load_tmp(bs,
1076 qemu_opt_get(sn_opts, SNAPSHOT_OPT_ID),
1077 qemu_opt_get(sn_opts, SNAPSHOT_OPT_NAME),
1078 &local_err);
1079 } else if (sn_id_or_name) {
1080 ret = bdrv_snapshot_load_tmp_by_id_or_name(bs, sn_id_or_name,
1081 &local_err);
1082 }
1083 if (ret < 0) {
c29b77f9 1084 error_reportf_err(local_err, "Failed to load snapshot: ");
85b01e09 1085 exit(EXIT_FAILURE);
8c116b0e
WX
1086 }
1087
b3838a40 1088 bs->detect_zeroes = detect_zeroes;
e424b655 1089
00917172
KW
1090 nbd_server_is_qemu_nbd(true);
1091
1092 export_opts = g_new(BlockExportOptions, 1);
1093 *export_opts = (BlockExportOptions) {
1094 .type = BLOCK_EXPORT_TYPE_NBD,
d53be9ce 1095 .id = g_strdup("qemu-nbd-export"),
b6076afc 1096 .node_name = g_strdup(bdrv_get_node_name(bs)),
00917172
KW
1097 .has_writethrough = true,
1098 .writethrough = writethrough,
30dbc81d
KW
1099 .has_writable = true,
1100 .writable = !readonly,
00917172 1101 .u.nbd = {
cbad81ce
EB
1102 .has_name = true,
1103 .name = g_strdup(export_name),
1104 .has_description = !!export_description,
1105 .description = g_strdup(export_description),
1106 .has_bitmaps = !!bitmaps,
1107 .bitmaps = bitmaps,
dbc7b014
EB
1108 .has_allocation_depth = alloc_depth,
1109 .allocation_depth = alloc_depth,
00917172
KW
1110 },
1111 };
1112 blk_exp_add(export_opts, &error_fatal);
1113 qapi_free_BlockExportOptions(export_opts);
3b05a8e9 1114
f1ef5555 1115 if (device) {
3c1fa35d 1116#if HAVE_NBD_DEVICE
f1ef5555
PB
1117 int ret;
1118
a6ac2313 1119 ret = pthread_create(&client_thread, NULL, nbd_client_thread, device);
f1ef5555 1120 if (ret != 0) {
85b01e09
MA
1121 error_report("Failed to create client thread: %s", strerror(ret));
1122 exit(EXIT_FAILURE);
f1ef5555 1123 }
3c1fa35d 1124#endif
f1ef5555
PB
1125 } else {
1126 /* Shut up GCC warnings. */
1127 memset(&client_thread, 0, sizeof(client_thread));
1128 }
1129
d0d6ff58 1130 nbd_update_server_watch();
7a5ca864 1131
637bc5a5
HR
1132 if (pid_file_name) {
1133 qemu_write_pidfile(pid_file_name, &error_fatal);
1134 }
1135
9faf31b6
MT
1136 /* now when the initialization is (almost) complete, chdir("/")
1137 * to free any busy filesystems */
1138 if (chdir("/") < 0) {
85b01e09
MA
1139 error_report("Could not chdir to root directory: %s",
1140 strerror(errno));
1141 exit(EXIT_FAILURE);
9faf31b6
MT
1142 }
1143
ffb31e1d
HR
1144 if (fork_process) {
1145 dup2(old_stderr, STDERR_FILENO);
1146 close(old_stderr);
1147 }
1148
7860a380 1149 state = RUNNING;
3b05a8e9 1150 do {
a61c6782 1151 main_loop_wait(false);
7860a380 1152 if (state == TERMINATE) {
bc4ee65b 1153 blk_exp_close_all();
d794f7f3 1154 state = TERMINATED;
7860a380
PB
1155 }
1156 } while (state != TERMINATED);
7a5ca864 1157
26f54e9a 1158 blk_unref(blk);
b32f6c28
PB
1159 if (sockpath) {
1160 unlink(sockpath);
1161 }
7a5ca864 1162
fbf28a43 1163 qemu_opts_del(sn_opts);
8c116b0e 1164
a517e88b
PB
1165 if (device) {
1166 void *ret;
1167 pthread_join(client_thread, &ret);
1168 exit(ret != NULL);
1169 } else {
1170 exit(EXIT_SUCCESS);
1171 }
7a5ca864 1172}