2 * Copyright (C) 2005 Anthony Liguori <anthony@codemonkey.ws>
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"
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>
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;
46 static char *sockpath;
47 static int persistent = 0;
48 static enum { RUNNING, TERMINATE, TERMINATING, TERMINATED } state;
49 static int shared = 1;
52 static void usage(const char *name)
55 "Usage: %s [OPTIONS] FILE\n"
56 "QEMU Disk Network Block Device Server\n"
58 " -h, --help display this help and exit\n"
59 " -V, --version output version information and exit\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"
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"
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"
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"
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"
97 "Report bugs to <qemu-devel@nongnu.org>\n"
98 , name, NBD_DEFAULT_PORT, "DEVICE");
101 static void version(const char *name)
105 "Written by Anthony Liguori.\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"
113 struct partition_record
117 uint32_t start_cylinder;
118 uint8_t start_sector;
121 uint8_t end_cylinder;
123 uint32_t start_sector_abs;
124 uint32_t nb_sectors_abs;
127 static void read_partition(uint8_t *p, struct partition_record *r)
130 r->start_head = p[1];
131 r->start_cylinder = p[3] | ((p[2] << 2) & 0x0300);
132 r->start_sector = p[2] & 0x3f;
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];
150 if ((ret = bdrv_read(bs, 0, data, 1)) < 0) {
152 err(EXIT_FAILURE, "error while reading");
155 if (data[510] != 0x55 || data[511] != 0xaa) {
159 for (i = 0; i < 4; i++) {
160 read_partition(&data[446 + 16 * i], &mbr[i]);
162 if (!mbr[i].nb_sectors_abs)
165 if (mbr[i].system == 0xF || mbr[i].system == 0x5) {
166 struct partition_record ext[4];
170 if ((ret = bdrv_read(bs, mbr[i].start_sector_abs, data1, 1)) < 0) {
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)
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;
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;
197 static void termsig_handler(int signum)
203 static void *show_parts(void *arg)
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);
220 static void *nbd_client_thread(void *arg)
228 pthread_t show_parts_thread;
230 sock = unix_socket_outgoing(sockpath);
235 ret = nbd_receive_negotiate(sock, NULL, &nbdflags,
241 fd = open(device, O_RDWR);
243 /* Linux-only, we can use %m in printf. */
244 fprintf(stderr, "Failed to open %s: %m", device);
248 ret = nbd_init(fd, sock, nbdflags, size, blocksize);
253 /* update partition table */
254 pthread_create(&show_parts_thread, NULL, show_parts, device);
257 fprintf(stderr, "NBD device %s is now connected to %s\n",
260 /* Close stderr so that the qemu-nbd process exits. */
261 dup2(STDOUT_FILENO, STDERR_FILENO);
264 ret = nbd_client(fd);
269 kill(getpid(), SIGTERM);
270 return (void *) EXIT_SUCCESS;
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);
288 static void nbd_client_closed(NBDClient *client)
291 if (nb_fds == 0 && !persistent && state == RUNNING) {
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) {
310 if (fd >= 0 && nbd_client_new(exp, fd, nbd_client_closed)) {
315 int main(int argc, char **argv)
317 BlockDriverState *bs;
319 off_t dev_offset = 0;
320 uint32_t nbdflags = 0;
321 bool disconnect = false;
322 const char *bindto = "0.0.0.0";
324 int port = NBD_DEFAULT_PORT;
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 },
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' },
358 int flags = BDRV_O_RDWR;
362 bool seen_cache = false;
363 bool seen_discard = false;
364 #ifdef CONFIG_LINUX_AIO
365 bool seen_aio = false;
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) {
382 flags |= BDRV_O_SNAPSHOT;
385 optarg = (char *) "none";
387 case QEMU_NBD_OPT_CACHE:
389 errx(EXIT_FAILURE, "-n and --cache can only be specified once");
392 if (bdrv_parse_cache_flags(optarg, &flags) == -1) {
393 errx(EXIT_FAILURE, "Invalid cache mode `%s'", optarg);
396 #ifdef CONFIG_LINUX_AIO
397 case QEMU_NBD_OPT_AIO:
399 errx(EXIT_FAILURE, "--aio can only be specified once");
402 if (!strcmp(optarg, "native")) {
403 flags |= BDRV_O_NATIVE_AIO;
404 } else if (!strcmp(optarg, "threads")) {
405 /* this is the default */
407 errx(EXIT_FAILURE, "invalid aio mode `%s'", optarg);
411 case QEMU_NBD_OPT_DISCARD:
413 errx(EXIT_FAILURE, "--discard can only be specified once");
416 if (bdrv_parse_discard_flags(optarg, &flags) == -1) {
417 errx(EXIT_FAILURE, "Invalid discard mode `%s'", optarg);
424 li = strtol(optarg, &end, 0);
426 errx(EXIT_FAILURE, "Invalid port `%s'", optarg);
428 if (li < 1 || li > 65535) {
429 errx(EXIT_FAILURE, "Port out of range `%s'", optarg);
434 dev_offset = strtoll (optarg, &end, 0);
436 errx(EXIT_FAILURE, "Invalid offset `%s'", optarg);
438 if (dev_offset < 0) {
439 errx(EXIT_FAILURE, "Offset must be positive `%s'", optarg);
443 if (strstart(optarg, SNAPSHOT_OPT_BASE, NULL)) {
444 sn_opts = qemu_opts_parse(&internal_snapshot_opts, optarg, 0);
446 errx(EXIT_FAILURE, "Failed in parsing snapshot param `%s'",
450 sn_id_or_name = optarg;
454 nbdflags |= NBD_FLAG_READ_ONLY;
455 flags &= ~BDRV_O_RDWR;
458 partition = strtol(optarg, &end, 0);
460 errx(EXIT_FAILURE, "Invalid partition `%s'", optarg);
461 if (partition < 1 || partition > 8)
462 errx(EXIT_FAILURE, "Invalid partition %d", partition);
466 if (sockpath[0] != '/')
467 errx(EXIT_FAILURE, "socket path must be absolute\n");
476 shared = strtol(optarg, &end, 0);
478 errx(EXIT_FAILURE, "Invalid shared device number '%s'", optarg);
481 errx(EXIT_FAILURE, "Shared device number must be greater than 0\n");
502 errx(EXIT_FAILURE, "Try `%s --help' for more information.",
507 if ((argc - optind) != 1) {
508 errx(EXIT_FAILURE, "Invalid number of argument.\n"
509 "Try `%s --help' for more information.",
514 fd = open(argv[optind], O_RDWR);
516 err(EXIT_FAILURE, "Cannot open %s", argv[optind]);
522 printf("%s disconnected\n", argv[optind]);
527 if (device && !verbose) {
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.
542 ret = qemu_daemon(1, 0);
544 /* Temporarily redirect stderr to the parent's pipe... */
545 dup2(stderr_fd[1], STDERR_FILENO);
547 err(EXIT_FAILURE, "Failed to daemonize");
550 /* ... close the descriptor we inherited and go on. */
556 /* In the parent. Print error messages from the child until
557 * it closes the pipe.
560 buf = g_malloc(1024);
561 while ((ret = read(stderr_fd[0], buf, 1024)) > 0) {
563 ret = qemu_write_full(STDERR_FILENO, buf, ret);
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.
579 if (device != NULL && sockpath == NULL) {
580 sockpath = g_malloc(128);
581 snprintf(sockpath, 128, SOCKET_PATH, basename(device));
584 qemu_init_main_loop();
586 atexit(bdrv_close_all);
589 drv = bdrv_find_format(fmt);
591 errx(EXIT_FAILURE, "Unknown file format '%s'", fmt);
597 bs = bdrv_new("hda");
598 srcpath = argv[optind];
599 ret = bdrv_open(bs, srcpath, NULL, flags, drv, &local_err);
602 err(EXIT_FAILURE, "Failed to bdrv_open '%s': %s", argv[optind],
603 error_get_pretty(local_err));
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),
611 } else if (sn_id_or_name) {
612 ret = bdrv_snapshot_load_tmp_by_id_or_name(bs, sn_id_or_name,
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);
628 err(EXIT_FAILURE, "Could not find partition %d", partition);
632 exp = nbd_export_new(bs, dev_offset, fd_size, nbdflags, nbd_export_closed);
635 fd = unix_socket_incoming(sockpath);
637 fd = tcp_socket_incoming(bindto, port);
647 ret = pthread_create(&client_thread, NULL, nbd_client_thread, device);
649 errx(EXIT_FAILURE, "Failed to create client thread: %s",
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");
668 main_loop_wait(false);
669 if (state == TERMINATE) {
671 nbd_export_close(exp);
675 } while (state != TERMINATED);
683 qemu_opts_del(sn_opts);
688 pthread_join(client_thread, &ret);