blob: 2ba2d4c5bd526da3a88194cc036beb5f53469e27 [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
170 if (!mbr[i].nb_sectors_abs)
171 continue;
172
173 if (mbr[i].system == 0xF || mbr[i].system == 0x5) {
174 struct partition_record ext[4];
175 uint8_t data1[512];
176 int j;
177
Max Reitz4c58e802014-11-18 12:21:19 +0100178 if ((ret = blk_read(blk, mbr[i].start_sector_abs, data1, 1)) < 0) {
Ryota Ozakicb7cf0e2010-05-03 06:50:25 +0900179 errno = -ret;
180 err(EXIT_FAILURE, "error while reading");
181 }
bellard7a5ca862008-05-27 21:13:40 +0000182
183 for (j = 0; j < 4; j++) {
184 read_partition(&data1[446 + 16 * j], &ext[j]);
185 if (!ext[j].nb_sectors_abs)
186 continue;
187
188 if ((ext_partnum + j + 1) == partition) {
189 *offset = (uint64_t)ext[j].start_sector_abs << 9;
190 *size = (uint64_t)ext[j].nb_sectors_abs << 9;
191 return 0;
192 }
193 }
194 ext_partnum += 4;
195 } else if ((i + 1) == partition) {
196 *offset = (uint64_t)mbr[i].start_sector_abs << 9;
197 *size = (uint64_t)mbr[i].nb_sectors_abs << 9;
198 return 0;
199 }
200 }
201
Paolo Bonzini185b4332012-03-05 08:56:10 +0100202 return -ENOENT;
bellard7a5ca862008-05-27 21:13:40 +0000203}
204
Paolo Bonzinibb345112011-11-04 15:51:19 +0100205static void termsig_handler(int signum)
206{
Paolo Bonzini7860a382012-09-18 13:31:56 +0200207 state = TERMINATE;
Paolo Bonzinia61c6782011-09-12 17:28:11 +0200208 qemu_notify_event();
Paolo Bonzinibb345112011-11-04 15:51:19 +0100209}
210
Paolo Bonzini537b41f2014-02-17 14:43:51 +0100211static void combine_addr(char *buf, size_t len, const char* address,
212 uint16_t port)
213{
214 /* If the address-part contains a colon, it's an IPv6 IP so needs [] */
215 if (strstr(address, ":")) {
216 snprintf(buf, len, "[%s]:%u", address, port);
217 } else {
218 snprintf(buf, len, "%s:%u", address, port);
219 }
220}
221
222static int tcp_socket_incoming(const char *address, uint16_t port)
223{
224 char address_and_port[128];
225 Error *local_err = NULL;
226
227 combine_addr(address_and_port, 128, address, port);
228 int fd = inet_listen(address_and_port, NULL, 0, SOCK_STREAM, 0, &local_err);
229
230 if (local_err != NULL) {
Markus Armbruster565f65d2015-02-12 13:55:05 +0100231 error_report_err(local_err);
Paolo Bonzini537b41f2014-02-17 14:43:51 +0100232 }
233 return fd;
234}
235
236static int unix_socket_incoming(const char *path)
237{
238 Error *local_err = NULL;
239 int fd = unix_listen(path, NULL, 0, &local_err);
240
241 if (local_err != NULL) {
Markus Armbruster565f65d2015-02-12 13:55:05 +0100242 error_report_err(local_err);
Paolo Bonzini537b41f2014-02-17 14:43:51 +0100243 }
244 return fd;
245}
246
247static int unix_socket_outgoing(const char *path)
248{
249 Error *local_err = NULL;
250 int fd = unix_connect(path, &local_err);
251
252 if (local_err != NULL) {
Markus Armbruster565f65d2015-02-12 13:55:05 +0100253 error_report_err(local_err);
Paolo Bonzini537b41f2014-02-17 14:43:51 +0100254 }
255 return fd;
256}
257
Paolo Bonzinia517e882011-11-04 15:51:21 +0100258static void *show_parts(void *arg)
thscd831bd2008-07-03 10:23:51 +0000259{
Paolo Bonzinia6ac2312011-12-06 09:07:00 +0100260 char *device = arg;
Paolo Bonzinia517e882011-11-04 15:51:21 +0100261 int nbd;
thscd831bd2008-07-03 10:23:51 +0000262
Paolo Bonzinia517e882011-11-04 15:51:21 +0100263 /* linux just needs an open() to trigger
264 * the partition table update
265 * but remember to load the module with max_part != 0 :
266 * modprobe nbd max_part=63
267 */
268 nbd = open(device, O_RDWR);
Paolo Bonzinifc19f8a2012-03-07 11:05:34 +0100269 if (nbd >= 0) {
Paolo Bonzinia517e882011-11-04 15:51:21 +0100270 close(nbd);
thscd831bd2008-07-03 10:23:51 +0000271 }
Paolo Bonzinia517e882011-11-04 15:51:21 +0100272 return NULL;
273}
274
275static void *nbd_client_thread(void *arg)
276{
Paolo Bonzinia6ac2312011-12-06 09:07:00 +0100277 char *device = arg;
Paolo Bonzinia517e882011-11-04 15:51:21 +0100278 off_t size;
279 size_t blocksize;
280 uint32_t nbdflags;
Paolo Bonzinia6ac2312011-12-06 09:07:00 +0100281 int fd, sock;
Paolo Bonzinia517e882011-11-04 15:51:21 +0100282 int ret;
283 pthread_t show_parts_thread;
Max Reitz1ce52842015-01-26 21:02:59 -0500284 Error *local_error = NULL;
Paolo Bonzinia517e882011-11-04 15:51:21 +0100285
Stefan Hajnoczidc10e8b2012-01-05 13:16:07 +0000286 sock = unix_socket_outgoing(sockpath);
Paolo Bonzinifc19f8a2012-03-07 11:05:34 +0100287 if (sock < 0) {
Stefan Hajnoczidc10e8b2012-01-05 13:16:07 +0000288 goto out;
289 }
Paolo Bonzinia517e882011-11-04 15:51:21 +0100290
291 ret = nbd_receive_negotiate(sock, NULL, &nbdflags,
Max Reitz1ce52842015-01-26 21:02:59 -0500292 &size, &blocksize, &local_error);
Paolo Bonzinifc19f8a2012-03-07 11:05:34 +0100293 if (ret < 0) {
Max Reitz1ce52842015-01-26 21:02:59 -0500294 if (local_error) {
295 fprintf(stderr, "%s\n", error_get_pretty(local_error));
296 error_free(local_error);
297 }
Paolo Bonzini0c544d72014-03-14 18:10:54 +0100298 goto out_socket;
Paolo Bonzinia517e882011-11-04 15:51:21 +0100299 }
300
Paolo Bonzinia6ac2312011-12-06 09:07:00 +0100301 fd = open(device, O_RDWR);
Paolo Bonzinifc19f8a2012-03-07 11:05:34 +0100302 if (fd < 0) {
Paolo Bonzinia6ac2312011-12-06 09:07:00 +0100303 /* Linux-only, we can use %m in printf. */
Hani Benhabiles5672ee52014-05-13 00:35:16 +0100304 fprintf(stderr, "Failed to open %s: %m\n", device);
Paolo Bonzini0c544d72014-03-14 18:10:54 +0100305 goto out_socket;
Paolo Bonzinia6ac2312011-12-06 09:07:00 +0100306 }
307
Paolo Bonzinia517e882011-11-04 15:51:21 +0100308 ret = nbd_init(fd, sock, nbdflags, size, blocksize);
Paolo Bonzinifc19f8a2012-03-07 11:05:34 +0100309 if (ret < 0) {
Paolo Bonzini0c544d72014-03-14 18:10:54 +0100310 goto out_fd;
Paolo Bonzinia517e882011-11-04 15:51:21 +0100311 }
312
313 /* update partition table */
Paolo Bonzinia6ac2312011-12-06 09:07:00 +0100314 pthread_create(&show_parts_thread, NULL, show_parts, device);
Paolo Bonzinia517e882011-11-04 15:51:21 +0100315
Paolo Bonzinic1f8fdc2011-11-04 15:51:22 +0100316 if (verbose) {
317 fprintf(stderr, "NBD device %s is now connected to %s\n",
318 device, srcpath);
319 } else {
320 /* Close stderr so that the qemu-nbd process exits. */
321 dup2(STDOUT_FILENO, STDERR_FILENO);
322 }
Paolo Bonzinia517e882011-11-04 15:51:21 +0100323
324 ret = nbd_client(fd);
325 if (ret) {
Paolo Bonzini0c544d72014-03-14 18:10:54 +0100326 goto out_fd;
Paolo Bonzinia517e882011-11-04 15:51:21 +0100327 }
328 close(fd);
329 kill(getpid(), SIGTERM);
330 return (void *) EXIT_SUCCESS;
331
Paolo Bonzini0c544d72014-03-14 18:10:54 +0100332out_fd:
333 close(fd);
334out_socket:
335 closesocket(sock);
Paolo Bonzinia517e882011-11-04 15:51:21 +0100336out:
337 kill(getpid(), SIGTERM);
338 return (void *) EXIT_FAILURE;
thscd831bd2008-07-03 10:23:51 +0000339}
340
Paolo Bonzinia61c6782011-09-12 17:28:11 +0200341static int nbd_can_accept(void *opaque)
342{
343 return nb_fds < shared;
344}
345
Paolo Bonzini7860a382012-09-18 13:31:56 +0200346static void nbd_export_closed(NBDExport *exp)
347{
348 assert(state == TERMINATING);
349 state = TERMINATED;
350}
351
Paolo Bonzini1743b512011-09-19 14:33:23 +0200352static void nbd_client_closed(NBDClient *client)
Paolo Bonzinia61c6782011-09-12 17:28:11 +0200353{
Paolo Bonzini1743b512011-09-19 14:33:23 +0200354 nb_fds--;
Paolo Bonzini7860a382012-09-18 13:31:56 +0200355 if (nb_fds == 0 && !persistent && state == RUNNING) {
356 state = TERMINATE;
357 }
Paolo Bonzini1743b512011-09-19 14:33:23 +0200358 qemu_notify_event();
Paolo Bonzini7860a382012-09-18 13:31:56 +0200359 nbd_client_put(client);
Paolo Bonzinia61c6782011-09-12 17:28:11 +0200360}
361
362static void nbd_accept(void *opaque)
363{
364 int server_fd = (uintptr_t) opaque;
365 struct sockaddr_in addr;
366 socklen_t addr_len = sizeof(addr);
367
368 int fd = accept(server_fd, (struct sockaddr *)&addr, &addr_len);
Paolo Bonzini0c544d72014-03-14 18:10:54 +0100369 if (fd < 0) {
370 perror("accept");
371 return;
372 }
373
Paolo Bonzini7860a382012-09-18 13:31:56 +0200374 if (state >= TERMINATE) {
375 close(fd);
376 return;
377 }
378
Hani Benhabiles36af5992014-05-13 00:35:15 +0100379 if (nbd_client_new(exp, fd, nbd_client_closed)) {
Paolo Bonzinia61c6782011-09-12 17:28:11 +0200380 nb_fds++;
Hani Benhabiles36af5992014-05-13 00:35:15 +0100381 } else {
Hani Benhabiles27e5eae2014-05-31 22:39:42 +0100382 shutdown(fd, 2);
Hani Benhabiles36af5992014-05-13 00:35:15 +0100383 close(fd);
Paolo Bonzinia61c6782011-09-12 17:28:11 +0200384 }
385}
386
bellard7a5ca862008-05-27 21:13:40 +0000387int main(int argc, char **argv)
388{
Markus Armbruster26f54e92014-10-07 13:59:04 +0200389 BlockBackend *blk;
bellard7a5ca862008-05-27 21:13:40 +0000390 BlockDriverState *bs;
Daniel P. Berrangee6b63672013-03-19 11:20:20 +0000391 BlockDriver *drv;
bellard7a5ca862008-05-27 21:13:40 +0000392 off_t dev_offset = 0;
Paolo Bonzinib90fb4b2011-09-08 17:24:54 +0200393 uint32_t nbdflags = 0;
thscd831bd2008-07-03 10:23:51 +0000394 bool disconnect = false;
bellard7a5ca862008-05-27 21:13:40 +0000395 const char *bindto = "0.0.0.0";
Paolo Bonzinia6ac2312011-12-06 09:07:00 +0100396 char *device = NULL;
Laurent Vivierc2e28722010-09-17 20:37:25 +0200397 int port = NBD_DEFAULT_PORT;
bellard7a5ca862008-05-27 21:13:40 +0000398 off_t fd_size;
Wenchao Xia8c116b02013-12-04 17:10:55 +0800399 QemuOpts *sn_opts = NULL;
400 const char *sn_id_or_name = NULL;
401 const char *sopt = "hVb:o:p:rsnP:c:dvk:e:f:tl:";
bellard7a5ca862008-05-27 21:13:40 +0000402 struct option lopt[] = {
Blue Swirl660f11b2009-07-31 21:16:51 +0000403 { "help", 0, NULL, 'h' },
404 { "version", 0, NULL, 'V' },
405 { "bind", 1, NULL, 'b' },
406 { "port", 1, NULL, 'p' },
407 { "socket", 1, NULL, 'k' },
408 { "offset", 1, NULL, 'o' },
409 { "read-only", 0, NULL, 'r' },
410 { "partition", 1, NULL, 'P' },
411 { "connect", 1, NULL, 'c' },
412 { "disconnect", 0, NULL, 'd' },
413 { "snapshot", 0, NULL, 's' },
Wenchao Xia8c116b02013-12-04 17:10:55 +0800414 { "load-snapshot", 1, NULL, 'l' },
Blue Swirl660f11b2009-07-31 21:16:51 +0000415 { "nocache", 0, NULL, 'n' },
Paolo Bonzini39a52352012-07-18 14:57:15 +0200416 { "cache", 1, NULL, QEMU_NBD_OPT_CACHE },
417#ifdef CONFIG_LINUX_AIO
418 { "aio", 1, NULL, QEMU_NBD_OPT_AIO },
419#endif
Paolo Bonzinided9d2d2013-02-08 14:06:13 +0100420 { "discard", 1, NULL, QEMU_NBD_OPT_DISCARD },
Peter Lievenb3838a42014-08-13 19:20:18 +0200421 { "detect-zeroes", 1, NULL, QEMU_NBD_OPT_DETECT_ZEROES },
Blue Swirl660f11b2009-07-31 21:16:51 +0000422 { "shared", 1, NULL, 'e' },
Daniel P. Berrangee6b63672013-03-19 11:20:20 +0000423 { "format", 1, NULL, 'f' },
Blue Swirl660f11b2009-07-31 21:16:51 +0000424 { "persistent", 0, NULL, 't' },
425 { "verbose", 0, NULL, 'v' },
426 { NULL, 0, NULL, 0 }
bellard7a5ca862008-05-27 21:13:40 +0000427 };
428 int ch;
429 int opt_ind = 0;
430 int li;
431 char *end;
Naphtali Spreif5edb012010-01-17 16:48:13 +0200432 int flags = BDRV_O_RDWR;
bellard7a5ca862008-05-27 21:13:40 +0000433 int partition = -1;
thscd831bd2008-07-03 10:23:51 +0000434 int ret;
ths3b05a8e2008-07-03 12:45:02 +0000435 int fd;
Paolo Bonzini39a52352012-07-18 14:57:15 +0200436 bool seen_cache = false;
Paolo Bonzinided9d2d2013-02-08 14:06:13 +0100437 bool seen_discard = false;
Paolo Bonzini39a52352012-07-18 14:57:15 +0200438#ifdef CONFIG_LINUX_AIO
439 bool seen_aio = false;
440#endif
Paolo Bonzinia517e882011-11-04 15:51:21 +0100441 pthread_t client_thread;
Daniel P. Berrangee6b63672013-03-19 11:20:20 +0000442 const char *fmt = NULL;
Max Reitz34b5d2c2013-09-05 14:45:29 +0200443 Error *local_err = NULL;
Peter Lievenb3838a42014-08-13 19:20:18 +0200444 BlockdevDetectZeroesOptions detect_zeroes = BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF;
bellard7a5ca862008-05-27 21:13:40 +0000445
Paolo Bonzinia517e882011-11-04 15:51:21 +0100446 /* The client thread uses SIGTERM to interrupt the server. A signal
447 * handler ensures that "qemu-nbd -v -c" exits with a nice status code.
448 */
Paolo Bonzinibb345112011-11-04 15:51:19 +0100449 struct sigaction sa_sigterm;
Paolo Bonzinibb345112011-11-04 15:51:19 +0100450 memset(&sa_sigterm, 0, sizeof(sa_sigterm));
451 sa_sigterm.sa_handler = termsig_handler;
452 sigaction(SIGTERM, &sa_sigterm, NULL);
Fam Zheng10f5bff2014-02-10 14:48:51 +0800453 qemu_init_exec_dir(argv[0]);
Paolo Bonzinibb345112011-11-04 15:51:19 +0100454
bellard7a5ca862008-05-27 21:13:40 +0000455 while ((ch = getopt_long(argc, argv, sopt, lopt, &opt_ind)) != -1) {
456 switch (ch) {
457 case 's':
ths2f726482008-07-03 11:47:46 +0000458 flags |= BDRV_O_SNAPSHOT;
459 break;
460 case 'n':
Paolo Bonzini39a52352012-07-18 14:57:15 +0200461 optarg = (char *) "none";
462 /* fallthrough */
463 case QEMU_NBD_OPT_CACHE:
464 if (seen_cache) {
465 errx(EXIT_FAILURE, "-n and --cache can only be specified once");
466 }
467 seen_cache = true;
468 if (bdrv_parse_cache_flags(optarg, &flags) == -1) {
469 errx(EXIT_FAILURE, "Invalid cache mode `%s'", optarg);
470 }
bellard7a5ca862008-05-27 21:13:40 +0000471 break;
Paolo Bonzini39a52352012-07-18 14:57:15 +0200472#ifdef CONFIG_LINUX_AIO
473 case QEMU_NBD_OPT_AIO:
474 if (seen_aio) {
475 errx(EXIT_FAILURE, "--aio can only be specified once");
476 }
477 seen_aio = true;
478 if (!strcmp(optarg, "native")) {
479 flags |= BDRV_O_NATIVE_AIO;
480 } else if (!strcmp(optarg, "threads")) {
481 /* this is the default */
482 } else {
483 errx(EXIT_FAILURE, "invalid aio mode `%s'", optarg);
484 }
485 break;
486#endif
Paolo Bonzinided9d2d2013-02-08 14:06:13 +0100487 case QEMU_NBD_OPT_DISCARD:
488 if (seen_discard) {
489 errx(EXIT_FAILURE, "--discard can only be specified once");
490 }
491 seen_discard = true;
492 if (bdrv_parse_discard_flags(optarg, &flags) == -1) {
493 errx(EXIT_FAILURE, "Invalid discard mode `%s'", optarg);
494 }
495 break;
Peter Lievenb3838a42014-08-13 19:20:18 +0200496 case QEMU_NBD_OPT_DETECT_ZEROES:
497 detect_zeroes =
498 qapi_enum_parse(BlockdevDetectZeroesOptions_lookup,
499 optarg,
500 BLOCKDEV_DETECT_ZEROES_OPTIONS_MAX,
501 BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF,
502 &local_err);
503 if (local_err) {
504 errx(EXIT_FAILURE, "Failed to parse detect_zeroes mode: %s",
505 error_get_pretty(local_err));
506 }
507 if (detect_zeroes == BLOCKDEV_DETECT_ZEROES_OPTIONS_UNMAP &&
508 !(flags & BDRV_O_UNMAP)) {
509 errx(EXIT_FAILURE, "setting detect-zeroes to unmap is not allowed "
510 "without setting discard operation to unmap");
511 }
512 break;
bellard7a5ca862008-05-27 21:13:40 +0000513 case 'b':
514 bindto = optarg;
515 break;
516 case 'p':
517 li = strtol(optarg, &end, 0);
518 if (*end) {
Ryota Ozakib6353be2010-03-20 15:23:23 +0900519 errx(EXIT_FAILURE, "Invalid port `%s'", optarg);
bellard7a5ca862008-05-27 21:13:40 +0000520 }
521 if (li < 1 || li > 65535) {
Ryota Ozakib6353be2010-03-20 15:23:23 +0900522 errx(EXIT_FAILURE, "Port out of range `%s'", optarg);
bellard7a5ca862008-05-27 21:13:40 +0000523 }
524 port = (uint16_t)li;
525 break;
526 case 'o':
527 dev_offset = strtoll (optarg, &end, 0);
528 if (*end) {
Ryota Ozakib6353be2010-03-20 15:23:23 +0900529 errx(EXIT_FAILURE, "Invalid offset `%s'", optarg);
bellard7a5ca862008-05-27 21:13:40 +0000530 }
531 if (dev_offset < 0) {
Ryota Ozakib6353be2010-03-20 15:23:23 +0900532 errx(EXIT_FAILURE, "Offset must be positive `%s'", optarg);
bellard7a5ca862008-05-27 21:13:40 +0000533 }
534 break;
Wenchao Xia8c116b02013-12-04 17:10:55 +0800535 case 'l':
536 if (strstart(optarg, SNAPSHOT_OPT_BASE, NULL)) {
537 sn_opts = qemu_opts_parse(&internal_snapshot_opts, optarg, 0);
538 if (!sn_opts) {
539 errx(EXIT_FAILURE, "Failed in parsing snapshot param `%s'",
540 optarg);
541 }
542 } else {
543 sn_id_or_name = optarg;
544 }
545 /* fall through */
bellard7a5ca862008-05-27 21:13:40 +0000546 case 'r':
Paolo Bonzinib90fb4b2011-09-08 17:24:54 +0200547 nbdflags |= NBD_FLAG_READ_ONLY;
Naphtali Sprei07108b22010-03-14 15:19:57 +0200548 flags &= ~BDRV_O_RDWR;
bellard7a5ca862008-05-27 21:13:40 +0000549 break;
550 case 'P':
551 partition = strtol(optarg, &end, 0);
Peter Lieven713cc672014-08-13 19:20:19 +0200552 if (*end) {
Ryota Ozakib6353be2010-03-20 15:23:23 +0900553 errx(EXIT_FAILURE, "Invalid partition `%s'", optarg);
Peter Lieven713cc672014-08-13 19:20:19 +0200554 }
555 if (partition < 1 || partition > 8) {
Ryota Ozakib6353be2010-03-20 15:23:23 +0900556 errx(EXIT_FAILURE, "Invalid partition %d", partition);
Peter Lieven713cc672014-08-13 19:20:19 +0200557 }
bellard7a5ca862008-05-27 21:13:40 +0000558 break;
thscd831bd2008-07-03 10:23:51 +0000559 case 'k':
Paolo Bonzinib32f6c22011-11-04 15:51:20 +0100560 sockpath = optarg;
Peter Lieven713cc672014-08-13 19:20:19 +0200561 if (sockpath[0] != '/') {
Ryota Ozakib6353be2010-03-20 15:23:23 +0900562 errx(EXIT_FAILURE, "socket path must be absolute\n");
Peter Lieven713cc672014-08-13 19:20:19 +0200563 }
thscd831bd2008-07-03 10:23:51 +0000564 break;
565 case 'd':
566 disconnect = true;
567 break;
568 case 'c':
569 device = optarg;
570 break;
ths3b05a8e2008-07-03 12:45:02 +0000571 case 'e':
572 shared = strtol(optarg, &end, 0);
573 if (*end) {
Ryota Ozakib6353be2010-03-20 15:23:23 +0900574 errx(EXIT_FAILURE, "Invalid shared device number '%s'", optarg);
ths3b05a8e2008-07-03 12:45:02 +0000575 }
576 if (shared < 1) {
Ryota Ozakib6353be2010-03-20 15:23:23 +0900577 errx(EXIT_FAILURE, "Shared device number must be greater than 0\n");
ths3b05a8e2008-07-03 12:45:02 +0000578 }
579 break;
Daniel P. Berrangee6b63672013-03-19 11:20:20 +0000580 case 'f':
581 fmt = optarg;
582 break;
Peter Lieven713cc672014-08-13 19:20:19 +0200583 case 't':
584 persistent = 1;
585 break;
bellard7a5ca862008-05-27 21:13:40 +0000586 case 'v':
587 verbose = 1;
588 break;
589 case 'V':
590 version(argv[0]);
591 exit(0);
592 break;
593 case 'h':
594 usage(argv[0]);
595 exit(0);
596 break;
597 case '?':
Ryota Ozakib6353be2010-03-20 15:23:23 +0900598 errx(EXIT_FAILURE, "Try `%s --help' for more information.",
bellard7a5ca862008-05-27 21:13:40 +0000599 argv[0]);
600 }
601 }
602
603 if ((argc - optind) != 1) {
Ryota Ozakib6353be2010-03-20 15:23:23 +0900604 errx(EXIT_FAILURE, "Invalid number of argument.\n"
bellard7a5ca862008-05-27 21:13:40 +0000605 "Try `%s --help' for more information.",
606 argv[0]);
607 }
608
thscd831bd2008-07-03 10:23:51 +0000609 if (disconnect) {
610 fd = open(argv[optind], O_RDWR);
Paolo Bonzinifc19f8a2012-03-07 11:05:34 +0100611 if (fd < 0) {
Ryota Ozakicb7cf0e2010-05-03 06:50:25 +0900612 err(EXIT_FAILURE, "Cannot open %s", argv[optind]);
Paolo Bonzinifc19f8a2012-03-07 11:05:34 +0100613 }
thscd831bd2008-07-03 10:23:51 +0000614 nbd_disconnect(fd);
615
616 close(fd);
617
618 printf("%s disconnected\n", argv[optind]);
619
Peter Lieven713cc672014-08-13 19:20:19 +0200620 return 0;
thscd831bd2008-07-03 10:23:51 +0000621 }
622
Paolo Bonzinic1f8fdc2011-11-04 15:51:22 +0100623 if (device && !verbose) {
624 int stderr_fd[2];
625 pid_t pid;
626 int ret;
627
Paolo Bonzinifc19f8a2012-03-07 11:05:34 +0100628 if (qemu_pipe(stderr_fd) < 0) {
Paolo Bonzinic1f8fdc2011-11-04 15:51:22 +0100629 err(EXIT_FAILURE, "Error setting up communication pipe");
630 }
631
632 /* Now daemonize, but keep a communication channel open to
633 * print errors and exit with the proper status code.
634 */
635 pid = fork();
636 if (pid == 0) {
637 close(stderr_fd[0]);
Michael Tokarev9faf31b2012-01-16 18:37:44 +0400638 ret = qemu_daemon(1, 0);
Paolo Bonzinic1f8fdc2011-11-04 15:51:22 +0100639
640 /* Temporarily redirect stderr to the parent's pipe... */
641 dup2(stderr_fd[1], STDERR_FILENO);
Paolo Bonzinifc19f8a2012-03-07 11:05:34 +0100642 if (ret < 0) {
Paolo Bonzinic1f8fdc2011-11-04 15:51:22 +0100643 err(EXIT_FAILURE, "Failed to daemonize");
644 }
645
646 /* ... close the descriptor we inherited and go on. */
647 close(stderr_fd[1]);
648 } else {
649 bool errors = false;
650 char *buf;
651
652 /* In the parent. Print error messages from the child until
653 * it closes the pipe.
654 */
655 close(stderr_fd[1]);
656 buf = g_malloc(1024);
657 while ((ret = read(stderr_fd[0], buf, 1024)) > 0) {
658 errors = true;
659 ret = qemu_write_full(STDERR_FILENO, buf, ret);
Paolo Bonzinifc19f8a2012-03-07 11:05:34 +0100660 if (ret < 0) {
Paolo Bonzinic1f8fdc2011-11-04 15:51:22 +0100661 exit(EXIT_FAILURE);
662 }
663 }
Paolo Bonzinifc19f8a2012-03-07 11:05:34 +0100664 if (ret < 0) {
Paolo Bonzinic1f8fdc2011-11-04 15:51:22 +0100665 err(EXIT_FAILURE, "Cannot read from daemon");
666 }
667
668 /* Usually the daemon should not print any message.
669 * Exit with zero status in that case.
670 */
671 exit(errors);
672 }
673 }
674
Paolo Bonzinia6ac2312011-12-06 09:07:00 +0100675 if (device != NULL && sockpath == NULL) {
676 sockpath = g_malloc(128);
677 snprintf(sockpath, 128, SOCKET_PATH, basename(device));
thscd831bd2008-07-03 10:23:51 +0000678 }
679
Chrysostomos Nanakos2f78e492014-09-18 14:30:49 +0300680 if (qemu_init_main_loop(&local_err)) {
Markus Armbruster565f65d2015-02-12 13:55:05 +0100681 error_report_err(local_err);
Chrysostomos Nanakos2f78e492014-09-18 14:30:49 +0300682 exit(EXIT_FAILURE);
683 }
Paolo Bonzini802ddc32011-11-04 15:51:24 +0100684 bdrv_init();
685 atexit(bdrv_close_all);
686
Daniel P. Berrangee6b63672013-03-19 11:20:20 +0000687 if (fmt) {
688 drv = bdrv_find_format(fmt);
689 if (!drv) {
690 errx(EXIT_FAILURE, "Unknown file format '%s'", fmt);
691 }
692 } else {
693 drv = NULL;
694 }
695
Markus Armbruster7e7d56d2014-10-07 13:59:05 +0200696 blk = blk_new_with_bs("hda", &error_abort);
697 bs = blk_bs(blk);
Kevin Wolf98522f62014-04-17 13:16:01 +0200698
Paolo Bonzini802ddc32011-11-04 15:51:24 +0100699 srcpath = argv[optind];
Max Reitzddf56362014-02-18 18:33:06 +0100700 ret = bdrv_open(&bs, srcpath, NULL, NULL, flags, drv, &local_err);
Daniel P. Berrangee6b63672013-03-19 11:20:20 +0000701 if (ret < 0) {
Paolo Bonzini802ddc32011-11-04 15:51:24 +0100702 errno = -ret;
Max Reitz34b5d2c2013-09-05 14:45:29 +0200703 err(EXIT_FAILURE, "Failed to bdrv_open '%s': %s", argv[optind],
704 error_get_pretty(local_err));
Paolo Bonzini802ddc32011-11-04 15:51:24 +0100705 }
706
Wenchao Xia8c116b02013-12-04 17:10:55 +0800707 if (sn_opts) {
708 ret = bdrv_snapshot_load_tmp(bs,
709 qemu_opt_get(sn_opts, SNAPSHOT_OPT_ID),
710 qemu_opt_get(sn_opts, SNAPSHOT_OPT_NAME),
711 &local_err);
712 } else if (sn_id_or_name) {
713 ret = bdrv_snapshot_load_tmp_by_id_or_name(bs, sn_id_or_name,
714 &local_err);
715 }
716 if (ret < 0) {
717 errno = -ret;
718 err(EXIT_FAILURE,
719 "Failed to load snapshot: %s",
720 error_get_pretty(local_err));
721 }
722
Peter Lievenb3838a42014-08-13 19:20:18 +0200723 bs->detect_zeroes = detect_zeroes;
Max Reitz4c58e802014-11-18 12:21:19 +0100724 fd_size = blk_getlength(blk);
Paolo Bonzini802ddc32011-11-04 15:51:24 +0100725
Paolo Bonzini185b4332012-03-05 08:56:10 +0100726 if (partition != -1) {
Max Reitz4c58e802014-11-18 12:21:19 +0100727 ret = find_partition(blk, partition, &dev_offset, &fd_size);
Paolo Bonzini185b4332012-03-05 08:56:10 +0100728 if (ret < 0) {
729 errno = -ret;
730 err(EXIT_FAILURE, "Could not find partition %d", partition);
731 }
Paolo Bonzini802ddc32011-11-04 15:51:24 +0100732 }
733
Max Reitze1401772014-11-18 12:21:17 +0100734 exp = nbd_export_new(blk, dev_offset, fd_size, nbdflags, nbd_export_closed);
ths3b05a8e2008-07-03 12:45:02 +0000735
Paolo Bonzinib32f6c22011-11-04 15:51:20 +0100736 if (sockpath) {
Paolo Bonzinia61c6782011-09-12 17:28:11 +0200737 fd = unix_socket_incoming(sockpath);
thscd831bd2008-07-03 10:23:51 +0000738 } else {
Paolo Bonzinia61c6782011-09-12 17:28:11 +0200739 fd = tcp_socket_incoming(bindto, port);
thscd831bd2008-07-03 10:23:51 +0000740 }
741
Paolo Bonzinifc19f8a2012-03-07 11:05:34 +0100742 if (fd < 0) {
bellard7a5ca862008-05-27 21:13:40 +0000743 return 1;
Paolo Bonzinia61c6782011-09-12 17:28:11 +0200744 }
Paolo Bonzinif1ef5552011-11-04 15:51:23 +0100745
746 if (device) {
747 int ret;
748
Paolo Bonzinia6ac2312011-12-06 09:07:00 +0100749 ret = pthread_create(&client_thread, NULL, nbd_client_thread, device);
Paolo Bonzinif1ef5552011-11-04 15:51:23 +0100750 if (ret != 0) {
751 errx(EXIT_FAILURE, "Failed to create client thread: %s",
752 strerror(ret));
753 }
754 } else {
755 /* Shut up GCC warnings. */
756 memset(&client_thread, 0, sizeof(client_thread));
757 }
758
Paolo Bonzinia61c6782011-09-12 17:28:11 +0200759 qemu_set_fd_handler2(fd, nbd_can_accept, nbd_accept, NULL,
760 (void *)(uintptr_t)fd);
bellard7a5ca862008-05-27 21:13:40 +0000761
Michael Tokarev9faf31b2012-01-16 18:37:44 +0400762 /* now when the initialization is (almost) complete, chdir("/")
763 * to free any busy filesystems */
764 if (chdir("/") < 0) {
765 err(EXIT_FAILURE, "Could not chdir to root directory");
766 }
767
Paolo Bonzini7860a382012-09-18 13:31:56 +0200768 state = RUNNING;
ths3b05a8e2008-07-03 12:45:02 +0000769 do {
Paolo Bonzinia61c6782011-09-12 17:28:11 +0200770 main_loop_wait(false);
Paolo Bonzini7860a382012-09-18 13:31:56 +0200771 if (state == TERMINATE) {
772 state = TERMINATING;
773 nbd_export_close(exp);
774 nbd_export_put(exp);
775 exp = NULL;
776 }
777 } while (state != TERMINATED);
ths3b05a8e2008-07-03 12:45:02 +0000778
Markus Armbruster26f54e92014-10-07 13:59:04 +0200779 blk_unref(blk);
Paolo Bonzinib32f6c22011-11-04 15:51:20 +0100780 if (sockpath) {
781 unlink(sockpath);
782 }
bellard7a5ca862008-05-27 21:13:40 +0000783
Markus Armbrusterfbf28a42014-09-29 16:07:55 +0200784 qemu_opts_del(sn_opts);
Wenchao Xia8c116b02013-12-04 17:10:55 +0800785
Paolo Bonzinia517e882011-11-04 15:51:21 +0100786 if (device) {
787 void *ret;
788 pthread_join(client_thread, &ret);
789 exit(ret != NULL);
790 } else {
791 exit(EXIT_SUCCESS);
792 }
bellard7a5ca862008-05-27 21:13:40 +0000793}