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