]> git.proxmox.com Git - mirror_qemu.git/blame - qemu-nbd.c
qemu-nbd: move client to a thread
[mirror_qemu.git] / qemu-nbd.c
CommitLineData
cd831bd7 1/*
7a5ca864
FB
2 * 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
8167ee88 16 * along with this program; if not, see <http://www.gnu.org/licenses/>.
7a5ca864
FB
17 */
18
5a61cb60 19#include "qemu-common.h"
7a5ca864
FB
20#include "block_int.h"
21#include "nbd.h"
22
7a5ca864
FB
23#include <stdarg.h>
24#include <stdio.h>
25#include <getopt.h>
26#include <err.h>
cd831bd7 27#include <sys/types.h>
7a5ca864
FB
28#include <sys/socket.h>
29#include <netinet/in.h>
30#include <netinet/tcp.h>
31#include <arpa/inet.h>
cd831bd7 32#include <signal.h>
2bff4b6f 33#include <libgen.h>
a517e88b 34#include <pthread.h>
cd831bd7
TS
35
36#define SOCKET_PATH "/var/lock/qemu-nbd-%s"
7a5ca864 37
2f726488
TS
38#define NBD_BUFFER_SIZE (1024*1024)
39
bb345110 40static int sigterm_wfd;
b1d8e52e 41static int verbose;
a517e88b
PB
42static char *device;
43static char *srcpath;
44static char *sockpath;
7a5ca864
FB
45
46static void usage(const char *name)
47{
48 printf(
49"Usage: %s [OPTIONS] FILE\n"
50"QEMU Disk Network Block Device Server\n"
51"\n"
c2e2872b 52" -p, --port=PORT port to listen on (default `%d')\n"
7a5ca864
FB
53" -o, --offset=OFFSET offset into the image\n"
54" -b, --bind=IFACE interface to bind to (default `0.0.0.0')\n"
cd831bd7
TS
55" -k, --socket=PATH path to the unix socket\n"
56" (default '"SOCKET_PATH"')\n"
7a5ca864
FB
57" -r, --read-only export read-only\n"
58" -P, --partition=NUM only expose partition NUM\n"
2f726488
TS
59" -s, --snapshot use snapshot file\n"
60" -n, --nocache disable host cache\n"
cd831bd7
TS
61" -c, --connect=DEV connect FILE to the local NBD device DEV\n"
62" -d, --disconnect disconnect the specified device\n"
3b05a8e9 63" -e, --shared=NUM device can be shared by NUM clients (default '1')\n"
75818250 64" -t, --persistent don't exit on the last connection\n"
7a5ca864
FB
65" -v, --verbose display extra debugging information\n"
66" -h, --help display this help and exit\n"
67" -V, --version output version information and exit\n"
68"\n"
69"Report bugs to <anthony@codemonkey.ws>\n"
c2e2872b 70 , name, NBD_DEFAULT_PORT, "DEVICE");
7a5ca864
FB
71}
72
73static void version(const char *name)
74{
75 printf(
315bc7aa 76"%s version 0.0.1\n"
7a5ca864
FB
77"Written by Anthony Liguori.\n"
78"\n"
79"Copyright (C) 2006 Anthony Liguori <anthony@codemonkey.ws>.\n"
80"This is free software; see the source for copying conditions. There is NO\n"
81"warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n"
315bc7aa 82 , name);
7a5ca864
FB
83}
84
85struct partition_record
86{
87 uint8_t bootable;
88 uint8_t start_head;
89 uint32_t start_cylinder;
90 uint8_t start_sector;
91 uint8_t system;
92 uint8_t end_head;
93 uint8_t end_cylinder;
94 uint8_t end_sector;
95 uint32_t start_sector_abs;
96 uint32_t nb_sectors_abs;
97};
98
99static void read_partition(uint8_t *p, struct partition_record *r)
100{
101 r->bootable = p[0];
102 r->start_head = p[1];
103 r->start_cylinder = p[3] | ((p[2] << 2) & 0x0300);
104 r->start_sector = p[2] & 0x3f;
105 r->system = p[4];
106 r->end_head = p[5];
107 r->end_cylinder = p[7] | ((p[6] << 2) & 0x300);
108 r->end_sector = p[6] & 0x3f;
109 r->start_sector_abs = p[8] | p[9] << 8 | p[10] << 16 | p[11] << 24;
110 r->nb_sectors_abs = p[12] | p[13] << 8 | p[14] << 16 | p[15] << 24;
111}
112
113static int find_partition(BlockDriverState *bs, int partition,
114 off_t *offset, off_t *size)
115{
116 struct partition_record mbr[4];
117 uint8_t data[512];
118 int i;
119 int ext_partnum = 4;
cb7cf0e3 120 int ret;
7a5ca864 121
cb7cf0e3
RO
122 if ((ret = bdrv_read(bs, 0, data, 1)) < 0) {
123 errno = -ret;
124 err(EXIT_FAILURE, "error while reading");
125 }
7a5ca864
FB
126
127 if (data[510] != 0x55 || data[511] != 0xaa) {
128 errno = -EINVAL;
129 return -1;
130 }
131
132 for (i = 0; i < 4; i++) {
133 read_partition(&data[446 + 16 * i], &mbr[i]);
134
135 if (!mbr[i].nb_sectors_abs)
136 continue;
137
138 if (mbr[i].system == 0xF || mbr[i].system == 0x5) {
139 struct partition_record ext[4];
140 uint8_t data1[512];
141 int j;
142
cb7cf0e3
RO
143 if ((ret = bdrv_read(bs, mbr[i].start_sector_abs, data1, 1)) < 0) {
144 errno = -ret;
145 err(EXIT_FAILURE, "error while reading");
146 }
7a5ca864
FB
147
148 for (j = 0; j < 4; j++) {
149 read_partition(&data1[446 + 16 * j], &ext[j]);
150 if (!ext[j].nb_sectors_abs)
151 continue;
152
153 if ((ext_partnum + j + 1) == partition) {
154 *offset = (uint64_t)ext[j].start_sector_abs << 9;
155 *size = (uint64_t)ext[j].nb_sectors_abs << 9;
156 return 0;
157 }
158 }
159 ext_partnum += 4;
160 } else if ((i + 1) == partition) {
161 *offset = (uint64_t)mbr[i].start_sector_abs << 9;
162 *size = (uint64_t)mbr[i].nb_sectors_abs << 9;
163 return 0;
164 }
165 }
166
167 errno = -ENOENT;
168 return -1;
169}
170
bb345110
PB
171static void termsig_handler(int signum)
172{
173 static int sigterm_reported;
174 if (!sigterm_reported) {
175 sigterm_reported = (write(sigterm_wfd, "", 1) == 1);
176 }
177}
178
a517e88b 179static void *show_parts(void *arg)
cd831bd7 180{
a517e88b
PB
181 int nbd;
182
183 /* linux just needs an open() to trigger
184 * the partition table update
185 * but remember to load the module with max_part != 0 :
186 * modprobe nbd max_part=63
187 */
188 nbd = open(device, O_RDWR);
189 if (nbd != -1) {
190 close(nbd);
191 }
192 return NULL;
193}
cd831bd7 194
a517e88b
PB
195static void *nbd_client_thread(void *arg)
196{
197 int fd = *(int *)arg;
198 off_t size;
199 size_t blocksize;
200 uint32_t nbdflags;
201 int sock;
202 int ret;
203 pthread_t show_parts_thread;
204
205 do {
206 sock = unix_socket_outgoing(sockpath);
207 if (sock == -1) {
208 if (errno != ENOENT && errno != ECONNREFUSED) {
209 goto out;
210 }
211 sleep(1); /* wait parent */
212 }
213 } while (sock == -1);
214
215 ret = nbd_receive_negotiate(sock, NULL, &nbdflags,
216 &size, &blocksize);
217 if (ret == -1) {
218 goto out;
219 }
220
221 ret = nbd_init(fd, sock, nbdflags, size, blocksize);
222 if (ret == -1) {
223 goto out;
224 }
225
226 /* update partition table */
227 pthread_create(&show_parts_thread, NULL, show_parts, NULL);
228
229 fprintf(stderr, "NBD device %s is now connected to %s\n",
230 device, srcpath);
231
232 ret = nbd_client(fd);
233 if (ret) {
234 goto out;
cd831bd7 235 }
a517e88b
PB
236 close(fd);
237 kill(getpid(), SIGTERM);
238 return (void *) EXIT_SUCCESS;
239
240out:
241 kill(getpid(), SIGTERM);
242 return (void *) EXIT_FAILURE;
cd831bd7
TS
243}
244
7a5ca864
FB
245int main(int argc, char **argv)
246{
247 BlockDriverState *bs;
248 off_t dev_offset = 0;
249 off_t offset = 0;
b90fb4b8 250 uint32_t nbdflags = 0;
cd831bd7 251 bool disconnect = false;
7a5ca864 252 const char *bindto = "0.0.0.0";
c2e2872b 253 int port = NBD_DEFAULT_PORT;
7a5ca864
FB
254 struct sockaddr_in addr;
255 socklen_t addr_len = sizeof(addr);
256 off_t fd_size;
d6aa671f 257 const char *sopt = "hVb:o:p:rsnP:c:dvk:e:t";
7a5ca864 258 struct option lopt[] = {
660f11be
BS
259 { "help", 0, NULL, 'h' },
260 { "version", 0, NULL, 'V' },
261 { "bind", 1, NULL, 'b' },
262 { "port", 1, NULL, 'p' },
263 { "socket", 1, NULL, 'k' },
264 { "offset", 1, NULL, 'o' },
265 { "read-only", 0, NULL, 'r' },
266 { "partition", 1, NULL, 'P' },
267 { "connect", 1, NULL, 'c' },
268 { "disconnect", 0, NULL, 'd' },
269 { "snapshot", 0, NULL, 's' },
270 { "nocache", 0, NULL, 'n' },
271 { "shared", 1, NULL, 'e' },
272 { "persistent", 0, NULL, 't' },
273 { "verbose", 0, NULL, 'v' },
274 { NULL, 0, NULL, 0 }
7a5ca864
FB
275 };
276 int ch;
277 int opt_ind = 0;
278 int li;
279 char *end;
f5edb014 280 int flags = BDRV_O_RDWR;
7a5ca864 281 int partition = -1;
cd831bd7 282 int ret;
3b05a8e9 283 int shared = 1;
2f726488 284 uint8_t *data;
3b05a8e9
TS
285 fd_set fds;
286 int *sharing_fds;
287 int fd;
288 int i;
289 int nb_fds = 0;
290 int max_fd;
75818250 291 int persistent = 0;
a517e88b 292 pthread_t client_thread;
7a5ca864 293
a517e88b
PB
294 /* The client thread uses SIGTERM to interrupt the server. A signal
295 * handler ensures that "qemu-nbd -v -c" exits with a nice status code.
296 */
bb345110
PB
297 struct sigaction sa_sigterm;
298 int sigterm_fd[2];
299 if (qemu_pipe(sigterm_fd) == -1) {
300 err(EXIT_FAILURE, "Error setting up communication pipe");
301 }
302
303 sigterm_wfd = sigterm_fd[1];
304 memset(&sa_sigterm, 0, sizeof(sa_sigterm));
305 sa_sigterm.sa_handler = termsig_handler;
306 sigaction(SIGTERM, &sa_sigterm, NULL);
307
7a5ca864
FB
308 while ((ch = getopt_long(argc, argv, sopt, lopt, &opt_ind)) != -1) {
309 switch (ch) {
310 case 's':
2f726488
TS
311 flags |= BDRV_O_SNAPSHOT;
312 break;
313 case 'n':
a6599793 314 flags |= BDRV_O_NOCACHE | BDRV_O_CACHE_WB;
7a5ca864
FB
315 break;
316 case 'b':
317 bindto = optarg;
318 break;
319 case 'p':
320 li = strtol(optarg, &end, 0);
321 if (*end) {
b6353bea 322 errx(EXIT_FAILURE, "Invalid port `%s'", optarg);
7a5ca864
FB
323 }
324 if (li < 1 || li > 65535) {
b6353bea 325 errx(EXIT_FAILURE, "Port out of range `%s'", optarg);
7a5ca864
FB
326 }
327 port = (uint16_t)li;
328 break;
329 case 'o':
330 dev_offset = strtoll (optarg, &end, 0);
331 if (*end) {
b6353bea 332 errx(EXIT_FAILURE, "Invalid offset `%s'", optarg);
7a5ca864
FB
333 }
334 if (dev_offset < 0) {
b6353bea 335 errx(EXIT_FAILURE, "Offset must be positive `%s'", optarg);
7a5ca864
FB
336 }
337 break;
338 case 'r':
b90fb4b8 339 nbdflags |= NBD_FLAG_READ_ONLY;
07108b29 340 flags &= ~BDRV_O_RDWR;
7a5ca864
FB
341 break;
342 case 'P':
343 partition = strtol(optarg, &end, 0);
344 if (*end)
b6353bea 345 errx(EXIT_FAILURE, "Invalid partition `%s'", optarg);
7a5ca864 346 if (partition < 1 || partition > 8)
b6353bea 347 errx(EXIT_FAILURE, "Invalid partition %d", partition);
7a5ca864 348 break;
cd831bd7 349 case 'k':
b32f6c28
PB
350 sockpath = optarg;
351 if (sockpath[0] != '/')
b6353bea 352 errx(EXIT_FAILURE, "socket path must be absolute\n");
cd831bd7
TS
353 break;
354 case 'd':
355 disconnect = true;
356 break;
357 case 'c':
358 device = optarg;
359 break;
3b05a8e9
TS
360 case 'e':
361 shared = strtol(optarg, &end, 0);
362 if (*end) {
b6353bea 363 errx(EXIT_FAILURE, "Invalid shared device number '%s'", optarg);
3b05a8e9
TS
364 }
365 if (shared < 1) {
b6353bea 366 errx(EXIT_FAILURE, "Shared device number must be greater than 0\n");
3b05a8e9
TS
367 }
368 break;
75818250
TS
369 case 't':
370 persistent = 1;
371 break;
7a5ca864
FB
372 case 'v':
373 verbose = 1;
374 break;
375 case 'V':
376 version(argv[0]);
377 exit(0);
378 break;
379 case 'h':
380 usage(argv[0]);
381 exit(0);
382 break;
383 case '?':
b6353bea 384 errx(EXIT_FAILURE, "Try `%s --help' for more information.",
7a5ca864
FB
385 argv[0]);
386 }
387 }
388
389 if ((argc - optind) != 1) {
b6353bea 390 errx(EXIT_FAILURE, "Invalid number of argument.\n"
7a5ca864
FB
391 "Try `%s --help' for more information.",
392 argv[0]);
393 }
394
cd831bd7
TS
395 if (disconnect) {
396 fd = open(argv[optind], O_RDWR);
397 if (fd == -1)
cb7cf0e3 398 err(EXIT_FAILURE, "Cannot open %s", argv[optind]);
cd831bd7
TS
399
400 nbd_disconnect(fd);
401
402 close(fd);
403
404 printf("%s disconnected\n", argv[optind]);
405
406 return 0;
407 }
408
7a5ca864
FB
409 bdrv_init();
410
411 bs = bdrv_new("hda");
7a5ca864 412
a517e88b
PB
413 srcpath = argv[optind];
414 if ((ret = bdrv_open(bs, srcpath, flags, NULL)) < 0) {
cb7cf0e3 415 errno = -ret;
a517e88b 416 err(EXIT_FAILURE, "Failed to bdrv_open '%s'", srcpath);
cb7cf0e3 417 }
7a5ca864
FB
418
419 fd_size = bs->total_sectors * 512;
420
421 if (partition != -1 &&
422 find_partition(bs, partition, &dev_offset, &fd_size))
cb7cf0e3 423 err(EXIT_FAILURE, "Could not find partition %d", partition);
7a5ca864 424
cd831bd7 425 if (device) {
a517e88b 426 int ret;
3b05a8e9 427
a517e88b
PB
428 /* Open before spawning new threads. In the future, we may
429 * drop privileges after opening.
430 */
431 fd = open(device, O_RDWR);
432 if (fd == -1) {
433 err(EXIT_FAILURE, "Failed to open %s", device);
cb7cf0e3
RO
434 }
435
f5de141b
AL
436 if (!verbose) {
437 /* detach client and server */
f97742d0 438 if (qemu_daemon(0, 0) == -1) {
cb7cf0e3 439 err(EXIT_FAILURE, "Failed to daemonize");
f5de141b
AL
440 }
441 }
cd831bd7 442
b32f6c28
PB
443 if (sockpath == NULL) {
444 sockpath = g_malloc(128);
445 snprintf(sockpath, 128, SOCKET_PATH, basename(device));
cd831bd7
TS
446 }
447
a517e88b
PB
448 ret = pthread_create(&client_thread, NULL, nbd_client_thread, &fd);
449 if (ret != 0) {
450 errx(EXIT_FAILURE, "Failed to create client thread: %s",
451 strerror(ret));
cd831bd7 452 }
a517e88b
PB
453 } else {
454 /* Shut up GCC warnings. */
455 memset(&client_thread, 0, sizeof(client_thread));
cd831bd7
TS
456 }
457
7267c094 458 sharing_fds = g_malloc((shared + 1) * sizeof(int));
3b05a8e9 459
b32f6c28
PB
460 if (sockpath) {
461 sharing_fds[0] = unix_socket_incoming(sockpath);
cd831bd7 462 } else {
3b05a8e9 463 sharing_fds[0] = tcp_socket_incoming(bindto, port);
cd831bd7
TS
464 }
465
3b05a8e9 466 if (sharing_fds[0] == -1)
7a5ca864 467 return 1;
3b05a8e9
TS
468 max_fd = sharing_fds[0];
469 nb_fds++;
7a5ca864 470
72aef731 471 data = qemu_blockalign(bs, NBD_BUFFER_SIZE);
bb345110 472 if (data == NULL) {
b6353bea 473 errx(EXIT_FAILURE, "Cannot allocate data buffer");
bb345110 474 }
7a5ca864 475
3b05a8e9 476 do {
3b05a8e9 477 FD_ZERO(&fds);
bb345110 478 FD_SET(sigterm_fd[0], &fds);
3b05a8e9
TS
479 for (i = 0; i < nb_fds; i++)
480 FD_SET(sharing_fds[i], &fds);
481
bb345110
PB
482 do {
483 ret = select(max_fd + 1, &fds, NULL, NULL, NULL);
484 } while (ret == -1 && errno == EINTR);
485 if (ret == -1 || FD_ISSET(sigterm_fd[0], &fds)) {
3b05a8e9 486 break;
bb345110 487 }
3b05a8e9
TS
488
489 if (FD_ISSET(sharing_fds[0], &fds))
490 ret--;
491 for (i = 1; i < nb_fds && ret; i++) {
492 if (FD_ISSET(sharing_fds[i], &fds)) {
493 if (nbd_trip(bs, sharing_fds[i], fd_size, dev_offset,
b90fb4b8 494 &offset, nbdflags, data, NBD_BUFFER_SIZE) != 0) {
3b05a8e9
TS
495 close(sharing_fds[i]);
496 nb_fds--;
497 sharing_fds[i] = sharing_fds[nb_fds];
498 i--;
499 }
500 ret--;
501 }
502 }
503 /* new connection ? */
504 if (FD_ISSET(sharing_fds[0], &fds)) {
505 if (nb_fds < shared + 1) {
506 sharing_fds[nb_fds] = accept(sharing_fds[0],
507 (struct sockaddr *)&addr,
508 &addr_len);
509 if (sharing_fds[nb_fds] != -1 &&
b90fb4b8 510 nbd_negotiate(sharing_fds[nb_fds], fd_size, nbdflags) != -1) {
3b05a8e9
TS
511 if (sharing_fds[nb_fds] > max_fd)
512 max_fd = sharing_fds[nb_fds];
513 nb_fds++;
514 }
515 }
516 }
75818250 517 } while (persistent || nb_fds > 1);
f8a83245 518 qemu_vfree(data);
7a5ca864 519
3b05a8e9 520 close(sharing_fds[0]);
7a5ca864 521 bdrv_close(bs);
7267c094 522 g_free(sharing_fds);
b32f6c28
PB
523 if (sockpath) {
524 unlink(sockpath);
525 }
7a5ca864 526
a517e88b
PB
527 if (device) {
528 void *ret;
529 pthread_join(client_thread, &ret);
530 exit(ret != NULL);
531 } else {
532 exit(EXIT_SUCCESS);
533 }
7a5ca864 534}