nbd: invert client logic for negotiating protocol version
[qemu/ar7.git] / blockdev-nbd.c
blob2148753fff3988a443a2f15f944504af663db19a
1 /*
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"
19 #include "trace.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,
27 gpointer opaque)
29 QIOChannelSocket *cioc;
31 cioc = qio_channel_socket_accept(QIO_CHANNEL_SOCKET(ioc),
32 NULL);
33 if (!cioc) {
34 return TRUE;
37 nbd_client_new(NULL, cioc, nbd_client_put);
38 object_unref(OBJECT(cioc));
39 return TRUE;
42 void qmp_nbd_server_start(SocketAddress *addr, Error **errp)
44 if (server_ioc) {
45 error_setg(errp, "NBD server already running");
46 return;
49 server_ioc = qio_channel_socket_new();
50 if (qio_channel_socket_listen_sync(server_ioc, addr, errp) < 0) {
51 return;
54 server_watch = qio_channel_add_watch(QIO_CHANNEL(server_ioc),
55 G_IO_IN,
56 nbd_accept,
57 NULL,
58 NULL);
61 void qmp_nbd_server_add(const char *device, bool has_writable, bool writable,
62 Error **errp)
64 BlockBackend *blk;
65 NBDExport *exp;
67 if (!server_ioc) {
68 error_setg(errp, "NBD server not running");
69 return;
72 if (nbd_export_find(device)) {
73 error_setg(errp, "NBD server already exporting device '%s'", device);
74 return;
77 blk = blk_by_name(device);
78 if (!blk) {
79 error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
80 "Device '%s' not found", device);
81 return;
83 if (!blk_is_inserted(blk)) {
84 error_setg(errp, QERR_DEVICE_HAS_NO_MEDIUM, device);
85 return;
88 if (!has_writable) {
89 writable = false;
91 if (blk_is_read_only(blk)) {
92 writable = false;
95 exp = nbd_export_new(blk, 0, -1, writable ? 0 : NBD_FLAG_READ_ONLY, NULL,
96 errp);
97 if (!exp) {
98 return;
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. */
106 nbd_export_put(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);
115 server_watch = -1;
117 if (server_ioc) {
118 object_unref(OBJECT(server_ioc));
119 server_ioc = NULL;