2 * Serving QEMU block devices via NBD
4 * Copyright (c) 2012 Red Hat, Inc.
6 * Author: Paolo Bonzini <pbonzini@redhat.com>
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.
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"
20 #include "block/nbd.h"
21 #include "io/channel-socket.h"
23 static QIOChannelSocket *server_ioc;
24 static int server_watch = -1;
26 static gboolean nbd_accept(QIOChannel *ioc, GIOCondition condition,
29 QIOChannelSocket *cioc;
31 cioc = qio_channel_socket_accept(QIO_CHANNEL_SOCKET(ioc),
37 nbd_client_new(NULL, cioc, nbd_client_put);
38 object_unref(OBJECT(cioc));
42 void qmp_nbd_server_start(SocketAddress *addr, Error **errp)
45 error_setg(errp, "NBD server already running");
49 server_ioc = qio_channel_socket_new();
50 if (qio_channel_socket_listen_sync(server_ioc, addr, errp) < 0) {
54 server_watch = qio_channel_add_watch(QIO_CHANNEL(server_ioc),
61 void qmp_nbd_server_add(const char *device, bool has_writable, bool writable,
68 error_setg(errp, "NBD server not running");
72 if (nbd_export_find(device)) {
73 error_setg(errp, "NBD server already exporting device '%s'", device);
77 blk = blk_by_name(device);
79 error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
80 "Device '%s' not found", device);
83 if (!blk_is_inserted(blk)) {
84 error_setg(errp, QERR_DEVICE_HAS_NO_MEDIUM, device);
91 if (blk_is_read_only(blk)) {
95 exp = nbd_export_new(blk, 0, -1, writable ? 0 : NBD_FLAG_READ_ONLY, NULL,
101 nbd_export_set_name(exp, device);
103 /* The list of named exports has a strong reference to this export now and
104 * our only way of accessing it is through nbd_export_find(), so we can drop
105 * the strong reference that is @exp. */
109 void qmp_nbd_server_stop(Error **errp)
111 nbd_export_close_all();
113 if (server_watch != -1) {
114 g_source_remove(server_watch);
118 object_unref(OBJECT(server_ioc));