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/osdep.h"
20 #include "qemu-common.h"
21 #include "sysemu/block-backend.h"
22 #include "block/block_int.h"
23 #include "block/nbd.h"
24 #include "qemu/main-loop.h"
25 #include "qemu/sockets.h"
26 #include "qemu/error-report.h"
27 #include "block/snapshot.h"
28 #include "qapi/util.h"
29 #include "qapi/qmp/qstring.h"
32 #include <sys/socket.h>
33 #include <netinet/in.h>
34 #include <netinet/tcp.h>
35 #include <arpa/inet.h>
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
43 #define QEMU_NBD_OPT_DETECT_ZEROES 4
45 static NBDExport *exp;
48 static SocketAddress *saddr;
49 static int persistent = 0;
50 static enum { RUNNING, TERMINATE, TERMINATING, TERMINATED } state;
51 static int shared = 1;
55 static void usage(const char *name)
58 "Usage: %s [OPTIONS] FILE\n"
59 "QEMU Disk Network Block Device Server\n"
61 " -h, --help display this help and exit\n"
62 " -V, --version output version information and exit\n"
64 "Connection properties:\n"
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"
73 "Exposing part of the image:\n"
74 " -o, --offset=OFFSET offset into the image\n"
75 " -P, --partition=NUM only expose partition NUM\n"
78 "Kernel NBD client support:\n"
79 " -c, --connect=DEV connect FILE to the local NBD device DEV\n"
80 " -d, --disconnect disconnect the specified device\n"
84 "Block device options:\n"
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"
90 " -l, --load-snapshot=SNAPSHOT_PARAM\n"
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"
95 " -n, --nocache disable host cache\n"
96 " --cache=MODE set cache mode (none, writeback, ...)\n"
97 " --aio=MODE set AIO mode (native or threads)\n"
98 " --discard=MODE set discard mode (ignore, unmap)\n"
99 " --detect-zeroes=MODE set detect-zeroes mode (off, on, unmap)\n"
102 , name, NBD_DEFAULT_PORT, "DEVICE");
105 static void version(const char *name)
109 "Written by Anthony Liguori.\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"
117 struct partition_record
121 uint32_t start_cylinder;
122 uint8_t start_sector;
125 uint8_t end_cylinder;
127 uint32_t start_sector_abs;
128 uint32_t nb_sectors_abs;
131 static void read_partition(uint8_t *p, struct partition_record *r)
134 r->start_head = p[1];
135 r->start_cylinder = p[3] | ((p[2] << 2) & 0x0300);
136 r->start_sector = p[2] & 0x3f;
139 r->end_cylinder = p[7] | ((p[6] << 2) & 0x300);
140 r->end_sector = p[6] & 0x3f;
142 r->start_sector_abs = le32_to_cpup((uint32_t *)(p + 8));
143 r->nb_sectors_abs = le32_to_cpup((uint32_t *)(p + 12));
146 static int find_partition(BlockBackend *blk, int partition,
147 off_t *offset, off_t *size)
149 struct partition_record mbr[4];
155 if ((ret = blk_read(blk, 0, data, 1)) < 0) {
156 error_report("error while reading: %s", strerror(-ret));
160 if (data[510] != 0x55 || data[511] != 0xaa) {
164 for (i = 0; i < 4; i++) {
165 read_partition(&data[446 + 16 * i], &mbr[i]);
167 if (!mbr[i].system || !mbr[i].nb_sectors_abs) {
171 if (mbr[i].system == 0xF || mbr[i].system == 0x5) {
172 struct partition_record ext[4];
176 if ((ret = blk_read(blk, mbr[i].start_sector_abs, data1, 1)) < 0) {
177 error_report("error while reading: %s", strerror(-ret));
181 for (j = 0; j < 4; j++) {
182 read_partition(&data1[446 + 16 * j], &ext[j]);
183 if (!ext[j].system || !ext[j].nb_sectors_abs) {
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;
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;
204 static void termsig_handler(int signum)
211 static void *show_parts(void *arg)
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
221 nbd = open(device, O_RDWR);
228 static void *nbd_client_thread(void *arg)
235 pthread_t show_parts_thread;
236 Error *local_error = NULL;
239 sock = socket_connect(saddr, &local_error, NULL, NULL);
241 error_report_err(local_error);
245 ret = nbd_receive_negotiate(sock, NULL, &nbdflags,
246 &size, &local_error);
249 error_report_err(local_error);
254 fd = open(device, O_RDWR);
256 /* Linux-only, we can use %m in printf. */
257 error_report("Failed to open %s: %m", device);
261 ret = nbd_init(fd, sock, nbdflags, size);
266 /* update partition table */
267 pthread_create(&show_parts_thread, NULL, show_parts, device);
270 fprintf(stderr, "NBD device %s is now connected to %s\n",
273 /* Close stderr so that the qemu-nbd process exits. */
274 dup2(STDOUT_FILENO, STDERR_FILENO);
277 ret = nbd_client(fd);
282 kill(getpid(), SIGTERM);
283 return (void *) EXIT_SUCCESS;
290 kill(getpid(), SIGTERM);
291 return (void *) EXIT_FAILURE;
294 static int nbd_can_accept(void)
296 return nb_fds < shared;
299 static void nbd_export_closed(NBDExport *exp)
301 assert(state == TERMINATING);
305 static void nbd_update_server_fd_handler(int fd);
307 static void nbd_client_closed(NBDClient *client)
310 if (nb_fds == 0 && !persistent && state == RUNNING) {
313 nbd_update_server_fd_handler(server_fd);
314 nbd_client_put(client);
317 static void nbd_accept(void *opaque)
319 struct sockaddr_in addr;
320 socklen_t addr_len = sizeof(addr);
322 int fd = accept(server_fd, (struct sockaddr *)&addr, &addr_len);
328 if (state >= TERMINATE) {
334 nbd_update_server_fd_handler(server_fd);
335 nbd_client_new(exp, fd, nbd_client_closed);
338 static void nbd_update_server_fd_handler(int fd)
340 if (nbd_can_accept()) {
341 qemu_set_fd_handler(fd, nbd_accept, NULL, (void *)(uintptr_t)fd);
343 qemu_set_fd_handler(fd, NULL, NULL, NULL);
348 static SocketAddress *nbd_build_socket_address(const char *sockpath,
352 SocketAddress *saddr;
354 saddr = g_new0(SocketAddress, 1);
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);
360 saddr->type = SOCKET_ADDRESS_KIND_INET;
361 saddr->u.inet = g_new0(InetSocketAddress, 1);
362 saddr->u.inet->host = g_strdup(bindto);
364 saddr->u.inet->port = g_strdup(port);
366 saddr->u.inet->port = g_strdup_printf("%d", NBD_DEFAULT_PORT);
374 int main(int argc, char **argv)
377 BlockDriverState *bs;
378 off_t dev_offset = 0;
379 uint32_t nbdflags = 0;
380 bool disconnect = false;
381 const char *bindto = "0.0.0.0";
382 const char *port = NULL;
383 char *sockpath = NULL;
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:";
389 struct option lopt[] = {
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' },
401 { "load-snapshot", 1, NULL, 'l' },
402 { "nocache", 0, NULL, 'n' },
403 { "cache", 1, NULL, QEMU_NBD_OPT_CACHE },
404 { "aio", 1, NULL, QEMU_NBD_OPT_AIO },
405 { "discard", 1, NULL, QEMU_NBD_OPT_DISCARD },
406 { "detect-zeroes", 1, NULL, QEMU_NBD_OPT_DETECT_ZEROES },
407 { "shared", 1, NULL, 'e' },
408 { "format", 1, NULL, 'f' },
409 { "persistent", 0, NULL, 't' },
410 { "verbose", 0, NULL, 'v' },
416 int flags = BDRV_O_RDWR;
420 bool seen_cache = false;
421 bool seen_discard = false;
422 bool seen_aio = false;
423 pthread_t client_thread;
424 const char *fmt = NULL;
425 Error *local_err = NULL;
426 BlockdevDetectZeroesOptions detect_zeroes = BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF;
427 QDict *options = NULL;
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.
432 struct sigaction sa_sigterm;
433 memset(&sa_sigterm, 0, sizeof(sa_sigterm));
434 sa_sigterm.sa_handler = termsig_handler;
435 sigaction(SIGTERM, &sa_sigterm, NULL);
436 qemu_init_exec_dir(argv[0]);
438 while ((ch = getopt_long(argc, argv, sopt, lopt, &opt_ind)) != -1) {
441 flags |= BDRV_O_SNAPSHOT;
444 optarg = (char *) "none";
446 case QEMU_NBD_OPT_CACHE:
448 error_report("-n and --cache can only be specified once");
452 if (bdrv_parse_cache_flags(optarg, &flags) == -1) {
453 error_report("Invalid cache mode `%s'", optarg);
457 case QEMU_NBD_OPT_AIO:
459 error_report("--aio can only be specified once");
463 if (!strcmp(optarg, "native")) {
464 flags |= BDRV_O_NATIVE_AIO;
465 } else if (!strcmp(optarg, "threads")) {
466 /* this is the default */
468 error_report("invalid aio mode `%s'", optarg);
472 case QEMU_NBD_OPT_DISCARD:
474 error_report("--discard can only be specified once");
478 if (bdrv_parse_discard_flags(optarg, &flags) == -1) {
479 error_report("Invalid discard mode `%s'", optarg);
483 case QEMU_NBD_OPT_DETECT_ZEROES:
485 qapi_enum_parse(BlockdevDetectZeroesOptions_lookup,
487 BLOCKDEV_DETECT_ZEROES_OPTIONS__MAX,
488 BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF,
491 error_reportf_err(local_err,
492 "Failed to parse detect_zeroes mode: ");
495 if (detect_zeroes == BLOCKDEV_DETECT_ZEROES_OPTIONS_UNMAP &&
496 !(flags & BDRV_O_UNMAP)) {
497 error_report("setting detect-zeroes to unmap is not allowed "
498 "without setting discard operation to unmap");
509 dev_offset = strtoll (optarg, &end, 0);
511 error_report("Invalid offset `%s'", optarg);
514 if (dev_offset < 0) {
515 error_report("Offset must be positive `%s'", optarg);
520 if (strstart(optarg, SNAPSHOT_OPT_BASE, NULL)) {
521 sn_opts = qemu_opts_parse_noisily(&internal_snapshot_opts,
524 error_report("Failed in parsing snapshot param `%s'",
529 sn_id_or_name = optarg;
533 nbdflags |= NBD_FLAG_READ_ONLY;
534 flags &= ~BDRV_O_RDWR;
537 partition = strtol(optarg, &end, 0);
539 error_report("Invalid partition `%s'", optarg);
542 if (partition < 1 || partition > 8) {
543 error_report("Invalid partition %d", partition);
549 if (sockpath[0] != '/') {
550 error_report("socket path must be absolute");
561 shared = strtol(optarg, &end, 0);
563 error_report("Invalid shared device number '%s'", optarg);
567 error_report("Shared device number must be greater than 0");
589 error_report("Try `%s --help' for more information.", argv[0]);
594 if ((argc - optind) != 1) {
595 error_report("Invalid number of arguments");
596 error_printf("Try `%s --help' for more information.\n", argv[0]);
601 fd = open(argv[optind], O_RDWR);
603 error_report("Cannot open %s: %s", argv[optind],
611 printf("%s disconnected\n", argv[optind]);
616 if (device && !verbose) {
621 if (qemu_pipe(stderr_fd) < 0) {
622 error_report("Error setting up communication pipe: %s",
627 /* Now daemonize, but keep a communication channel open to
628 * print errors and exit with the proper status code.
632 error_report("Failed to fork: %s", strerror(errno));
634 } else if (pid == 0) {
636 ret = qemu_daemon(1, 0);
638 /* Temporarily redirect stderr to the parent's pipe... */
639 dup2(stderr_fd[1], STDERR_FILENO);
641 error_report("Failed to daemonize: %s", strerror(errno));
645 /* ... close the descriptor we inherited and go on. */
651 /* In the parent. Print error messages from the child until
652 * it closes the pipe.
655 buf = g_malloc(1024);
656 while ((ret = read(stderr_fd[0], buf, 1024)) > 0) {
658 ret = qemu_write_full(STDERR_FILENO, buf, ret);
664 error_report("Cannot read from daemon: %s",
669 /* Usually the daemon should not print any message.
670 * Exit with zero status in that case.
676 if (device != NULL && sockpath == NULL) {
677 sockpath = g_malloc(128);
678 snprintf(sockpath, 128, SOCKET_PATH, basename(device));
681 saddr = nbd_build_socket_address(sockpath, bindto, port);
683 if (qemu_init_main_loop(&local_err)) {
684 error_report_err(local_err);
688 atexit(bdrv_close_all);
691 options = qdict_new();
692 qdict_put(options, "driver", qstring_from_str(fmt));
695 srcpath = argv[optind];
696 blk = blk_new_open("hda", srcpath, NULL, options, flags, &local_err);
698 error_reportf_err(local_err, "Failed to blk_new_open '%s': ",
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),
709 } else if (sn_id_or_name) {
710 ret = bdrv_snapshot_load_tmp_by_id_or_name(bs, sn_id_or_name,
714 error_reportf_err(local_err, "Failed to load snapshot: ");
718 bs->detect_zeroes = detect_zeroes;
719 fd_size = blk_getlength(blk);
721 error_report("Failed to determine the image length: %s",
726 if (partition != -1) {
727 ret = find_partition(blk, partition, &dev_offset, &fd_size);
729 error_report("Could not find partition %d: %s", partition,
735 exp = nbd_export_new(blk, dev_offset, fd_size, nbdflags, nbd_export_closed,
738 error_report_err(local_err);
742 fd = socket_listen(saddr, &local_err);
744 error_report_err(local_err);
751 ret = pthread_create(&client_thread, NULL, nbd_client_thread, device);
753 error_report("Failed to create client thread: %s", strerror(ret));
757 /* Shut up GCC warnings. */
758 memset(&client_thread, 0, sizeof(client_thread));
762 nbd_update_server_fd_handler(fd);
764 /* now when the initialization is (almost) complete, chdir("/")
765 * to free any busy filesystems */
766 if (chdir("/") < 0) {
767 error_report("Could not chdir to root directory: %s",
774 main_loop_wait(false);
775 if (state == TERMINATE) {
777 nbd_export_close(exp);
781 } while (state != TERMINATED);
788 qemu_opts_del(sn_opts);
792 pthread_join(client_thread, &ret);