qemu-iotests: add 058 internal snapshot export with qemu-nbd case
[qemu.git] / qemu-nbd.c
blobfe6053ca56ee8a5f7ab71e13a70d23881d26c8e0
1 /*
2 * Copyright (C) 2005 Anthony Liguori <anthony@codemonkey.ws>
4 * Network Block Device
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.
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.
15 * You should have received a copy of the GNU General Public License
16 * along with this program; if not, see <http://www.gnu.org/licenses/>.
19 #include "qemu-common.h"
20 #include "block/block.h"
21 #include "block/nbd.h"
22 #include "qemu/main-loop.h"
23 #include "block/snapshot.h"
25 #include <stdarg.h>
26 #include <stdio.h>
27 #include <getopt.h>
28 #include <err.h>
29 #include <sys/types.h>
30 #include <sys/socket.h>
31 #include <netinet/in.h>
32 #include <netinet/tcp.h>
33 #include <arpa/inet.h>
34 #include <signal.h>
35 #include <libgen.h>
36 #include <pthread.h>
38 #define SOCKET_PATH "/var/lock/qemu-nbd-%s"
39 #define QEMU_NBD_OPT_CACHE 1
40 #define QEMU_NBD_OPT_AIO 2
41 #define QEMU_NBD_OPT_DISCARD 3
43 static NBDExport *exp;
44 static int verbose;
45 static char *srcpath;
46 static char *sockpath;
47 static int persistent = 0;
48 static enum { RUNNING, TERMINATE, TERMINATING, TERMINATED } state;
49 static int shared = 1;
50 static int nb_fds;
52 static void usage(const char *name)
54 (printf) (
55 "Usage: %s [OPTIONS] FILE\n"
56 "QEMU Disk Network Block Device Server\n"
57 "\n"
58 " -h, --help display this help and exit\n"
59 " -V, --version output version information and exit\n"
60 "\n"
61 "Connection properties:\n"
62 " -p, --port=PORT port to listen on (default `%d')\n"
63 " -b, --bind=IFACE interface to bind to (default `0.0.0.0')\n"
64 " -k, --socket=PATH path to the unix socket\n"
65 " (default '"SOCKET_PATH"')\n"
66 " -e, --shared=NUM device can be shared by NUM clients (default '1')\n"
67 " -t, --persistent don't exit on the last connection\n"
68 " -v, --verbose display extra debugging information\n"
69 "\n"
70 "Exposing part of the image:\n"
71 " -o, --offset=OFFSET offset into the image\n"
72 " -P, --partition=NUM only expose partition NUM\n"
73 "\n"
74 #ifdef __linux__
75 "Kernel NBD client support:\n"
76 " -c, --connect=DEV connect FILE to the local NBD device DEV\n"
77 " -d, --disconnect disconnect the specified device\n"
78 "\n"
79 #endif
80 "\n"
81 "Block device options:\n"
82 " -r, --read-only export read-only\n"
83 " -s, --snapshot use FILE as an external snapshot, create a temporary\n"
84 " file with backing_file=FILE, redirect the write to\n"
85 " the temporary one\n"
86 " -l, --load-snapshot=SNAPSHOT_PARAM\n"
87 " load an internal snapshot inside FILE and export it\n"
88 " as an read-only device, SNAPSHOT_PARAM format is\n"
89 " 'snapshot.id=[ID],snapshot.name=[NAME]', or\n"
90 " '[ID_OR_NAME]'\n"
91 " -n, --nocache disable host cache\n"
92 " --cache=MODE set cache mode (none, writeback, ...)\n"
93 #ifdef CONFIG_LINUX_AIO
94 " --aio=MODE set AIO mode (native or threads)\n"
95 #endif
96 "\n"
97 "Report bugs to <qemu-devel@nongnu.org>\n"
98 , name, NBD_DEFAULT_PORT, "DEVICE");
101 static void version(const char *name)
103 printf(
104 "%s version 0.0.1\n"
105 "Written by Anthony Liguori.\n"
106 "\n"
107 "Copyright (C) 2006 Anthony Liguori <anthony@codemonkey.ws>.\n"
108 "This is free software; see the source for copying conditions. There is NO\n"
109 "warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n"
110 , name);
113 struct partition_record
115 uint8_t bootable;
116 uint8_t start_head;
117 uint32_t start_cylinder;
118 uint8_t start_sector;
119 uint8_t system;
120 uint8_t end_head;
121 uint8_t end_cylinder;
122 uint8_t end_sector;
123 uint32_t start_sector_abs;
124 uint32_t nb_sectors_abs;
127 static void read_partition(uint8_t *p, struct partition_record *r)
129 r->bootable = p[0];
130 r->start_head = p[1];
131 r->start_cylinder = p[3] | ((p[2] << 2) & 0x0300);
132 r->start_sector = p[2] & 0x3f;
133 r->system = p[4];
134 r->end_head = p[5];
135 r->end_cylinder = p[7] | ((p[6] << 2) & 0x300);
136 r->end_sector = p[6] & 0x3f;
137 r->start_sector_abs = p[8] | p[9] << 8 | p[10] << 16 | p[11] << 24;
138 r->nb_sectors_abs = p[12] | p[13] << 8 | p[14] << 16 | p[15] << 24;
141 static int find_partition(BlockDriverState *bs, int partition,
142 off_t *offset, off_t *size)
144 struct partition_record mbr[4];
145 uint8_t data[512];
146 int i;
147 int ext_partnum = 4;
148 int ret;
150 if ((ret = bdrv_read(bs, 0, data, 1)) < 0) {
151 errno = -ret;
152 err(EXIT_FAILURE, "error while reading");
155 if (data[510] != 0x55 || data[511] != 0xaa) {
156 return -EINVAL;
159 for (i = 0; i < 4; i++) {
160 read_partition(&data[446 + 16 * i], &mbr[i]);
162 if (!mbr[i].nb_sectors_abs)
163 continue;
165 if (mbr[i].system == 0xF || mbr[i].system == 0x5) {
166 struct partition_record ext[4];
167 uint8_t data1[512];
168 int j;
170 if ((ret = bdrv_read(bs, mbr[i].start_sector_abs, data1, 1)) < 0) {
171 errno = -ret;
172 err(EXIT_FAILURE, "error while reading");
175 for (j = 0; j < 4; j++) {
176 read_partition(&data1[446 + 16 * j], &ext[j]);
177 if (!ext[j].nb_sectors_abs)
178 continue;
180 if ((ext_partnum + j + 1) == partition) {
181 *offset = (uint64_t)ext[j].start_sector_abs << 9;
182 *size = (uint64_t)ext[j].nb_sectors_abs << 9;
183 return 0;
186 ext_partnum += 4;
187 } else if ((i + 1) == partition) {
188 *offset = (uint64_t)mbr[i].start_sector_abs << 9;
189 *size = (uint64_t)mbr[i].nb_sectors_abs << 9;
190 return 0;
194 return -ENOENT;
197 static void termsig_handler(int signum)
199 state = TERMINATE;
200 qemu_notify_event();
203 static void *show_parts(void *arg)
205 char *device = arg;
206 int nbd;
208 /* linux just needs an open() to trigger
209 * the partition table update
210 * but remember to load the module with max_part != 0 :
211 * modprobe nbd max_part=63
213 nbd = open(device, O_RDWR);
214 if (nbd >= 0) {
215 close(nbd);
217 return NULL;
220 static void *nbd_client_thread(void *arg)
222 char *device = arg;
223 off_t size;
224 size_t blocksize;
225 uint32_t nbdflags;
226 int fd, sock;
227 int ret;
228 pthread_t show_parts_thread;
230 sock = unix_socket_outgoing(sockpath);
231 if (sock < 0) {
232 goto out;
235 ret = nbd_receive_negotiate(sock, NULL, &nbdflags,
236 &size, &blocksize);
237 if (ret < 0) {
238 goto out;
241 fd = open(device, O_RDWR);
242 if (fd < 0) {
243 /* Linux-only, we can use %m in printf. */
244 fprintf(stderr, "Failed to open %s: %m", device);
245 goto out;
248 ret = nbd_init(fd, sock, nbdflags, size, blocksize);
249 if (ret < 0) {
250 goto out;
253 /* update partition table */
254 pthread_create(&show_parts_thread, NULL, show_parts, device);
256 if (verbose) {
257 fprintf(stderr, "NBD device %s is now connected to %s\n",
258 device, srcpath);
259 } else {
260 /* Close stderr so that the qemu-nbd process exits. */
261 dup2(STDOUT_FILENO, STDERR_FILENO);
264 ret = nbd_client(fd);
265 if (ret) {
266 goto out;
268 close(fd);
269 kill(getpid(), SIGTERM);
270 return (void *) EXIT_SUCCESS;
272 out:
273 kill(getpid(), SIGTERM);
274 return (void *) EXIT_FAILURE;
277 static int nbd_can_accept(void *opaque)
279 return nb_fds < shared;
282 static void nbd_export_closed(NBDExport *exp)
284 assert(state == TERMINATING);
285 state = TERMINATED;
288 static void nbd_client_closed(NBDClient *client)
290 nb_fds--;
291 if (nb_fds == 0 && !persistent && state == RUNNING) {
292 state = TERMINATE;
294 qemu_notify_event();
295 nbd_client_put(client);
298 static void nbd_accept(void *opaque)
300 int server_fd = (uintptr_t) opaque;
301 struct sockaddr_in addr;
302 socklen_t addr_len = sizeof(addr);
304 int fd = accept(server_fd, (struct sockaddr *)&addr, &addr_len);
305 if (state >= TERMINATE) {
306 close(fd);
307 return;
310 if (fd >= 0 && nbd_client_new(exp, fd, nbd_client_closed)) {
311 nb_fds++;
315 int main(int argc, char **argv)
317 BlockDriverState *bs;
318 BlockDriver *drv;
319 off_t dev_offset = 0;
320 uint32_t nbdflags = 0;
321 bool disconnect = false;
322 const char *bindto = "0.0.0.0";
323 char *device = NULL;
324 int port = NBD_DEFAULT_PORT;
325 off_t fd_size;
326 QemuOpts *sn_opts = NULL;
327 const char *sn_id_or_name = NULL;
328 const char *sopt = "hVb:o:p:rsnP:c:dvk:e:f:tl:";
329 struct option lopt[] = {
330 { "help", 0, NULL, 'h' },
331 { "version", 0, NULL, 'V' },
332 { "bind", 1, NULL, 'b' },
333 { "port", 1, NULL, 'p' },
334 { "socket", 1, NULL, 'k' },
335 { "offset", 1, NULL, 'o' },
336 { "read-only", 0, NULL, 'r' },
337 { "partition", 1, NULL, 'P' },
338 { "connect", 1, NULL, 'c' },
339 { "disconnect", 0, NULL, 'd' },
340 { "snapshot", 0, NULL, 's' },
341 { "load-snapshot", 1, NULL, 'l' },
342 { "nocache", 0, NULL, 'n' },
343 { "cache", 1, NULL, QEMU_NBD_OPT_CACHE },
344 #ifdef CONFIG_LINUX_AIO
345 { "aio", 1, NULL, QEMU_NBD_OPT_AIO },
346 #endif
347 { "discard", 1, NULL, QEMU_NBD_OPT_DISCARD },
348 { "shared", 1, NULL, 'e' },
349 { "format", 1, NULL, 'f' },
350 { "persistent", 0, NULL, 't' },
351 { "verbose", 0, NULL, 'v' },
352 { NULL, 0, NULL, 0 }
354 int ch;
355 int opt_ind = 0;
356 int li;
357 char *end;
358 int flags = BDRV_O_RDWR;
359 int partition = -1;
360 int ret;
361 int fd;
362 bool seen_cache = false;
363 bool seen_discard = false;
364 #ifdef CONFIG_LINUX_AIO
365 bool seen_aio = false;
366 #endif
367 pthread_t client_thread;
368 const char *fmt = NULL;
369 Error *local_err = NULL;
371 /* The client thread uses SIGTERM to interrupt the server. A signal
372 * handler ensures that "qemu-nbd -v -c" exits with a nice status code.
374 struct sigaction sa_sigterm;
375 memset(&sa_sigterm, 0, sizeof(sa_sigterm));
376 sa_sigterm.sa_handler = termsig_handler;
377 sigaction(SIGTERM, &sa_sigterm, NULL);
379 while ((ch = getopt_long(argc, argv, sopt, lopt, &opt_ind)) != -1) {
380 switch (ch) {
381 case 's':
382 flags |= BDRV_O_SNAPSHOT;
383 break;
384 case 'n':
385 optarg = (char *) "none";
386 /* fallthrough */
387 case QEMU_NBD_OPT_CACHE:
388 if (seen_cache) {
389 errx(EXIT_FAILURE, "-n and --cache can only be specified once");
391 seen_cache = true;
392 if (bdrv_parse_cache_flags(optarg, &flags) == -1) {
393 errx(EXIT_FAILURE, "Invalid cache mode `%s'", optarg);
395 break;
396 #ifdef CONFIG_LINUX_AIO
397 case QEMU_NBD_OPT_AIO:
398 if (seen_aio) {
399 errx(EXIT_FAILURE, "--aio can only be specified once");
401 seen_aio = true;
402 if (!strcmp(optarg, "native")) {
403 flags |= BDRV_O_NATIVE_AIO;
404 } else if (!strcmp(optarg, "threads")) {
405 /* this is the default */
406 } else {
407 errx(EXIT_FAILURE, "invalid aio mode `%s'", optarg);
409 break;
410 #endif
411 case QEMU_NBD_OPT_DISCARD:
412 if (seen_discard) {
413 errx(EXIT_FAILURE, "--discard can only be specified once");
415 seen_discard = true;
416 if (bdrv_parse_discard_flags(optarg, &flags) == -1) {
417 errx(EXIT_FAILURE, "Invalid discard mode `%s'", optarg);
419 break;
420 case 'b':
421 bindto = optarg;
422 break;
423 case 'p':
424 li = strtol(optarg, &end, 0);
425 if (*end) {
426 errx(EXIT_FAILURE, "Invalid port `%s'", optarg);
428 if (li < 1 || li > 65535) {
429 errx(EXIT_FAILURE, "Port out of range `%s'", optarg);
431 port = (uint16_t)li;
432 break;
433 case 'o':
434 dev_offset = strtoll (optarg, &end, 0);
435 if (*end) {
436 errx(EXIT_FAILURE, "Invalid offset `%s'", optarg);
438 if (dev_offset < 0) {
439 errx(EXIT_FAILURE, "Offset must be positive `%s'", optarg);
441 break;
442 case 'l':
443 if (strstart(optarg, SNAPSHOT_OPT_BASE, NULL)) {
444 sn_opts = qemu_opts_parse(&internal_snapshot_opts, optarg, 0);
445 if (!sn_opts) {
446 errx(EXIT_FAILURE, "Failed in parsing snapshot param `%s'",
447 optarg);
449 } else {
450 sn_id_or_name = optarg;
452 /* fall through */
453 case 'r':
454 nbdflags |= NBD_FLAG_READ_ONLY;
455 flags &= ~BDRV_O_RDWR;
456 break;
457 case 'P':
458 partition = strtol(optarg, &end, 0);
459 if (*end)
460 errx(EXIT_FAILURE, "Invalid partition `%s'", optarg);
461 if (partition < 1 || partition > 8)
462 errx(EXIT_FAILURE, "Invalid partition %d", partition);
463 break;
464 case 'k':
465 sockpath = optarg;
466 if (sockpath[0] != '/')
467 errx(EXIT_FAILURE, "socket path must be absolute\n");
468 break;
469 case 'd':
470 disconnect = true;
471 break;
472 case 'c':
473 device = optarg;
474 break;
475 case 'e':
476 shared = strtol(optarg, &end, 0);
477 if (*end) {
478 errx(EXIT_FAILURE, "Invalid shared device number '%s'", optarg);
480 if (shared < 1) {
481 errx(EXIT_FAILURE, "Shared device number must be greater than 0\n");
483 break;
484 case 'f':
485 fmt = optarg;
486 break;
487 case 't':
488 persistent = 1;
489 break;
490 case 'v':
491 verbose = 1;
492 break;
493 case 'V':
494 version(argv[0]);
495 exit(0);
496 break;
497 case 'h':
498 usage(argv[0]);
499 exit(0);
500 break;
501 case '?':
502 errx(EXIT_FAILURE, "Try `%s --help' for more information.",
503 argv[0]);
507 if ((argc - optind) != 1) {
508 errx(EXIT_FAILURE, "Invalid number of argument.\n"
509 "Try `%s --help' for more information.",
510 argv[0]);
513 if (disconnect) {
514 fd = open(argv[optind], O_RDWR);
515 if (fd < 0) {
516 err(EXIT_FAILURE, "Cannot open %s", argv[optind]);
518 nbd_disconnect(fd);
520 close(fd);
522 printf("%s disconnected\n", argv[optind]);
524 return 0;
527 if (device && !verbose) {
528 int stderr_fd[2];
529 pid_t pid;
530 int ret;
532 if (qemu_pipe(stderr_fd) < 0) {
533 err(EXIT_FAILURE, "Error setting up communication pipe");
536 /* Now daemonize, but keep a communication channel open to
537 * print errors and exit with the proper status code.
539 pid = fork();
540 if (pid == 0) {
541 close(stderr_fd[0]);
542 ret = qemu_daemon(1, 0);
544 /* Temporarily redirect stderr to the parent's pipe... */
545 dup2(stderr_fd[1], STDERR_FILENO);
546 if (ret < 0) {
547 err(EXIT_FAILURE, "Failed to daemonize");
550 /* ... close the descriptor we inherited and go on. */
551 close(stderr_fd[1]);
552 } else {
553 bool errors = false;
554 char *buf;
556 /* In the parent. Print error messages from the child until
557 * it closes the pipe.
559 close(stderr_fd[1]);
560 buf = g_malloc(1024);
561 while ((ret = read(stderr_fd[0], buf, 1024)) > 0) {
562 errors = true;
563 ret = qemu_write_full(STDERR_FILENO, buf, ret);
564 if (ret < 0) {
565 exit(EXIT_FAILURE);
568 if (ret < 0) {
569 err(EXIT_FAILURE, "Cannot read from daemon");
572 /* Usually the daemon should not print any message.
573 * Exit with zero status in that case.
575 exit(errors);
579 if (device != NULL && sockpath == NULL) {
580 sockpath = g_malloc(128);
581 snprintf(sockpath, 128, SOCKET_PATH, basename(device));
584 qemu_init_main_loop();
585 bdrv_init();
586 atexit(bdrv_close_all);
588 if (fmt) {
589 drv = bdrv_find_format(fmt);
590 if (!drv) {
591 errx(EXIT_FAILURE, "Unknown file format '%s'", fmt);
593 } else {
594 drv = NULL;
597 bs = bdrv_new("hda");
598 srcpath = argv[optind];
599 ret = bdrv_open(bs, srcpath, NULL, flags, drv, &local_err);
600 if (ret < 0) {
601 errno = -ret;
602 err(EXIT_FAILURE, "Failed to bdrv_open '%s': %s", argv[optind],
603 error_get_pretty(local_err));
606 if (sn_opts) {
607 ret = bdrv_snapshot_load_tmp(bs,
608 qemu_opt_get(sn_opts, SNAPSHOT_OPT_ID),
609 qemu_opt_get(sn_opts, SNAPSHOT_OPT_NAME),
610 &local_err);
611 } else if (sn_id_or_name) {
612 ret = bdrv_snapshot_load_tmp_by_id_or_name(bs, sn_id_or_name,
613 &local_err);
615 if (ret < 0) {
616 errno = -ret;
617 err(EXIT_FAILURE,
618 "Failed to load snapshot: %s",
619 error_get_pretty(local_err));
622 fd_size = bdrv_getlength(bs);
624 if (partition != -1) {
625 ret = find_partition(bs, partition, &dev_offset, &fd_size);
626 if (ret < 0) {
627 errno = -ret;
628 err(EXIT_FAILURE, "Could not find partition %d", partition);
632 exp = nbd_export_new(bs, dev_offset, fd_size, nbdflags, nbd_export_closed);
634 if (sockpath) {
635 fd = unix_socket_incoming(sockpath);
636 } else {
637 fd = tcp_socket_incoming(bindto, port);
640 if (fd < 0) {
641 return 1;
644 if (device) {
645 int ret;
647 ret = pthread_create(&client_thread, NULL, nbd_client_thread, device);
648 if (ret != 0) {
649 errx(EXIT_FAILURE, "Failed to create client thread: %s",
650 strerror(ret));
652 } else {
653 /* Shut up GCC warnings. */
654 memset(&client_thread, 0, sizeof(client_thread));
657 qemu_set_fd_handler2(fd, nbd_can_accept, nbd_accept, NULL,
658 (void *)(uintptr_t)fd);
660 /* now when the initialization is (almost) complete, chdir("/")
661 * to free any busy filesystems */
662 if (chdir("/") < 0) {
663 err(EXIT_FAILURE, "Could not chdir to root directory");
666 state = RUNNING;
667 do {
668 main_loop_wait(false);
669 if (state == TERMINATE) {
670 state = TERMINATING;
671 nbd_export_close(exp);
672 nbd_export_put(exp);
673 exp = NULL;
675 } while (state != TERMINATED);
677 bdrv_close(bs);
678 if (sockpath) {
679 unlink(sockpath);
682 if (sn_opts) {
683 qemu_opts_del(sn_opts);
686 if (device) {
687 void *ret;
688 pthread_join(client_thread, &ret);
689 exit(ret != NULL);
690 } else {
691 exit(EXIT_SUCCESS);