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