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