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