xref: /openbmc/qemu/blockdev-nbd.c (revision c964b660)
1 /*
2  * Serving QEMU block devices via NBD
3  *
4  * Copyright (c) 2012 Red Hat, Inc.
5  *
6  * Author: Paolo Bonzini <pbonzini@redhat.com>
7  *
8  * This work is licensed under the terms of the GNU GPL, version 2 or
9  * later.  See the COPYING file in the top-level directory.
10  */
11 
12 #include "qemu/osdep.h"
13 #include "sysemu/blockdev.h"
14 #include "sysemu/block-backend.h"
15 #include "hw/block/block.h"
16 #include "qapi/qmp/qerror.h"
17 #include "sysemu/sysemu.h"
18 #include "qmp-commands.h"
19 #include "trace.h"
20 #include "block/nbd.h"
21 #include "qemu/sockets.h"
22 
23 static int server_fd = -1;
24 
25 static void nbd_accept(void *opaque)
26 {
27     struct sockaddr_in addr;
28     socklen_t addr_len = sizeof(addr);
29 
30     int fd = accept(server_fd, (struct sockaddr *)&addr, &addr_len);
31     if (fd >= 0) {
32         nbd_client_new(NULL, fd, nbd_client_put);
33     }
34 }
35 
36 void qmp_nbd_server_start(SocketAddress *addr, Error **errp)
37 {
38     if (server_fd != -1) {
39         error_setg(errp, "NBD server already running");
40         return;
41     }
42 
43     server_fd = socket_listen(addr, errp);
44     if (server_fd != -1) {
45         qemu_set_fd_handler(server_fd, nbd_accept, NULL, NULL);
46     }
47 }
48 
49 void qmp_nbd_server_add(const char *device, bool has_writable, bool writable,
50                         Error **errp)
51 {
52     BlockBackend *blk;
53     NBDExport *exp;
54 
55     if (server_fd == -1) {
56         error_setg(errp, "NBD server not running");
57         return;
58     }
59 
60     if (nbd_export_find(device)) {
61         error_setg(errp, "NBD server already exporting device '%s'", device);
62         return;
63     }
64 
65     blk = blk_by_name(device);
66     if (!blk) {
67         error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
68                   "Device '%s' not found", device);
69         return;
70     }
71     if (!blk_is_inserted(blk)) {
72         error_setg(errp, QERR_DEVICE_HAS_NO_MEDIUM, device);
73         return;
74     }
75 
76     if (!has_writable) {
77         writable = false;
78     }
79     if (blk_is_read_only(blk)) {
80         writable = false;
81     }
82 
83     exp = nbd_export_new(blk, 0, -1, writable ? 0 : NBD_FLAG_READ_ONLY, NULL,
84                          errp);
85     if (!exp) {
86         return;
87     }
88 
89     nbd_export_set_name(exp, device);
90 
91     /* The list of named exports has a strong reference to this export now and
92      * our only way of accessing it is through nbd_export_find(), so we can drop
93      * the strong reference that is @exp. */
94     nbd_export_put(exp);
95 }
96 
97 void qmp_nbd_server_stop(Error **errp)
98 {
99     nbd_export_close_all();
100 
101     if (server_fd != -1) {
102         qemu_set_fd_handler(server_fd, NULL, NULL, NULL);
103         close(server_fd);
104         server_fd = -1;
105     }
106 }
107