blob: 65dc30c189b1c6e534f20f959051302cf91accf5 [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"
Markus Armbrusterd49b6832015-03-17 18:29:20 +010028#include "qapi/qmp/qstring.h"
bellard7a5ca862008-05-27 21:13:40 +000029
bellard7a5ca862008-05-27 21:13:40 +000030#include <stdarg.h>
31#include <stdio.h>
32#include <getopt.h>
33#include <err.h>
thscd831bd2008-07-03 10:23:51 +000034#include <sys/types.h>
bellard7a5ca862008-05-27 21:13:40 +000035#include <sys/socket.h>
36#include <netinet/in.h>
37#include <netinet/tcp.h>
38#include <arpa/inet.h>
thscd831bd2008-07-03 10:23:51 +000039#include <signal.h>
Blue Swirl2bff4b62009-12-23 15:34:04 +000040#include <libgen.h>
Paolo Bonzinia517e882011-11-04 15:51:21 +010041#include <pthread.h>
thscd831bd2008-07-03 10:23:51 +000042
Peter Lieven713cc672014-08-13 19:20:19 +020043#define SOCKET_PATH "/var/lock/qemu-nbd-%s"
44#define QEMU_NBD_OPT_CACHE 1
45#define QEMU_NBD_OPT_AIO 2
46#define QEMU_NBD_OPT_DISCARD 3
Peter Lievenb3838a42014-08-13 19:20:18 +020047#define QEMU_NBD_OPT_DETECT_ZEROES 4
bellard7a5ca862008-05-27 21:13:40 +000048
Paolo Bonziniaf49bbb2011-09-19 14:03:37 +020049static NBDExport *exp;
blueswir1b1d8e522008-10-26 13:43:07 +000050static int verbose;
Paolo Bonzinia517e882011-11-04 15:51:21 +010051static char *srcpath;
Daniel P. Berrange48bec072015-09-16 14:52:23 +010052static SocketAddress *saddr;
Paolo Bonzini7860a382012-09-18 13:31:56 +020053static int persistent = 0;
54static enum { RUNNING, TERMINATE, TERMINATING, TERMINATED } state;
Paolo Bonzinia61c6782011-09-12 17:28:11 +020055static int shared = 1;
56static int nb_fds;
Fam Zhenge4afbf42015-05-19 10:50:59 +000057static int server_fd;
bellard7a5ca862008-05-27 21:13:40 +000058
59static void usage(const char *name)
60{
Paolo Bonzinib033cd82012-07-18 14:50:52 +020061 (printf) (
bellard7a5ca862008-05-27 21:13:40 +000062"Usage: %s [OPTIONS] FILE\n"
63"QEMU Disk Network Block Device Server\n"
64"\n"
Peter Lieven713cc672014-08-13 19:20:19 +020065" -h, --help display this help and exit\n"
66" -V, --version output version information and exit\n"
bellard7a5ca862008-05-27 21:13:40 +000067"\n"
Paolo Bonzinib033cd82012-07-18 14:50:52 +020068"Connection properties:\n"
Peter Lieven713cc672014-08-13 19:20:19 +020069" -p, --port=PORT port to listen on (default `%d')\n"
70" -b, --bind=IFACE interface to bind to (default `0.0.0.0')\n"
71" -k, --socket=PATH path to the unix socket\n"
72" (default '"SOCKET_PATH"')\n"
73" -e, --shared=NUM device can be shared by NUM clients (default '1')\n"
74" -t, --persistent don't exit on the last connection\n"
75" -v, --verbose display extra debugging information\n"
Paolo Bonzinib033cd82012-07-18 14:50:52 +020076"\n"
77"Exposing part of the image:\n"
Peter Lieven713cc672014-08-13 19:20:19 +020078" -o, --offset=OFFSET offset into the image\n"
79" -P, --partition=NUM only expose partition NUM\n"
Paolo Bonzinib033cd82012-07-18 14:50:52 +020080"\n"
81#ifdef __linux__
82"Kernel NBD client support:\n"
Peter Lieven713cc672014-08-13 19:20:19 +020083" -c, --connect=DEV connect FILE to the local NBD device DEV\n"
84" -d, --disconnect disconnect the specified device\n"
Paolo Bonzinib033cd82012-07-18 14:50:52 +020085"\n"
86#endif
87"\n"
88"Block device options:\n"
Peter Lieven713cc672014-08-13 19:20:19 +020089" -f, --format=FORMAT set image format (raw, qcow2, ...)\n"
90" -r, --read-only export read-only\n"
91" -s, --snapshot use FILE as an external snapshot, create a temporary\n"
92" file with backing_file=FILE, redirect the write to\n"
93" the temporary one\n"
Wenchao Xia8c116b02013-12-04 17:10:55 +080094" -l, --load-snapshot=SNAPSHOT_PARAM\n"
Peter Lieven713cc672014-08-13 19:20:19 +020095" load an internal snapshot inside FILE and export it\n"
96" as an read-only device, SNAPSHOT_PARAM format is\n"
97" 'snapshot.id=[ID],snapshot.name=[NAME]', or\n"
98" '[ID_OR_NAME]'\n"
99" -n, --nocache disable host cache\n"
100" --cache=MODE set cache mode (none, writeback, ...)\n"
Peter Lieven713cc672014-08-13 19:20:19 +0200101" --aio=MODE set AIO mode (native or threads)\n"
Peter Lievenb3838a42014-08-13 19:20:18 +0200102" --discard=MODE set discard mode (ignore, unmap)\n"
Andrey Korolyov6883de62015-07-31 22:12:54 +0300103" --detect-zeroes=MODE set detect-zeroes mode (off, on, unmap)\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;
Max Reitzac973932015-02-25 13:08:23 -0500145
146 r->start_sector_abs = le32_to_cpup((uint32_t *)(p + 8));
147 r->nb_sectors_abs = le32_to_cpup((uint32_t *)(p + 12));
bellard7a5ca862008-05-27 21:13:40 +0000148}
149
Max Reitz4c58e802014-11-18 12:21:19 +0100150static int find_partition(BlockBackend *blk, int partition,
bellard7a5ca862008-05-27 21:13:40 +0000151 off_t *offset, off_t *size)
152{
153 struct partition_record mbr[4];
154 uint8_t data[512];
155 int i;
156 int ext_partnum = 4;
Ryota Ozakicb7cf0e2010-05-03 06:50:25 +0900157 int ret;
bellard7a5ca862008-05-27 21:13:40 +0000158
Max Reitz4c58e802014-11-18 12:21:19 +0100159 if ((ret = blk_read(blk, 0, data, 1)) < 0) {
Ryota Ozakicb7cf0e2010-05-03 06:50:25 +0900160 errno = -ret;
161 err(EXIT_FAILURE, "error while reading");
162 }
bellard7a5ca862008-05-27 21:13:40 +0000163
164 if (data[510] != 0x55 || data[511] != 0xaa) {
Paolo Bonzini185b4332012-03-05 08:56:10 +0100165 return -EINVAL;
bellard7a5ca862008-05-27 21:13:40 +0000166 }
167
168 for (i = 0; i < 4; i++) {
169 read_partition(&data[446 + 16 * i], &mbr[i]);
170
Max Reitz453b07b2015-02-25 13:08:15 -0500171 if (!mbr[i].system || !mbr[i].nb_sectors_abs) {
bellard7a5ca862008-05-27 21:13:40 +0000172 continue;
Max Reitz453b07b2015-02-25 13:08:15 -0500173 }
bellard7a5ca862008-05-27 21:13:40 +0000174
175 if (mbr[i].system == 0xF || mbr[i].system == 0x5) {
176 struct partition_record ext[4];
177 uint8_t data1[512];
178 int j;
179
Max Reitz4c58e802014-11-18 12:21:19 +0100180 if ((ret = blk_read(blk, mbr[i].start_sector_abs, data1, 1)) < 0) {
Ryota Ozakicb7cf0e2010-05-03 06:50:25 +0900181 errno = -ret;
182 err(EXIT_FAILURE, "error while reading");
183 }
bellard7a5ca862008-05-27 21:13:40 +0000184
185 for (j = 0; j < 4; j++) {
186 read_partition(&data1[446 + 16 * j], &ext[j]);
Max Reitz453b07b2015-02-25 13:08:15 -0500187 if (!ext[j].system || !ext[j].nb_sectors_abs) {
bellard7a5ca862008-05-27 21:13:40 +0000188 continue;
Max Reitz453b07b2015-02-25 13:08:15 -0500189 }
bellard7a5ca862008-05-27 21:13:40 +0000190
191 if ((ext_partnum + j + 1) == partition) {
192 *offset = (uint64_t)ext[j].start_sector_abs << 9;
193 *size = (uint64_t)ext[j].nb_sectors_abs << 9;
194 return 0;
195 }
196 }
197 ext_partnum += 4;
198 } else if ((i + 1) == partition) {
199 *offset = (uint64_t)mbr[i].start_sector_abs << 9;
200 *size = (uint64_t)mbr[i].nb_sectors_abs << 9;
201 return 0;
202 }
203 }
204
Paolo Bonzini185b4332012-03-05 08:56:10 +0100205 return -ENOENT;
bellard7a5ca862008-05-27 21:13:40 +0000206}
207
Paolo Bonzinibb345112011-11-04 15:51:19 +0100208static void termsig_handler(int signum)
209{
Paolo Bonzini7860a382012-09-18 13:31:56 +0200210 state = TERMINATE;
Paolo Bonzinia61c6782011-09-12 17:28:11 +0200211 qemu_notify_event();
Paolo Bonzinibb345112011-11-04 15:51:19 +0100212}
213
Paolo Bonzini537b41f2014-02-17 14:43:51 +0100214
Paolo Bonzinia517e882011-11-04 15:51:21 +0100215static void *show_parts(void *arg)
thscd831bd2008-07-03 10:23:51 +0000216{
Paolo Bonzinia6ac2312011-12-06 09:07:00 +0100217 char *device = arg;
Paolo Bonzinia517e882011-11-04 15:51:21 +0100218 int nbd;
thscd831bd2008-07-03 10:23:51 +0000219
Paolo Bonzinia517e882011-11-04 15:51:21 +0100220 /* linux just needs an open() to trigger
221 * the partition table update
222 * but remember to load the module with max_part != 0 :
223 * modprobe nbd max_part=63
224 */
225 nbd = open(device, O_RDWR);
Paolo Bonzinifc19f8a2012-03-07 11:05:34 +0100226 if (nbd >= 0) {
Paolo Bonzinia517e882011-11-04 15:51:21 +0100227 close(nbd);
thscd831bd2008-07-03 10:23:51 +0000228 }
Paolo Bonzinia517e882011-11-04 15:51:21 +0100229 return NULL;
230}
231
232static void *nbd_client_thread(void *arg)
233{
Paolo Bonzinia6ac2312011-12-06 09:07:00 +0100234 char *device = arg;
Paolo Bonzinia517e882011-11-04 15:51:21 +0100235 off_t size;
Paolo Bonzinia517e882011-11-04 15:51:21 +0100236 uint32_t nbdflags;
Paolo Bonzinia6ac2312011-12-06 09:07:00 +0100237 int fd, sock;
Paolo Bonzinia517e882011-11-04 15:51:21 +0100238 int ret;
239 pthread_t show_parts_thread;
Max Reitz1ce52842015-01-26 21:02:59 -0500240 Error *local_error = NULL;
Paolo Bonzinia517e882011-11-04 15:51:21 +0100241
Daniel P. Berrange48bec072015-09-16 14:52:23 +0100242
243 sock = socket_connect(saddr, &local_error, NULL, NULL);
Paolo Bonzinifc19f8a2012-03-07 11:05:34 +0100244 if (sock < 0) {
Daniel P. Berrange48bec072015-09-16 14:52:23 +0100245 error_report_err(local_error);
Stefan Hajnoczidc10e8b2012-01-05 13:16:07 +0000246 goto out;
247 }
Paolo Bonzinia517e882011-11-04 15:51:21 +0100248
249 ret = nbd_receive_negotiate(sock, NULL, &nbdflags,
Max Reitz3f472652015-02-25 13:08:25 -0500250 &size, &local_error);
Paolo Bonzinifc19f8a2012-03-07 11:05:34 +0100251 if (ret < 0) {
Max Reitz1ce52842015-01-26 21:02:59 -0500252 if (local_error) {
253 fprintf(stderr, "%s\n", error_get_pretty(local_error));
254 error_free(local_error);
255 }
Paolo Bonzini0c544d72014-03-14 18:10:54 +0100256 goto out_socket;
Paolo Bonzinia517e882011-11-04 15:51:21 +0100257 }
258
Paolo Bonzinia6ac2312011-12-06 09:07:00 +0100259 fd = open(device, O_RDWR);
Paolo Bonzinifc19f8a2012-03-07 11:05:34 +0100260 if (fd < 0) {
Paolo Bonzinia6ac2312011-12-06 09:07:00 +0100261 /* Linux-only, we can use %m in printf. */
Hani Benhabiles5672ee52014-05-13 00:35:16 +0100262 fprintf(stderr, "Failed to open %s: %m\n", device);
Paolo Bonzini0c544d72014-03-14 18:10:54 +0100263 goto out_socket;
Paolo Bonzinia6ac2312011-12-06 09:07:00 +0100264 }
265
Max Reitz3f472652015-02-25 13:08:25 -0500266 ret = nbd_init(fd, sock, nbdflags, size);
Paolo Bonzinifc19f8a2012-03-07 11:05:34 +0100267 if (ret < 0) {
Paolo Bonzini0c544d72014-03-14 18:10:54 +0100268 goto out_fd;
Paolo Bonzinia517e882011-11-04 15:51:21 +0100269 }
270
271 /* update partition table */
Paolo Bonzinia6ac2312011-12-06 09:07:00 +0100272 pthread_create(&show_parts_thread, NULL, show_parts, device);
Paolo Bonzinia517e882011-11-04 15:51:21 +0100273
Paolo Bonzinic1f8fdc2011-11-04 15:51:22 +0100274 if (verbose) {
275 fprintf(stderr, "NBD device %s is now connected to %s\n",
276 device, srcpath);
277 } else {
278 /* Close stderr so that the qemu-nbd process exits. */
279 dup2(STDOUT_FILENO, STDERR_FILENO);
280 }
Paolo Bonzinia517e882011-11-04 15:51:21 +0100281
282 ret = nbd_client(fd);
283 if (ret) {
Paolo Bonzini0c544d72014-03-14 18:10:54 +0100284 goto out_fd;
Paolo Bonzinia517e882011-11-04 15:51:21 +0100285 }
286 close(fd);
287 kill(getpid(), SIGTERM);
288 return (void *) EXIT_SUCCESS;
289
Paolo Bonzini0c544d72014-03-14 18:10:54 +0100290out_fd:
291 close(fd);
292out_socket:
293 closesocket(sock);
Paolo Bonzinia517e882011-11-04 15:51:21 +0100294out:
295 kill(getpid(), SIGTERM);
296 return (void *) EXIT_FAILURE;
thscd831bd2008-07-03 10:23:51 +0000297}
298
Fam Zhenge4afbf42015-05-19 10:50:59 +0000299static int nbd_can_accept(void)
Paolo Bonzinia61c6782011-09-12 17:28:11 +0200300{
301 return nb_fds < shared;
302}
303
Paolo Bonzini7860a382012-09-18 13:31:56 +0200304static void nbd_export_closed(NBDExport *exp)
305{
306 assert(state == TERMINATING);
307 state = TERMINATED;
308}
309
Fam Zhenge4afbf42015-05-19 10:50:59 +0000310static void nbd_update_server_fd_handler(int fd);
311
Paolo Bonzini1743b512011-09-19 14:33:23 +0200312static void nbd_client_closed(NBDClient *client)
Paolo Bonzinia61c6782011-09-12 17:28:11 +0200313{
Paolo Bonzini1743b512011-09-19 14:33:23 +0200314 nb_fds--;
Paolo Bonzini7860a382012-09-18 13:31:56 +0200315 if (nb_fds == 0 && !persistent && state == RUNNING) {
316 state = TERMINATE;
317 }
Fam Zhenge4afbf42015-05-19 10:50:59 +0000318 nbd_update_server_fd_handler(server_fd);
Paolo Bonzini7860a382012-09-18 13:31:56 +0200319 nbd_client_put(client);
Paolo Bonzinia61c6782011-09-12 17:28:11 +0200320}
321
322static void nbd_accept(void *opaque)
323{
Paolo Bonzinia61c6782011-09-12 17:28:11 +0200324 struct sockaddr_in addr;
325 socklen_t addr_len = sizeof(addr);
326
327 int fd = accept(server_fd, (struct sockaddr *)&addr, &addr_len);
Paolo Bonzini0c544d72014-03-14 18:10:54 +0100328 if (fd < 0) {
329 perror("accept");
330 return;
331 }
332
Paolo Bonzini7860a382012-09-18 13:31:56 +0200333 if (state >= TERMINATE) {
334 close(fd);
335 return;
336 }
337
Hani Benhabiles36af5992014-05-13 00:35:15 +0100338 if (nbd_client_new(exp, fd, nbd_client_closed)) {
Paolo Bonzinia61c6782011-09-12 17:28:11 +0200339 nb_fds++;
Fam Zhenge4afbf42015-05-19 10:50:59 +0000340 nbd_update_server_fd_handler(server_fd);
Hani Benhabiles36af5992014-05-13 00:35:15 +0100341 } else {
Hani Benhabiles27e5eae2014-05-31 22:39:42 +0100342 shutdown(fd, 2);
Hani Benhabiles36af5992014-05-13 00:35:15 +0100343 close(fd);
Paolo Bonzinia61c6782011-09-12 17:28:11 +0200344 }
345}
346
Fam Zhenge4afbf42015-05-19 10:50:59 +0000347static void nbd_update_server_fd_handler(int fd)
348{
349 if (nbd_can_accept()) {
350 qemu_set_fd_handler(fd, nbd_accept, NULL, (void *)(uintptr_t)fd);
351 } else {
352 qemu_set_fd_handler(fd, NULL, NULL, NULL);
353 }
354}
355
Daniel P. Berrange48bec072015-09-16 14:52:23 +0100356
357static SocketAddress *nbd_build_socket_address(const char *sockpath,
358 const char *bindto,
359 const char *port)
360{
361 SocketAddress *saddr;
362
363 saddr = g_new0(SocketAddress, 1);
364 if (sockpath) {
Eric Blake2d32add2015-10-26 16:34:55 -0600365 saddr->type = SOCKET_ADDRESS_KIND_UNIX;
366 saddr->u.q_unix = g_new0(UnixSocketAddress, 1);
367 saddr->u.q_unix->path = g_strdup(sockpath);
Daniel P. Berrange48bec072015-09-16 14:52:23 +0100368 } else {
Eric Blake2d32add2015-10-26 16:34:55 -0600369 saddr->type = SOCKET_ADDRESS_KIND_INET;
370 saddr->u.inet = g_new0(InetSocketAddress, 1);
371 saddr->u.inet->host = g_strdup(bindto);
Daniel P. Berrange48bec072015-09-16 14:52:23 +0100372 if (port) {
Eric Blake2d32add2015-10-26 16:34:55 -0600373 saddr->u.inet->port = g_strdup(port);
Daniel P. Berrange48bec072015-09-16 14:52:23 +0100374 } else {
Eric Blake2d32add2015-10-26 16:34:55 -0600375 saddr->u.inet->port = g_strdup_printf("%d", NBD_DEFAULT_PORT);
Daniel P. Berrange48bec072015-09-16 14:52:23 +0100376 }
377 }
378
379 return saddr;
380}
381
382
bellard7a5ca862008-05-27 21:13:40 +0000383int main(int argc, char **argv)
384{
Markus Armbruster26f54e92014-10-07 13:59:04 +0200385 BlockBackend *blk;
bellard7a5ca862008-05-27 21:13:40 +0000386 BlockDriverState *bs;
387 off_t dev_offset = 0;
Paolo Bonzinib90fb4b2011-09-08 17:24:54 +0200388 uint32_t nbdflags = 0;
thscd831bd2008-07-03 10:23:51 +0000389 bool disconnect = false;
bellard7a5ca862008-05-27 21:13:40 +0000390 const char *bindto = "0.0.0.0";
Daniel P. Berrange48bec072015-09-16 14:52:23 +0100391 const char *port = NULL;
392 char *sockpath = NULL;
Paolo Bonzinia6ac2312011-12-06 09:07:00 +0100393 char *device = NULL;
bellard7a5ca862008-05-27 21:13:40 +0000394 off_t fd_size;
Wenchao Xia8c116b02013-12-04 17:10:55 +0800395 QemuOpts *sn_opts = NULL;
396 const char *sn_id_or_name = NULL;
397 const char *sopt = "hVb:o:p:rsnP:c:dvk:e:f:tl:";
bellard7a5ca862008-05-27 21:13:40 +0000398 struct option lopt[] = {
Blue Swirl660f11b2009-07-31 21:16:51 +0000399 { "help", 0, NULL, 'h' },
400 { "version", 0, NULL, 'V' },
401 { "bind", 1, NULL, 'b' },
402 { "port", 1, NULL, 'p' },
403 { "socket", 1, NULL, 'k' },
404 { "offset", 1, NULL, 'o' },
405 { "read-only", 0, NULL, 'r' },
406 { "partition", 1, NULL, 'P' },
407 { "connect", 1, NULL, 'c' },
408 { "disconnect", 0, NULL, 'd' },
409 { "snapshot", 0, NULL, 's' },
Wenchao Xia8c116b02013-12-04 17:10:55 +0800410 { "load-snapshot", 1, NULL, 'l' },
Blue Swirl660f11b2009-07-31 21:16:51 +0000411 { "nocache", 0, NULL, 'n' },
Paolo Bonzini39a52352012-07-18 14:57:15 +0200412 { "cache", 1, NULL, QEMU_NBD_OPT_CACHE },
Paolo Bonzini39a52352012-07-18 14:57:15 +0200413 { "aio", 1, NULL, QEMU_NBD_OPT_AIO },
Paolo Bonzinided9d2d2013-02-08 14:06:13 +0100414 { "discard", 1, NULL, QEMU_NBD_OPT_DISCARD },
Peter Lievenb3838a42014-08-13 19:20:18 +0200415 { "detect-zeroes", 1, NULL, QEMU_NBD_OPT_DETECT_ZEROES },
Blue Swirl660f11b2009-07-31 21:16:51 +0000416 { "shared", 1, NULL, 'e' },
Daniel P. Berrangee6b63672013-03-19 11:20:20 +0000417 { "format", 1, NULL, 'f' },
Blue Swirl660f11b2009-07-31 21:16:51 +0000418 { "persistent", 0, NULL, 't' },
419 { "verbose", 0, NULL, 'v' },
420 { NULL, 0, NULL, 0 }
bellard7a5ca862008-05-27 21:13:40 +0000421 };
422 int ch;
423 int opt_ind = 0;
bellard7a5ca862008-05-27 21:13:40 +0000424 char *end;
Naphtali Spreif5edb012010-01-17 16:48:13 +0200425 int flags = BDRV_O_RDWR;
bellard7a5ca862008-05-27 21:13:40 +0000426 int partition = -1;
Max Reitz4fbec262015-02-05 13:58:19 -0500427 int ret = 0;
ths3b05a8e2008-07-03 12:45:02 +0000428 int fd;
Paolo Bonzini39a52352012-07-18 14:57:15 +0200429 bool seen_cache = false;
Paolo Bonzinided9d2d2013-02-08 14:06:13 +0100430 bool seen_discard = false;
Paolo Bonzini39a52352012-07-18 14:57:15 +0200431 bool seen_aio = false;
Paolo Bonzinia517e882011-11-04 15:51:21 +0100432 pthread_t client_thread;
Daniel P. Berrangee6b63672013-03-19 11:20:20 +0000433 const char *fmt = NULL;
Max Reitz34b5d2c2013-09-05 14:45:29 +0200434 Error *local_err = NULL;
Peter Lievenb3838a42014-08-13 19:20:18 +0200435 BlockdevDetectZeroesOptions detect_zeroes = BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF;
Max Reitz4fbec262015-02-05 13:58:19 -0500436 QDict *options = NULL;
bellard7a5ca862008-05-27 21:13:40 +0000437
Paolo Bonzinia517e882011-11-04 15:51:21 +0100438 /* The client thread uses SIGTERM to interrupt the server. A signal
439 * handler ensures that "qemu-nbd -v -c" exits with a nice status code.
440 */
Paolo Bonzinibb345112011-11-04 15:51:19 +0100441 struct sigaction sa_sigterm;
Paolo Bonzinibb345112011-11-04 15:51:19 +0100442 memset(&sa_sigterm, 0, sizeof(sa_sigterm));
443 sa_sigterm.sa_handler = termsig_handler;
444 sigaction(SIGTERM, &sa_sigterm, NULL);
Fam Zheng10f5bff2014-02-10 14:48:51 +0800445 qemu_init_exec_dir(argv[0]);
Paolo Bonzinibb345112011-11-04 15:51:19 +0100446
bellard7a5ca862008-05-27 21:13:40 +0000447 while ((ch = getopt_long(argc, argv, sopt, lopt, &opt_ind)) != -1) {
448 switch (ch) {
449 case 's':
ths2f726482008-07-03 11:47:46 +0000450 flags |= BDRV_O_SNAPSHOT;
451 break;
452 case 'n':
Paolo Bonzini39a52352012-07-18 14:57:15 +0200453 optarg = (char *) "none";
454 /* fallthrough */
455 case QEMU_NBD_OPT_CACHE:
456 if (seen_cache) {
457 errx(EXIT_FAILURE, "-n and --cache can only be specified once");
458 }
459 seen_cache = true;
460 if (bdrv_parse_cache_flags(optarg, &flags) == -1) {
461 errx(EXIT_FAILURE, "Invalid cache mode `%s'", optarg);
462 }
bellard7a5ca862008-05-27 21:13:40 +0000463 break;
Paolo Bonzini39a52352012-07-18 14:57:15 +0200464 case QEMU_NBD_OPT_AIO:
465 if (seen_aio) {
466 errx(EXIT_FAILURE, "--aio can only be specified once");
467 }
468 seen_aio = true;
469 if (!strcmp(optarg, "native")) {
470 flags |= BDRV_O_NATIVE_AIO;
471 } else if (!strcmp(optarg, "threads")) {
472 /* this is the default */
473 } else {
474 errx(EXIT_FAILURE, "invalid aio mode `%s'", optarg);
475 }
476 break;
Paolo Bonzinided9d2d2013-02-08 14:06:13 +0100477 case QEMU_NBD_OPT_DISCARD:
478 if (seen_discard) {
479 errx(EXIT_FAILURE, "--discard can only be specified once");
480 }
481 seen_discard = true;
482 if (bdrv_parse_discard_flags(optarg, &flags) == -1) {
483 errx(EXIT_FAILURE, "Invalid discard mode `%s'", optarg);
484 }
485 break;
Peter Lievenb3838a42014-08-13 19:20:18 +0200486 case QEMU_NBD_OPT_DETECT_ZEROES:
487 detect_zeroes =
488 qapi_enum_parse(BlockdevDetectZeroesOptions_lookup,
489 optarg,
Eric Blake7fb1cf12015-11-18 01:52:57 -0700490 BLOCKDEV_DETECT_ZEROES_OPTIONS__MAX,
Peter Lievenb3838a42014-08-13 19:20:18 +0200491 BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF,
492 &local_err);
493 if (local_err) {
494 errx(EXIT_FAILURE, "Failed to parse detect_zeroes mode: %s",
495 error_get_pretty(local_err));
496 }
497 if (detect_zeroes == BLOCKDEV_DETECT_ZEROES_OPTIONS_UNMAP &&
498 !(flags & BDRV_O_UNMAP)) {
499 errx(EXIT_FAILURE, "setting detect-zeroes to unmap is not allowed "
500 "without setting discard operation to unmap");
501 }
502 break;
bellard7a5ca862008-05-27 21:13:40 +0000503 case 'b':
504 bindto = optarg;
505 break;
506 case 'p':
Daniel P. Berrange48bec072015-09-16 14:52:23 +0100507 port = optarg;
bellard7a5ca862008-05-27 21:13:40 +0000508 break;
509 case 'o':
510 dev_offset = strtoll (optarg, &end, 0);
511 if (*end) {
Ryota Ozakib6353be2010-03-20 15:23:23 +0900512 errx(EXIT_FAILURE, "Invalid offset `%s'", optarg);
bellard7a5ca862008-05-27 21:13:40 +0000513 }
514 if (dev_offset < 0) {
Ryota Ozakib6353be2010-03-20 15:23:23 +0900515 errx(EXIT_FAILURE, "Offset must be positive `%s'", optarg);
bellard7a5ca862008-05-27 21:13:40 +0000516 }
517 break;
Wenchao Xia8c116b02013-12-04 17:10:55 +0800518 case 'l':
519 if (strstart(optarg, SNAPSHOT_OPT_BASE, NULL)) {
Markus Armbruster70b94332015-02-13 12:50:26 +0100520 sn_opts = qemu_opts_parse_noisily(&internal_snapshot_opts,
521 optarg, false);
Wenchao Xia8c116b02013-12-04 17:10:55 +0800522 if (!sn_opts) {
523 errx(EXIT_FAILURE, "Failed in parsing snapshot param `%s'",
524 optarg);
525 }
526 } else {
527 sn_id_or_name = optarg;
528 }
529 /* fall through */
bellard7a5ca862008-05-27 21:13:40 +0000530 case 'r':
Paolo Bonzinib90fb4b2011-09-08 17:24:54 +0200531 nbdflags |= NBD_FLAG_READ_ONLY;
Naphtali Sprei07108b22010-03-14 15:19:57 +0200532 flags &= ~BDRV_O_RDWR;
bellard7a5ca862008-05-27 21:13:40 +0000533 break;
534 case 'P':
535 partition = strtol(optarg, &end, 0);
Peter Lieven713cc672014-08-13 19:20:19 +0200536 if (*end) {
Ryota Ozakib6353be2010-03-20 15:23:23 +0900537 errx(EXIT_FAILURE, "Invalid partition `%s'", optarg);
Peter Lieven713cc672014-08-13 19:20:19 +0200538 }
539 if (partition < 1 || partition > 8) {
Ryota Ozakib6353be2010-03-20 15:23:23 +0900540 errx(EXIT_FAILURE, "Invalid partition %d", partition);
Peter Lieven713cc672014-08-13 19:20:19 +0200541 }
bellard7a5ca862008-05-27 21:13:40 +0000542 break;
thscd831bd2008-07-03 10:23:51 +0000543 case 'k':
Paolo Bonzinib32f6c22011-11-04 15:51:20 +0100544 sockpath = optarg;
Peter Lieven713cc672014-08-13 19:20:19 +0200545 if (sockpath[0] != '/') {
Ryota Ozakib6353be2010-03-20 15:23:23 +0900546 errx(EXIT_FAILURE, "socket path must be absolute\n");
Peter Lieven713cc672014-08-13 19:20:19 +0200547 }
thscd831bd2008-07-03 10:23:51 +0000548 break;
549 case 'd':
550 disconnect = true;
551 break;
552 case 'c':
553 device = optarg;
554 break;
ths3b05a8e2008-07-03 12:45:02 +0000555 case 'e':
556 shared = strtol(optarg, &end, 0);
557 if (*end) {
Ryota Ozakib6353be2010-03-20 15:23:23 +0900558 errx(EXIT_FAILURE, "Invalid shared device number '%s'", optarg);
ths3b05a8e2008-07-03 12:45:02 +0000559 }
560 if (shared < 1) {
Ryota Ozakib6353be2010-03-20 15:23:23 +0900561 errx(EXIT_FAILURE, "Shared device number must be greater than 0\n");
ths3b05a8e2008-07-03 12:45:02 +0000562 }
563 break;
Daniel P. Berrangee6b63672013-03-19 11:20:20 +0000564 case 'f':
565 fmt = optarg;
566 break;
Peter Lieven713cc672014-08-13 19:20:19 +0200567 case 't':
568 persistent = 1;
569 break;
bellard7a5ca862008-05-27 21:13:40 +0000570 case 'v':
571 verbose = 1;
572 break;
573 case 'V':
574 version(argv[0]);
575 exit(0);
576 break;
577 case 'h':
578 usage(argv[0]);
579 exit(0);
580 break;
581 case '?':
Ryota Ozakib6353be2010-03-20 15:23:23 +0900582 errx(EXIT_FAILURE, "Try `%s --help' for more information.",
bellard7a5ca862008-05-27 21:13:40 +0000583 argv[0]);
584 }
585 }
586
587 if ((argc - optind) != 1) {
Ryota Ozakib6353be2010-03-20 15:23:23 +0900588 errx(EXIT_FAILURE, "Invalid number of argument.\n"
bellard7a5ca862008-05-27 21:13:40 +0000589 "Try `%s --help' for more information.",
590 argv[0]);
591 }
592
thscd831bd2008-07-03 10:23:51 +0000593 if (disconnect) {
594 fd = open(argv[optind], O_RDWR);
Paolo Bonzinifc19f8a2012-03-07 11:05:34 +0100595 if (fd < 0) {
Ryota Ozakicb7cf0e2010-05-03 06:50:25 +0900596 err(EXIT_FAILURE, "Cannot open %s", argv[optind]);
Paolo Bonzinifc19f8a2012-03-07 11:05:34 +0100597 }
thscd831bd2008-07-03 10:23:51 +0000598 nbd_disconnect(fd);
599
600 close(fd);
601
602 printf("%s disconnected\n", argv[optind]);
603
Peter Lieven713cc672014-08-13 19:20:19 +0200604 return 0;
thscd831bd2008-07-03 10:23:51 +0000605 }
606
Paolo Bonzinic1f8fdc2011-11-04 15:51:22 +0100607 if (device && !verbose) {
608 int stderr_fd[2];
609 pid_t pid;
610 int ret;
611
Paolo Bonzinifc19f8a2012-03-07 11:05:34 +0100612 if (qemu_pipe(stderr_fd) < 0) {
Paolo Bonzinic1f8fdc2011-11-04 15:51:22 +0100613 err(EXIT_FAILURE, "Error setting up communication pipe");
614 }
615
616 /* Now daemonize, but keep a communication channel open to
617 * print errors and exit with the proper status code.
618 */
619 pid = fork();
Max Reitz70d47392015-02-25 13:08:22 -0500620 if (pid < 0) {
621 err(EXIT_FAILURE, "Failed to fork");
622 } else if (pid == 0) {
Paolo Bonzinic1f8fdc2011-11-04 15:51:22 +0100623 close(stderr_fd[0]);
Michael Tokarev9faf31b2012-01-16 18:37:44 +0400624 ret = qemu_daemon(1, 0);
Paolo Bonzinic1f8fdc2011-11-04 15:51:22 +0100625
626 /* Temporarily redirect stderr to the parent's pipe... */
627 dup2(stderr_fd[1], STDERR_FILENO);
Paolo Bonzinifc19f8a2012-03-07 11:05:34 +0100628 if (ret < 0) {
Paolo Bonzinic1f8fdc2011-11-04 15:51:22 +0100629 err(EXIT_FAILURE, "Failed to daemonize");
630 }
631
632 /* ... close the descriptor we inherited and go on. */
633 close(stderr_fd[1]);
634 } else {
635 bool errors = false;
636 char *buf;
637
638 /* In the parent. Print error messages from the child until
639 * it closes the pipe.
640 */
641 close(stderr_fd[1]);
642 buf = g_malloc(1024);
643 while ((ret = read(stderr_fd[0], buf, 1024)) > 0) {
644 errors = true;
645 ret = qemu_write_full(STDERR_FILENO, buf, ret);
Paolo Bonzinifc19f8a2012-03-07 11:05:34 +0100646 if (ret < 0) {
Paolo Bonzinic1f8fdc2011-11-04 15:51:22 +0100647 exit(EXIT_FAILURE);
648 }
649 }
Paolo Bonzinifc19f8a2012-03-07 11:05:34 +0100650 if (ret < 0) {
Paolo Bonzinic1f8fdc2011-11-04 15:51:22 +0100651 err(EXIT_FAILURE, "Cannot read from daemon");
652 }
653
654 /* Usually the daemon should not print any message.
655 * Exit with zero status in that case.
656 */
657 exit(errors);
658 }
659 }
660
Paolo Bonzinia6ac2312011-12-06 09:07:00 +0100661 if (device != NULL && sockpath == NULL) {
662 sockpath = g_malloc(128);
663 snprintf(sockpath, 128, SOCKET_PATH, basename(device));
thscd831bd2008-07-03 10:23:51 +0000664 }
665
Daniel P. Berrange48bec072015-09-16 14:52:23 +0100666 saddr = nbd_build_socket_address(sockpath, bindto, port);
667
Chrysostomos Nanakos2f78e492014-09-18 14:30:49 +0300668 if (qemu_init_main_loop(&local_err)) {
Markus Armbruster565f65d2015-02-12 13:55:05 +0100669 error_report_err(local_err);
Chrysostomos Nanakos2f78e492014-09-18 14:30:49 +0300670 exit(EXIT_FAILURE);
671 }
Paolo Bonzini802ddc32011-11-04 15:51:24 +0100672 bdrv_init();
673 atexit(bdrv_close_all);
674
Daniel P. Berrangee6b63672013-03-19 11:20:20 +0000675 if (fmt) {
Max Reitz4fbec262015-02-05 13:58:19 -0500676 options = qdict_new();
677 qdict_put(options, "driver", qstring_from_str(fmt));
Daniel P. Berrangee6b63672013-03-19 11:20:20 +0000678 }
679
Paolo Bonzini802ddc32011-11-04 15:51:24 +0100680 srcpath = argv[optind];
Max Reitz4fbec262015-02-05 13:58:19 -0500681 blk = blk_new_open("hda", srcpath, NULL, options, flags, &local_err);
682 if (!blk) {
683 errx(EXIT_FAILURE, "Failed to blk_new_open '%s': %s", argv[optind],
684 error_get_pretty(local_err));
Paolo Bonzini802ddc32011-11-04 15:51:24 +0100685 }
Max Reitz4fbec262015-02-05 13:58:19 -0500686 bs = blk_bs(blk);
Paolo Bonzini802ddc32011-11-04 15:51:24 +0100687
Wenchao Xia8c116b02013-12-04 17:10:55 +0800688 if (sn_opts) {
689 ret = bdrv_snapshot_load_tmp(bs,
690 qemu_opt_get(sn_opts, SNAPSHOT_OPT_ID),
691 qemu_opt_get(sn_opts, SNAPSHOT_OPT_NAME),
692 &local_err);
693 } else if (sn_id_or_name) {
694 ret = bdrv_snapshot_load_tmp_by_id_or_name(bs, sn_id_or_name,
695 &local_err);
696 }
697 if (ret < 0) {
698 errno = -ret;
699 err(EXIT_FAILURE,
700 "Failed to load snapshot: %s",
701 error_get_pretty(local_err));
702 }
703
Peter Lievenb3838a42014-08-13 19:20:18 +0200704 bs->detect_zeroes = detect_zeroes;
Max Reitz4c58e802014-11-18 12:21:19 +0100705 fd_size = blk_getlength(blk);
Max Reitz98f44bb2015-02-25 13:08:21 -0500706 if (fd_size < 0) {
707 errx(EXIT_FAILURE, "Failed to determine the image length: %s",
708 strerror(-fd_size));
709 }
Paolo Bonzini802ddc32011-11-04 15:51:24 +0100710
Paolo Bonzini185b4332012-03-05 08:56:10 +0100711 if (partition != -1) {
Max Reitz4c58e802014-11-18 12:21:19 +0100712 ret = find_partition(blk, partition, &dev_offset, &fd_size);
Paolo Bonzini185b4332012-03-05 08:56:10 +0100713 if (ret < 0) {
714 errno = -ret;
715 err(EXIT_FAILURE, "Could not find partition %d", partition);
716 }
Paolo Bonzini802ddc32011-11-04 15:51:24 +0100717 }
718
Max Reitz98f44bb2015-02-25 13:08:21 -0500719 exp = nbd_export_new(blk, dev_offset, fd_size, nbdflags, nbd_export_closed,
720 &local_err);
721 if (!exp) {
722 errx(EXIT_FAILURE, "%s", error_get_pretty(local_err));
723 }
ths3b05a8e2008-07-03 12:45:02 +0000724
Daniel P. Berrange48bec072015-09-16 14:52:23 +0100725 fd = socket_listen(saddr, &local_err);
Paolo Bonzinifc19f8a2012-03-07 11:05:34 +0100726 if (fd < 0) {
Daniel P. Berrange48bec072015-09-16 14:52:23 +0100727 error_report_err(local_err);
bellard7a5ca862008-05-27 21:13:40 +0000728 return 1;
Paolo Bonzinia61c6782011-09-12 17:28:11 +0200729 }
Paolo Bonzinif1ef5552011-11-04 15:51:23 +0100730
731 if (device) {
732 int ret;
733
Paolo Bonzinia6ac2312011-12-06 09:07:00 +0100734 ret = pthread_create(&client_thread, NULL, nbd_client_thread, device);
Paolo Bonzinif1ef5552011-11-04 15:51:23 +0100735 if (ret != 0) {
736 errx(EXIT_FAILURE, "Failed to create client thread: %s",
737 strerror(ret));
738 }
739 } else {
740 /* Shut up GCC warnings. */
741 memset(&client_thread, 0, sizeof(client_thread));
742 }
743
Fam Zhenge4afbf42015-05-19 10:50:59 +0000744 server_fd = fd;
745 nbd_update_server_fd_handler(fd);
bellard7a5ca862008-05-27 21:13:40 +0000746
Michael Tokarev9faf31b2012-01-16 18:37:44 +0400747 /* now when the initialization is (almost) complete, chdir("/")
748 * to free any busy filesystems */
749 if (chdir("/") < 0) {
750 err(EXIT_FAILURE, "Could not chdir to root directory");
751 }
752
Paolo Bonzini7860a382012-09-18 13:31:56 +0200753 state = RUNNING;
ths3b05a8e2008-07-03 12:45:02 +0000754 do {
Paolo Bonzinia61c6782011-09-12 17:28:11 +0200755 main_loop_wait(false);
Paolo Bonzini7860a382012-09-18 13:31:56 +0200756 if (state == TERMINATE) {
757 state = TERMINATING;
758 nbd_export_close(exp);
759 nbd_export_put(exp);
760 exp = NULL;
761 }
762 } while (state != TERMINATED);
ths3b05a8e2008-07-03 12:45:02 +0000763
Markus Armbruster26f54e92014-10-07 13:59:04 +0200764 blk_unref(blk);
Paolo Bonzinib32f6c22011-11-04 15:51:20 +0100765 if (sockpath) {
766 unlink(sockpath);
767 }
bellard7a5ca862008-05-27 21:13:40 +0000768
Markus Armbrusterfbf28a42014-09-29 16:07:55 +0200769 qemu_opts_del(sn_opts);
Wenchao Xia8c116b02013-12-04 17:10:55 +0800770
Paolo Bonzinia517e882011-11-04 15:51:21 +0100771 if (device) {
772 void *ret;
773 pthread_join(client_thread, &ret);
774 exit(ret != NULL);
775 } else {
776 exit(EXIT_SUCCESS);
777 }
bellard7a5ca862008-05-27 21:13:40 +0000778}