Merge remote-tracking branch 'remotes/awilliam/tags/vfio-update-20150210.0' into...
[sdk/emulator/qemu.git] / qemu-nbd.c
1 /*
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
16  *  along with this program; if not, see <http://www.gnu.org/licenses/>.
17  */
18
19 #include "qemu-common.h"
20 #include "sysemu/block-backend.h"
21 #include "block/block_int.h"
22 #include "block/nbd.h"
23 #include "qemu/main-loop.h"
24 #include "qemu/sockets.h"
25 #include "qemu/error-report.h"
26 #include "block/snapshot.h"
27 #include "qapi/util.h"
28
29 #include <stdarg.h>
30 #include <stdio.h>
31 #include <getopt.h>
32 #include <err.h>
33 #include <sys/types.h>
34 #include <sys/socket.h>
35 #include <netinet/in.h>
36 #include <netinet/tcp.h>
37 #include <arpa/inet.h>
38 #include <signal.h>
39 #include <libgen.h>
40 #include <pthread.h>
41
42 #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
46 #define QEMU_NBD_OPT_DETECT_ZEROES 4
47
48 static NBDExport *exp;
49 static int verbose;
50 static char *srcpath;
51 static char *sockpath;
52 static int persistent = 0;
53 static enum { RUNNING, TERMINATE, TERMINATING, TERMINATED } state;
54 static int shared = 1;
55 static int nb_fds;
56
57 static void usage(const char *name)
58 {
59     (printf) (
60 "Usage: %s [OPTIONS] FILE\n"
61 "QEMU Disk Network Block Device Server\n"
62 "\n"
63 "  -h, --help                display this help and exit\n"
64 "  -V, --version             output version information and exit\n"
65 "\n"
66 "Connection properties:\n"
67 "  -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"
74 "\n"
75 "Exposing part of the image:\n"
76 "  -o, --offset=OFFSET       offset into the image\n"
77 "  -P, --partition=NUM       only expose partition NUM\n"
78 "\n"
79 #ifdef __linux__
80 "Kernel NBD client support:\n"
81 "  -c, --connect=DEV         connect FILE to the local NBD device DEV\n"
82 "  -d, --disconnect          disconnect the specified device\n"
83 "\n"
84 #endif
85 "\n"
86 "Block device options:\n"
87 "  -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"
92 "  -l, --load-snapshot=SNAPSHOT_PARAM\n"
93 "                            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"
99 #ifdef CONFIG_LINUX_AIO
100 "      --aio=MODE            set AIO mode (native or threads)\n"
101 #endif
102 "      --discard=MODE        set discard mode (ignore, unmap)\n"
103 "      --detect-zeroes=MODE  set detect-zeroes mode (off, on, discard)\n"
104 "\n"
105 "Report bugs to <qemu-devel@nongnu.org>\n"
106     , name, NBD_DEFAULT_PORT, "DEVICE");
107 }
108
109 static void version(const char *name)
110 {
111     printf(
112 "%s version 0.0.1\n"
113 "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"
118     , name);
119 }
120
121 struct 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
135 static 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
149 static int find_partition(BlockBackend *blk, int partition,
150                           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;
156     int ret;
157
158     if ((ret = blk_read(blk, 0, data, 1)) < 0) {
159         errno = -ret;
160         err(EXIT_FAILURE, "error while reading");
161     }
162
163     if (data[510] != 0x55 || data[511] != 0xaa) {
164         return -EINVAL;
165     }
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
178             if ((ret = blk_read(blk, mbr[i].start_sector_abs, data1, 1)) < 0) {
179                 errno = -ret;
180                 err(EXIT_FAILURE, "error while reading");
181             }
182
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
202     return -ENOENT;
203 }
204
205 static void termsig_handler(int signum)
206 {
207     state = TERMINATE;
208     qemu_notify_event();
209 }
210
211 static 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
222 static 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) {
231         error_report("%s", error_get_pretty(local_err));
232         error_free(local_err);
233     }
234     return fd;
235 }
236
237 static int unix_socket_incoming(const char *path)
238 {
239     Error *local_err = NULL;
240     int fd = unix_listen(path, NULL, 0, &local_err);
241
242     if (local_err != NULL) {
243         error_report("%s", error_get_pretty(local_err));
244         error_free(local_err);
245     }
246     return fd;
247 }
248
249 static int unix_socket_outgoing(const char *path)
250 {
251     Error *local_err = NULL;
252     int fd = unix_connect(path, &local_err);
253
254     if (local_err != NULL) {
255         error_report("%s", error_get_pretty(local_err));
256         error_free(local_err);
257     }
258     return fd;
259 }
260
261 static void *show_parts(void *arg)
262 {
263     char *device = arg;
264     int nbd;
265
266     /* linux just needs an open() to trigger
267      * the partition table update
268      * but remember to load the module with max_part != 0 :
269      *     modprobe nbd max_part=63
270      */
271     nbd = open(device, O_RDWR);
272     if (nbd >= 0) {
273         close(nbd);
274     }
275     return NULL;
276 }
277
278 static void *nbd_client_thread(void *arg)
279 {
280     char *device = arg;
281     off_t size;
282     size_t blocksize;
283     uint32_t nbdflags;
284     int fd, sock;
285     int ret;
286     pthread_t show_parts_thread;
287     Error *local_error = NULL;
288
289     sock = unix_socket_outgoing(sockpath);
290     if (sock < 0) {
291         goto out;
292     }
293
294     ret = nbd_receive_negotiate(sock, NULL, &nbdflags,
295                                 &size, &blocksize, &local_error);
296     if (ret < 0) {
297         if (local_error) {
298             fprintf(stderr, "%s\n", error_get_pretty(local_error));
299             error_free(local_error);
300         }
301         goto out_socket;
302     }
303
304     fd = open(device, O_RDWR);
305     if (fd < 0) {
306         /* Linux-only, we can use %m in printf.  */
307         fprintf(stderr, "Failed to open %s: %m\n", device);
308         goto out_socket;
309     }
310
311     ret = nbd_init(fd, sock, nbdflags, size, blocksize);
312     if (ret < 0) {
313         goto out_fd;
314     }
315
316     /* update partition table */
317     pthread_create(&show_parts_thread, NULL, show_parts, device);
318
319     if (verbose) {
320         fprintf(stderr, "NBD device %s is now connected to %s\n",
321                 device, srcpath);
322     } else {
323         /* Close stderr so that the qemu-nbd process exits.  */
324         dup2(STDOUT_FILENO, STDERR_FILENO);
325     }
326
327     ret = nbd_client(fd);
328     if (ret) {
329         goto out_fd;
330     }
331     close(fd);
332     kill(getpid(), SIGTERM);
333     return (void *) EXIT_SUCCESS;
334
335 out_fd:
336     close(fd);
337 out_socket:
338     closesocket(sock);
339 out:
340     kill(getpid(), SIGTERM);
341     return (void *) EXIT_FAILURE;
342 }
343
344 static int nbd_can_accept(void *opaque)
345 {
346     return nb_fds < shared;
347 }
348
349 static void nbd_export_closed(NBDExport *exp)
350 {
351     assert(state == TERMINATING);
352     state = TERMINATED;
353 }
354
355 static void nbd_client_closed(NBDClient *client)
356 {
357     nb_fds--;
358     if (nb_fds == 0 && !persistent && state == RUNNING) {
359         state = TERMINATE;
360     }
361     qemu_notify_event();
362     nbd_client_put(client);
363 }
364
365 static void nbd_accept(void *opaque)
366 {
367     int server_fd = (uintptr_t) opaque;
368     struct sockaddr_in addr;
369     socklen_t addr_len = sizeof(addr);
370
371     int fd = accept(server_fd, (struct sockaddr *)&addr, &addr_len);
372     if (fd < 0) {
373         perror("accept");
374         return;
375     }
376
377     if (state >= TERMINATE) {
378         close(fd);
379         return;
380     }
381
382     if (nbd_client_new(exp, fd, nbd_client_closed)) {
383         nb_fds++;
384     } else {
385         shutdown(fd, 2);
386         close(fd);
387     }
388 }
389
390 int main(int argc, char **argv)
391 {
392     BlockBackend *blk;
393     BlockDriverState *bs;
394     BlockDriver *drv;
395     off_t dev_offset = 0;
396     uint32_t nbdflags = 0;
397     bool disconnect = false;
398     const char *bindto = "0.0.0.0";
399     char *device = NULL;
400     int port = NBD_DEFAULT_PORT;
401     off_t fd_size;
402     QemuOpts *sn_opts = NULL;
403     const char *sn_id_or_name = NULL;
404     const char *sopt = "hVb:o:p:rsnP:c:dvk:e:f:tl:";
405     struct option lopt[] = {
406         { "help", 0, NULL, 'h' },
407         { "version", 0, NULL, 'V' },
408         { "bind", 1, NULL, 'b' },
409         { "port", 1, NULL, 'p' },
410         { "socket", 1, NULL, 'k' },
411         { "offset", 1, NULL, 'o' },
412         { "read-only", 0, NULL, 'r' },
413         { "partition", 1, NULL, 'P' },
414         { "connect", 1, NULL, 'c' },
415         { "disconnect", 0, NULL, 'd' },
416         { "snapshot", 0, NULL, 's' },
417         { "load-snapshot", 1, NULL, 'l' },
418         { "nocache", 0, NULL, 'n' },
419         { "cache", 1, NULL, QEMU_NBD_OPT_CACHE },
420 #ifdef CONFIG_LINUX_AIO
421         { "aio", 1, NULL, QEMU_NBD_OPT_AIO },
422 #endif
423         { "discard", 1, NULL, QEMU_NBD_OPT_DISCARD },
424         { "detect-zeroes", 1, NULL, QEMU_NBD_OPT_DETECT_ZEROES },
425         { "shared", 1, NULL, 'e' },
426         { "format", 1, NULL, 'f' },
427         { "persistent", 0, NULL, 't' },
428         { "verbose", 0, NULL, 'v' },
429         { NULL, 0, NULL, 0 }
430     };
431     int ch;
432     int opt_ind = 0;
433     int li;
434     char *end;
435     int flags = BDRV_O_RDWR;
436     int partition = -1;
437     int ret;
438     int fd;
439     bool seen_cache = false;
440     bool seen_discard = false;
441 #ifdef CONFIG_LINUX_AIO
442     bool seen_aio = false;
443 #endif
444     pthread_t client_thread;
445     const char *fmt = NULL;
446     Error *local_err = NULL;
447     BlockdevDetectZeroesOptions detect_zeroes = BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF;
448
449     /* The client thread uses SIGTERM to interrupt the server.  A signal
450      * handler ensures that "qemu-nbd -v -c" exits with a nice status code.
451      */
452     struct sigaction sa_sigterm;
453     memset(&sa_sigterm, 0, sizeof(sa_sigterm));
454     sa_sigterm.sa_handler = termsig_handler;
455     sigaction(SIGTERM, &sa_sigterm, NULL);
456     qemu_init_exec_dir(argv[0]);
457
458     while ((ch = getopt_long(argc, argv, sopt, lopt, &opt_ind)) != -1) {
459         switch (ch) {
460         case 's':
461             flags |= BDRV_O_SNAPSHOT;
462             break;
463         case 'n':
464             optarg = (char *) "none";
465             /* fallthrough */
466         case QEMU_NBD_OPT_CACHE:
467             if (seen_cache) {
468                 errx(EXIT_FAILURE, "-n and --cache can only be specified once");
469             }
470             seen_cache = true;
471             if (bdrv_parse_cache_flags(optarg, &flags) == -1) {
472                 errx(EXIT_FAILURE, "Invalid cache mode `%s'", optarg);
473             }
474             break;
475 #ifdef CONFIG_LINUX_AIO
476         case QEMU_NBD_OPT_AIO:
477             if (seen_aio) {
478                 errx(EXIT_FAILURE, "--aio can only be specified once");
479             }
480             seen_aio = true;
481             if (!strcmp(optarg, "native")) {
482                 flags |= BDRV_O_NATIVE_AIO;
483             } else if (!strcmp(optarg, "threads")) {
484                 /* this is the default */
485             } else {
486                errx(EXIT_FAILURE, "invalid aio mode `%s'", optarg);
487             }
488             break;
489 #endif
490         case QEMU_NBD_OPT_DISCARD:
491             if (seen_discard) {
492                 errx(EXIT_FAILURE, "--discard can only be specified once");
493             }
494             seen_discard = true;
495             if (bdrv_parse_discard_flags(optarg, &flags) == -1) {
496                 errx(EXIT_FAILURE, "Invalid discard mode `%s'", optarg);
497             }
498             break;
499         case QEMU_NBD_OPT_DETECT_ZEROES:
500             detect_zeroes =
501                 qapi_enum_parse(BlockdevDetectZeroesOptions_lookup,
502                                 optarg,
503                                 BLOCKDEV_DETECT_ZEROES_OPTIONS_MAX,
504                                 BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF,
505                                 &local_err);
506             if (local_err) {
507                 errx(EXIT_FAILURE, "Failed to parse detect_zeroes mode: %s", 
508                      error_get_pretty(local_err));
509             }
510             if (detect_zeroes == BLOCKDEV_DETECT_ZEROES_OPTIONS_UNMAP &&
511                 !(flags & BDRV_O_UNMAP)) {
512                 errx(EXIT_FAILURE, "setting detect-zeroes to unmap is not allowed "
513                                    "without setting discard operation to unmap"); 
514             }
515             break;
516         case 'b':
517             bindto = optarg;
518             break;
519         case 'p':
520             li = strtol(optarg, &end, 0);
521             if (*end) {
522                 errx(EXIT_FAILURE, "Invalid port `%s'", optarg);
523             }
524             if (li < 1 || li > 65535) {
525                 errx(EXIT_FAILURE, "Port out of range `%s'", optarg);
526             }
527             port = (uint16_t)li;
528             break;
529         case 'o':
530                 dev_offset = strtoll (optarg, &end, 0);
531             if (*end) {
532                 errx(EXIT_FAILURE, "Invalid offset `%s'", optarg);
533             }
534             if (dev_offset < 0) {
535                 errx(EXIT_FAILURE, "Offset must be positive `%s'", optarg);
536             }
537             break;
538         case 'l':
539             if (strstart(optarg, SNAPSHOT_OPT_BASE, NULL)) {
540                 sn_opts = qemu_opts_parse(&internal_snapshot_opts, optarg, 0);
541                 if (!sn_opts) {
542                     errx(EXIT_FAILURE, "Failed in parsing snapshot param `%s'",
543                          optarg);
544                 }
545             } else {
546                 sn_id_or_name = optarg;
547             }
548             /* fall through */
549         case 'r':
550             nbdflags |= NBD_FLAG_READ_ONLY;
551             flags &= ~BDRV_O_RDWR;
552             break;
553         case 'P':
554             partition = strtol(optarg, &end, 0);
555             if (*end) {
556                 errx(EXIT_FAILURE, "Invalid partition `%s'", optarg);
557             }
558             if (partition < 1 || partition > 8) {
559                 errx(EXIT_FAILURE, "Invalid partition %d", partition);
560             }
561             break;
562         case 'k':
563             sockpath = optarg;
564             if (sockpath[0] != '/') {
565                 errx(EXIT_FAILURE, "socket path must be absolute\n");
566             }
567             break;
568         case 'd':
569             disconnect = true;
570             break;
571         case 'c':
572             device = optarg;
573             break;
574         case 'e':
575             shared = strtol(optarg, &end, 0);
576             if (*end) {
577                 errx(EXIT_FAILURE, "Invalid shared device number '%s'", optarg);
578             }
579             if (shared < 1) {
580                 errx(EXIT_FAILURE, "Shared device number must be greater than 0\n");
581             }
582             break;
583         case 'f':
584             fmt = optarg;
585             break;
586         case 't':
587             persistent = 1;
588             break;
589         case 'v':
590             verbose = 1;
591             break;
592         case 'V':
593             version(argv[0]);
594             exit(0);
595             break;
596         case 'h':
597             usage(argv[0]);
598             exit(0);
599             break;
600         case '?':
601             errx(EXIT_FAILURE, "Try `%s --help' for more information.",
602                  argv[0]);
603         }
604     }
605
606     if ((argc - optind) != 1) {
607         errx(EXIT_FAILURE, "Invalid number of argument.\n"
608              "Try `%s --help' for more information.",
609              argv[0]);
610     }
611
612     if (disconnect) {
613         fd = open(argv[optind], O_RDWR);
614         if (fd < 0) {
615             err(EXIT_FAILURE, "Cannot open %s", argv[optind]);
616         }
617         nbd_disconnect(fd);
618
619         close(fd);
620
621         printf("%s disconnected\n", argv[optind]);
622
623         return 0;
624     }
625
626     if (device && !verbose) {
627         int stderr_fd[2];
628         pid_t pid;
629         int ret;
630
631         if (qemu_pipe(stderr_fd) < 0) {
632             err(EXIT_FAILURE, "Error setting up communication pipe");
633         }
634
635         /* Now daemonize, but keep a communication channel open to
636          * print errors and exit with the proper status code.
637          */
638         pid = fork();
639         if (pid == 0) {
640             close(stderr_fd[0]);
641             ret = qemu_daemon(1, 0);
642
643             /* Temporarily redirect stderr to the parent's pipe...  */
644             dup2(stderr_fd[1], STDERR_FILENO);
645             if (ret < 0) {
646                 err(EXIT_FAILURE, "Failed to daemonize");
647             }
648
649             /* ... close the descriptor we inherited and go on.  */
650             close(stderr_fd[1]);
651         } else {
652             bool errors = false;
653             char *buf;
654
655             /* In the parent.  Print error messages from the child until
656              * it closes the pipe.
657              */
658             close(stderr_fd[1]);
659             buf = g_malloc(1024);
660             while ((ret = read(stderr_fd[0], buf, 1024)) > 0) {
661                 errors = true;
662                 ret = qemu_write_full(STDERR_FILENO, buf, ret);
663                 if (ret < 0) {
664                     exit(EXIT_FAILURE);
665                 }
666             }
667             if (ret < 0) {
668                 err(EXIT_FAILURE, "Cannot read from daemon");
669             }
670
671             /* Usually the daemon should not print any message.
672              * Exit with zero status in that case.
673              */
674             exit(errors);
675         }
676     }
677
678     if (device != NULL && sockpath == NULL) {
679         sockpath = g_malloc(128);
680         snprintf(sockpath, 128, SOCKET_PATH, basename(device));
681     }
682
683     if (qemu_init_main_loop(&local_err)) {
684         error_report("%s", error_get_pretty(local_err));
685         error_free(local_err);
686         exit(EXIT_FAILURE);
687     }
688     bdrv_init();
689     atexit(bdrv_close_all);
690
691     if (fmt) {
692         drv = bdrv_find_format(fmt);
693         if (!drv) {
694             errx(EXIT_FAILURE, "Unknown file format '%s'", fmt);
695         }
696     } else {
697         drv = NULL;
698     }
699
700     blk = blk_new_with_bs("hda", &error_abort);
701     bs = blk_bs(blk);
702
703     srcpath = argv[optind];
704     ret = bdrv_open(&bs, srcpath, NULL, NULL, flags, drv, &local_err);
705     if (ret < 0) {
706         errno = -ret;
707         err(EXIT_FAILURE, "Failed to bdrv_open '%s': %s", argv[optind],
708             error_get_pretty(local_err));
709     }
710
711     if (sn_opts) {
712         ret = bdrv_snapshot_load_tmp(bs,
713                                      qemu_opt_get(sn_opts, SNAPSHOT_OPT_ID),
714                                      qemu_opt_get(sn_opts, SNAPSHOT_OPT_NAME),
715                                      &local_err);
716     } else if (sn_id_or_name) {
717         ret = bdrv_snapshot_load_tmp_by_id_or_name(bs, sn_id_or_name,
718                                                    &local_err);
719     }
720     if (ret < 0) {
721         errno = -ret;
722         err(EXIT_FAILURE,
723             "Failed to load snapshot: %s",
724             error_get_pretty(local_err));
725     }
726
727     bs->detect_zeroes = detect_zeroes;
728     fd_size = blk_getlength(blk);
729
730     if (partition != -1) {
731         ret = find_partition(blk, partition, &dev_offset, &fd_size);
732         if (ret < 0) {
733             errno = -ret;
734             err(EXIT_FAILURE, "Could not find partition %d", partition);
735         }
736     }
737
738     exp = nbd_export_new(blk, dev_offset, fd_size, nbdflags, nbd_export_closed);
739
740     if (sockpath) {
741         fd = unix_socket_incoming(sockpath);
742     } else {
743         fd = tcp_socket_incoming(bindto, port);
744     }
745
746     if (fd < 0) {
747         return 1;
748     }
749
750     if (device) {
751         int ret;
752
753         ret = pthread_create(&client_thread, NULL, nbd_client_thread, device);
754         if (ret != 0) {
755             errx(EXIT_FAILURE, "Failed to create client thread: %s",
756                  strerror(ret));
757         }
758     } else {
759         /* Shut up GCC warnings.  */
760         memset(&client_thread, 0, sizeof(client_thread));
761     }
762
763     qemu_set_fd_handler2(fd, nbd_can_accept, nbd_accept, NULL,
764                          (void *)(uintptr_t)fd);
765
766     /* now when the initialization is (almost) complete, chdir("/")
767      * to free any busy filesystems */
768     if (chdir("/") < 0) {
769         err(EXIT_FAILURE, "Could not chdir to root directory");
770     }
771
772     state = RUNNING;
773     do {
774         main_loop_wait(false);
775         if (state == TERMINATE) {
776             state = TERMINATING;
777             nbd_export_close(exp);
778             nbd_export_put(exp);
779             exp = NULL;
780         }
781     } while (state != TERMINATED);
782
783     blk_unref(blk);
784     if (sockpath) {
785         unlink(sockpath);
786     }
787
788     qemu_opts_del(sn_opts);
789
790     if (device) {
791         void *ret;
792         pthread_join(client_thread, &ret);
793         exit(ret != NULL);
794     } else {
795         exit(EXIT_SUCCESS);
796     }
797 }