blob: 0c9e807a1a95d305a6e827d90dbed5636dec0665 [file] [log] [blame]
thscd831bd2008-07-03 10:23:51 +00001/*
bellard7a5ca862008-05-27 21:13:40 +00002 * Copyright (C) 2005 Anthony Liguori <anthony@codemonkey.ws>
3 *
4 * Network Block Device
5 *
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.
9 *
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.
14 *
15 * You should have received a copy of the GNU General Public License
Blue Swirl8167ee82009-07-16 20:47:01 +000016 * along with this program; if not, see <http://www.gnu.org/licenses/>.
bellard7a5ca862008-05-27 21:13:40 +000017 */
18
Stefan Weil5a61cb62011-09-08 17:55:32 +020019#include "qemu-common.h"
Markus Armbruster26f54e92014-10-07 13:59:04 +020020#include "sysemu/block-backend.h"
Peter Lievenb3838a42014-08-13 19:20:18 +020021#include "block/block_int.h"
Paolo Bonzini737e1502012-12-17 18:19:44 +010022#include "block/nbd.h"
Alex Bligh6a1751b2013-08-21 16:02:47 +010023#include "qemu/main-loop.h"
Paolo Bonzini537b41f2014-02-17 14:43:51 +010024#include "qemu/sockets.h"
25#include "qemu/error-report.h"
Wenchao Xia8c116b02013-12-04 17:10:55 +080026#include "block/snapshot.h"
Peter Lievenb3838a42014-08-13 19:20:18 +020027#include "qapi/util.h"
bellard7a5ca862008-05-27 21:13:40 +000028
bellard7a5ca862008-05-27 21:13:40 +000029#include <stdarg.h>
30#include <stdio.h>
31#include <getopt.h>
32#include <err.h>
thscd831bd2008-07-03 10:23:51 +000033#include <sys/types.h>
bellard7a5ca862008-05-27 21:13:40 +000034#include <sys/socket.h>
35#include <netinet/in.h>
36#include <netinet/tcp.h>
37#include <arpa/inet.h>
thscd831bd2008-07-03 10:23:51 +000038#include <signal.h>
Blue Swirl2bff4b62009-12-23 15:34:04 +000039#include <libgen.h>
Paolo Bonzinia517e882011-11-04 15:51:21 +010040#include <pthread.h>
thscd831bd2008-07-03 10:23:51 +000041
Peter Lieven713cc672014-08-13 19:20:19 +020042#define SOCKET_PATH "/var/lock/qemu-nbd-%s"
43#define QEMU_NBD_OPT_CACHE 1
44#define QEMU_NBD_OPT_AIO 2
45#define QEMU_NBD_OPT_DISCARD 3
Peter Lievenb3838a42014-08-13 19:20:18 +020046#define QEMU_NBD_OPT_DETECT_ZEROES 4
bellard7a5ca862008-05-27 21:13:40 +000047
Paolo Bonziniaf49bbb2011-09-19 14:03:37 +020048static NBDExport *exp;
blueswir1b1d8e522008-10-26 13:43:07 +000049static int verbose;
Paolo Bonzinia517e882011-11-04 15:51:21 +010050static char *srcpath;
51static char *sockpath;
Paolo Bonzini7860a382012-09-18 13:31:56 +020052static int persistent = 0;
53static enum { RUNNING, TERMINATE, TERMINATING, TERMINATED } state;
Paolo Bonzinia61c6782011-09-12 17:28:11 +020054static int shared = 1;
55static int nb_fds;
bellard7a5ca862008-05-27 21:13:40 +000056
57static void usage(const char *name)
58{
Paolo Bonzinib033cd82012-07-18 14:50:52 +020059 (printf) (
bellard7a5ca862008-05-27 21:13:40 +000060"Usage: %s [OPTIONS] FILE\n"
61"QEMU Disk Network Block Device Server\n"
62"\n"
Peter Lieven713cc672014-08-13 19:20:19 +020063" -h, --help display this help and exit\n"
64" -V, --version output version information and exit\n"
bellard7a5ca862008-05-27 21:13:40 +000065"\n"
Paolo Bonzinib033cd82012-07-18 14:50:52 +020066"Connection properties:\n"
Peter Lieven713cc672014-08-13 19:20:19 +020067" -p, --port=PORT port to listen on (default `%d')\n"
68" -b, --bind=IFACE interface to bind to (default `0.0.0.0')\n"
69" -k, --socket=PATH path to the unix socket\n"
70" (default '"SOCKET_PATH"')\n"
71" -e, --shared=NUM device can be shared by NUM clients (default '1')\n"
72" -t, --persistent don't exit on the last connection\n"
73" -v, --verbose display extra debugging information\n"
Paolo Bonzinib033cd82012-07-18 14:50:52 +020074"\n"
75"Exposing part of the image:\n"
Peter Lieven713cc672014-08-13 19:20:19 +020076" -o, --offset=OFFSET offset into the image\n"
77" -P, --partition=NUM only expose partition NUM\n"
Paolo Bonzinib033cd82012-07-18 14:50:52 +020078"\n"
79#ifdef __linux__
80"Kernel NBD client support:\n"
Peter Lieven713cc672014-08-13 19:20:19 +020081" -c, --connect=DEV connect FILE to the local NBD device DEV\n"
82" -d, --disconnect disconnect the specified device\n"
Paolo Bonzinib033cd82012-07-18 14:50:52 +020083"\n"
84#endif
85"\n"
86"Block device options:\n"
Peter Lieven713cc672014-08-13 19:20:19 +020087" -f, --format=FORMAT set image format (raw, qcow2, ...)\n"
88" -r, --read-only export read-only\n"
89" -s, --snapshot use FILE as an external snapshot, create a temporary\n"
90" file with backing_file=FILE, redirect the write to\n"
91" the temporary one\n"
Wenchao Xia8c116b02013-12-04 17:10:55 +080092" -l, --load-snapshot=SNAPSHOT_PARAM\n"
Peter Lieven713cc672014-08-13 19:20:19 +020093" load an internal snapshot inside FILE and export it\n"
94" as an read-only device, SNAPSHOT_PARAM format is\n"
95" 'snapshot.id=[ID],snapshot.name=[NAME]', or\n"
96" '[ID_OR_NAME]'\n"
97" -n, --nocache disable host cache\n"
98" --cache=MODE set cache mode (none, writeback, ...)\n"
Paolo Bonzini39a52352012-07-18 14:57:15 +020099#ifdef CONFIG_LINUX_AIO
Peter Lieven713cc672014-08-13 19:20:19 +0200100" --aio=MODE set AIO mode (native or threads)\n"
Paolo Bonzini39a52352012-07-18 14:57:15 +0200101#endif
Peter Lievenb3838a42014-08-13 19:20:18 +0200102" --discard=MODE set discard mode (ignore, unmap)\n"
103" --detect-zeroes=MODE set detect-zeroes mode (off, on, discard)\n"
Paolo Bonzinib033cd82012-07-18 14:50:52 +0200104"\n"
105"Report bugs to <qemu-devel@nongnu.org>\n"
Laurent Vivierc2e28722010-09-17 20:37:25 +0200106 , name, NBD_DEFAULT_PORT, "DEVICE");
bellard7a5ca862008-05-27 21:13:40 +0000107}
108
109static void version(const char *name)
110{
111 printf(
ths315bc7a2008-07-18 18:06:23 +0000112"%s version 0.0.1\n"
bellard7a5ca862008-05-27 21:13:40 +0000113"Written by Anthony Liguori.\n"
114"\n"
115"Copyright (C) 2006 Anthony Liguori <anthony@codemonkey.ws>.\n"
116"This is free software; see the source for copying conditions. There is NO\n"
117"warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n"
ths315bc7a2008-07-18 18:06:23 +0000118 , name);
bellard7a5ca862008-05-27 21:13:40 +0000119}
120
121struct partition_record
122{
123 uint8_t bootable;
124 uint8_t start_head;
125 uint32_t start_cylinder;
126 uint8_t start_sector;
127 uint8_t system;
128 uint8_t end_head;
129 uint8_t end_cylinder;
130 uint8_t end_sector;
131 uint32_t start_sector_abs;
132 uint32_t nb_sectors_abs;
133};
134
135static void read_partition(uint8_t *p, struct partition_record *r)
136{
137 r->bootable = p[0];
138 r->start_head = p[1];
139 r->start_cylinder = p[3] | ((p[2] << 2) & 0x0300);
140 r->start_sector = p[2] & 0x3f;
141 r->system = p[4];
142 r->end_head = p[5];
143 r->end_cylinder = p[7] | ((p[6] << 2) & 0x300);
144 r->end_sector = p[6] & 0x3f;
145 r->start_sector_abs = p[8] | p[9] << 8 | p[10] << 16 | p[11] << 24;
146 r->nb_sectors_abs = p[12] | p[13] << 8 | p[14] << 16 | p[15] << 24;
147}
148
Max Reitz4c58e802014-11-18 12:21:19 +0100149static int find_partition(BlockBackend *blk, int partition,
bellard7a5ca862008-05-27 21:13:40 +0000150 off_t *offset, off_t *size)
151{
152 struct partition_record mbr[4];
153 uint8_t data[512];
154 int i;
155 int ext_partnum = 4;
Ryota Ozakicb7cf0e2010-05-03 06:50:25 +0900156 int ret;
bellard7a5ca862008-05-27 21:13:40 +0000157
Max Reitz4c58e802014-11-18 12:21:19 +0100158 if ((ret = blk_read(blk, 0, data, 1)) < 0) {
Ryota Ozakicb7cf0e2010-05-03 06:50:25 +0900159 errno = -ret;
160 err(EXIT_FAILURE, "error while reading");
161 }
bellard7a5ca862008-05-27 21:13:40 +0000162
163 if (data[510] != 0x55 || data[511] != 0xaa) {
Paolo Bonzini185b4332012-03-05 08:56:10 +0100164 return -EINVAL;
bellard7a5ca862008-05-27 21:13:40 +0000165 }
166
167 for (i = 0; i < 4; i++) {
168 read_partition(&data[446 + 16 * i], &mbr[i]);
169
Max Reitz453b07b2015-02-25 13:08:15 -0500170 if (!mbr[i].system || !mbr[i].nb_sectors_abs) {
bellard7a5ca862008-05-27 21:13:40 +0000171 continue;
Max Reitz453b07b2015-02-25 13:08:15 -0500172 }
bellard7a5ca862008-05-27 21:13:40 +0000173
174 if (mbr[i].system == 0xF || mbr[i].system == 0x5) {
175 struct partition_record ext[4];
176 uint8_t data1[512];
177 int j;
178
Max Reitz4c58e802014-11-18 12:21:19 +0100179 if ((ret = blk_read(blk, mbr[i].start_sector_abs, data1, 1)) < 0) {
Ryota Ozakicb7cf0e2010-05-03 06:50:25 +0900180 errno = -ret;
181 err(EXIT_FAILURE, "error while reading");
182 }
bellard7a5ca862008-05-27 21:13:40 +0000183
184 for (j = 0; j < 4; j++) {
185 read_partition(&data1[446 + 16 * j], &ext[j]);
Max Reitz453b07b2015-02-25 13:08:15 -0500186 if (!ext[j].system || !ext[j].nb_sectors_abs) {
bellard7a5ca862008-05-27 21:13:40 +0000187 continue;
Max Reitz453b07b2015-02-25 13:08:15 -0500188 }
bellard7a5ca862008-05-27 21:13:40 +0000189
190 if ((ext_partnum + j + 1) == partition) {
191 *offset = (uint64_t)ext[j].start_sector_abs << 9;
192 *size = (uint64_t)ext[j].nb_sectors_abs << 9;
193 return 0;
194 }
195 }
196 ext_partnum += 4;
197 } else if ((i + 1) == partition) {
198 *offset = (uint64_t)mbr[i].start_sector_abs << 9;
199 *size = (uint64_t)mbr[i].nb_sectors_abs << 9;
200 return 0;
201 }
202 }
203
Paolo Bonzini185b4332012-03-05 08:56:10 +0100204 return -ENOENT;
bellard7a5ca862008-05-27 21:13:40 +0000205}
206
Paolo Bonzinibb345112011-11-04 15:51:19 +0100207static void termsig_handler(int signum)
208{
Paolo Bonzini7860a382012-09-18 13:31:56 +0200209 state = TERMINATE;
Paolo Bonzinia61c6782011-09-12 17:28:11 +0200210 qemu_notify_event();
Paolo Bonzinibb345112011-11-04 15:51:19 +0100211}
212
Paolo Bonzini537b41f2014-02-17 14:43:51 +0100213static void combine_addr(char *buf, size_t len, const char* address,
214 uint16_t port)
215{
216 /* If the address-part contains a colon, it's an IPv6 IP so needs [] */
217 if (strstr(address, ":")) {
218 snprintf(buf, len, "[%s]:%u", address, port);
219 } else {
220 snprintf(buf, len, "%s:%u", address, port);
221 }
222}
223
224static int tcp_socket_incoming(const char *address, uint16_t port)
225{
226 char address_and_port[128];
227 Error *local_err = NULL;
228
229 combine_addr(address_and_port, 128, address, port);
230 int fd = inet_listen(address_and_port, NULL, 0, SOCK_STREAM, 0, &local_err);
231
232 if (local_err != NULL) {
Markus Armbruster565f65d2015-02-12 13:55:05 +0100233 error_report_err(local_err);
Paolo Bonzini537b41f2014-02-17 14:43:51 +0100234 }
235 return fd;
236}
237
238static int unix_socket_incoming(const char *path)
239{
240 Error *local_err = NULL;
241 int fd = unix_listen(path, NULL, 0, &local_err);
242
243 if (local_err != NULL) {
Markus Armbruster565f65d2015-02-12 13:55:05 +0100244 error_report_err(local_err);
Paolo Bonzini537b41f2014-02-17 14:43:51 +0100245 }
246 return fd;
247}
248
249static int unix_socket_outgoing(const char *path)
250{
251 Error *local_err = NULL;
252 int fd = unix_connect(path, &local_err);
253
254 if (local_err != NULL) {
Markus Armbruster565f65d2015-02-12 13:55:05 +0100255 error_report_err(local_err);
Paolo Bonzini537b41f2014-02-17 14:43:51 +0100256 }
257 return fd;
258}
259
Paolo Bonzinia517e882011-11-04 15:51:21 +0100260static void *show_parts(void *arg)
thscd831bd2008-07-03 10:23:51 +0000261{
Paolo Bonzinia6ac2312011-12-06 09:07:00 +0100262 char *device = arg;
Paolo Bonzinia517e882011-11-04 15:51:21 +0100263 int nbd;
thscd831bd2008-07-03 10:23:51 +0000264
Paolo Bonzinia517e882011-11-04 15:51:21 +0100265 /* linux just needs an open() to trigger
266 * the partition table update
267 * but remember to load the module with max_part != 0 :
268 * modprobe nbd max_part=63
269 */
270 nbd = open(device, O_RDWR);
Paolo Bonzinifc19f8a2012-03-07 11:05:34 +0100271 if (nbd >= 0) {
Paolo Bonzinia517e882011-11-04 15:51:21 +0100272 close(nbd);
thscd831bd2008-07-03 10:23:51 +0000273 }
Paolo Bonzinia517e882011-11-04 15:51:21 +0100274 return NULL;
275}
276
277static void *nbd_client_thread(void *arg)
278{
Paolo Bonzinia6ac2312011-12-06 09:07:00 +0100279 char *device = arg;
Paolo Bonzinia517e882011-11-04 15:51:21 +0100280 off_t size;
281 size_t blocksize;
282 uint32_t nbdflags;
Paolo Bonzinia6ac2312011-12-06 09:07:00 +0100283 int fd, sock;
Paolo Bonzinia517e882011-11-04 15:51:21 +0100284 int ret;
285 pthread_t show_parts_thread;
Max Reitz1ce52842015-01-26 21:02:59 -0500286 Error *local_error = NULL;
Paolo Bonzinia517e882011-11-04 15:51:21 +0100287
Stefan Hajnoczidc10e8b2012-01-05 13:16:07 +0000288 sock = unix_socket_outgoing(sockpath);
Paolo Bonzinifc19f8a2012-03-07 11:05:34 +0100289 if (sock < 0) {
Stefan Hajnoczidc10e8b2012-01-05 13:16:07 +0000290 goto out;
291 }
Paolo Bonzinia517e882011-11-04 15:51:21 +0100292
293 ret = nbd_receive_negotiate(sock, NULL, &nbdflags,
Max Reitz1ce52842015-01-26 21:02:59 -0500294 &size, &blocksize, &local_error);
Paolo Bonzinifc19f8a2012-03-07 11:05:34 +0100295 if (ret < 0) {
Max Reitz1ce52842015-01-26 21:02:59 -0500296 if (local_error) {
297 fprintf(stderr, "%s\n", error_get_pretty(local_error));
298 error_free(local_error);
299 }
Paolo Bonzini0c544d72014-03-14 18:10:54 +0100300 goto out_socket;
Paolo Bonzinia517e882011-11-04 15:51:21 +0100301 }
302
Paolo Bonzinia6ac2312011-12-06 09:07:00 +0100303 fd = open(device, O_RDWR);
Paolo Bonzinifc19f8a2012-03-07 11:05:34 +0100304 if (fd < 0) {
Paolo Bonzinia6ac2312011-12-06 09:07:00 +0100305 /* Linux-only, we can use %m in printf. */
Hani Benhabiles5672ee52014-05-13 00:35:16 +0100306 fprintf(stderr, "Failed to open %s: %m\n", device);
Paolo Bonzini0c544d72014-03-14 18:10:54 +0100307 goto out_socket;
Paolo Bonzinia6ac2312011-12-06 09:07:00 +0100308 }
309
Paolo Bonzinia517e882011-11-04 15:51:21 +0100310 ret = nbd_init(fd, sock, nbdflags, size, blocksize);
Paolo Bonzinifc19f8a2012-03-07 11:05:34 +0100311 if (ret < 0) {
Paolo Bonzini0c544d72014-03-14 18:10:54 +0100312 goto out_fd;
Paolo Bonzinia517e882011-11-04 15:51:21 +0100313 }
314
315 /* update partition table */
Paolo Bonzinia6ac2312011-12-06 09:07:00 +0100316 pthread_create(&show_parts_thread, NULL, show_parts, device);
Paolo Bonzinia517e882011-11-04 15:51:21 +0100317
Paolo Bonzinic1f8fdc2011-11-04 15:51:22 +0100318 if (verbose) {
319 fprintf(stderr, "NBD device %s is now connected to %s\n",
320 device, srcpath);
321 } else {
322 /* Close stderr so that the qemu-nbd process exits. */
323 dup2(STDOUT_FILENO, STDERR_FILENO);
324 }
Paolo Bonzinia517e882011-11-04 15:51:21 +0100325
326 ret = nbd_client(fd);
327 if (ret) {
Paolo Bonzini0c544d72014-03-14 18:10:54 +0100328 goto out_fd;
Paolo Bonzinia517e882011-11-04 15:51:21 +0100329 }
330 close(fd);
331 kill(getpid(), SIGTERM);
332 return (void *) EXIT_SUCCESS;
333
Paolo Bonzini0c544d72014-03-14 18:10:54 +0100334out_fd:
335 close(fd);
336out_socket:
337 closesocket(sock);
Paolo Bonzinia517e882011-11-04 15:51:21 +0100338out:
339 kill(getpid(), SIGTERM);
340 return (void *) EXIT_FAILURE;
thscd831bd2008-07-03 10:23:51 +0000341}
342
Paolo Bonzinia61c6782011-09-12 17:28:11 +0200343static int nbd_can_accept(void *opaque)
344{
345 return nb_fds < shared;
346}
347
Paolo Bonzini7860a382012-09-18 13:31:56 +0200348static void nbd_export_closed(NBDExport *exp)
349{
350 assert(state == TERMINATING);
351 state = TERMINATED;
352}
353
Paolo Bonzini1743b512011-09-19 14:33:23 +0200354static void nbd_client_closed(NBDClient *client)
Paolo Bonzinia61c6782011-09-12 17:28:11 +0200355{
Paolo Bonzini1743b512011-09-19 14:33:23 +0200356 nb_fds--;
Paolo Bonzini7860a382012-09-18 13:31:56 +0200357 if (nb_fds == 0 && !persistent && state == RUNNING) {
358 state = TERMINATE;
359 }
Paolo Bonzini1743b512011-09-19 14:33:23 +0200360 qemu_notify_event();
Paolo Bonzini7860a382012-09-18 13:31:56 +0200361 nbd_client_put(client);
Paolo Bonzinia61c6782011-09-12 17:28:11 +0200362}
363
364static void nbd_accept(void *opaque)
365{
366 int server_fd = (uintptr_t) opaque;
367 struct sockaddr_in addr;
368 socklen_t addr_len = sizeof(addr);
369
370 int fd = accept(server_fd, (struct sockaddr *)&addr, &addr_len);
Paolo Bonzini0c544d72014-03-14 18:10:54 +0100371 if (fd < 0) {
372 perror("accept");
373 return;
374 }
375
Paolo Bonzini7860a382012-09-18 13:31:56 +0200376 if (state >= TERMINATE) {
377 close(fd);
378 return;
379 }
380
Hani Benhabiles36af5992014-05-13 00:35:15 +0100381 if (nbd_client_new(exp, fd, nbd_client_closed)) {
Paolo Bonzinia61c6782011-09-12 17:28:11 +0200382 nb_fds++;
Hani Benhabiles36af5992014-05-13 00:35:15 +0100383 } else {
Hani Benhabiles27e5eae2014-05-31 22:39:42 +0100384 shutdown(fd, 2);
Hani Benhabiles36af5992014-05-13 00:35:15 +0100385 close(fd);
Paolo Bonzinia61c6782011-09-12 17:28:11 +0200386 }
387}
388
bellard7a5ca862008-05-27 21:13:40 +0000389int main(int argc, char **argv)
390{
Markus Armbruster26f54e92014-10-07 13:59:04 +0200391 BlockBackend *blk;
bellard7a5ca862008-05-27 21:13:40 +0000392 BlockDriverState *bs;
393 off_t dev_offset = 0;
Paolo Bonzinib90fb4b2011-09-08 17:24:54 +0200394 uint32_t nbdflags = 0;
thscd831bd2008-07-03 10:23:51 +0000395 bool disconnect = false;
bellard7a5ca862008-05-27 21:13:40 +0000396 const char *bindto = "0.0.0.0";
Paolo Bonzinia6ac2312011-12-06 09:07:00 +0100397 char *device = NULL;
Laurent Vivierc2e28722010-09-17 20:37:25 +0200398 int port = NBD_DEFAULT_PORT;
bellard7a5ca862008-05-27 21:13:40 +0000399 off_t fd_size;
Wenchao Xia8c116b02013-12-04 17:10:55 +0800400 QemuOpts *sn_opts = NULL;
401 const char *sn_id_or_name = NULL;
402 const char *sopt = "hVb:o:p:rsnP:c:dvk:e:f:tl:";
bellard7a5ca862008-05-27 21:13:40 +0000403 struct option lopt[] = {
Blue Swirl660f11b2009-07-31 21:16:51 +0000404 { "help", 0, NULL, 'h' },
405 { "version", 0, NULL, 'V' },
406 { "bind", 1, NULL, 'b' },
407 { "port", 1, NULL, 'p' },
408 { "socket", 1, NULL, 'k' },
409 { "offset", 1, NULL, 'o' },
410 { "read-only", 0, NULL, 'r' },
411 { "partition", 1, NULL, 'P' },
412 { "connect", 1, NULL, 'c' },
413 { "disconnect", 0, NULL, 'd' },
414 { "snapshot", 0, NULL, 's' },
Wenchao Xia8c116b02013-12-04 17:10:55 +0800415 { "load-snapshot", 1, NULL, 'l' },
Blue Swirl660f11b2009-07-31 21:16:51 +0000416 { "nocache", 0, NULL, 'n' },
Paolo Bonzini39a52352012-07-18 14:57:15 +0200417 { "cache", 1, NULL, QEMU_NBD_OPT_CACHE },
418#ifdef CONFIG_LINUX_AIO
419 { "aio", 1, NULL, QEMU_NBD_OPT_AIO },
420#endif
Paolo Bonzinided9d2d2013-02-08 14:06:13 +0100421 { "discard", 1, NULL, QEMU_NBD_OPT_DISCARD },
Peter Lievenb3838a42014-08-13 19:20:18 +0200422 { "detect-zeroes", 1, NULL, QEMU_NBD_OPT_DETECT_ZEROES },
Blue Swirl660f11b2009-07-31 21:16:51 +0000423 { "shared", 1, NULL, 'e' },
Daniel P. Berrangee6b63672013-03-19 11:20:20 +0000424 { "format", 1, NULL, 'f' },
Blue Swirl660f11b2009-07-31 21:16:51 +0000425 { "persistent", 0, NULL, 't' },
426 { "verbose", 0, NULL, 'v' },
427 { NULL, 0, NULL, 0 }
bellard7a5ca862008-05-27 21:13:40 +0000428 };
429 int ch;
430 int opt_ind = 0;
431 int li;
432 char *end;
Naphtali Spreif5edb012010-01-17 16:48:13 +0200433 int flags = BDRV_O_RDWR;
bellard7a5ca862008-05-27 21:13:40 +0000434 int partition = -1;
Max Reitz4fbec262015-02-05 13:58:19 -0500435 int ret = 0;
ths3b05a8e2008-07-03 12:45:02 +0000436 int fd;
Paolo Bonzini39a52352012-07-18 14:57:15 +0200437 bool seen_cache = false;
Paolo Bonzinided9d2d2013-02-08 14:06:13 +0100438 bool seen_discard = false;
Paolo Bonzini39a52352012-07-18 14:57:15 +0200439#ifdef CONFIG_LINUX_AIO
440 bool seen_aio = false;
441#endif
Paolo Bonzinia517e882011-11-04 15:51:21 +0100442 pthread_t client_thread;
Daniel P. Berrangee6b63672013-03-19 11:20:20 +0000443 const char *fmt = NULL;
Max Reitz34b5d2c2013-09-05 14:45:29 +0200444 Error *local_err = NULL;
Peter Lievenb3838a42014-08-13 19:20:18 +0200445 BlockdevDetectZeroesOptions detect_zeroes = BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF;
Max Reitz4fbec262015-02-05 13:58:19 -0500446 QDict *options = NULL;
bellard7a5ca862008-05-27 21:13:40 +0000447
Paolo Bonzinia517e882011-11-04 15:51:21 +0100448 /* The client thread uses SIGTERM to interrupt the server. A signal
449 * handler ensures that "qemu-nbd -v -c" exits with a nice status code.
450 */
Paolo Bonzinibb345112011-11-04 15:51:19 +0100451 struct sigaction sa_sigterm;
Paolo Bonzinibb345112011-11-04 15:51:19 +0100452 memset(&sa_sigterm, 0, sizeof(sa_sigterm));
453 sa_sigterm.sa_handler = termsig_handler;
454 sigaction(SIGTERM, &sa_sigterm, NULL);
Fam Zheng10f5bff2014-02-10 14:48:51 +0800455 qemu_init_exec_dir(argv[0]);
Paolo Bonzinibb345112011-11-04 15:51:19 +0100456
bellard7a5ca862008-05-27 21:13:40 +0000457 while ((ch = getopt_long(argc, argv, sopt, lopt, &opt_ind)) != -1) {
458 switch (ch) {
459 case 's':
ths2f726482008-07-03 11:47:46 +0000460 flags |= BDRV_O_SNAPSHOT;
461 break;
462 case 'n':
Paolo Bonzini39a52352012-07-18 14:57:15 +0200463 optarg = (char *) "none";
464 /* fallthrough */
465 case QEMU_NBD_OPT_CACHE:
466 if (seen_cache) {
467 errx(EXIT_FAILURE, "-n and --cache can only be specified once");
468 }
469 seen_cache = true;
470 if (bdrv_parse_cache_flags(optarg, &flags) == -1) {
471 errx(EXIT_FAILURE, "Invalid cache mode `%s'", optarg);
472 }
bellard7a5ca862008-05-27 21:13:40 +0000473 break;
Paolo Bonzini39a52352012-07-18 14:57:15 +0200474#ifdef CONFIG_LINUX_AIO
475 case QEMU_NBD_OPT_AIO:
476 if (seen_aio) {
477 errx(EXIT_FAILURE, "--aio can only be specified once");
478 }
479 seen_aio = true;
480 if (!strcmp(optarg, "native")) {
481 flags |= BDRV_O_NATIVE_AIO;
482 } else if (!strcmp(optarg, "threads")) {
483 /* this is the default */
484 } else {
485 errx(EXIT_FAILURE, "invalid aio mode `%s'", optarg);
486 }
487 break;
488#endif
Paolo Bonzinided9d2d2013-02-08 14:06:13 +0100489 case QEMU_NBD_OPT_DISCARD:
490 if (seen_discard) {
491 errx(EXIT_FAILURE, "--discard can only be specified once");
492 }
493 seen_discard = true;
494 if (bdrv_parse_discard_flags(optarg, &flags) == -1) {
495 errx(EXIT_FAILURE, "Invalid discard mode `%s'", optarg);
496 }
497 break;
Peter Lievenb3838a42014-08-13 19:20:18 +0200498 case QEMU_NBD_OPT_DETECT_ZEROES:
499 detect_zeroes =
500 qapi_enum_parse(BlockdevDetectZeroesOptions_lookup,
501 optarg,
502 BLOCKDEV_DETECT_ZEROES_OPTIONS_MAX,
503 BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF,
504 &local_err);
505 if (local_err) {
506 errx(EXIT_FAILURE, "Failed to parse detect_zeroes mode: %s",
507 error_get_pretty(local_err));
508 }
509 if (detect_zeroes == BLOCKDEV_DETECT_ZEROES_OPTIONS_UNMAP &&
510 !(flags & BDRV_O_UNMAP)) {
511 errx(EXIT_FAILURE, "setting detect-zeroes to unmap is not allowed "
512 "without setting discard operation to unmap");
513 }
514 break;
bellard7a5ca862008-05-27 21:13:40 +0000515 case 'b':
516 bindto = optarg;
517 break;
518 case 'p':
519 li = strtol(optarg, &end, 0);
520 if (*end) {
Ryota Ozakib6353be2010-03-20 15:23:23 +0900521 errx(EXIT_FAILURE, "Invalid port `%s'", optarg);
bellard7a5ca862008-05-27 21:13:40 +0000522 }
523 if (li < 1 || li > 65535) {
Ryota Ozakib6353be2010-03-20 15:23:23 +0900524 errx(EXIT_FAILURE, "Port out of range `%s'", optarg);
bellard7a5ca862008-05-27 21:13:40 +0000525 }
526 port = (uint16_t)li;
527 break;
528 case 'o':
529 dev_offset = strtoll (optarg, &end, 0);
530 if (*end) {
Ryota Ozakib6353be2010-03-20 15:23:23 +0900531 errx(EXIT_FAILURE, "Invalid offset `%s'", optarg);
bellard7a5ca862008-05-27 21:13:40 +0000532 }
533 if (dev_offset < 0) {
Ryota Ozakib6353be2010-03-20 15:23:23 +0900534 errx(EXIT_FAILURE, "Offset must be positive `%s'", optarg);
bellard7a5ca862008-05-27 21:13:40 +0000535 }
536 break;
Wenchao Xia8c116b02013-12-04 17:10:55 +0800537 case 'l':
538 if (strstart(optarg, SNAPSHOT_OPT_BASE, NULL)) {
539 sn_opts = qemu_opts_parse(&internal_snapshot_opts, optarg, 0);
540 if (!sn_opts) {
541 errx(EXIT_FAILURE, "Failed in parsing snapshot param `%s'",
542 optarg);
543 }
544 } else {
545 sn_id_or_name = optarg;
546 }
547 /* fall through */
bellard7a5ca862008-05-27 21:13:40 +0000548 case 'r':
Paolo Bonzinib90fb4b2011-09-08 17:24:54 +0200549 nbdflags |= NBD_FLAG_READ_ONLY;
Naphtali Sprei07108b22010-03-14 15:19:57 +0200550 flags &= ~BDRV_O_RDWR;
bellard7a5ca862008-05-27 21:13:40 +0000551 break;
552 case 'P':
553 partition = strtol(optarg, &end, 0);
Peter Lieven713cc672014-08-13 19:20:19 +0200554 if (*end) {
Ryota Ozakib6353be2010-03-20 15:23:23 +0900555 errx(EXIT_FAILURE, "Invalid partition `%s'", optarg);
Peter Lieven713cc672014-08-13 19:20:19 +0200556 }
557 if (partition < 1 || partition > 8) {
Ryota Ozakib6353be2010-03-20 15:23:23 +0900558 errx(EXIT_FAILURE, "Invalid partition %d", partition);
Peter Lieven713cc672014-08-13 19:20:19 +0200559 }
bellard7a5ca862008-05-27 21:13:40 +0000560 break;
thscd831bd2008-07-03 10:23:51 +0000561 case 'k':
Paolo Bonzinib32f6c22011-11-04 15:51:20 +0100562 sockpath = optarg;
Peter Lieven713cc672014-08-13 19:20:19 +0200563 if (sockpath[0] != '/') {
Ryota Ozakib6353be2010-03-20 15:23:23 +0900564 errx(EXIT_FAILURE, "socket path must be absolute\n");
Peter Lieven713cc672014-08-13 19:20:19 +0200565 }
thscd831bd2008-07-03 10:23:51 +0000566 break;
567 case 'd':
568 disconnect = true;
569 break;
570 case 'c':
571 device = optarg;
572 break;
ths3b05a8e2008-07-03 12:45:02 +0000573 case 'e':
574 shared = strtol(optarg, &end, 0);
575 if (*end) {
Ryota Ozakib6353be2010-03-20 15:23:23 +0900576 errx(EXIT_FAILURE, "Invalid shared device number '%s'", optarg);
ths3b05a8e2008-07-03 12:45:02 +0000577 }
578 if (shared < 1) {
Ryota Ozakib6353be2010-03-20 15:23:23 +0900579 errx(EXIT_FAILURE, "Shared device number must be greater than 0\n");
ths3b05a8e2008-07-03 12:45:02 +0000580 }
581 break;
Daniel P. Berrangee6b63672013-03-19 11:20:20 +0000582 case 'f':
583 fmt = optarg;
584 break;
Peter Lieven713cc672014-08-13 19:20:19 +0200585 case 't':
586 persistent = 1;
587 break;
bellard7a5ca862008-05-27 21:13:40 +0000588 case 'v':
589 verbose = 1;
590 break;
591 case 'V':
592 version(argv[0]);
593 exit(0);
594 break;
595 case 'h':
596 usage(argv[0]);
597 exit(0);
598 break;
599 case '?':
Ryota Ozakib6353be2010-03-20 15:23:23 +0900600 errx(EXIT_FAILURE, "Try `%s --help' for more information.",
bellard7a5ca862008-05-27 21:13:40 +0000601 argv[0]);
602 }
603 }
604
605 if ((argc - optind) != 1) {
Ryota Ozakib6353be2010-03-20 15:23:23 +0900606 errx(EXIT_FAILURE, "Invalid number of argument.\n"
bellard7a5ca862008-05-27 21:13:40 +0000607 "Try `%s --help' for more information.",
608 argv[0]);
609 }
610
thscd831bd2008-07-03 10:23:51 +0000611 if (disconnect) {
612 fd = open(argv[optind], O_RDWR);
Paolo Bonzinifc19f8a2012-03-07 11:05:34 +0100613 if (fd < 0) {
Ryota Ozakicb7cf0e2010-05-03 06:50:25 +0900614 err(EXIT_FAILURE, "Cannot open %s", argv[optind]);
Paolo Bonzinifc19f8a2012-03-07 11:05:34 +0100615 }
thscd831bd2008-07-03 10:23:51 +0000616 nbd_disconnect(fd);
617
618 close(fd);
619
620 printf("%s disconnected\n", argv[optind]);
621
Peter Lieven713cc672014-08-13 19:20:19 +0200622 return 0;
thscd831bd2008-07-03 10:23:51 +0000623 }
624
Paolo Bonzinic1f8fdc2011-11-04 15:51:22 +0100625 if (device && !verbose) {
626 int stderr_fd[2];
627 pid_t pid;
628 int ret;
629
Paolo Bonzinifc19f8a2012-03-07 11:05:34 +0100630 if (qemu_pipe(stderr_fd) < 0) {
Paolo Bonzinic1f8fdc2011-11-04 15:51:22 +0100631 err(EXIT_FAILURE, "Error setting up communication pipe");
632 }
633
634 /* Now daemonize, but keep a communication channel open to
635 * print errors and exit with the proper status code.
636 */
637 pid = fork();
Max Reitz70d47392015-02-25 13:08:22 -0500638 if (pid < 0) {
639 err(EXIT_FAILURE, "Failed to fork");
640 } else if (pid == 0) {
Paolo Bonzinic1f8fdc2011-11-04 15:51:22 +0100641 close(stderr_fd[0]);
Michael Tokarev9faf31b2012-01-16 18:37:44 +0400642 ret = qemu_daemon(1, 0);
Paolo Bonzinic1f8fdc2011-11-04 15:51:22 +0100643
644 /* Temporarily redirect stderr to the parent's pipe... */
645 dup2(stderr_fd[1], STDERR_FILENO);
Paolo Bonzinifc19f8a2012-03-07 11:05:34 +0100646 if (ret < 0) {
Paolo Bonzinic1f8fdc2011-11-04 15:51:22 +0100647 err(EXIT_FAILURE, "Failed to daemonize");
648 }
649
650 /* ... close the descriptor we inherited and go on. */
651 close(stderr_fd[1]);
652 } else {
653 bool errors = false;
654 char *buf;
655
656 /* In the parent. Print error messages from the child until
657 * it closes the pipe.
658 */
659 close(stderr_fd[1]);
660 buf = g_malloc(1024);
661 while ((ret = read(stderr_fd[0], buf, 1024)) > 0) {
662 errors = true;
663 ret = qemu_write_full(STDERR_FILENO, buf, ret);
Paolo Bonzinifc19f8a2012-03-07 11:05:34 +0100664 if (ret < 0) {
Paolo Bonzinic1f8fdc2011-11-04 15:51:22 +0100665 exit(EXIT_FAILURE);
666 }
667 }
Paolo Bonzinifc19f8a2012-03-07 11:05:34 +0100668 if (ret < 0) {
Paolo Bonzinic1f8fdc2011-11-04 15:51:22 +0100669 err(EXIT_FAILURE, "Cannot read from daemon");
670 }
671
672 /* Usually the daemon should not print any message.
673 * Exit with zero status in that case.
674 */
675 exit(errors);
676 }
677 }
678
Paolo Bonzinia6ac2312011-12-06 09:07:00 +0100679 if (device != NULL && sockpath == NULL) {
680 sockpath = g_malloc(128);
681 snprintf(sockpath, 128, SOCKET_PATH, basename(device));
thscd831bd2008-07-03 10:23:51 +0000682 }
683
Chrysostomos Nanakos2f78e492014-09-18 14:30:49 +0300684 if (qemu_init_main_loop(&local_err)) {
Markus Armbruster565f65d2015-02-12 13:55:05 +0100685 error_report_err(local_err);
Chrysostomos Nanakos2f78e492014-09-18 14:30:49 +0300686 exit(EXIT_FAILURE);
687 }
Paolo Bonzini802ddc32011-11-04 15:51:24 +0100688 bdrv_init();
689 atexit(bdrv_close_all);
690
Daniel P. Berrangee6b63672013-03-19 11:20:20 +0000691 if (fmt) {
Max Reitz4fbec262015-02-05 13:58:19 -0500692 options = qdict_new();
693 qdict_put(options, "driver", qstring_from_str(fmt));
Daniel P. Berrangee6b63672013-03-19 11:20:20 +0000694 }
695
Paolo Bonzini802ddc32011-11-04 15:51:24 +0100696 srcpath = argv[optind];
Max Reitz4fbec262015-02-05 13:58:19 -0500697 blk = blk_new_open("hda", srcpath, NULL, options, flags, &local_err);
698 if (!blk) {
699 errx(EXIT_FAILURE, "Failed to blk_new_open '%s': %s", argv[optind],
700 error_get_pretty(local_err));
Paolo Bonzini802ddc32011-11-04 15:51:24 +0100701 }
Max Reitz4fbec262015-02-05 13:58:19 -0500702 bs = blk_bs(blk);
Paolo Bonzini802ddc32011-11-04 15:51:24 +0100703
Wenchao Xia8c116b02013-12-04 17:10:55 +0800704 if (sn_opts) {
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),
708 &local_err);
709 } else if (sn_id_or_name) {
710 ret = bdrv_snapshot_load_tmp_by_id_or_name(bs, sn_id_or_name,
711 &local_err);
712 }
713 if (ret < 0) {
714 errno = -ret;
715 err(EXIT_FAILURE,
716 "Failed to load snapshot: %s",
717 error_get_pretty(local_err));
718 }
719
Peter Lievenb3838a42014-08-13 19:20:18 +0200720 bs->detect_zeroes = detect_zeroes;
Max Reitz4c58e802014-11-18 12:21:19 +0100721 fd_size = blk_getlength(blk);
Max Reitz98f44bb2015-02-25 13:08:21 -0500722 if (fd_size < 0) {
723 errx(EXIT_FAILURE, "Failed to determine the image length: %s",
724 strerror(-fd_size));
725 }
Paolo Bonzini802ddc32011-11-04 15:51:24 +0100726
Paolo Bonzini185b4332012-03-05 08:56:10 +0100727 if (partition != -1) {
Max Reitz4c58e802014-11-18 12:21:19 +0100728 ret = find_partition(blk, partition, &dev_offset, &fd_size);
Paolo Bonzini185b4332012-03-05 08:56:10 +0100729 if (ret < 0) {
730 errno = -ret;
731 err(EXIT_FAILURE, "Could not find partition %d", partition);
732 }
Paolo Bonzini802ddc32011-11-04 15:51:24 +0100733 }
734
Max Reitz98f44bb2015-02-25 13:08:21 -0500735 exp = nbd_export_new(blk, dev_offset, fd_size, nbdflags, nbd_export_closed,
736 &local_err);
737 if (!exp) {
738 errx(EXIT_FAILURE, "%s", error_get_pretty(local_err));
739 }
ths3b05a8e2008-07-03 12:45:02 +0000740
Paolo Bonzinib32f6c22011-11-04 15:51:20 +0100741 if (sockpath) {
Paolo Bonzinia61c6782011-09-12 17:28:11 +0200742 fd = unix_socket_incoming(sockpath);
thscd831bd2008-07-03 10:23:51 +0000743 } else {
Paolo Bonzinia61c6782011-09-12 17:28:11 +0200744 fd = tcp_socket_incoming(bindto, port);
thscd831bd2008-07-03 10:23:51 +0000745 }
746
Paolo Bonzinifc19f8a2012-03-07 11:05:34 +0100747 if (fd < 0) {
bellard7a5ca862008-05-27 21:13:40 +0000748 return 1;
Paolo Bonzinia61c6782011-09-12 17:28:11 +0200749 }
Paolo Bonzinif1ef5552011-11-04 15:51:23 +0100750
751 if (device) {
752 int ret;
753
Paolo Bonzinia6ac2312011-12-06 09:07:00 +0100754 ret = pthread_create(&client_thread, NULL, nbd_client_thread, device);
Paolo Bonzinif1ef5552011-11-04 15:51:23 +0100755 if (ret != 0) {
756 errx(EXIT_FAILURE, "Failed to create client thread: %s",
757 strerror(ret));
758 }
759 } else {
760 /* Shut up GCC warnings. */
761 memset(&client_thread, 0, sizeof(client_thread));
762 }
763
Paolo Bonzinia61c6782011-09-12 17:28:11 +0200764 qemu_set_fd_handler2(fd, nbd_can_accept, nbd_accept, NULL,
765 (void *)(uintptr_t)fd);
bellard7a5ca862008-05-27 21:13:40 +0000766
Michael Tokarev9faf31b2012-01-16 18:37:44 +0400767 /* now when the initialization is (almost) complete, chdir("/")
768 * to free any busy filesystems */
769 if (chdir("/") < 0) {
770 err(EXIT_FAILURE, "Could not chdir to root directory");
771 }
772
Paolo Bonzini7860a382012-09-18 13:31:56 +0200773 state = RUNNING;
ths3b05a8e2008-07-03 12:45:02 +0000774 do {
Paolo Bonzinia61c6782011-09-12 17:28:11 +0200775 main_loop_wait(false);
Paolo Bonzini7860a382012-09-18 13:31:56 +0200776 if (state == TERMINATE) {
777 state = TERMINATING;
778 nbd_export_close(exp);
779 nbd_export_put(exp);
780 exp = NULL;
781 }
782 } while (state != TERMINATED);
ths3b05a8e2008-07-03 12:45:02 +0000783
Markus Armbruster26f54e92014-10-07 13:59:04 +0200784 blk_unref(blk);
Paolo Bonzinib32f6c22011-11-04 15:51:20 +0100785 if (sockpath) {
786 unlink(sockpath);
787 }
bellard7a5ca862008-05-27 21:13:40 +0000788
Markus Armbrusterfbf28a42014-09-29 16:07:55 +0200789 qemu_opts_del(sn_opts);
Wenchao Xia8c116b02013-12-04 17:10:55 +0800790
Paolo Bonzinia517e882011-11-04 15:51:21 +0100791 if (device) {
792 void *ret;
793 pthread_join(client_thread, &ret);
794 exit(ret != NULL);
795 } else {
796 exit(EXIT_SUCCESS);
797 }
bellard7a5ca862008-05-27 21:13:40 +0000798}