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"
28 #include <sys/types.h>
29 #include <sys/socket.h>
30 #include <netinet/in.h>
31 #include <netinet/tcp.h>
32 #include <arpa/inet.h>
37 #define SOCKET_PATH "/var/lock/qemu-nbd-%s"
38 #define QEMU_NBD_OPT_CACHE 1
39 #define QEMU_NBD_OPT_AIO 2
40 #define QEMU_NBD_OPT_DISCARD 3
42 static NBDExport
*exp
;
45 static char *sockpath
;
46 static int persistent
= 0;
47 static enum { RUNNING
, TERMINATE
, TERMINATING
, TERMINATED
} state
;
48 static int shared
= 1;
51 static void usage(const char *name
)
54 "Usage: %s [OPTIONS] FILE\n"
55 "QEMU Disk Network Block Device Server\n"
57 " -h, --help display this help and exit\n"
58 " -V, --version output version information and exit\n"
60 "Connection properties:\n"
61 " -p, --port=PORT port to listen on (default `%d')\n"
62 " -b, --bind=IFACE interface to bind to (default `0.0.0.0')\n"
63 " -k, --socket=PATH path to the unix socket\n"
64 " (default '"SOCKET_PATH
"')\n"
65 " -e, --shared=NUM device can be shared by NUM clients (default '1')\n"
66 " -t, --persistent don't exit on the last connection\n"
67 " -v, --verbose display extra debugging information\n"
69 "Exposing part of the image:\n"
70 " -o, --offset=OFFSET offset into the image\n"
71 " -P, --partition=NUM only expose partition NUM\n"
74 "Kernel NBD client support:\n"
75 " -c, --connect=DEV connect FILE to the local NBD device DEV\n"
76 " -d, --disconnect disconnect the specified device\n"
80 "Block device options:\n"
81 " -r, --read-only export read-only\n"
82 " -s, --snapshot use snapshot file\n"
83 " -n, --nocache disable host cache\n"
84 " --cache=MODE set cache mode (none, writeback, ...)\n"
85 #ifdef CONFIG_LINUX_AIO
86 " --aio=MODE set AIO mode (native or threads)\n"
89 "Report bugs to <qemu-devel@nongnu.org>\n"
90 , name
, NBD_DEFAULT_PORT
, "DEVICE");
93 static void version(const char *name
)
97 "Written by Anthony Liguori.\n"
99 "Copyright (C) 2006 Anthony Liguori <anthony@codemonkey.ws>.\n"
100 "This is free software; see the source for copying conditions. There is NO\n"
101 "warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n"
105 struct partition_record
109 uint32_t start_cylinder
;
110 uint8_t start_sector
;
113 uint8_t end_cylinder
;
115 uint32_t start_sector_abs
;
116 uint32_t nb_sectors_abs
;
119 static void read_partition(uint8_t *p
, struct partition_record
*r
)
122 r
->start_head
= p
[1];
123 r
->start_cylinder
= p
[3] | ((p
[2] << 2) & 0x0300);
124 r
->start_sector
= p
[2] & 0x3f;
127 r
->end_cylinder
= p
[7] | ((p
[6] << 2) & 0x300);
128 r
->end_sector
= p
[6] & 0x3f;
129 r
->start_sector_abs
= p
[8] | p
[9] << 8 | p
[10] << 16 | p
[11] << 24;
130 r
->nb_sectors_abs
= p
[12] | p
[13] << 8 | p
[14] << 16 | p
[15] << 24;
133 static int find_partition(BlockDriverState
*bs
, int partition
,
134 off_t
*offset
, off_t
*size
)
136 struct partition_record mbr
[4];
142 if ((ret
= bdrv_read(bs
, 0, data
, 1)) < 0) {
144 err(EXIT_FAILURE
, "error while reading");
147 if (data
[510] != 0x55 || data
[511] != 0xaa) {
151 for (i
= 0; i
< 4; i
++) {
152 read_partition(&data
[446 + 16 * i
], &mbr
[i
]);
154 if (!mbr
[i
].nb_sectors_abs
)
157 if (mbr
[i
].system
== 0xF || mbr
[i
].system
== 0x5) {
158 struct partition_record ext
[4];
162 if ((ret
= bdrv_read(bs
, mbr
[i
].start_sector_abs
, data1
, 1)) < 0) {
164 err(EXIT_FAILURE
, "error while reading");
167 for (j
= 0; j
< 4; j
++) {
168 read_partition(&data1
[446 + 16 * j
], &ext
[j
]);
169 if (!ext
[j
].nb_sectors_abs
)
172 if ((ext_partnum
+ j
+ 1) == partition
) {
173 *offset
= (uint64_t)ext
[j
].start_sector_abs
<< 9;
174 *size
= (uint64_t)ext
[j
].nb_sectors_abs
<< 9;
179 } else if ((i
+ 1) == partition
) {
180 *offset
= (uint64_t)mbr
[i
].start_sector_abs
<< 9;
181 *size
= (uint64_t)mbr
[i
].nb_sectors_abs
<< 9;
189 static void termsig_handler(int signum
)
195 static void *show_parts(void *arg
)
200 /* linux just needs an open() to trigger
201 * the partition table update
202 * but remember to load the module with max_part != 0 :
203 * modprobe nbd max_part=63
205 nbd
= open(device
, O_RDWR
);
212 static void *nbd_client_thread(void *arg
)
220 pthread_t show_parts_thread
;
222 sock
= unix_socket_outgoing(sockpath
);
227 ret
= nbd_receive_negotiate(sock
, NULL
, &nbdflags
,
233 fd
= open(device
, O_RDWR
);
235 /* Linux-only, we can use %m in printf. */
236 fprintf(stderr
, "Failed to open %s: %m", device
);
240 ret
= nbd_init(fd
, sock
, nbdflags
, size
, blocksize
);
245 /* update partition table */
246 pthread_create(&show_parts_thread
, NULL
, show_parts
, device
);
249 fprintf(stderr
, "NBD device %s is now connected to %s\n",
252 /* Close stderr so that the qemu-nbd process exits. */
253 dup2(STDOUT_FILENO
, STDERR_FILENO
);
256 ret
= nbd_client(fd
);
261 kill(getpid(), SIGTERM
);
262 return (void *) EXIT_SUCCESS
;
265 kill(getpid(), SIGTERM
);
266 return (void *) EXIT_FAILURE
;
269 static int nbd_can_accept(void *opaque
)
271 return nb_fds
< shared
;
274 static void nbd_export_closed(NBDExport
*exp
)
276 assert(state
== TERMINATING
);
280 static void nbd_client_closed(NBDClient
*client
)
283 if (nb_fds
== 0 && !persistent
&& state
== RUNNING
) {
287 nbd_client_put(client
);
290 static void nbd_accept(void *opaque
)
292 int server_fd
= (uintptr_t) opaque
;
293 struct sockaddr_in addr
;
294 socklen_t addr_len
= sizeof(addr
);
296 int fd
= accept(server_fd
, (struct sockaddr
*)&addr
, &addr_len
);
297 if (state
>= TERMINATE
) {
302 if (fd
>= 0 && nbd_client_new(exp
, fd
, nbd_client_closed
)) {
307 int main(int argc
, char **argv
)
309 BlockDriverState
*bs
;
311 off_t dev_offset
= 0;
312 uint32_t nbdflags
= 0;
313 bool disconnect
= false;
314 const char *bindto
= "0.0.0.0";
316 int port
= NBD_DEFAULT_PORT
;
318 const char *sopt
= "hVb:o:p:rsnP:c:dvk:e:f:t";
319 struct option lopt
[] = {
320 { "help", 0, NULL
, 'h' },
321 { "version", 0, NULL
, 'V' },
322 { "bind", 1, NULL
, 'b' },
323 { "port", 1, NULL
, 'p' },
324 { "socket", 1, NULL
, 'k' },
325 { "offset", 1, NULL
, 'o' },
326 { "read-only", 0, NULL
, 'r' },
327 { "partition", 1, NULL
, 'P' },
328 { "connect", 1, NULL
, 'c' },
329 { "disconnect", 0, NULL
, 'd' },
330 { "snapshot", 0, NULL
, 's' },
331 { "nocache", 0, NULL
, 'n' },
332 { "cache", 1, NULL
, QEMU_NBD_OPT_CACHE
},
333 #ifdef CONFIG_LINUX_AIO
334 { "aio", 1, NULL
, QEMU_NBD_OPT_AIO
},
336 { "discard", 1, NULL
, QEMU_NBD_OPT_DISCARD
},
337 { "shared", 1, NULL
, 'e' },
338 { "format", 1, NULL
, 'f' },
339 { "persistent", 0, NULL
, 't' },
340 { "verbose", 0, NULL
, 'v' },
347 int flags
= BDRV_O_RDWR
;
351 bool seen_cache
= false;
352 bool seen_discard
= false;
353 #ifdef CONFIG_LINUX_AIO
354 bool seen_aio
= false;
356 pthread_t client_thread
;
357 const char *fmt
= NULL
;
358 Error
*local_err
= NULL
;
360 /* The client thread uses SIGTERM to interrupt the server. A signal
361 * handler ensures that "qemu-nbd -v -c" exits with a nice status code.
363 struct sigaction sa_sigterm
;
364 memset(&sa_sigterm
, 0, sizeof(sa_sigterm
));
365 sa_sigterm
.sa_handler
= termsig_handler
;
366 sigaction(SIGTERM
, &sa_sigterm
, NULL
);
368 while ((ch
= getopt_long(argc
, argv
, sopt
, lopt
, &opt_ind
)) != -1) {
371 flags
|= BDRV_O_SNAPSHOT
;
374 optarg
= (char *) "none";
376 case QEMU_NBD_OPT_CACHE
:
378 errx(EXIT_FAILURE
, "-n and --cache can only be specified once");
381 if (bdrv_parse_cache_flags(optarg
, &flags
) == -1) {
382 errx(EXIT_FAILURE
, "Invalid cache mode `%s'", optarg
);
385 #ifdef CONFIG_LINUX_AIO
386 case QEMU_NBD_OPT_AIO
:
388 errx(EXIT_FAILURE
, "--aio can only be specified once");
391 if (!strcmp(optarg
, "native")) {
392 flags
|= BDRV_O_NATIVE_AIO
;
393 } else if (!strcmp(optarg
, "threads")) {
394 /* this is the default */
396 errx(EXIT_FAILURE
, "invalid aio mode `%s'", optarg
);
400 case QEMU_NBD_OPT_DISCARD
:
402 errx(EXIT_FAILURE
, "--discard can only be specified once");
405 if (bdrv_parse_discard_flags(optarg
, &flags
) == -1) {
406 errx(EXIT_FAILURE
, "Invalid discard mode `%s'", optarg
);
413 li
= strtol(optarg
, &end
, 0);
415 errx(EXIT_FAILURE
, "Invalid port `%s'", optarg
);
417 if (li
< 1 || li
> 65535) {
418 errx(EXIT_FAILURE
, "Port out of range `%s'", optarg
);
423 dev_offset
= strtoll (optarg
, &end
, 0);
425 errx(EXIT_FAILURE
, "Invalid offset `%s'", optarg
);
427 if (dev_offset
< 0) {
428 errx(EXIT_FAILURE
, "Offset must be positive `%s'", optarg
);
432 nbdflags
|= NBD_FLAG_READ_ONLY
;
433 flags
&= ~BDRV_O_RDWR
;
436 partition
= strtol(optarg
, &end
, 0);
438 errx(EXIT_FAILURE
, "Invalid partition `%s'", optarg
);
439 if (partition
< 1 || partition
> 8)
440 errx(EXIT_FAILURE
, "Invalid partition %d", partition
);
444 if (sockpath
[0] != '/')
445 errx(EXIT_FAILURE
, "socket path must be absolute\n");
454 shared
= strtol(optarg
, &end
, 0);
456 errx(EXIT_FAILURE
, "Invalid shared device number '%s'", optarg
);
459 errx(EXIT_FAILURE
, "Shared device number must be greater than 0\n");
480 errx(EXIT_FAILURE
, "Try `%s --help' for more information.",
485 if ((argc
- optind
) != 1) {
486 errx(EXIT_FAILURE
, "Invalid number of argument.\n"
487 "Try `%s --help' for more information.",
492 fd
= open(argv
[optind
], O_RDWR
);
494 err(EXIT_FAILURE
, "Cannot open %s", argv
[optind
]);
500 printf("%s disconnected\n", argv
[optind
]);
505 if (device
&& !verbose
) {
510 if (qemu_pipe(stderr_fd
) < 0) {
511 err(EXIT_FAILURE
, "Error setting up communication pipe");
514 /* Now daemonize, but keep a communication channel open to
515 * print errors and exit with the proper status code.
520 ret
= qemu_daemon(1, 0);
522 /* Temporarily redirect stderr to the parent's pipe... */
523 dup2(stderr_fd
[1], STDERR_FILENO
);
525 err(EXIT_FAILURE
, "Failed to daemonize");
528 /* ... close the descriptor we inherited and go on. */
534 /* In the parent. Print error messages from the child until
535 * it closes the pipe.
538 buf
= g_malloc(1024);
539 while ((ret
= read(stderr_fd
[0], buf
, 1024)) > 0) {
541 ret
= qemu_write_full(STDERR_FILENO
, buf
, ret
);
547 err(EXIT_FAILURE
, "Cannot read from daemon");
550 /* Usually the daemon should not print any message.
551 * Exit with zero status in that case.
557 if (device
!= NULL
&& sockpath
== NULL
) {
558 sockpath
= g_malloc(128);
559 snprintf(sockpath
, 128, SOCKET_PATH
, basename(device
));
562 qemu_init_main_loop();
564 atexit(bdrv_close_all
);
567 drv
= bdrv_find_format(fmt
);
569 errx(EXIT_FAILURE
, "Unknown file format '%s'", fmt
);
575 bs
= bdrv_new("hda");
576 srcpath
= argv
[optind
];
577 ret
= bdrv_open(bs
, srcpath
, NULL
, flags
, drv
, &local_err
);
580 err(EXIT_FAILURE
, "Failed to bdrv_open '%s': %s", argv
[optind
],
581 error_get_pretty(local_err
));
584 fd_size
= bdrv_getlength(bs
);
586 if (partition
!= -1) {
587 ret
= find_partition(bs
, partition
, &dev_offset
, &fd_size
);
590 err(EXIT_FAILURE
, "Could not find partition %d", partition
);
594 exp
= nbd_export_new(bs
, dev_offset
, fd_size
, nbdflags
, nbd_export_closed
);
597 fd
= unix_socket_incoming(sockpath
);
599 fd
= tcp_socket_incoming(bindto
, port
);
609 ret
= pthread_create(&client_thread
, NULL
, nbd_client_thread
, device
);
611 errx(EXIT_FAILURE
, "Failed to create client thread: %s",
615 /* Shut up GCC warnings. */
616 memset(&client_thread
, 0, sizeof(client_thread
));
619 qemu_set_fd_handler2(fd
, nbd_can_accept
, nbd_accept
, NULL
,
620 (void *)(uintptr_t)fd
);
622 /* now when the initialization is (almost) complete, chdir("/")
623 * to free any busy filesystems */
624 if (chdir("/") < 0) {
625 err(EXIT_FAILURE
, "Could not chdir to root directory");
630 main_loop_wait(false);
631 if (state
== TERMINATE
) {
633 nbd_export_close(exp
);
637 } while (state
!= TERMINATED
);
646 pthread_join(client_thread
, &ret
);