]> git.proxmox.com Git - mirror_qemu.git/blame - qemu-nbd.c
Replaced get_tick_per_sec() by NANOSECONDS_PER_SECOND
[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"
da34e65c 20#include "qapi/error.h"
5a61cb60 21#include "qemu-common.h"
26f54e9a 22#include "sysemu/block-backend.h"
b3838a40 23#include "block/block_int.h"
737e150e 24#include "block/nbd.h"
6a1751b7 25#include "qemu/main-loop.h"
537b41f5 26#include "qemu/error-report.h"
0ab3b337 27#include "qemu/config-file.h"
8c116b0e 28#include "block/snapshot.h"
b3838a40 29#include "qapi/util.h"
d49b6836 30#include "qapi/qmp/qstring.h"
0ab3b337 31#include "qom/object_interfaces.h"
d0d6ff58 32#include "io/channel-socket.h"
7a5ca864 33
7a5ca864 34#include <getopt.h>
2bff4b6f 35#include <libgen.h>
a517e88b 36#include <pthread.h>
cd831bd7 37
713cc671 38#define SOCKET_PATH "/var/lock/qemu-nbd-%s"
fa8b7ce2
DB
39#define QEMU_NBD_OPT_CACHE 256
40#define QEMU_NBD_OPT_AIO 257
41#define QEMU_NBD_OPT_DISCARD 258
42#define QEMU_NBD_OPT_DETECT_ZEROES 259
43#define QEMU_NBD_OPT_OBJECT 260
44#define QEMU_NBD_OPT_TLSCREDS 261
45#define QEMU_NBD_OPT_IMAGE_OPTS 262
7a5ca864 46
af49bbbe 47static NBDExport *exp;
3d4b2f9c 48static bool newproto;
b1d8e52e 49static int verbose;
a517e88b 50static char *srcpath;
48bec07e 51static SocketAddress *saddr;
7860a380
PB
52static int persistent = 0;
53static enum { RUNNING, TERMINATE, TERMINATING, TERMINATED } state;
a61c6782
PB
54static int shared = 1;
55static int nb_fds;
d0d6ff58
DB
56static QIOChannelSocket *server_ioc;
57static int server_watch = -1;
145614a1 58static QCryptoTLSCreds *tlscreds;
7a5ca864
FB
59
60static void usage(const char *name)
61{
b033cd86 62 (printf) (
7a5ca864
FB
63"Usage: %s [OPTIONS] FILE\n"
64"QEMU Disk Network Block Device Server\n"
65"\n"
713cc671
PL
66" -h, --help display this help and exit\n"
67" -V, --version output version information and exit\n"
b033cd86
PB
68"\n"
69"Connection properties:\n"
713cc671
PL
70" -p, --port=PORT port to listen on (default `%d')\n"
71" -b, --bind=IFACE interface to bind to (default `0.0.0.0')\n"
72" -k, --socket=PATH path to the unix socket\n"
73" (default '"SOCKET_PATH"')\n"
74" -e, --shared=NUM device can be shared by NUM clients (default '1')\n"
75" -t, --persistent don't exit on the last connection\n"
76" -v, --verbose display extra debugging information\n"
7a5ca864 77"\n"
b033cd86 78"Exposing part of the image:\n"
713cc671
PL
79" -o, --offset=OFFSET offset into the image\n"
80" -P, --partition=NUM only expose partition NUM\n"
b033cd86 81"\n"
0ab3b337
DB
82"General purpose options:\n"
83" --object type,id=ID,... define an object such as 'secret' for providing\n"
84" passwords and/or encryption keys\n"
b033cd86
PB
85#ifdef __linux__
86"Kernel NBD client support:\n"
713cc671
PL
87" -c, --connect=DEV connect FILE to the local NBD device DEV\n"
88" -d, --disconnect disconnect the specified device\n"
b033cd86
PB
89"\n"
90#endif
91"\n"
92"Block device options:\n"
713cc671
PL
93" -f, --format=FORMAT set image format (raw, qcow2, ...)\n"
94" -r, --read-only export read-only\n"
95" -s, --snapshot use FILE as an external snapshot, create a temporary\n"
96" file with backing_file=FILE, redirect the write to\n"
97" the temporary one\n"
8c116b0e 98" -l, --load-snapshot=SNAPSHOT_PARAM\n"
713cc671
PL
99" load an internal snapshot inside FILE and export it\n"
100" as an read-only device, SNAPSHOT_PARAM format is\n"
101" 'snapshot.id=[ID],snapshot.name=[NAME]', or\n"
102" '[ID_OR_NAME]'\n"
103" -n, --nocache disable host cache\n"
104" --cache=MODE set cache mode (none, writeback, ...)\n"
713cc671 105" --aio=MODE set AIO mode (native or threads)\n"
b3838a40 106" --discard=MODE set discard mode (ignore, unmap)\n"
6883de6c 107" --detect-zeroes=MODE set detect-zeroes mode (off, on, unmap)\n"
77c9aaef 108" --image-opts treat FILE as a full set of image options\n"
b033cd86
PB
109"\n"
110"Report bugs to <qemu-devel@nongnu.org>\n"
c2e2872b 111 , name, NBD_DEFAULT_PORT, "DEVICE");
7a5ca864
FB
112}
113
114static void version(const char *name)
115{
116 printf(
315bc7aa 117"%s version 0.0.1\n"
7a5ca864
FB
118"Written by Anthony Liguori.\n"
119"\n"
120"Copyright (C) 2006 Anthony Liguori <anthony@codemonkey.ws>.\n"
121"This is free software; see the source for copying conditions. There is NO\n"
122"warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n"
315bc7aa 123 , name);
7a5ca864
FB
124}
125
126struct partition_record
127{
128 uint8_t bootable;
129 uint8_t start_head;
130 uint32_t start_cylinder;
131 uint8_t start_sector;
132 uint8_t system;
133 uint8_t end_head;
134 uint8_t end_cylinder;
135 uint8_t end_sector;
136 uint32_t start_sector_abs;
137 uint32_t nb_sectors_abs;
138};
139
140static void read_partition(uint8_t *p, struct partition_record *r)
141{
142 r->bootable = p[0];
143 r->start_head = p[1];
144 r->start_cylinder = p[3] | ((p[2] << 2) & 0x0300);
145 r->start_sector = p[2] & 0x3f;
146 r->system = p[4];
147 r->end_head = p[5];
148 r->end_cylinder = p[7] | ((p[6] << 2) & 0x300);
149 r->end_sector = p[6] & 0x3f;
ac97393d
HR
150
151 r->start_sector_abs = le32_to_cpup((uint32_t *)(p + 8));
152 r->nb_sectors_abs = le32_to_cpup((uint32_t *)(p + 12));
7a5ca864
FB
153}
154
4c58e80a 155static int find_partition(BlockBackend *blk, int partition,
7a5ca864
FB
156 off_t *offset, off_t *size)
157{
158 struct partition_record mbr[4];
159 uint8_t data[512];
160 int i;
161 int ext_partnum = 4;
cb7cf0e3 162 int ret;
7a5ca864 163
4c58e80a 164 if ((ret = blk_read(blk, 0, data, 1)) < 0) {
a4699e55 165 error_report("error while reading: %s", strerror(-ret));
85b01e09 166 exit(EXIT_FAILURE);
cb7cf0e3 167 }
7a5ca864
FB
168
169 if (data[510] != 0x55 || data[511] != 0xaa) {
185b4338 170 return -EINVAL;
7a5ca864
FB
171 }
172
173 for (i = 0; i < 4; i++) {
174 read_partition(&data[446 + 16 * i], &mbr[i]);
175
453b07b1 176 if (!mbr[i].system || !mbr[i].nb_sectors_abs) {
7a5ca864 177 continue;
453b07b1 178 }
7a5ca864
FB
179
180 if (mbr[i].system == 0xF || mbr[i].system == 0x5) {
181 struct partition_record ext[4];
182 uint8_t data1[512];
183 int j;
184
4c58e80a 185 if ((ret = blk_read(blk, mbr[i].start_sector_abs, data1, 1)) < 0) {
a4699e55 186 error_report("error while reading: %s", strerror(-ret));
85b01e09 187 exit(EXIT_FAILURE);
cb7cf0e3 188 }
7a5ca864
FB
189
190 for (j = 0; j < 4; j++) {
191 read_partition(&data1[446 + 16 * j], &ext[j]);
453b07b1 192 if (!ext[j].system || !ext[j].nb_sectors_abs) {
7a5ca864 193 continue;
453b07b1 194 }
7a5ca864
FB
195
196 if ((ext_partnum + j + 1) == partition) {
197 *offset = (uint64_t)ext[j].start_sector_abs << 9;
198 *size = (uint64_t)ext[j].nb_sectors_abs << 9;
199 return 0;
200 }
201 }
202 ext_partnum += 4;
203 } else if ((i + 1) == partition) {
204 *offset = (uint64_t)mbr[i].start_sector_abs << 9;
205 *size = (uint64_t)mbr[i].nb_sectors_abs << 9;
206 return 0;
207 }
208 }
209
185b4338 210 return -ENOENT;
7a5ca864
FB
211}
212
bb345110
PB
213static void termsig_handler(int signum)
214{
7860a380 215 state = TERMINATE;
a61c6782 216 qemu_notify_event();
bb345110
PB
217}
218
537b41f5 219
a517e88b 220static void *show_parts(void *arg)
cd831bd7 221{
a6ac2313 222 char *device = arg;
a517e88b
PB
223 int nbd;
224
225 /* linux just needs an open() to trigger
226 * the partition table update
227 * but remember to load the module with max_part != 0 :
228 * modprobe nbd max_part=63
229 */
230 nbd = open(device, O_RDWR);
fc19f8a0 231 if (nbd >= 0) {
a517e88b
PB
232 close(nbd);
233 }
234 return NULL;
235}
cd831bd7 236
a517e88b
PB
237static void *nbd_client_thread(void *arg)
238{
a6ac2313 239 char *device = arg;
a517e88b 240 off_t size;
a517e88b 241 uint32_t nbdflags;
d0d6ff58
DB
242 QIOChannelSocket *sioc;
243 int fd;
a517e88b
PB
244 int ret;
245 pthread_t show_parts_thread;
1ce52846 246 Error *local_error = NULL;
a517e88b 247
d0d6ff58
DB
248 sioc = qio_channel_socket_new();
249 if (qio_channel_socket_connect_sync(sioc,
250 saddr,
251 &local_error) < 0) {
48bec07e 252 error_report_err(local_error);
dc10e8b3
SH
253 goto out;
254 }
a517e88b 255
1c778ef7 256 ret = nbd_receive_negotiate(QIO_CHANNEL(sioc), NULL, &nbdflags,
f95910fe 257 NULL, NULL, NULL,
3f472659 258 &size, &local_error);
fc19f8a0 259 if (ret < 0) {
1ce52846 260 if (local_error) {
78288671 261 error_report_err(local_error);
1ce52846 262 }
0c544d73 263 goto out_socket;
a517e88b
PB
264 }
265
a6ac2313 266 fd = open(device, O_RDWR);
fc19f8a0 267 if (fd < 0) {
a6ac2313 268 /* Linux-only, we can use %m in printf. */
b9884681 269 error_report("Failed to open %s: %m", device);
0c544d73 270 goto out_socket;
a6ac2313
PB
271 }
272
1c778ef7 273 ret = nbd_init(fd, sioc, nbdflags, size);
fc19f8a0 274 if (ret < 0) {
0c544d73 275 goto out_fd;
a517e88b
PB
276 }
277
278 /* update partition table */
a6ac2313 279 pthread_create(&show_parts_thread, NULL, show_parts, device);
a517e88b 280
c1f8fdc3
PB
281 if (verbose) {
282 fprintf(stderr, "NBD device %s is now connected to %s\n",
283 device, srcpath);
284 } else {
285 /* Close stderr so that the qemu-nbd process exits. */
286 dup2(STDOUT_FILENO, STDERR_FILENO);
287 }
a517e88b
PB
288
289 ret = nbd_client(fd);
290 if (ret) {
0c544d73 291 goto out_fd;
cd831bd7 292 }
a517e88b 293 close(fd);
d0d6ff58 294 object_unref(OBJECT(sioc));
a517e88b
PB
295 kill(getpid(), SIGTERM);
296 return (void *) EXIT_SUCCESS;
297
0c544d73
PB
298out_fd:
299 close(fd);
300out_socket:
d0d6ff58 301 object_unref(OBJECT(sioc));
a517e88b
PB
302out:
303 kill(getpid(), SIGTERM);
304 return (void *) EXIT_FAILURE;
cd831bd7
TS
305}
306
e4afbf4f 307static int nbd_can_accept(void)
a61c6782
PB
308{
309 return nb_fds < shared;
310}
311
7860a380
PB
312static void nbd_export_closed(NBDExport *exp)
313{
314 assert(state == TERMINATING);
315 state = TERMINATED;
316}
317
d0d6ff58 318static void nbd_update_server_watch(void);
e4afbf4f 319
1743b515 320static void nbd_client_closed(NBDClient *client)
a61c6782 321{
1743b515 322 nb_fds--;
7860a380
PB
323 if (nb_fds == 0 && !persistent && state == RUNNING) {
324 state = TERMINATE;
325 }
d0d6ff58 326 nbd_update_server_watch();
7860a380 327 nbd_client_put(client);
a61c6782
PB
328}
329
d0d6ff58 330static gboolean nbd_accept(QIOChannel *ioc, GIOCondition cond, gpointer opaque)
a61c6782 331{
d0d6ff58 332 QIOChannelSocket *cioc;
a61c6782 333
d0d6ff58
DB
334 cioc = qio_channel_socket_accept(QIO_CHANNEL_SOCKET(ioc),
335 NULL);
336 if (!cioc) {
337 return TRUE;
0c544d73
PB
338 }
339
7860a380 340 if (state >= TERMINATE) {
d0d6ff58
DB
341 object_unref(OBJECT(cioc));
342 return TRUE;
7860a380
PB
343 }
344
ee7d7aab 345 nb_fds++;
d0d6ff58 346 nbd_update_server_watch();
f95910fe 347 nbd_client_new(newproto ? NULL : exp, cioc,
145614a1 348 tlscreds, NULL, nbd_client_closed);
d0d6ff58
DB
349 object_unref(OBJECT(cioc));
350
351 return TRUE;
a61c6782
PB
352}
353
d0d6ff58 354static void nbd_update_server_watch(void)
e4afbf4f
FZ
355{
356 if (nbd_can_accept()) {
d0d6ff58
DB
357 if (server_watch == -1) {
358 server_watch = qio_channel_add_watch(QIO_CHANNEL(server_ioc),
359 G_IO_IN,
360 nbd_accept,
361 NULL, NULL);
362 }
e4afbf4f 363 } else {
d0d6ff58
DB
364 if (server_watch != -1) {
365 g_source_remove(server_watch);
366 server_watch = -1;
367 }
e4afbf4f
FZ
368 }
369}
370
48bec07e
DB
371
372static SocketAddress *nbd_build_socket_address(const char *sockpath,
373 const char *bindto,
374 const char *port)
375{
376 SocketAddress *saddr;
377
378 saddr = g_new0(SocketAddress, 1);
379 if (sockpath) {
2d32adda 380 saddr->type = SOCKET_ADDRESS_KIND_UNIX;
32bafa8f
EB
381 saddr->u.q_unix.data = g_new0(UnixSocketAddress, 1);
382 saddr->u.q_unix.data->path = g_strdup(sockpath);
48bec07e 383 } else {
0399293e 384 InetSocketAddress *inet;
2d32adda 385 saddr->type = SOCKET_ADDRESS_KIND_INET;
32bafa8f 386 inet = saddr->u.inet.data = g_new0(InetSocketAddress, 1);
0399293e 387 inet->host = g_strdup(bindto);
48bec07e 388 if (port) {
0399293e 389 inet->port = g_strdup(port);
48bec07e 390 } else {
0399293e 391 inet->port = g_strdup_printf("%d", NBD_DEFAULT_PORT);
48bec07e
DB
392 }
393 }
394
395 return saddr;
396}
397
398
77c9aaef
DB
399static QemuOptsList file_opts = {
400 .name = "file",
401 .implied_opt_name = "file",
402 .head = QTAILQ_HEAD_INITIALIZER(file_opts.head),
403 .desc = {
404 /* no elements => accept any params */
405 { /* end of list */ }
406 },
407};
408
0ab3b337
DB
409static QemuOptsList qemu_object_opts = {
410 .name = "object",
411 .implied_opt_name = "qom-type",
412 .head = QTAILQ_HEAD_INITIALIZER(qemu_object_opts.head),
413 .desc = {
414 { }
415 },
416};
417
418
145614a1
DB
419
420static QCryptoTLSCreds *nbd_get_tls_creds(const char *id, Error **errp)
421{
422 Object *obj;
423 QCryptoTLSCreds *creds;
424
425 obj = object_resolve_path_component(
426 object_get_objects_root(), id);
427 if (!obj) {
428 error_setg(errp, "No TLS credentials with id '%s'",
429 id);
430 return NULL;
431 }
432 creds = (QCryptoTLSCreds *)
433 object_dynamic_cast(obj, TYPE_QCRYPTO_TLS_CREDS);
434 if (!creds) {
435 error_setg(errp, "Object with id '%s' is not TLS credentials",
436 id);
437 return NULL;
438 }
439
440 if (creds->endpoint != QCRYPTO_TLS_CREDS_ENDPOINT_SERVER) {
441 error_setg(errp,
442 "Expecting TLS credentials with a server endpoint");
443 return NULL;
444 }
445 object_ref(obj);
446 return creds;
447}
448
449
7a5ca864
FB
450int main(int argc, char **argv)
451{
26f54e9a 452 BlockBackend *blk;
7a5ca864
FB
453 BlockDriverState *bs;
454 off_t dev_offset = 0;
b90fb4b8 455 uint32_t nbdflags = 0;
cd831bd7 456 bool disconnect = false;
7a5ca864 457 const char *bindto = "0.0.0.0";
48bec07e
DB
458 const char *port = NULL;
459 char *sockpath = NULL;
a6ac2313 460 char *device = NULL;
7a5ca864 461 off_t fd_size;
8c116b0e
WX
462 QemuOpts *sn_opts = NULL;
463 const char *sn_id_or_name = NULL;
3d4b2f9c 464 const char *sopt = "hVb:o:p:rsnP:c:dvk:e:f:tl:x:";
7a5ca864 465 struct option lopt[] = {
aa6e546c
DB
466 { "help", no_argument, NULL, 'h' },
467 { "version", no_argument, NULL, 'V' },
468 { "bind", required_argument, NULL, 'b' },
469 { "port", required_argument, NULL, 'p' },
470 { "socket", required_argument, NULL, 'k' },
471 { "offset", required_argument, NULL, 'o' },
472 { "read-only", no_argument, NULL, 'r' },
473 { "partition", required_argument, NULL, 'P' },
474 { "connect", required_argument, NULL, 'c' },
475 { "disconnect", no_argument, NULL, 'd' },
476 { "snapshot", no_argument, NULL, 's' },
477 { "load-snapshot", required_argument, NULL, 'l' },
478 { "nocache", no_argument, NULL, 'n' },
479 { "cache", required_argument, NULL, QEMU_NBD_OPT_CACHE },
480 { "aio", required_argument, NULL, QEMU_NBD_OPT_AIO },
481 { "discard", required_argument, NULL, QEMU_NBD_OPT_DISCARD },
482 { "detect-zeroes", required_argument, NULL,
483 QEMU_NBD_OPT_DETECT_ZEROES },
484 { "shared", required_argument, NULL, 'e' },
485 { "format", required_argument, NULL, 'f' },
486 { "persistent", no_argument, NULL, 't' },
487 { "verbose", no_argument, NULL, 'v' },
488 { "object", required_argument, NULL, QEMU_NBD_OPT_OBJECT },
489 { "export-name", required_argument, NULL, 'x' },
490 { "tls-creds", required_argument, NULL, QEMU_NBD_OPT_TLSCREDS },
491 { "image-opts", no_argument, NULL, QEMU_NBD_OPT_IMAGE_OPTS },
660f11be 492 { NULL, 0, NULL, 0 }
7a5ca864
FB
493 };
494 int ch;
495 int opt_ind = 0;
7a5ca864 496 char *end;
f5edb014 497 int flags = BDRV_O_RDWR;
7a5ca864 498 int partition = -1;
4fbec260 499 int ret = 0;
39a5235c 500 bool seen_cache = false;
ded9d2d5 501 bool seen_discard = false;
39a5235c 502 bool seen_aio = false;
a517e88b 503 pthread_t client_thread;
e6b63677 504 const char *fmt = NULL;
34b5d2c6 505 Error *local_err = NULL;
b3838a40 506 BlockdevDetectZeroesOptions detect_zeroes = BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF;
4fbec260 507 QDict *options = NULL;
3d4b2f9c 508 const char *export_name = NULL;
145614a1 509 const char *tlscredsid = NULL;
77c9aaef 510 bool imageOpts = false;
7a5ca864 511
a517e88b
PB
512 /* The client thread uses SIGTERM to interrupt the server. A signal
513 * handler ensures that "qemu-nbd -v -c" exits with a nice status code.
514 */
bb345110 515 struct sigaction sa_sigterm;
bb345110
PB
516 memset(&sa_sigterm, 0, sizeof(sa_sigterm));
517 sa_sigterm.sa_handler = termsig_handler;
518 sigaction(SIGTERM, &sa_sigterm, NULL);
0ab3b337
DB
519 module_call_init(MODULE_INIT_QOM);
520 qemu_add_opts(&qemu_object_opts);
10f5bff6 521 qemu_init_exec_dir(argv[0]);
bb345110 522
7a5ca864
FB
523 while ((ch = getopt_long(argc, argv, sopt, lopt, &opt_ind)) != -1) {
524 switch (ch) {
525 case 's':
2f726488
TS
526 flags |= BDRV_O_SNAPSHOT;
527 break;
528 case 'n':
39a5235c
PB
529 optarg = (char *) "none";
530 /* fallthrough */
531 case QEMU_NBD_OPT_CACHE:
532 if (seen_cache) {
85b01e09
MA
533 error_report("-n and --cache can only be specified once");
534 exit(EXIT_FAILURE);
39a5235c
PB
535 }
536 seen_cache = true;
537 if (bdrv_parse_cache_flags(optarg, &flags) == -1) {
85b01e09
MA
538 error_report("Invalid cache mode `%s'", optarg);
539 exit(EXIT_FAILURE);
39a5235c 540 }
7a5ca864 541 break;
39a5235c
PB
542 case QEMU_NBD_OPT_AIO:
543 if (seen_aio) {
85b01e09
MA
544 error_report("--aio can only be specified once");
545 exit(EXIT_FAILURE);
39a5235c
PB
546 }
547 seen_aio = true;
548 if (!strcmp(optarg, "native")) {
549 flags |= BDRV_O_NATIVE_AIO;
550 } else if (!strcmp(optarg, "threads")) {
551 /* this is the default */
552 } else {
85b01e09
MA
553 error_report("invalid aio mode `%s'", optarg);
554 exit(EXIT_FAILURE);
39a5235c
PB
555 }
556 break;
ded9d2d5
PB
557 case QEMU_NBD_OPT_DISCARD:
558 if (seen_discard) {
85b01e09
MA
559 error_report("--discard can only be specified once");
560 exit(EXIT_FAILURE);
ded9d2d5
PB
561 }
562 seen_discard = true;
563 if (bdrv_parse_discard_flags(optarg, &flags) == -1) {
85b01e09
MA
564 error_report("Invalid discard mode `%s'", optarg);
565 exit(EXIT_FAILURE);
ded9d2d5
PB
566 }
567 break;
b3838a40
PL
568 case QEMU_NBD_OPT_DETECT_ZEROES:
569 detect_zeroes =
570 qapi_enum_parse(BlockdevDetectZeroesOptions_lookup,
571 optarg,
7fb1cf16 572 BLOCKDEV_DETECT_ZEROES_OPTIONS__MAX,
b3838a40
PL
573 BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF,
574 &local_err);
575 if (local_err) {
c29b77f9
MA
576 error_reportf_err(local_err,
577 "Failed to parse detect_zeroes mode: ");
85b01e09 578 exit(EXIT_FAILURE);
b3838a40
PL
579 }
580 if (detect_zeroes == BLOCKDEV_DETECT_ZEROES_OPTIONS_UNMAP &&
581 !(flags & BDRV_O_UNMAP)) {
85b01e09
MA
582 error_report("setting detect-zeroes to unmap is not allowed "
583 "without setting discard operation to unmap");
584 exit(EXIT_FAILURE);
b3838a40
PL
585 }
586 break;
7a5ca864
FB
587 case 'b':
588 bindto = optarg;
589 break;
590 case 'p':
48bec07e 591 port = optarg;
7a5ca864
FB
592 break;
593 case 'o':
594 dev_offset = strtoll (optarg, &end, 0);
595 if (*end) {
85b01e09
MA
596 error_report("Invalid offset `%s'", optarg);
597 exit(EXIT_FAILURE);
7a5ca864
FB
598 }
599 if (dev_offset < 0) {
85b01e09
MA
600 error_report("Offset must be positive `%s'", optarg);
601 exit(EXIT_FAILURE);
7a5ca864
FB
602 }
603 break;
8c116b0e
WX
604 case 'l':
605 if (strstart(optarg, SNAPSHOT_OPT_BASE, NULL)) {
70b94331
MA
606 sn_opts = qemu_opts_parse_noisily(&internal_snapshot_opts,
607 optarg, false);
8c116b0e 608 if (!sn_opts) {
85b01e09
MA
609 error_report("Failed in parsing snapshot param `%s'",
610 optarg);
611 exit(EXIT_FAILURE);
8c116b0e
WX
612 }
613 } else {
614 sn_id_or_name = optarg;
615 }
616 /* fall through */
7a5ca864 617 case 'r':
b90fb4b8 618 nbdflags |= NBD_FLAG_READ_ONLY;
07108b29 619 flags &= ~BDRV_O_RDWR;
7a5ca864
FB
620 break;
621 case 'P':
622 partition = strtol(optarg, &end, 0);
713cc671 623 if (*end) {
85b01e09
MA
624 error_report("Invalid partition `%s'", optarg);
625 exit(EXIT_FAILURE);
713cc671
PL
626 }
627 if (partition < 1 || partition > 8) {
85b01e09
MA
628 error_report("Invalid partition %d", partition);
629 exit(EXIT_FAILURE);
713cc671 630 }
7a5ca864 631 break;
cd831bd7 632 case 'k':
b32f6c28 633 sockpath = optarg;
713cc671 634 if (sockpath[0] != '/') {
9af9e0fe 635 error_report("socket path must be absolute");
85b01e09 636 exit(EXIT_FAILURE);
713cc671 637 }
cd831bd7
TS
638 break;
639 case 'd':
640 disconnect = true;
641 break;
642 case 'c':
643 device = optarg;
644 break;
3b05a8e9
TS
645 case 'e':
646 shared = strtol(optarg, &end, 0);
647 if (*end) {
85b01e09
MA
648 error_report("Invalid shared device number '%s'", optarg);
649 exit(EXIT_FAILURE);
3b05a8e9
TS
650 }
651 if (shared < 1) {
9af9e0fe 652 error_report("Shared device number must be greater than 0");
85b01e09 653 exit(EXIT_FAILURE);
3b05a8e9
TS
654 }
655 break;
e6b63677
DB
656 case 'f':
657 fmt = optarg;
658 break;
713cc671
PL
659 case 't':
660 persistent = 1;
661 break;
3d4b2f9c
DB
662 case 'x':
663 export_name = optarg;
664 break;
7a5ca864
FB
665 case 'v':
666 verbose = 1;
667 break;
668 case 'V':
669 version(argv[0]);
670 exit(0);
671 break;
672 case 'h':
673 usage(argv[0]);
674 exit(0);
675 break;
676 case '?':
85b01e09
MA
677 error_report("Try `%s --help' for more information.", argv[0]);
678 exit(EXIT_FAILURE);
0ab3b337
DB
679 case QEMU_NBD_OPT_OBJECT: {
680 QemuOpts *opts;
681 opts = qemu_opts_parse_noisily(&qemu_object_opts,
682 optarg, true);
683 if (!opts) {
684 exit(EXIT_FAILURE);
685 }
686 } break;
145614a1
DB
687 case QEMU_NBD_OPT_TLSCREDS:
688 tlscredsid = optarg;
689 break;
77c9aaef
DB
690 case QEMU_NBD_OPT_IMAGE_OPTS:
691 imageOpts = true;
692 break;
7a5ca864
FB
693 }
694 }
695
696 if ((argc - optind) != 1) {
433672b0
MA
697 error_report("Invalid number of arguments");
698 error_printf("Try `%s --help' for more information.\n", argv[0]);
85b01e09 699 exit(EXIT_FAILURE);
7a5ca864
FB
700 }
701
0ab3b337
DB
702 if (qemu_opts_foreach(&qemu_object_opts,
703 user_creatable_add_opts_foreach,
704 NULL, &local_err)) {
705 error_report_err(local_err);
706 exit(EXIT_FAILURE);
707 }
708
145614a1
DB
709 if (tlscredsid) {
710 if (sockpath) {
711 error_report("TLS is only supported with IPv4/IPv6");
712 exit(EXIT_FAILURE);
713 }
714 if (device) {
715 error_report("TLS is not supported with a host device");
716 exit(EXIT_FAILURE);
717 }
718 if (!export_name) {
719 /* Set the default NBD protocol export name, since
720 * we *must* use new style protocol for TLS */
721 export_name = "";
722 }
723 tlscreds = nbd_get_tls_creds(tlscredsid, &local_err);
724 if (local_err) {
725 error_report("Failed to get TLS creds %s",
726 error_get_pretty(local_err));
727 exit(EXIT_FAILURE);
728 }
729 }
730
cd831bd7 731 if (disconnect) {
d0d6ff58
DB
732 int nbdfd = open(argv[optind], O_RDWR);
733 if (nbdfd < 0) {
85b01e09
MA
734 error_report("Cannot open %s: %s", argv[optind],
735 strerror(errno));
736 exit(EXIT_FAILURE);
fc19f8a0 737 }
d0d6ff58 738 nbd_disconnect(nbdfd);
cd831bd7 739
d0d6ff58 740 close(nbdfd);
cd831bd7
TS
741
742 printf("%s disconnected\n", argv[optind]);
743
713cc671 744 return 0;
cd831bd7
TS
745 }
746
c1f8fdc3
PB
747 if (device && !verbose) {
748 int stderr_fd[2];
749 pid_t pid;
750 int ret;
751
fc19f8a0 752 if (qemu_pipe(stderr_fd) < 0) {
85b01e09
MA
753 error_report("Error setting up communication pipe: %s",
754 strerror(errno));
755 exit(EXIT_FAILURE);
c1f8fdc3
PB
756 }
757
758 /* Now daemonize, but keep a communication channel open to
759 * print errors and exit with the proper status code.
760 */
761 pid = fork();
70d4739e 762 if (pid < 0) {
85b01e09
MA
763 error_report("Failed to fork: %s", strerror(errno));
764 exit(EXIT_FAILURE);
70d4739e 765 } else if (pid == 0) {
c1f8fdc3 766 close(stderr_fd[0]);
9faf31b6 767 ret = qemu_daemon(1, 0);
c1f8fdc3
PB
768
769 /* Temporarily redirect stderr to the parent's pipe... */
770 dup2(stderr_fd[1], STDERR_FILENO);
fc19f8a0 771 if (ret < 0) {
85b01e09
MA
772 error_report("Failed to daemonize: %s", strerror(errno));
773 exit(EXIT_FAILURE);
c1f8fdc3
PB
774 }
775
776 /* ... close the descriptor we inherited and go on. */
777 close(stderr_fd[1]);
778 } else {
779 bool errors = false;
780 char *buf;
781
782 /* In the parent. Print error messages from the child until
783 * it closes the pipe.
784 */
785 close(stderr_fd[1]);
786 buf = g_malloc(1024);
787 while ((ret = read(stderr_fd[0], buf, 1024)) > 0) {
788 errors = true;
789 ret = qemu_write_full(STDERR_FILENO, buf, ret);
fc19f8a0 790 if (ret < 0) {
c1f8fdc3
PB
791 exit(EXIT_FAILURE);
792 }
793 }
fc19f8a0 794 if (ret < 0) {
85b01e09
MA
795 error_report("Cannot read from daemon: %s",
796 strerror(errno));
797 exit(EXIT_FAILURE);
c1f8fdc3
PB
798 }
799
800 /* Usually the daemon should not print any message.
801 * Exit with zero status in that case.
802 */
803 exit(errors);
804 }
805 }
806
a6ac2313
PB
807 if (device != NULL && sockpath == NULL) {
808 sockpath = g_malloc(128);
809 snprintf(sockpath, 128, SOCKET_PATH, basename(device));
cd831bd7
TS
810 }
811
48bec07e
DB
812 saddr = nbd_build_socket_address(sockpath, bindto, port);
813
2f78e491 814 if (qemu_init_main_loop(&local_err)) {
565f65d2 815 error_report_err(local_err);
2f78e491
CN
816 exit(EXIT_FAILURE);
817 }
802ddc37
PB
818 bdrv_init();
819 atexit(bdrv_close_all);
820
77c9aaef
DB
821 srcpath = argv[optind];
822 if (imageOpts) {
823 QemuOpts *opts;
824 if (fmt) {
825 error_report("--image-opts and -f are mutually exclusive");
826 exit(EXIT_FAILURE);
827 }
828 opts = qemu_opts_parse_noisily(&file_opts, srcpath, true);
829 if (!opts) {
830 qemu_opts_reset(&file_opts);
831 exit(EXIT_FAILURE);
832 }
833 options = qemu_opts_to_qdict(opts, NULL);
834 qemu_opts_reset(&file_opts);
efaa7c4e 835 blk = blk_new_open(NULL, NULL, options, flags, &local_err);
77c9aaef
DB
836 } else {
837 if (fmt) {
838 options = qdict_new();
839 qdict_put(options, "driver", qstring_from_str(fmt));
840 }
efaa7c4e 841 blk = blk_new_open(srcpath, NULL, options, flags, &local_err);
e6b63677
DB
842 }
843
4fbec260 844 if (!blk) {
c29b77f9
MA
845 error_reportf_err(local_err, "Failed to blk_new_open '%s': ",
846 argv[optind]);
85b01e09 847 exit(EXIT_FAILURE);
802ddc37 848 }
4fbec260 849 bs = blk_bs(blk);
802ddc37 850
8c116b0e
WX
851 if (sn_opts) {
852 ret = bdrv_snapshot_load_tmp(bs,
853 qemu_opt_get(sn_opts, SNAPSHOT_OPT_ID),
854 qemu_opt_get(sn_opts, SNAPSHOT_OPT_NAME),
855 &local_err);
856 } else if (sn_id_or_name) {
857 ret = bdrv_snapshot_load_tmp_by_id_or_name(bs, sn_id_or_name,
858 &local_err);
859 }
860 if (ret < 0) {
c29b77f9 861 error_reportf_err(local_err, "Failed to load snapshot: ");
85b01e09 862 exit(EXIT_FAILURE);
8c116b0e
WX
863 }
864
b3838a40 865 bs->detect_zeroes = detect_zeroes;
4c58e80a 866 fd_size = blk_getlength(blk);
98f44bbe 867 if (fd_size < 0) {
85b01e09
MA
868 error_report("Failed to determine the image length: %s",
869 strerror(-fd_size));
870 exit(EXIT_FAILURE);
98f44bbe 871 }
802ddc37 872
185b4338 873 if (partition != -1) {
4c58e80a 874 ret = find_partition(blk, partition, &dev_offset, &fd_size);
185b4338 875 if (ret < 0) {
85b01e09 876 error_report("Could not find partition %d: %s", partition,
a4699e55 877 strerror(-ret));
85b01e09 878 exit(EXIT_FAILURE);
185b4338 879 }
802ddc37
PB
880 }
881
98f44bbe
HR
882 exp = nbd_export_new(blk, dev_offset, fd_size, nbdflags, nbd_export_closed,
883 &local_err);
884 if (!exp) {
4fffeb5e 885 error_report_err(local_err);
85b01e09 886 exit(EXIT_FAILURE);
98f44bbe 887 }
3d4b2f9c
DB
888 if (export_name) {
889 nbd_export_set_name(exp, export_name);
890 newproto = true;
891 }
3b05a8e9 892
d0d6ff58
DB
893 server_ioc = qio_channel_socket_new();
894 if (qio_channel_socket_listen_sync(server_ioc, saddr, &local_err) < 0) {
895 object_unref(OBJECT(server_ioc));
48bec07e 896 error_report_err(local_err);
7a5ca864 897 return 1;
a61c6782 898 }
f1ef5555
PB
899
900 if (device) {
901 int ret;
902
a6ac2313 903 ret = pthread_create(&client_thread, NULL, nbd_client_thread, device);
f1ef5555 904 if (ret != 0) {
85b01e09
MA
905 error_report("Failed to create client thread: %s", strerror(ret));
906 exit(EXIT_FAILURE);
f1ef5555
PB
907 }
908 } else {
909 /* Shut up GCC warnings. */
910 memset(&client_thread, 0, sizeof(client_thread));
911 }
912
d0d6ff58 913 nbd_update_server_watch();
7a5ca864 914
9faf31b6
MT
915 /* now when the initialization is (almost) complete, chdir("/")
916 * to free any busy filesystems */
917 if (chdir("/") < 0) {
85b01e09
MA
918 error_report("Could not chdir to root directory: %s",
919 strerror(errno));
920 exit(EXIT_FAILURE);
9faf31b6
MT
921 }
922
7860a380 923 state = RUNNING;
3b05a8e9 924 do {
a61c6782 925 main_loop_wait(false);
7860a380
PB
926 if (state == TERMINATE) {
927 state = TERMINATING;
928 nbd_export_close(exp);
929 nbd_export_put(exp);
930 exp = NULL;
931 }
932 } while (state != TERMINATED);
7a5ca864 933
26f54e9a 934 blk_unref(blk);
b32f6c28
PB
935 if (sockpath) {
936 unlink(sockpath);
937 }
7a5ca864 938
fbf28a43 939 qemu_opts_del(sn_opts);
8c116b0e 940
a517e88b
PB
941 if (device) {
942 void *ret;
943 pthread_join(client_thread, &ret);
944 exit(ret != NULL);
945 } else {
946 exit(EXIT_SUCCESS);
947 }
7a5ca864 948}