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