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