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"
27 #include <sys/types.h>
28 #include <sys/socket.h>
29 #include <netinet/in.h>
30 #include <netinet/tcp.h>
31 #include <arpa/inet.h>
36 #define SOCKET_PATH "/var/lock/qemu-nbd-%s"
37 #define QEMU_NBD_OPT_CACHE 1
38 #define QEMU_NBD_OPT_AIO 2
40 static NBDExport
*exp
;
43 static char *sockpath
;
44 static int persistent
= 0;
45 static enum { RUNNING
, TERMINATE
, TERMINATING
, TERMINATED
} state
;
46 static int shared
= 1;
49 static void usage(const char *name
)
52 "Usage: %s [OPTIONS] FILE\n"
53 "QEMU Disk Network Block Device Server\n"
55 " -h, --help display this help and exit\n"
56 " -V, --version output version information and exit\n"
58 "Connection properties:\n"
59 " -p, --port=PORT port to listen on (default `%d')\n"
60 " -b, --bind=IFACE interface to bind to (default `0.0.0.0')\n"
61 " -k, --socket=PATH path to the unix socket\n"
62 " (default '"SOCKET_PATH
"')\n"
63 " -e, --shared=NUM device can be shared by NUM clients (default '1')\n"
64 " -t, --persistent don't exit on the last connection\n"
65 " -v, --verbose display extra debugging information\n"
67 "Exposing part of the image:\n"
68 " -o, --offset=OFFSET offset into the image\n"
69 " -P, --partition=NUM only expose partition NUM\n"
72 "Kernel NBD client support:\n"
73 " -c, --connect=DEV connect FILE to the local NBD device DEV\n"
74 " -d, --disconnect disconnect the specified device\n"
78 "Block device options:\n"
79 " -r, --read-only export read-only\n"
80 " -s, --snapshot use snapshot file\n"
81 " -n, --nocache disable host cache\n"
82 " --cache=MODE set cache mode (none, writeback, ...)\n"
83 #ifdef CONFIG_LINUX_AIO
84 " --aio=MODE set AIO mode (native or threads)\n"
87 "Report bugs to <qemu-devel@nongnu.org>\n"
88 , name
, NBD_DEFAULT_PORT
, "DEVICE");
91 static void version(const char *name
)
95 "Written by Anthony Liguori.\n"
97 "Copyright (C) 2006 Anthony Liguori <anthony@codemonkey.ws>.\n"
98 "This is free software; see the source for copying conditions. There is NO\n"
99 "warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n"
103 struct partition_record
107 uint32_t start_cylinder
;
108 uint8_t start_sector
;
111 uint8_t end_cylinder
;
113 uint32_t start_sector_abs
;
114 uint32_t nb_sectors_abs
;
117 static void read_partition(uint8_t *p
, struct partition_record
*r
)
120 r
->start_head
= p
[1];
121 r
->start_cylinder
= p
[3] | ((p
[2] << 2) & 0x0300);
122 r
->start_sector
= p
[2] & 0x3f;
125 r
->end_cylinder
= p
[7] | ((p
[6] << 2) & 0x300);
126 r
->end_sector
= p
[6] & 0x3f;
127 r
->start_sector_abs
= p
[8] | p
[9] << 8 | p
[10] << 16 | p
[11] << 24;
128 r
->nb_sectors_abs
= p
[12] | p
[13] << 8 | p
[14] << 16 | p
[15] << 24;
131 static int find_partition(BlockDriverState
*bs
, int partition
,
132 off_t
*offset
, off_t
*size
)
134 struct partition_record mbr
[4];
140 if ((ret
= bdrv_read(bs
, 0, data
, 1)) < 0) {
142 err(EXIT_FAILURE
, "error while reading");
145 if (data
[510] != 0x55 || data
[511] != 0xaa) {
149 for (i
= 0; i
< 4; i
++) {
150 read_partition(&data
[446 + 16 * i
], &mbr
[i
]);
152 if (!mbr
[i
].nb_sectors_abs
)
155 if (mbr
[i
].system
== 0xF || mbr
[i
].system
== 0x5) {
156 struct partition_record ext
[4];
160 if ((ret
= bdrv_read(bs
, mbr
[i
].start_sector_abs
, data1
, 1)) < 0) {
162 err(EXIT_FAILURE
, "error while reading");
165 for (j
= 0; j
< 4; j
++) {
166 read_partition(&data1
[446 + 16 * j
], &ext
[j
]);
167 if (!ext
[j
].nb_sectors_abs
)
170 if ((ext_partnum
+ j
+ 1) == partition
) {
171 *offset
= (uint64_t)ext
[j
].start_sector_abs
<< 9;
172 *size
= (uint64_t)ext
[j
].nb_sectors_abs
<< 9;
177 } else if ((i
+ 1) == partition
) {
178 *offset
= (uint64_t)mbr
[i
].start_sector_abs
<< 9;
179 *size
= (uint64_t)mbr
[i
].nb_sectors_abs
<< 9;
187 static void termsig_handler(int signum
)
193 static void *show_parts(void *arg
)
198 /* linux just needs an open() to trigger
199 * the partition table update
200 * but remember to load the module with max_part != 0 :
201 * modprobe nbd max_part=63
203 nbd
= open(device
, O_RDWR
);
210 static void *nbd_client_thread(void *arg
)
218 pthread_t show_parts_thread
;
220 sock
= unix_socket_outgoing(sockpath
);
225 ret
= nbd_receive_negotiate(sock
, NULL
, &nbdflags
,
231 fd
= open(device
, O_RDWR
);
233 /* Linux-only, we can use %m in printf. */
234 fprintf(stderr
, "Failed to open %s: %m", device
);
238 ret
= nbd_init(fd
, sock
, nbdflags
, size
, blocksize
);
243 /* update partition table */
244 pthread_create(&show_parts_thread
, NULL
, show_parts
, device
);
247 fprintf(stderr
, "NBD device %s is now connected to %s\n",
250 /* Close stderr so that the qemu-nbd process exits. */
251 dup2(STDOUT_FILENO
, STDERR_FILENO
);
254 ret
= nbd_client(fd
);
259 kill(getpid(), SIGTERM
);
260 return (void *) EXIT_SUCCESS
;
263 kill(getpid(), SIGTERM
);
264 return (void *) EXIT_FAILURE
;
267 static int nbd_can_accept(void *opaque
)
269 return nb_fds
< shared
;
272 static void nbd_export_closed(NBDExport
*exp
)
274 assert(state
== TERMINATING
);
278 static void nbd_client_closed(NBDClient
*client
)
281 if (nb_fds
== 0 && !persistent
&& state
== RUNNING
) {
285 nbd_client_put(client
);
288 static void nbd_accept(void *opaque
)
290 int server_fd
= (uintptr_t) opaque
;
291 struct sockaddr_in addr
;
292 socklen_t addr_len
= sizeof(addr
);
294 int fd
= accept(server_fd
, (struct sockaddr
*)&addr
, &addr_len
);
295 if (state
>= TERMINATE
) {
300 if (fd
>= 0 && nbd_client_new(exp
, fd
, nbd_client_closed
)) {
305 int main(int argc
, char **argv
)
307 BlockDriverState
*bs
;
308 off_t dev_offset
= 0;
309 uint32_t nbdflags
= 0;
310 bool disconnect
= false;
311 const char *bindto
= "0.0.0.0";
313 int port
= NBD_DEFAULT_PORT
;
315 const char *sopt
= "hVb:o:p:rsnP:c:dvk:e:t";
316 struct option lopt
[] = {
317 { "help", 0, NULL
, 'h' },
318 { "version", 0, NULL
, 'V' },
319 { "bind", 1, NULL
, 'b' },
320 { "port", 1, NULL
, 'p' },
321 { "socket", 1, NULL
, 'k' },
322 { "offset", 1, NULL
, 'o' },
323 { "read-only", 0, NULL
, 'r' },
324 { "partition", 1, NULL
, 'P' },
325 { "connect", 1, NULL
, 'c' },
326 { "disconnect", 0, NULL
, 'd' },
327 { "snapshot", 0, NULL
, 's' },
328 { "nocache", 0, NULL
, 'n' },
329 { "cache", 1, NULL
, QEMU_NBD_OPT_CACHE
},
330 #ifdef CONFIG_LINUX_AIO
331 { "aio", 1, NULL
, QEMU_NBD_OPT_AIO
},
333 { "shared", 1, NULL
, 'e' },
334 { "persistent", 0, NULL
, 't' },
335 { "verbose", 0, NULL
, 'v' },
342 int flags
= BDRV_O_RDWR
;
346 bool seen_cache
= false;
347 #ifdef CONFIG_LINUX_AIO
348 bool seen_aio
= false;
350 pthread_t client_thread
;
352 /* The client thread uses SIGTERM to interrupt the server. A signal
353 * handler ensures that "qemu-nbd -v -c" exits with a nice status code.
355 struct sigaction sa_sigterm
;
356 memset(&sa_sigterm
, 0, sizeof(sa_sigterm
));
357 sa_sigterm
.sa_handler
= termsig_handler
;
358 sigaction(SIGTERM
, &sa_sigterm
, NULL
);
360 while ((ch
= getopt_long(argc
, argv
, sopt
, lopt
, &opt_ind
)) != -1) {
363 flags
|= BDRV_O_SNAPSHOT
;
366 optarg
= (char *) "none";
368 case QEMU_NBD_OPT_CACHE
:
370 errx(EXIT_FAILURE
, "-n and --cache can only be specified once");
373 if (bdrv_parse_cache_flags(optarg
, &flags
) == -1) {
374 errx(EXIT_FAILURE
, "Invalid cache mode `%s'", optarg
);
377 #ifdef CONFIG_LINUX_AIO
378 case QEMU_NBD_OPT_AIO
:
380 errx(EXIT_FAILURE
, "--aio can only be specified once");
383 if (!strcmp(optarg
, "native")) {
384 flags
|= BDRV_O_NATIVE_AIO
;
385 } else if (!strcmp(optarg
, "threads")) {
386 /* this is the default */
388 errx(EXIT_FAILURE
, "invalid aio mode `%s'", optarg
);
396 li
= strtol(optarg
, &end
, 0);
398 errx(EXIT_FAILURE
, "Invalid port `%s'", optarg
);
400 if (li
< 1 || li
> 65535) {
401 errx(EXIT_FAILURE
, "Port out of range `%s'", optarg
);
406 dev_offset
= strtoll (optarg
, &end
, 0);
408 errx(EXIT_FAILURE
, "Invalid offset `%s'", optarg
);
410 if (dev_offset
< 0) {
411 errx(EXIT_FAILURE
, "Offset must be positive `%s'", optarg
);
415 nbdflags
|= NBD_FLAG_READ_ONLY
;
416 flags
&= ~BDRV_O_RDWR
;
419 partition
= strtol(optarg
, &end
, 0);
421 errx(EXIT_FAILURE
, "Invalid partition `%s'", optarg
);
422 if (partition
< 1 || partition
> 8)
423 errx(EXIT_FAILURE
, "Invalid partition %d", partition
);
427 if (sockpath
[0] != '/')
428 errx(EXIT_FAILURE
, "socket path must be absolute\n");
437 shared
= strtol(optarg
, &end
, 0);
439 errx(EXIT_FAILURE
, "Invalid shared device number '%s'", optarg
);
442 errx(EXIT_FAILURE
, "Shared device number must be greater than 0\n");
460 errx(EXIT_FAILURE
, "Try `%s --help' for more information.",
465 if ((argc
- optind
) != 1) {
466 errx(EXIT_FAILURE
, "Invalid number of argument.\n"
467 "Try `%s --help' for more information.",
472 fd
= open(argv
[optind
], O_RDWR
);
474 err(EXIT_FAILURE
, "Cannot open %s", argv
[optind
]);
480 printf("%s disconnected\n", argv
[optind
]);
485 if (device
&& !verbose
) {
490 if (qemu_pipe(stderr_fd
) < 0) {
491 err(EXIT_FAILURE
, "Error setting up communication pipe");
494 /* Now daemonize, but keep a communication channel open to
495 * print errors and exit with the proper status code.
500 ret
= qemu_daemon(1, 0);
502 /* Temporarily redirect stderr to the parent's pipe... */
503 dup2(stderr_fd
[1], STDERR_FILENO
);
505 err(EXIT_FAILURE
, "Failed to daemonize");
508 /* ... close the descriptor we inherited and go on. */
514 /* In the parent. Print error messages from the child until
515 * it closes the pipe.
518 buf
= g_malloc(1024);
519 while ((ret
= read(stderr_fd
[0], buf
, 1024)) > 0) {
521 ret
= qemu_write_full(STDERR_FILENO
, buf
, ret
);
527 err(EXIT_FAILURE
, "Cannot read from daemon");
530 /* Usually the daemon should not print any message.
531 * Exit with zero status in that case.
537 if (device
!= NULL
&& sockpath
== NULL
) {
538 sockpath
= g_malloc(128);
539 snprintf(sockpath
, 128, SOCKET_PATH
, basename(device
));
542 qemu_init_main_loop();
544 atexit(bdrv_close_all
);
546 bs
= bdrv_new("hda");
547 srcpath
= argv
[optind
];
548 if ((ret
= bdrv_open(bs
, srcpath
, flags
, NULL
)) < 0) {
550 err(EXIT_FAILURE
, "Failed to bdrv_open '%s'", argv
[optind
]);
553 fd_size
= bdrv_getlength(bs
);
555 if (partition
!= -1) {
556 ret
= find_partition(bs
, partition
, &dev_offset
, &fd_size
);
559 err(EXIT_FAILURE
, "Could not find partition %d", partition
);
563 exp
= nbd_export_new(bs
, dev_offset
, fd_size
, nbdflags
, nbd_export_closed
);
566 fd
= unix_socket_incoming(sockpath
);
568 fd
= tcp_socket_incoming(bindto
, port
);
578 ret
= pthread_create(&client_thread
, NULL
, nbd_client_thread
, device
);
580 errx(EXIT_FAILURE
, "Failed to create client thread: %s",
584 /* Shut up GCC warnings. */
585 memset(&client_thread
, 0, sizeof(client_thread
));
588 qemu_set_fd_handler2(fd
, nbd_can_accept
, nbd_accept
, NULL
,
589 (void *)(uintptr_t)fd
);
591 /* now when the initialization is (almost) complete, chdir("/")
592 * to free any busy filesystems */
593 if (chdir("/") < 0) {
594 err(EXIT_FAILURE
, "Could not chdir to root directory");
599 main_loop_wait(false);
600 if (state
== TERMINATE
) {
602 nbd_export_close(exp
);
606 } while (state
!= TERMINATED
);
615 pthread_join(client_thread
, &ret
);