blob: 6428c15403be3eff93cb03554ce513ea64f191f9 [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"
Paolo Bonzini39a52352012-07-18 14:57:15 +0200101#ifdef CONFIG_LINUX_AIO
Peter Lieven713cc672014-08-13 19:20:19 +0200102" --aio=MODE set AIO mode (native or threads)\n"
Paolo Bonzini39a52352012-07-18 14:57:15 +0200103#endif
Peter Lievenb3838a42014-08-13 19:20:18 +0200104" --discard=MODE set discard mode (ignore, unmap)\n"
Andrey Korolyov6883de62015-07-31 22:12:54 +0300105" --detect-zeroes=MODE set detect-zeroes mode (off, on, unmap)\n"
Paolo Bonzinib033cd82012-07-18 14:50:52 +0200106"\n"
107"Report bugs to <qemu-devel@nongnu.org>\n"
Laurent Vivierc2e28722010-09-17 20:37:25 +0200108 , name, NBD_DEFAULT_PORT, "DEVICE");
bellard7a5ca862008-05-27 21:13:40 +0000109}
110
111static void version(const char *name)
112{
113 printf(
ths315bc7a2008-07-18 18:06:23 +0000114"%s version 0.0.1\n"
bellard7a5ca862008-05-27 21:13:40 +0000115"Written by Anthony Liguori.\n"
116"\n"
117"Copyright (C) 2006 Anthony Liguori <anthony@codemonkey.ws>.\n"
118"This is free software; see the source for copying conditions. There is NO\n"
119"warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n"
ths315bc7a2008-07-18 18:06:23 +0000120 , name);
bellard7a5ca862008-05-27 21:13:40 +0000121}
122
123struct partition_record
124{
125 uint8_t bootable;
126 uint8_t start_head;
127 uint32_t start_cylinder;
128 uint8_t start_sector;
129 uint8_t system;
130 uint8_t end_head;
131 uint8_t end_cylinder;
132 uint8_t end_sector;
133 uint32_t start_sector_abs;
134 uint32_t nb_sectors_abs;
135};
136
137static void read_partition(uint8_t *p, struct partition_record *r)
138{
139 r->bootable = p[0];
140 r->start_head = p[1];
141 r->start_cylinder = p[3] | ((p[2] << 2) & 0x0300);
142 r->start_sector = p[2] & 0x3f;
143 r->system = p[4];
144 r->end_head = p[5];
145 r->end_cylinder = p[7] | ((p[6] << 2) & 0x300);
146 r->end_sector = p[6] & 0x3f;
Max Reitzac973932015-02-25 13:08:23 -0500147
148 r->start_sector_abs = le32_to_cpup((uint32_t *)(p + 8));
149 r->nb_sectors_abs = le32_to_cpup((uint32_t *)(p + 12));
bellard7a5ca862008-05-27 21:13:40 +0000150}
151
Max Reitz4c58e802014-11-18 12:21:19 +0100152static int find_partition(BlockBackend *blk, int partition,
bellard7a5ca862008-05-27 21:13:40 +0000153 off_t *offset, off_t *size)
154{
155 struct partition_record mbr[4];
156 uint8_t data[512];
157 int i;
158 int ext_partnum = 4;
Ryota Ozakicb7cf0e2010-05-03 06:50:25 +0900159 int ret;
bellard7a5ca862008-05-27 21:13:40 +0000160
Max Reitz4c58e802014-11-18 12:21:19 +0100161 if ((ret = blk_read(blk, 0, data, 1)) < 0) {
Ryota Ozakicb7cf0e2010-05-03 06:50:25 +0900162 errno = -ret;
163 err(EXIT_FAILURE, "error while reading");
164 }
bellard7a5ca862008-05-27 21:13:40 +0000165
166 if (data[510] != 0x55 || data[511] != 0xaa) {
Paolo Bonzini185b4332012-03-05 08:56:10 +0100167 return -EINVAL;
bellard7a5ca862008-05-27 21:13:40 +0000168 }
169
170 for (i = 0; i < 4; i++) {
171 read_partition(&data[446 + 16 * i], &mbr[i]);
172
Max Reitz453b07b2015-02-25 13:08:15 -0500173 if (!mbr[i].system || !mbr[i].nb_sectors_abs) {
bellard7a5ca862008-05-27 21:13:40 +0000174 continue;
Max Reitz453b07b2015-02-25 13:08:15 -0500175 }
bellard7a5ca862008-05-27 21:13:40 +0000176
177 if (mbr[i].system == 0xF || mbr[i].system == 0x5) {
178 struct partition_record ext[4];
179 uint8_t data1[512];
180 int j;
181
Max Reitz4c58e802014-11-18 12:21:19 +0100182 if ((ret = blk_read(blk, mbr[i].start_sector_abs, data1, 1)) < 0) {
Ryota Ozakicb7cf0e2010-05-03 06:50:25 +0900183 errno = -ret;
184 err(EXIT_FAILURE, "error while reading");
185 }
bellard7a5ca862008-05-27 21:13:40 +0000186
187 for (j = 0; j < 4; j++) {
188 read_partition(&data1[446 + 16 * j], &ext[j]);
Max Reitz453b07b2015-02-25 13:08:15 -0500189 if (!ext[j].system || !ext[j].nb_sectors_abs) {
bellard7a5ca862008-05-27 21:13:40 +0000190 continue;
Max Reitz453b07b2015-02-25 13:08:15 -0500191 }
bellard7a5ca862008-05-27 21:13:40 +0000192
193 if ((ext_partnum + j + 1) == partition) {
194 *offset = (uint64_t)ext[j].start_sector_abs << 9;
195 *size = (uint64_t)ext[j].nb_sectors_abs << 9;
196 return 0;
197 }
198 }
199 ext_partnum += 4;
200 } else if ((i + 1) == partition) {
201 *offset = (uint64_t)mbr[i].start_sector_abs << 9;
202 *size = (uint64_t)mbr[i].nb_sectors_abs << 9;
203 return 0;
204 }
205 }
206
Paolo Bonzini185b4332012-03-05 08:56:10 +0100207 return -ENOENT;
bellard7a5ca862008-05-27 21:13:40 +0000208}
209
Paolo Bonzinibb345112011-11-04 15:51:19 +0100210static void termsig_handler(int signum)
211{
Paolo Bonzini7860a382012-09-18 13:31:56 +0200212 state = TERMINATE;
Paolo Bonzinia61c6782011-09-12 17:28:11 +0200213 qemu_notify_event();
Paolo Bonzinibb345112011-11-04 15:51:19 +0100214}
215
Paolo Bonzini537b41f2014-02-17 14:43:51 +0100216
Paolo Bonzinia517e882011-11-04 15:51:21 +0100217static void *show_parts(void *arg)
thscd831bd2008-07-03 10:23:51 +0000218{
Paolo Bonzinia6ac2312011-12-06 09:07:00 +0100219 char *device = arg;
Paolo Bonzinia517e882011-11-04 15:51:21 +0100220 int nbd;
thscd831bd2008-07-03 10:23:51 +0000221
Paolo Bonzinia517e882011-11-04 15:51:21 +0100222 /* linux just needs an open() to trigger
223 * the partition table update
224 * but remember to load the module with max_part != 0 :
225 * modprobe nbd max_part=63
226 */
227 nbd = open(device, O_RDWR);
Paolo Bonzinifc19f8a2012-03-07 11:05:34 +0100228 if (nbd >= 0) {
Paolo Bonzinia517e882011-11-04 15:51:21 +0100229 close(nbd);
thscd831bd2008-07-03 10:23:51 +0000230 }
Paolo Bonzinia517e882011-11-04 15:51:21 +0100231 return NULL;
232}
233
234static void *nbd_client_thread(void *arg)
235{
Paolo Bonzinia6ac2312011-12-06 09:07:00 +0100236 char *device = arg;
Paolo Bonzinia517e882011-11-04 15:51:21 +0100237 off_t size;
Paolo Bonzinia517e882011-11-04 15:51:21 +0100238 uint32_t nbdflags;
Paolo Bonzinia6ac2312011-12-06 09:07:00 +0100239 int fd, sock;
Paolo Bonzinia517e882011-11-04 15:51:21 +0100240 int ret;
241 pthread_t show_parts_thread;
Max Reitz1ce52842015-01-26 21:02:59 -0500242 Error *local_error = NULL;
Paolo Bonzinia517e882011-11-04 15:51:21 +0100243
Daniel P. Berrange48bec072015-09-16 14:52:23 +0100244
245 sock = socket_connect(saddr, &local_error, NULL, NULL);
Paolo Bonzinifc19f8a2012-03-07 11:05:34 +0100246 if (sock < 0) {
Daniel P. Berrange48bec072015-09-16 14:52:23 +0100247 error_report_err(local_error);
Stefan Hajnoczidc10e8b2012-01-05 13:16:07 +0000248 goto out;
249 }
Paolo Bonzinia517e882011-11-04 15:51:21 +0100250
251 ret = nbd_receive_negotiate(sock, NULL, &nbdflags,
Max Reitz3f472652015-02-25 13:08:25 -0500252 &size, &local_error);
Paolo Bonzinifc19f8a2012-03-07 11:05:34 +0100253 if (ret < 0) {
Max Reitz1ce52842015-01-26 21:02:59 -0500254 if (local_error) {
255 fprintf(stderr, "%s\n", error_get_pretty(local_error));
256 error_free(local_error);
257 }
Paolo Bonzini0c544d72014-03-14 18:10:54 +0100258 goto out_socket;
Paolo Bonzinia517e882011-11-04 15:51:21 +0100259 }
260
Paolo Bonzinia6ac2312011-12-06 09:07:00 +0100261 fd = open(device, O_RDWR);
Paolo Bonzinifc19f8a2012-03-07 11:05:34 +0100262 if (fd < 0) {
Paolo Bonzinia6ac2312011-12-06 09:07:00 +0100263 /* Linux-only, we can use %m in printf. */
Hani Benhabiles5672ee52014-05-13 00:35:16 +0100264 fprintf(stderr, "Failed to open %s: %m\n", device);
Paolo Bonzini0c544d72014-03-14 18:10:54 +0100265 goto out_socket;
Paolo Bonzinia6ac2312011-12-06 09:07:00 +0100266 }
267
Max Reitz3f472652015-02-25 13:08:25 -0500268 ret = nbd_init(fd, sock, nbdflags, size);
Paolo Bonzinifc19f8a2012-03-07 11:05:34 +0100269 if (ret < 0) {
Paolo Bonzini0c544d72014-03-14 18:10:54 +0100270 goto out_fd;
Paolo Bonzinia517e882011-11-04 15:51:21 +0100271 }
272
273 /* update partition table */
Paolo Bonzinia6ac2312011-12-06 09:07:00 +0100274 pthread_create(&show_parts_thread, NULL, show_parts, device);
Paolo Bonzinia517e882011-11-04 15:51:21 +0100275
Paolo Bonzinic1f8fdc2011-11-04 15:51:22 +0100276 if (verbose) {
277 fprintf(stderr, "NBD device %s is now connected to %s\n",
278 device, srcpath);
279 } else {
280 /* Close stderr so that the qemu-nbd process exits. */
281 dup2(STDOUT_FILENO, STDERR_FILENO);
282 }
Paolo Bonzinia517e882011-11-04 15:51:21 +0100283
284 ret = nbd_client(fd);
285 if (ret) {
Paolo Bonzini0c544d72014-03-14 18:10:54 +0100286 goto out_fd;
Paolo Bonzinia517e882011-11-04 15:51:21 +0100287 }
288 close(fd);
289 kill(getpid(), SIGTERM);
290 return (void *) EXIT_SUCCESS;
291
Paolo Bonzini0c544d72014-03-14 18:10:54 +0100292out_fd:
293 close(fd);
294out_socket:
295 closesocket(sock);
Paolo Bonzinia517e882011-11-04 15:51:21 +0100296out:
297 kill(getpid(), SIGTERM);
298 return (void *) EXIT_FAILURE;
thscd831bd2008-07-03 10:23:51 +0000299}
300
Fam Zhenge4afbf42015-05-19 10:50:59 +0000301static int nbd_can_accept(void)
Paolo Bonzinia61c6782011-09-12 17:28:11 +0200302{
303 return nb_fds < shared;
304}
305
Paolo Bonzini7860a382012-09-18 13:31:56 +0200306static void nbd_export_closed(NBDExport *exp)
307{
308 assert(state == TERMINATING);
309 state = TERMINATED;
310}
311
Fam Zhenge4afbf42015-05-19 10:50:59 +0000312static void nbd_update_server_fd_handler(int fd);
313
Paolo Bonzini1743b512011-09-19 14:33:23 +0200314static void nbd_client_closed(NBDClient *client)
Paolo Bonzinia61c6782011-09-12 17:28:11 +0200315{
Paolo Bonzini1743b512011-09-19 14:33:23 +0200316 nb_fds--;
Paolo Bonzini7860a382012-09-18 13:31:56 +0200317 if (nb_fds == 0 && !persistent && state == RUNNING) {
318 state = TERMINATE;
319 }
Fam Zhenge4afbf42015-05-19 10:50:59 +0000320 nbd_update_server_fd_handler(server_fd);
Paolo Bonzini7860a382012-09-18 13:31:56 +0200321 nbd_client_put(client);
Paolo Bonzinia61c6782011-09-12 17:28:11 +0200322}
323
324static void nbd_accept(void *opaque)
325{
Paolo Bonzinia61c6782011-09-12 17:28:11 +0200326 struct sockaddr_in addr;
327 socklen_t addr_len = sizeof(addr);
328
329 int fd = accept(server_fd, (struct sockaddr *)&addr, &addr_len);
Paolo Bonzini0c544d72014-03-14 18:10:54 +0100330 if (fd < 0) {
331 perror("accept");
332 return;
333 }
334
Paolo Bonzini7860a382012-09-18 13:31:56 +0200335 if (state >= TERMINATE) {
336 close(fd);
337 return;
338 }
339
Hani Benhabiles36af5992014-05-13 00:35:15 +0100340 if (nbd_client_new(exp, fd, nbd_client_closed)) {
Paolo Bonzinia61c6782011-09-12 17:28:11 +0200341 nb_fds++;
Fam Zhenge4afbf42015-05-19 10:50:59 +0000342 nbd_update_server_fd_handler(server_fd);
Hani Benhabiles36af5992014-05-13 00:35:15 +0100343 } else {
Hani Benhabiles27e5eae2014-05-31 22:39:42 +0100344 shutdown(fd, 2);
Hani Benhabiles36af5992014-05-13 00:35:15 +0100345 close(fd);
Paolo Bonzinia61c6782011-09-12 17:28:11 +0200346 }
347}
348
Fam Zhenge4afbf42015-05-19 10:50:59 +0000349static void nbd_update_server_fd_handler(int fd)
350{
351 if (nbd_can_accept()) {
352 qemu_set_fd_handler(fd, nbd_accept, NULL, (void *)(uintptr_t)fd);
353 } else {
354 qemu_set_fd_handler(fd, NULL, NULL, NULL);
355 }
356}
357
Daniel P. Berrange48bec072015-09-16 14:52:23 +0100358
359static SocketAddress *nbd_build_socket_address(const char *sockpath,
360 const char *bindto,
361 const char *port)
362{
363 SocketAddress *saddr;
364
365 saddr = g_new0(SocketAddress, 1);
366 if (sockpath) {
367 saddr->kind = SOCKET_ADDRESS_KIND_UNIX;
368 saddr->q_unix = g_new0(UnixSocketAddress, 1);
369 saddr->q_unix->path = g_strdup(sockpath);
370 } else {
371 saddr->kind = SOCKET_ADDRESS_KIND_INET;
372 saddr->inet = g_new0(InetSocketAddress, 1);
373 saddr->inet->host = g_strdup(bindto);
374 if (port) {
375 saddr->inet->port = g_strdup(port);
376 } else {
377 saddr->inet->port = g_strdup_printf("%d", NBD_DEFAULT_PORT);
378 }
379 }
380
381 return saddr;
382}
383
384
bellard7a5ca862008-05-27 21:13:40 +0000385int main(int argc, char **argv)
386{
Markus Armbruster26f54e92014-10-07 13:59:04 +0200387 BlockBackend *blk;
bellard7a5ca862008-05-27 21:13:40 +0000388 BlockDriverState *bs;
389 off_t dev_offset = 0;
Paolo Bonzinib90fb4b2011-09-08 17:24:54 +0200390 uint32_t nbdflags = 0;
thscd831bd2008-07-03 10:23:51 +0000391 bool disconnect = false;
bellard7a5ca862008-05-27 21:13:40 +0000392 const char *bindto = "0.0.0.0";
Daniel P. Berrange48bec072015-09-16 14:52:23 +0100393 const char *port = NULL;
394 char *sockpath = NULL;
Paolo Bonzinia6ac2312011-12-06 09:07:00 +0100395 char *device = NULL;
bellard7a5ca862008-05-27 21:13:40 +0000396 off_t fd_size;
Wenchao Xia8c116b02013-12-04 17:10:55 +0800397 QemuOpts *sn_opts = NULL;
398 const char *sn_id_or_name = NULL;
399 const char *sopt = "hVb:o:p:rsnP:c:dvk:e:f:tl:";
bellard7a5ca862008-05-27 21:13:40 +0000400 struct option lopt[] = {
Blue Swirl660f11b2009-07-31 21:16:51 +0000401 { "help", 0, NULL, 'h' },
402 { "version", 0, NULL, 'V' },
403 { "bind", 1, NULL, 'b' },
404 { "port", 1, NULL, 'p' },
405 { "socket", 1, NULL, 'k' },
406 { "offset", 1, NULL, 'o' },
407 { "read-only", 0, NULL, 'r' },
408 { "partition", 1, NULL, 'P' },
409 { "connect", 1, NULL, 'c' },
410 { "disconnect", 0, NULL, 'd' },
411 { "snapshot", 0, NULL, 's' },
Wenchao Xia8c116b02013-12-04 17:10:55 +0800412 { "load-snapshot", 1, NULL, 'l' },
Blue Swirl660f11b2009-07-31 21:16:51 +0000413 { "nocache", 0, NULL, 'n' },
Paolo Bonzini39a52352012-07-18 14:57:15 +0200414 { "cache", 1, NULL, QEMU_NBD_OPT_CACHE },
415#ifdef CONFIG_LINUX_AIO
416 { "aio", 1, NULL, QEMU_NBD_OPT_AIO },
417#endif
Paolo Bonzinided9d2d2013-02-08 14:06:13 +0100418 { "discard", 1, NULL, QEMU_NBD_OPT_DISCARD },
Peter Lievenb3838a42014-08-13 19:20:18 +0200419 { "detect-zeroes", 1, NULL, QEMU_NBD_OPT_DETECT_ZEROES },
Blue Swirl660f11b2009-07-31 21:16:51 +0000420 { "shared", 1, NULL, 'e' },
Daniel P. Berrangee6b63672013-03-19 11:20:20 +0000421 { "format", 1, NULL, 'f' },
Blue Swirl660f11b2009-07-31 21:16:51 +0000422 { "persistent", 0, NULL, 't' },
423 { "verbose", 0, NULL, 'v' },
424 { NULL, 0, NULL, 0 }
bellard7a5ca862008-05-27 21:13:40 +0000425 };
426 int ch;
427 int opt_ind = 0;
bellard7a5ca862008-05-27 21:13:40 +0000428 char *end;
Naphtali Spreif5edb012010-01-17 16:48:13 +0200429 int flags = BDRV_O_RDWR;
bellard7a5ca862008-05-27 21:13:40 +0000430 int partition = -1;
Max Reitz4fbec262015-02-05 13:58:19 -0500431 int ret = 0;
ths3b05a8e2008-07-03 12:45:02 +0000432 int fd;
Paolo Bonzini39a52352012-07-18 14:57:15 +0200433 bool seen_cache = false;
Paolo Bonzinided9d2d2013-02-08 14:06:13 +0100434 bool seen_discard = false;
Paolo Bonzini39a52352012-07-18 14:57:15 +0200435#ifdef CONFIG_LINUX_AIO
436 bool seen_aio = false;
437#endif
Paolo Bonzinia517e882011-11-04 15:51:21 +0100438 pthread_t client_thread;
Daniel P. Berrangee6b63672013-03-19 11:20:20 +0000439 const char *fmt = NULL;
Max Reitz34b5d2c2013-09-05 14:45:29 +0200440 Error *local_err = NULL;
Peter Lievenb3838a42014-08-13 19:20:18 +0200441 BlockdevDetectZeroesOptions detect_zeroes = BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF;
Max Reitz4fbec262015-02-05 13:58:19 -0500442 QDict *options = NULL;
bellard7a5ca862008-05-27 21:13:40 +0000443
Paolo Bonzinia517e882011-11-04 15:51:21 +0100444 /* The client thread uses SIGTERM to interrupt the server. A signal
445 * handler ensures that "qemu-nbd -v -c" exits with a nice status code.
446 */
Paolo Bonzinibb345112011-11-04 15:51:19 +0100447 struct sigaction sa_sigterm;
Paolo Bonzinibb345112011-11-04 15:51:19 +0100448 memset(&sa_sigterm, 0, sizeof(sa_sigterm));
449 sa_sigterm.sa_handler = termsig_handler;
450 sigaction(SIGTERM, &sa_sigterm, NULL);
Fam Zheng10f5bff2014-02-10 14:48:51 +0800451 qemu_init_exec_dir(argv[0]);
Paolo Bonzinibb345112011-11-04 15:51:19 +0100452
bellard7a5ca862008-05-27 21:13:40 +0000453 while ((ch = getopt_long(argc, argv, sopt, lopt, &opt_ind)) != -1) {
454 switch (ch) {
455 case 's':
ths2f726482008-07-03 11:47:46 +0000456 flags |= BDRV_O_SNAPSHOT;
457 break;
458 case 'n':
Paolo Bonzini39a52352012-07-18 14:57:15 +0200459 optarg = (char *) "none";
460 /* fallthrough */
461 case QEMU_NBD_OPT_CACHE:
462 if (seen_cache) {
463 errx(EXIT_FAILURE, "-n and --cache can only be specified once");
464 }
465 seen_cache = true;
466 if (bdrv_parse_cache_flags(optarg, &flags) == -1) {
467 errx(EXIT_FAILURE, "Invalid cache mode `%s'", optarg);
468 }
bellard7a5ca862008-05-27 21:13:40 +0000469 break;
Paolo Bonzini39a52352012-07-18 14:57:15 +0200470#ifdef CONFIG_LINUX_AIO
471 case QEMU_NBD_OPT_AIO:
472 if (seen_aio) {
473 errx(EXIT_FAILURE, "--aio can only be specified once");
474 }
475 seen_aio = true;
476 if (!strcmp(optarg, "native")) {
477 flags |= BDRV_O_NATIVE_AIO;
478 } else if (!strcmp(optarg, "threads")) {
479 /* this is the default */
480 } else {
481 errx(EXIT_FAILURE, "invalid aio mode `%s'", optarg);
482 }
483 break;
484#endif
Paolo Bonzinided9d2d2013-02-08 14:06:13 +0100485 case QEMU_NBD_OPT_DISCARD:
486 if (seen_discard) {
487 errx(EXIT_FAILURE, "--discard can only be specified once");
488 }
489 seen_discard = true;
490 if (bdrv_parse_discard_flags(optarg, &flags) == -1) {
491 errx(EXIT_FAILURE, "Invalid discard mode `%s'", optarg);
492 }
493 break;
Peter Lievenb3838a42014-08-13 19:20:18 +0200494 case QEMU_NBD_OPT_DETECT_ZEROES:
495 detect_zeroes =
496 qapi_enum_parse(BlockdevDetectZeroesOptions_lookup,
497 optarg,
498 BLOCKDEV_DETECT_ZEROES_OPTIONS_MAX,
499 BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF,
500 &local_err);
501 if (local_err) {
502 errx(EXIT_FAILURE, "Failed to parse detect_zeroes mode: %s",
503 error_get_pretty(local_err));
504 }
505 if (detect_zeroes == BLOCKDEV_DETECT_ZEROES_OPTIONS_UNMAP &&
506 !(flags & BDRV_O_UNMAP)) {
507 errx(EXIT_FAILURE, "setting detect-zeroes to unmap is not allowed "
508 "without setting discard operation to unmap");
509 }
510 break;
bellard7a5ca862008-05-27 21:13:40 +0000511 case 'b':
512 bindto = optarg;
513 break;
514 case 'p':
Daniel P. Berrange48bec072015-09-16 14:52:23 +0100515 port = optarg;
bellard7a5ca862008-05-27 21:13:40 +0000516 break;
517 case 'o':
518 dev_offset = strtoll (optarg, &end, 0);
519 if (*end) {
Ryota Ozakib6353be2010-03-20 15:23:23 +0900520 errx(EXIT_FAILURE, "Invalid offset `%s'", optarg);
bellard7a5ca862008-05-27 21:13:40 +0000521 }
522 if (dev_offset < 0) {
Ryota Ozakib6353be2010-03-20 15:23:23 +0900523 errx(EXIT_FAILURE, "Offset must be positive `%s'", optarg);
bellard7a5ca862008-05-27 21:13:40 +0000524 }
525 break;
Wenchao Xia8c116b02013-12-04 17:10:55 +0800526 case 'l':
527 if (strstart(optarg, SNAPSHOT_OPT_BASE, NULL)) {
Markus Armbruster70b94332015-02-13 12:50:26 +0100528 sn_opts = qemu_opts_parse_noisily(&internal_snapshot_opts,
529 optarg, false);
Wenchao Xia8c116b02013-12-04 17:10:55 +0800530 if (!sn_opts) {
531 errx(EXIT_FAILURE, "Failed in parsing snapshot param `%s'",
532 optarg);
533 }
534 } else {
535 sn_id_or_name = optarg;
536 }
537 /* fall through */
bellard7a5ca862008-05-27 21:13:40 +0000538 case 'r':
Paolo Bonzinib90fb4b2011-09-08 17:24:54 +0200539 nbdflags |= NBD_FLAG_READ_ONLY;
Naphtali Sprei07108b22010-03-14 15:19:57 +0200540 flags &= ~BDRV_O_RDWR;
bellard7a5ca862008-05-27 21:13:40 +0000541 break;
542 case 'P':
543 partition = strtol(optarg, &end, 0);
Peter Lieven713cc672014-08-13 19:20:19 +0200544 if (*end) {
Ryota Ozakib6353be2010-03-20 15:23:23 +0900545 errx(EXIT_FAILURE, "Invalid partition `%s'", optarg);
Peter Lieven713cc672014-08-13 19:20:19 +0200546 }
547 if (partition < 1 || partition > 8) {
Ryota Ozakib6353be2010-03-20 15:23:23 +0900548 errx(EXIT_FAILURE, "Invalid partition %d", partition);
Peter Lieven713cc672014-08-13 19:20:19 +0200549 }
bellard7a5ca862008-05-27 21:13:40 +0000550 break;
thscd831bd2008-07-03 10:23:51 +0000551 case 'k':
Paolo Bonzinib32f6c22011-11-04 15:51:20 +0100552 sockpath = optarg;
Peter Lieven713cc672014-08-13 19:20:19 +0200553 if (sockpath[0] != '/') {
Ryota Ozakib6353be2010-03-20 15:23:23 +0900554 errx(EXIT_FAILURE, "socket path must be absolute\n");
Peter Lieven713cc672014-08-13 19:20:19 +0200555 }
thscd831bd2008-07-03 10:23:51 +0000556 break;
557 case 'd':
558 disconnect = true;
559 break;
560 case 'c':
561 device = optarg;
562 break;
ths3b05a8e2008-07-03 12:45:02 +0000563 case 'e':
564 shared = strtol(optarg, &end, 0);
565 if (*end) {
Ryota Ozakib6353be2010-03-20 15:23:23 +0900566 errx(EXIT_FAILURE, "Invalid shared device number '%s'", optarg);
ths3b05a8e2008-07-03 12:45:02 +0000567 }
568 if (shared < 1) {
Ryota Ozakib6353be2010-03-20 15:23:23 +0900569 errx(EXIT_FAILURE, "Shared device number must be greater than 0\n");
ths3b05a8e2008-07-03 12:45:02 +0000570 }
571 break;
Daniel P. Berrangee6b63672013-03-19 11:20:20 +0000572 case 'f':
573 fmt = optarg;
574 break;
Peter Lieven713cc672014-08-13 19:20:19 +0200575 case 't':
576 persistent = 1;
577 break;
bellard7a5ca862008-05-27 21:13:40 +0000578 case 'v':
579 verbose = 1;
580 break;
581 case 'V':
582 version(argv[0]);
583 exit(0);
584 break;
585 case 'h':
586 usage(argv[0]);
587 exit(0);
588 break;
589 case '?':
Ryota Ozakib6353be2010-03-20 15:23:23 +0900590 errx(EXIT_FAILURE, "Try `%s --help' for more information.",
bellard7a5ca862008-05-27 21:13:40 +0000591 argv[0]);
592 }
593 }
594
595 if ((argc - optind) != 1) {
Ryota Ozakib6353be2010-03-20 15:23:23 +0900596 errx(EXIT_FAILURE, "Invalid number of argument.\n"
bellard7a5ca862008-05-27 21:13:40 +0000597 "Try `%s --help' for more information.",
598 argv[0]);
599 }
600
thscd831bd2008-07-03 10:23:51 +0000601 if (disconnect) {
602 fd = open(argv[optind], O_RDWR);
Paolo Bonzinifc19f8a2012-03-07 11:05:34 +0100603 if (fd < 0) {
Ryota Ozakicb7cf0e2010-05-03 06:50:25 +0900604 err(EXIT_FAILURE, "Cannot open %s", argv[optind]);
Paolo Bonzinifc19f8a2012-03-07 11:05:34 +0100605 }
thscd831bd2008-07-03 10:23:51 +0000606 nbd_disconnect(fd);
607
608 close(fd);
609
610 printf("%s disconnected\n", argv[optind]);
611
Peter Lieven713cc672014-08-13 19:20:19 +0200612 return 0;
thscd831bd2008-07-03 10:23:51 +0000613 }
614
Paolo Bonzinic1f8fdc2011-11-04 15:51:22 +0100615 if (device && !verbose) {
616 int stderr_fd[2];
617 pid_t pid;
618 int ret;
619
Paolo Bonzinifc19f8a2012-03-07 11:05:34 +0100620 if (qemu_pipe(stderr_fd) < 0) {
Paolo Bonzinic1f8fdc2011-11-04 15:51:22 +0100621 err(EXIT_FAILURE, "Error setting up communication pipe");
622 }
623
624 /* Now daemonize, but keep a communication channel open to
625 * print errors and exit with the proper status code.
626 */
627 pid = fork();
Max Reitz70d47392015-02-25 13:08:22 -0500628 if (pid < 0) {
629 err(EXIT_FAILURE, "Failed to fork");
630 } else if (pid == 0) {
Paolo Bonzinic1f8fdc2011-11-04 15:51:22 +0100631 close(stderr_fd[0]);
Michael Tokarev9faf31b2012-01-16 18:37:44 +0400632 ret = qemu_daemon(1, 0);
Paolo Bonzinic1f8fdc2011-11-04 15:51:22 +0100633
634 /* Temporarily redirect stderr to the parent's pipe... */
635 dup2(stderr_fd[1], STDERR_FILENO);
Paolo Bonzinifc19f8a2012-03-07 11:05:34 +0100636 if (ret < 0) {
Paolo Bonzinic1f8fdc2011-11-04 15:51:22 +0100637 err(EXIT_FAILURE, "Failed to daemonize");
638 }
639
640 /* ... close the descriptor we inherited and go on. */
641 close(stderr_fd[1]);
642 } else {
643 bool errors = false;
644 char *buf;
645
646 /* In the parent. Print error messages from the child until
647 * it closes the pipe.
648 */
649 close(stderr_fd[1]);
650 buf = g_malloc(1024);
651 while ((ret = read(stderr_fd[0], buf, 1024)) > 0) {
652 errors = true;
653 ret = qemu_write_full(STDERR_FILENO, buf, ret);
Paolo Bonzinifc19f8a2012-03-07 11:05:34 +0100654 if (ret < 0) {
Paolo Bonzinic1f8fdc2011-11-04 15:51:22 +0100655 exit(EXIT_FAILURE);
656 }
657 }
Paolo Bonzinifc19f8a2012-03-07 11:05:34 +0100658 if (ret < 0) {
Paolo Bonzinic1f8fdc2011-11-04 15:51:22 +0100659 err(EXIT_FAILURE, "Cannot read from daemon");
660 }
661
662 /* Usually the daemon should not print any message.
663 * Exit with zero status in that case.
664 */
665 exit(errors);
666 }
667 }
668
Paolo Bonzinia6ac2312011-12-06 09:07:00 +0100669 if (device != NULL && sockpath == NULL) {
670 sockpath = g_malloc(128);
671 snprintf(sockpath, 128, SOCKET_PATH, basename(device));
thscd831bd2008-07-03 10:23:51 +0000672 }
673
Daniel P. Berrange48bec072015-09-16 14:52:23 +0100674 saddr = nbd_build_socket_address(sockpath, bindto, port);
675
Chrysostomos Nanakos2f78e492014-09-18 14:30:49 +0300676 if (qemu_init_main_loop(&local_err)) {
Markus Armbruster565f65d2015-02-12 13:55:05 +0100677 error_report_err(local_err);
Chrysostomos Nanakos2f78e492014-09-18 14:30:49 +0300678 exit(EXIT_FAILURE);
679 }
Paolo Bonzini802ddc32011-11-04 15:51:24 +0100680 bdrv_init();
681 atexit(bdrv_close_all);
682
Daniel P. Berrangee6b63672013-03-19 11:20:20 +0000683 if (fmt) {
Max Reitz4fbec262015-02-05 13:58:19 -0500684 options = qdict_new();
685 qdict_put(options, "driver", qstring_from_str(fmt));
Daniel P. Berrangee6b63672013-03-19 11:20:20 +0000686 }
687
Paolo Bonzini802ddc32011-11-04 15:51:24 +0100688 srcpath = argv[optind];
Max Reitz4fbec262015-02-05 13:58:19 -0500689 blk = blk_new_open("hda", srcpath, NULL, options, flags, &local_err);
690 if (!blk) {
691 errx(EXIT_FAILURE, "Failed to blk_new_open '%s': %s", argv[optind],
692 error_get_pretty(local_err));
Paolo Bonzini802ddc32011-11-04 15:51:24 +0100693 }
Max Reitz4fbec262015-02-05 13:58:19 -0500694 bs = blk_bs(blk);
Paolo Bonzini802ddc32011-11-04 15:51:24 +0100695
Wenchao Xia8c116b02013-12-04 17:10:55 +0800696 if (sn_opts) {
697 ret = bdrv_snapshot_load_tmp(bs,
698 qemu_opt_get(sn_opts, SNAPSHOT_OPT_ID),
699 qemu_opt_get(sn_opts, SNAPSHOT_OPT_NAME),
700 &local_err);
701 } else if (sn_id_or_name) {
702 ret = bdrv_snapshot_load_tmp_by_id_or_name(bs, sn_id_or_name,
703 &local_err);
704 }
705 if (ret < 0) {
706 errno = -ret;
707 err(EXIT_FAILURE,
708 "Failed to load snapshot: %s",
709 error_get_pretty(local_err));
710 }
711
Peter Lievenb3838a42014-08-13 19:20:18 +0200712 bs->detect_zeroes = detect_zeroes;
Max Reitz4c58e802014-11-18 12:21:19 +0100713 fd_size = blk_getlength(blk);
Max Reitz98f44bb2015-02-25 13:08:21 -0500714 if (fd_size < 0) {
715 errx(EXIT_FAILURE, "Failed to determine the image length: %s",
716 strerror(-fd_size));
717 }
Paolo Bonzini802ddc32011-11-04 15:51:24 +0100718
Paolo Bonzini185b4332012-03-05 08:56:10 +0100719 if (partition != -1) {
Max Reitz4c58e802014-11-18 12:21:19 +0100720 ret = find_partition(blk, partition, &dev_offset, &fd_size);
Paolo Bonzini185b4332012-03-05 08:56:10 +0100721 if (ret < 0) {
722 errno = -ret;
723 err(EXIT_FAILURE, "Could not find partition %d", partition);
724 }
Paolo Bonzini802ddc32011-11-04 15:51:24 +0100725 }
726
Max Reitz98f44bb2015-02-25 13:08:21 -0500727 exp = nbd_export_new(blk, dev_offset, fd_size, nbdflags, nbd_export_closed,
728 &local_err);
729 if (!exp) {
730 errx(EXIT_FAILURE, "%s", error_get_pretty(local_err));
731 }
ths3b05a8e2008-07-03 12:45:02 +0000732
Daniel P. Berrange48bec072015-09-16 14:52:23 +0100733 fd = socket_listen(saddr, &local_err);
Paolo Bonzinifc19f8a2012-03-07 11:05:34 +0100734 if (fd < 0) {
Daniel P. Berrange48bec072015-09-16 14:52:23 +0100735 error_report_err(local_err);
bellard7a5ca862008-05-27 21:13:40 +0000736 return 1;
Paolo Bonzinia61c6782011-09-12 17:28:11 +0200737 }
Paolo Bonzinif1ef5552011-11-04 15:51:23 +0100738
739 if (device) {
740 int ret;
741
Paolo Bonzinia6ac2312011-12-06 09:07:00 +0100742 ret = pthread_create(&client_thread, NULL, nbd_client_thread, device);
Paolo Bonzinif1ef5552011-11-04 15:51:23 +0100743 if (ret != 0) {
744 errx(EXIT_FAILURE, "Failed to create client thread: %s",
745 strerror(ret));
746 }
747 } else {
748 /* Shut up GCC warnings. */
749 memset(&client_thread, 0, sizeof(client_thread));
750 }
751
Fam Zhenge4afbf42015-05-19 10:50:59 +0000752 server_fd = fd;
753 nbd_update_server_fd_handler(fd);
bellard7a5ca862008-05-27 21:13:40 +0000754
Michael Tokarev9faf31b2012-01-16 18:37:44 +0400755 /* now when the initialization is (almost) complete, chdir("/")
756 * to free any busy filesystems */
757 if (chdir("/") < 0) {
758 err(EXIT_FAILURE, "Could not chdir to root directory");
759 }
760
Paolo Bonzini7860a382012-09-18 13:31:56 +0200761 state = RUNNING;
ths3b05a8e2008-07-03 12:45:02 +0000762 do {
Paolo Bonzinia61c6782011-09-12 17:28:11 +0200763 main_loop_wait(false);
Paolo Bonzini7860a382012-09-18 13:31:56 +0200764 if (state == TERMINATE) {
765 state = TERMINATING;
766 nbd_export_close(exp);
767 nbd_export_put(exp);
768 exp = NULL;
769 }
770 } while (state != TERMINATED);
ths3b05a8e2008-07-03 12:45:02 +0000771
Markus Armbruster26f54e92014-10-07 13:59:04 +0200772 blk_unref(blk);
Paolo Bonzinib32f6c22011-11-04 15:51:20 +0100773 if (sockpath) {
774 unlink(sockpath);
775 }
bellard7a5ca862008-05-27 21:13:40 +0000776
Markus Armbrusterfbf28a42014-09-29 16:07:55 +0200777 qemu_opts_del(sn_opts);
Wenchao Xia8c116b02013-12-04 17:10:55 +0800778
Paolo Bonzinia517e882011-11-04 15:51:21 +0100779 if (device) {
780 void *ret;
781 pthread_join(client_thread, &ret);
782 exit(ret != NULL);
783 } else {
784 exit(EXIT_SUCCESS);
785 }
bellard7a5ca862008-05-27 21:13:40 +0000786}