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