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