4 * Network Block Device Server Side
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.
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.
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/>.
19 #include "qemu/osdep.h"
20 #include "qapi/error.h"
21 #include "nbd-internal.h"
23 static int system_errno_to_nbd_errno(int err)
47 /* Definitions for opaque data types */
49 typedef struct NBDRequest NBDRequest;
52 QSIMPLEQ_ENTRY(NBDRequest) entry;
60 void (*close)(NBDExport *exp);
68 QTAILQ_HEAD(, NBDClient) clients;
69 QTAILQ_ENTRY(NBDExport) next;
73 BlockBackend *eject_notifier_blk;
74 Notifier eject_notifier;
77 static QTAILQ_HEAD(, NBDExport) exports = QTAILQ_HEAD_INITIALIZER(exports);
81 void (*close)(NBDClient *client);
84 QCryptoTLSCreds *tlscreds;
86 QIOChannelSocket *sioc; /* The underlying data channel */
87 QIOChannel *ioc; /* The current I/O channel which may differ (eg TLS) */
89 Coroutine *recv_coroutine;
92 Coroutine *send_coroutine;
96 QTAILQ_ENTRY(NBDClient) next;
101 /* That's all folks */
103 static void nbd_set_handlers(NBDClient *client);
104 static void nbd_unset_handlers(NBDClient *client);
105 static void nbd_update_can_read(NBDClient *client);
107 static gboolean nbd_negotiate_continue(QIOChannel *ioc,
108 GIOCondition condition,
111 qemu_coroutine_enter(opaque);
115 static ssize_t nbd_negotiate_read(QIOChannel *ioc, void *buffer, size_t size)
120 assert(qemu_in_coroutine());
121 /* Negotiation are always in main loop. */
122 watch = qio_channel_add_watch(ioc,
124 nbd_negotiate_continue,
125 qemu_coroutine_self(),
127 ret = read_sync(ioc, buffer, size);
128 g_source_remove(watch);
133 static ssize_t nbd_negotiate_write(QIOChannel *ioc, const void *buffer,
139 assert(qemu_in_coroutine());
140 /* Negotiation are always in main loop. */
141 watch = qio_channel_add_watch(ioc,
143 nbd_negotiate_continue,
144 qemu_coroutine_self(),
146 ret = write_sync(ioc, buffer, size);
147 g_source_remove(watch);
151 static ssize_t nbd_negotiate_drop_sync(QIOChannel *ioc, size_t size)
153 ssize_t ret, dropped = size;
154 uint8_t *buffer = g_malloc(MIN(65536, size));
157 ret = nbd_negotiate_read(ioc, buffer, MIN(65536, size));
171 /* Basic flow for negotiation
198 static int nbd_negotiate_send_rep(QIOChannel *ioc, uint32_t type, uint32_t opt)
203 TRACE("Reply opt=%" PRIx32 " type=%" PRIx32, type, opt);
205 magic = cpu_to_be64(NBD_REP_MAGIC);
206 if (nbd_negotiate_write(ioc, &magic, sizeof(magic)) != sizeof(magic)) {
207 LOG("write failed (rep magic)");
210 opt = cpu_to_be32(opt);
211 if (nbd_negotiate_write(ioc, &opt, sizeof(opt)) != sizeof(opt)) {
212 LOG("write failed (rep opt)");
215 type = cpu_to_be32(type);
216 if (nbd_negotiate_write(ioc, &type, sizeof(type)) != sizeof(type)) {
217 LOG("write failed (rep type)");
220 len = cpu_to_be32(0);
221 if (nbd_negotiate_write(ioc, &len, sizeof(len)) != sizeof(len)) {
222 LOG("write failed (rep data length)");
228 static int nbd_negotiate_send_rep_list(QIOChannel *ioc, NBDExport *exp)
231 size_t name_len, desc_len;
232 uint32_t opt, type, len;
233 const char *name = exp->name ? exp->name : "";
234 const char *desc = exp->description ? exp->description : "";
236 TRACE("Advertising export name '%s' description '%s'", name, desc);
237 name_len = strlen(name);
238 desc_len = strlen(desc);
239 magic = cpu_to_be64(NBD_REP_MAGIC);
240 if (nbd_negotiate_write(ioc, &magic, sizeof(magic)) != sizeof(magic)) {
241 LOG("write failed (magic)");
244 opt = cpu_to_be32(NBD_OPT_LIST);
245 if (nbd_negotiate_write(ioc, &opt, sizeof(opt)) != sizeof(opt)) {
246 LOG("write failed (opt)");
249 type = cpu_to_be32(NBD_REP_SERVER);
250 if (nbd_negotiate_write(ioc, &type, sizeof(type)) != sizeof(type)) {
251 LOG("write failed (reply type)");
254 len = cpu_to_be32(name_len + desc_len + sizeof(len));
255 if (nbd_negotiate_write(ioc, &len, sizeof(len)) != sizeof(len)) {
256 LOG("write failed (length)");
259 len = cpu_to_be32(name_len);
260 if (nbd_negotiate_write(ioc, &len, sizeof(len)) != sizeof(len)) {
261 LOG("write failed (name length)");
264 if (nbd_negotiate_write(ioc, name, name_len) != name_len) {
265 LOG("write failed (name buffer)");
268 if (nbd_negotiate_write(ioc, desc, desc_len) != desc_len) {
269 LOG("write failed (description buffer)");
275 static int nbd_negotiate_handle_list(NBDClient *client, uint32_t length)
280 if (nbd_negotiate_drop_sync(client->ioc, length) != length) {
283 return nbd_negotiate_send_rep(client->ioc,
284 NBD_REP_ERR_INVALID, NBD_OPT_LIST);
287 /* For each export, send a NBD_REP_SERVER reply. */
288 QTAILQ_FOREACH(exp, &exports, next) {
289 if (nbd_negotiate_send_rep_list(client->ioc, exp)) {
293 /* Finish with a NBD_REP_ACK. */
294 return nbd_negotiate_send_rep(client->ioc, NBD_REP_ACK, NBD_OPT_LIST);
297 static int nbd_negotiate_handle_export_name(NBDClient *client, uint32_t length)
300 char name[NBD_MAX_NAME_SIZE + 1];
303 [20 .. xx] export name (length bytes)
305 TRACE("Checking length");
306 if (length >= sizeof(name)) {
307 LOG("Bad length received");
310 if (nbd_negotiate_read(client->ioc, name, length) != length) {
316 TRACE("Client requested export '%s'", name);
318 client->exp = nbd_export_find(name);
320 LOG("export not found");
324 QTAILQ_INSERT_TAIL(&client->exp->clients, client, next);
325 nbd_export_get(client->exp);
332 static QIOChannel *nbd_negotiate_handle_starttls(NBDClient *client,
337 struct NBDTLSHandshakeData data = { 0 };
339 TRACE("Setting up TLS");
342 if (nbd_negotiate_drop_sync(ioc, length) != length) {
345 nbd_negotiate_send_rep(ioc, NBD_REP_ERR_INVALID, NBD_OPT_STARTTLS);
349 if (nbd_negotiate_send_rep(client->ioc, NBD_REP_ACK,
350 NBD_OPT_STARTTLS) < 0) {
354 tioc = qio_channel_tls_new_server(ioc,
362 qio_channel_set_name(QIO_CHANNEL(tioc), "nbd-server-tls");
363 TRACE("Starting TLS handshake");
364 data.loop = g_main_loop_new(g_main_context_default(), FALSE);
365 qio_channel_tls_handshake(tioc,
370 if (!data.complete) {
371 g_main_loop_run(data.loop);
373 g_main_loop_unref(data.loop);
375 object_unref(OBJECT(tioc));
376 error_free(data.error);
380 return QIO_CHANNEL(tioc);
384 static int nbd_negotiate_options(NBDClient *client)
387 bool fixedNewstyle = false;
390 [ 0 .. 3] client flags
392 [ 0 .. 7] NBD_OPTS_MAGIC
393 [ 8 .. 11] NBD option
394 [12 .. 15] Data length
397 [ 0 .. 7] NBD_OPTS_MAGIC
398 [ 8 .. 11] Second NBD option
399 [12 .. 15] Data length
403 if (nbd_negotiate_read(client->ioc, &flags, sizeof(flags)) !=
408 TRACE("Checking client flags");
409 be32_to_cpus(&flags);
410 if (flags & NBD_FLAG_C_FIXED_NEWSTYLE) {
411 TRACE("Client supports fixed newstyle handshake");
412 fixedNewstyle = true;
413 flags &= ~NBD_FLAG_C_FIXED_NEWSTYLE;
416 TRACE("Unknown client flags 0x%" PRIx32 " received", flags);
422 uint32_t clientflags, length;
425 if (nbd_negotiate_read(client->ioc, &magic, sizeof(magic)) !=
430 TRACE("Checking opts magic");
431 if (magic != be64_to_cpu(NBD_OPTS_MAGIC)) {
432 LOG("Bad magic received");
436 if (nbd_negotiate_read(client->ioc, &clientflags,
437 sizeof(clientflags)) != sizeof(clientflags)) {
441 clientflags = be32_to_cpu(clientflags);
443 if (nbd_negotiate_read(client->ioc, &length, sizeof(length)) !=
448 length = be32_to_cpu(length);
450 TRACE("Checking option 0x%" PRIx32, clientflags);
451 if (client->tlscreds &&
452 client->ioc == (QIOChannel *)client->sioc) {
454 if (!fixedNewstyle) {
455 TRACE("Unsupported option 0x%" PRIx32, clientflags);
458 switch (clientflags) {
459 case NBD_OPT_STARTTLS:
460 tioc = nbd_negotiate_handle_starttls(client, length);
464 object_unref(OBJECT(client->ioc));
465 client->ioc = QIO_CHANNEL(tioc);
468 case NBD_OPT_EXPORT_NAME:
469 /* No way to return an error to client, so drop connection */
470 TRACE("Option 0x%x not permitted before TLS", clientflags);
474 TRACE("Option 0x%" PRIx32 " not permitted before TLS",
476 if (nbd_negotiate_drop_sync(client->ioc, length) != length) {
479 ret = nbd_negotiate_send_rep(client->ioc, NBD_REP_ERR_TLS_REQD,
486 } else if (fixedNewstyle) {
487 switch (clientflags) {
489 ret = nbd_negotiate_handle_list(client, length);
498 case NBD_OPT_EXPORT_NAME:
499 return nbd_negotiate_handle_export_name(client, length);
501 case NBD_OPT_STARTTLS:
502 if (nbd_negotiate_drop_sync(client->ioc, length) != length) {
505 if (client->tlscreds) {
506 TRACE("TLS already enabled");
507 ret = nbd_negotiate_send_rep(client->ioc,
511 TRACE("TLS not configured");
512 ret = nbd_negotiate_send_rep(client->ioc,
521 TRACE("Unsupported option 0x%" PRIx32, clientflags);
522 if (nbd_negotiate_drop_sync(client->ioc, length) != length) {
525 ret = nbd_negotiate_send_rep(client->ioc, NBD_REP_ERR_UNSUP,
534 * If broken new-style we should drop the connection
535 * for anything except NBD_OPT_EXPORT_NAME
537 switch (clientflags) {
538 case NBD_OPT_EXPORT_NAME:
539 return nbd_negotiate_handle_export_name(client, length);
542 TRACE("Unsupported option 0x%" PRIx32, clientflags);
554 static coroutine_fn int nbd_negotiate(NBDClientNewData *data)
556 NBDClient *client = data->client;
557 char buf[8 + 8 + 8 + 128];
559 const uint16_t myflags = (NBD_FLAG_HAS_FLAGS | NBD_FLAG_SEND_TRIM |
560 NBD_FLAG_SEND_FLUSH | NBD_FLAG_SEND_FUA);
563 /* Old style negotiation header without options
564 [ 0 .. 7] passwd ("NBDMAGIC")
565 [ 8 .. 15] magic (NBD_CLIENT_MAGIC)
567 [24 .. 25] server flags (0)
568 [26 .. 27] export flags
569 [28 .. 151] reserved (0)
571 New style negotiation header with options
572 [ 0 .. 7] passwd ("NBDMAGIC")
573 [ 8 .. 15] magic (NBD_OPTS_MAGIC)
574 [16 .. 17] server flags (0)
577 [26 .. 27] export flags
578 [28 .. 151] reserved (0)
581 qio_channel_set_blocking(client->ioc, false, NULL);
584 TRACE("Beginning negotiation.");
585 memset(buf, 0, sizeof(buf));
586 memcpy(buf, "NBDMAGIC", 8);
588 oldStyle = client->exp != NULL && !client->tlscreds;
590 TRACE("advertising size %" PRIu64 " and flags %x",
591 client->exp->size, client->exp->nbdflags | myflags);
592 stq_be_p(buf + 8, NBD_CLIENT_MAGIC);
593 stq_be_p(buf + 16, client->exp->size);
594 stw_be_p(buf + 26, client->exp->nbdflags | myflags);
596 stq_be_p(buf + 8, NBD_OPTS_MAGIC);
597 stw_be_p(buf + 16, NBD_FLAG_FIXED_NEWSTYLE);
601 if (client->tlscreds) {
602 TRACE("TLS cannot be enabled with oldstyle protocol");
605 if (nbd_negotiate_write(client->ioc, buf, sizeof(buf)) != sizeof(buf)) {
610 if (nbd_negotiate_write(client->ioc, buf, 18) != 18) {
614 rc = nbd_negotiate_options(client);
616 LOG("option negotiation failed");
620 TRACE("advertising size %" PRIu64 " and flags %x",
621 client->exp->size, client->exp->nbdflags | myflags);
622 stq_be_p(buf + 18, client->exp->size);
623 stw_be_p(buf + 26, client->exp->nbdflags | myflags);
624 if (nbd_negotiate_write(client->ioc, buf + 18, sizeof(buf) - 18) !=
631 TRACE("Negotiation succeeded.");
637 static ssize_t nbd_receive_request(QIOChannel *ioc, struct nbd_request *request)
639 uint8_t buf[NBD_REQUEST_SIZE];
643 ret = read_sync(ioc, buf, sizeof(buf));
648 if (ret != sizeof(buf)) {
654 [ 0 .. 3] magic (NBD_REQUEST_MAGIC)
655 [ 4 .. 7] type (0 == READ, 1 == WRITE)
661 magic = ldl_be_p(buf);
662 request->type = ldl_be_p(buf + 4);
663 request->handle = ldq_be_p(buf + 8);
664 request->from = ldq_be_p(buf + 16);
665 request->len = ldl_be_p(buf + 24);
667 TRACE("Got request: { magic = 0x%" PRIx32 ", .type = %" PRIx32
668 ", from = %" PRIu64 " , len = %" PRIu32 " }",
669 magic, request->type, request->from, request->len);
671 if (magic != NBD_REQUEST_MAGIC) {
672 LOG("invalid magic (got 0x%" PRIx32 ")", magic);
678 static ssize_t nbd_send_reply(QIOChannel *ioc, struct nbd_reply *reply)
680 uint8_t buf[NBD_REPLY_SIZE];
683 reply->error = system_errno_to_nbd_errno(reply->error);
685 TRACE("Sending response to client: { .error = %" PRId32
686 ", handle = %" PRIu64 " }",
687 reply->error, reply->handle);
690 [ 0 .. 3] magic (NBD_REPLY_MAGIC)
691 [ 4 .. 7] error (0 == no error)
694 stl_be_p(buf, NBD_REPLY_MAGIC);
695 stl_be_p(buf + 4, reply->error);
696 stq_be_p(buf + 8, reply->handle);
698 ret = write_sync(ioc, buf, sizeof(buf));
703 if (ret != sizeof(buf)) {
704 LOG("writing to socket failed");
710 #define MAX_NBD_REQUESTS 16
712 void nbd_client_get(NBDClient *client)
717 void nbd_client_put(NBDClient *client)
719 if (--client->refcount == 0) {
720 /* The last reference should be dropped by client->close,
721 * which is called by client_close.
723 assert(client->closing);
725 nbd_unset_handlers(client);
726 object_unref(OBJECT(client->sioc));
727 object_unref(OBJECT(client->ioc));
728 if (client->tlscreds) {
729 object_unref(OBJECT(client->tlscreds));
731 g_free(client->tlsaclname);
733 QTAILQ_REMOVE(&client->exp->clients, client, next);
734 nbd_export_put(client->exp);
740 static void client_close(NBDClient *client)
742 if (client->closing) {
746 client->closing = true;
748 /* Force requests to finish. They will drop their own references,
749 * then we'll close the socket and free the NBDClient.
751 qio_channel_shutdown(client->ioc, QIO_CHANNEL_SHUTDOWN_BOTH,
754 /* Also tell the client, so that they release their reference. */
756 client->close(client);
760 static NBDRequest *nbd_request_get(NBDClient *client)
764 assert(client->nb_requests <= MAX_NBD_REQUESTS - 1);
765 client->nb_requests++;
766 nbd_update_can_read(client);
768 req = g_new0(NBDRequest, 1);
769 nbd_client_get(client);
770 req->client = client;
774 static void nbd_request_put(NBDRequest *req)
776 NBDClient *client = req->client;
779 qemu_vfree(req->data);
783 client->nb_requests--;
784 nbd_update_can_read(client);
785 nbd_client_put(client);
788 static void blk_aio_attached(AioContext *ctx, void *opaque)
790 NBDExport *exp = opaque;
793 TRACE("Export %s: Attaching clients to AIO context %p\n", exp->name, ctx);
797 QTAILQ_FOREACH(client, &exp->clients, next) {
798 nbd_set_handlers(client);
802 static void blk_aio_detach(void *opaque)
804 NBDExport *exp = opaque;
807 TRACE("Export %s: Detaching clients from AIO context %p\n", exp->name, exp->ctx);
809 QTAILQ_FOREACH(client, &exp->clients, next) {
810 nbd_unset_handlers(client);
816 static void nbd_eject_notifier(Notifier *n, void *data)
818 NBDExport *exp = container_of(n, NBDExport, eject_notifier);
819 nbd_export_close(exp);
822 NBDExport *nbd_export_new(BlockDriverState *bs, off_t dev_offset, off_t size,
823 uint16_t nbdflags, void (*close)(NBDExport *),
824 bool writethrough, BlockBackend *on_eject_blk,
828 NBDExport *exp = g_malloc0(sizeof(NBDExport));
831 blk_insert_bs(blk, bs);
832 blk_set_enable_write_cache(blk, !writethrough);
835 QTAILQ_INIT(&exp->clients);
837 exp->dev_offset = dev_offset;
838 exp->nbdflags = nbdflags;
839 exp->size = size < 0 ? blk_getlength(blk) : size;
841 error_setg_errno(errp, -exp->size,
842 "Failed to determine the NBD export's length");
845 exp->size -= exp->size % BDRV_SECTOR_SIZE;
848 exp->ctx = blk_get_aio_context(blk);
849 blk_add_aio_context_notifier(blk, blk_aio_attached, blk_aio_detach, exp);
852 blk_ref(on_eject_blk);
853 exp->eject_notifier_blk = on_eject_blk;
854 exp->eject_notifier.notify = nbd_eject_notifier;
855 blk_add_remove_bs_notifier(on_eject_blk, &exp->eject_notifier);
859 * NBD exports are used for non-shared storage migration. Make sure
860 * that BDRV_O_INACTIVE is cleared and the image is ready for write
861 * access since the export could be available before migration handover.
863 aio_context_acquire(exp->ctx);
864 blk_invalidate_cache(blk, NULL);
865 aio_context_release(exp->ctx);
874 NBDExport *nbd_export_find(const char *name)
877 QTAILQ_FOREACH(exp, &exports, next) {
878 if (strcmp(name, exp->name) == 0) {
886 void nbd_export_set_name(NBDExport *exp, const char *name)
888 if (exp->name == name) {
893 if (exp->name != NULL) {
896 QTAILQ_REMOVE(&exports, exp, next);
901 exp->name = g_strdup(name);
902 QTAILQ_INSERT_TAIL(&exports, exp, next);
907 void nbd_export_set_description(NBDExport *exp, const char *description)
909 g_free(exp->description);
910 exp->description = g_strdup(description);
913 void nbd_export_close(NBDExport *exp)
915 NBDClient *client, *next;
918 QTAILQ_FOREACH_SAFE(client, &exp->clients, next, next) {
919 client_close(client);
921 nbd_export_set_name(exp, NULL);
922 nbd_export_set_description(exp, NULL);
926 void nbd_export_get(NBDExport *exp)
928 assert(exp->refcount > 0);
932 void nbd_export_put(NBDExport *exp)
934 assert(exp->refcount > 0);
935 if (exp->refcount == 1) {
936 nbd_export_close(exp);
939 if (--exp->refcount == 0) {
940 assert(exp->name == NULL);
941 assert(exp->description == NULL);
948 if (exp->eject_notifier_blk) {
949 notifier_remove(&exp->eject_notifier);
950 blk_unref(exp->eject_notifier_blk);
952 blk_remove_aio_context_notifier(exp->blk, blk_aio_attached,
953 blk_aio_detach, exp);
962 BlockBackend *nbd_export_get_blockdev(NBDExport *exp)
967 void nbd_export_close_all(void)
969 NBDExport *exp, *next;
971 QTAILQ_FOREACH_SAFE(exp, &exports, next, next) {
972 nbd_export_close(exp);
976 static ssize_t nbd_co_send_reply(NBDRequest *req, struct nbd_reply *reply,
979 NBDClient *client = req->client;
982 g_assert(qemu_in_coroutine());
983 qemu_co_mutex_lock(&client->send_lock);
984 client->send_coroutine = qemu_coroutine_self();
985 nbd_set_handlers(client);
988 rc = nbd_send_reply(client->ioc, reply);
990 qio_channel_set_cork(client->ioc, true);
991 rc = nbd_send_reply(client->ioc, reply);
993 ret = write_sync(client->ioc, req->data, len);
998 qio_channel_set_cork(client->ioc, false);
1001 client->send_coroutine = NULL;
1002 nbd_set_handlers(client);
1003 qemu_co_mutex_unlock(&client->send_lock);
1007 /* Collect a client request. Return 0 if request looks valid, -EAGAIN
1008 * to keep trying the collection, -EIO to drop connection right away,
1009 * and any other negative value to report an error to the client
1010 * (although the caller may still need to disconnect after reporting
1012 static ssize_t nbd_co_receive_request(NBDRequest *req,
1013 struct nbd_request *request)
1015 NBDClient *client = req->client;
1019 g_assert(qemu_in_coroutine());
1020 client->recv_coroutine = qemu_coroutine_self();
1021 nbd_update_can_read(client);
1023 rc = nbd_receive_request(client->ioc, request);
1025 if (rc != -EAGAIN) {
1031 TRACE("Decoding type");
1033 command = request->type & NBD_CMD_MASK_COMMAND;
1034 if (command != NBD_CMD_WRITE) {
1035 /* No payload, we are ready to read the next request. */
1036 req->complete = true;
1039 if (command == NBD_CMD_DISC) {
1040 /* Special case: we're going to disconnect without a reply,
1041 * whether or not flags, from, or len are bogus */
1042 TRACE("Request type is DISCONNECT");
1047 /* Check for sanity in the parameters, part 1. Defer as many
1048 * checks as possible until after reading any NBD_CMD_WRITE
1049 * payload, so we can try and keep the connection alive. */
1050 if ((request->from + request->len) < request->from) {
1051 LOG("integer overflow detected, you're probably being attacked");
1056 if (command == NBD_CMD_READ || command == NBD_CMD_WRITE) {
1057 if (request->len > NBD_MAX_BUFFER_SIZE) {
1058 LOG("len (%" PRIu32" ) is larger than max len (%u)",
1059 request->len, NBD_MAX_BUFFER_SIZE);
1064 req->data = blk_try_blockalign(client->exp->blk, request->len);
1065 if (req->data == NULL) {
1070 if (command == NBD_CMD_WRITE) {
1071 TRACE("Reading %" PRIu32 " byte(s)", request->len);
1073 if (read_sync(client->ioc, req->data, request->len) != request->len) {
1074 LOG("reading from socket failed");
1078 req->complete = true;
1081 /* Sanity checks, part 2. */
1082 if (request->from + request->len > client->exp->size) {
1083 LOG("operation past EOF; From: %" PRIu64 ", Len: %" PRIu32
1084 ", Size: %" PRIu64, request->from, request->len,
1085 (uint64_t)client->exp->size);
1086 rc = command == NBD_CMD_WRITE ? -ENOSPC : -EINVAL;
1089 if (request->type & ~NBD_CMD_MASK_COMMAND & ~NBD_CMD_FLAG_FUA) {
1090 LOG("unsupported flags (got 0x%x)",
1091 request->type & ~NBD_CMD_MASK_COMMAND);
1099 client->recv_coroutine = NULL;
1100 nbd_update_can_read(client);
1105 static void nbd_trip(void *opaque)
1107 NBDClient *client = opaque;
1108 NBDExport *exp = client->exp;
1110 struct nbd_request request;
1111 struct nbd_reply reply;
1116 TRACE("Reading request.");
1117 if (client->closing) {
1121 req = nbd_request_get(client);
1122 ret = nbd_co_receive_request(req, &request);
1123 if (ret == -EAGAIN) {
1130 reply.handle = request.handle;
1137 command = request.type & NBD_CMD_MASK_COMMAND;
1139 if (client->closing) {
1141 * The client may be closed when we are blocked in
1142 * nbd_co_receive_request()
1149 TRACE("Request type is READ");
1151 if (request.type & NBD_CMD_FLAG_FUA) {
1152 ret = blk_co_flush(exp->blk);
1154 LOG("flush failed");
1160 ret = blk_pread(exp->blk, request.from + exp->dev_offset,
1161 req->data, request.len);
1163 LOG("reading from file failed");
1168 TRACE("Read %" PRIu32" byte(s)", request.len);
1169 if (nbd_co_send_reply(req, &reply, request.len) < 0)
1173 TRACE("Request type is WRITE");
1175 if (exp->nbdflags & NBD_FLAG_READ_ONLY) {
1176 TRACE("Server is read-only, return error");
1177 reply.error = EROFS;
1181 TRACE("Writing to device");
1184 if (request.type & NBD_CMD_FLAG_FUA) {
1185 flags |= BDRV_REQ_FUA;
1187 ret = blk_pwrite(exp->blk, request.from + exp->dev_offset,
1188 req->data, request.len, flags);
1190 LOG("writing to file failed");
1195 if (nbd_co_send_reply(req, &reply, 0) < 0) {
1201 /* unreachable, thanks to special case in nbd_co_receive_request() */
1205 TRACE("Request type is FLUSH");
1207 ret = blk_co_flush(exp->blk);
1209 LOG("flush failed");
1212 if (nbd_co_send_reply(req, &reply, 0) < 0) {
1217 TRACE("Request type is TRIM");
1218 ret = blk_co_pdiscard(exp->blk, request.from + exp->dev_offset,
1221 LOG("discard failed");
1224 if (nbd_co_send_reply(req, &reply, 0) < 0) {
1229 LOG("invalid request type (%" PRIu32 ") received", request.type);
1230 reply.error = EINVAL;
1232 /* We must disconnect after NBD_CMD_WRITE if we did not
1235 if (nbd_co_send_reply(req, &reply, 0) < 0 || !req->complete) {
1241 TRACE("Request/Reply complete");
1244 nbd_request_put(req);
1248 nbd_request_put(req);
1249 client_close(client);
1252 static void nbd_read(void *opaque)
1254 NBDClient *client = opaque;
1256 if (client->recv_coroutine) {
1257 qemu_coroutine_enter(client->recv_coroutine);
1259 qemu_coroutine_enter(qemu_coroutine_create(nbd_trip, client));
1263 static void nbd_restart_write(void *opaque)
1265 NBDClient *client = opaque;
1267 qemu_coroutine_enter(client->send_coroutine);
1270 static void nbd_set_handlers(NBDClient *client)
1272 if (client->exp && client->exp->ctx) {
1273 aio_set_fd_handler(client->exp->ctx, client->sioc->fd,
1275 client->can_read ? nbd_read : NULL,
1276 client->send_coroutine ? nbd_restart_write : NULL,
1281 static void nbd_unset_handlers(NBDClient *client)
1283 if (client->exp && client->exp->ctx) {
1284 aio_set_fd_handler(client->exp->ctx, client->sioc->fd,
1285 true, NULL, NULL, NULL);
1289 static void nbd_update_can_read(NBDClient *client)
1291 bool can_read = client->recv_coroutine ||
1292 client->nb_requests < MAX_NBD_REQUESTS;
1294 if (can_read != client->can_read) {
1295 client->can_read = can_read;
1296 nbd_set_handlers(client);
1298 /* There is no need to invoke aio_notify(), since aio_set_fd_handler()
1299 * in nbd_set_handlers() will have taken care of that */
1303 static coroutine_fn void nbd_co_client_start(void *opaque)
1305 NBDClientNewData *data = opaque;
1306 NBDClient *client = data->client;
1307 NBDExport *exp = client->exp;
1310 nbd_export_get(exp);
1312 if (nbd_negotiate(data)) {
1313 client_close(client);
1316 qemu_co_mutex_init(&client->send_lock);
1317 nbd_set_handlers(client);
1320 QTAILQ_INSERT_TAIL(&exp->clients, client, next);
1326 void nbd_client_new(NBDExport *exp,
1327 QIOChannelSocket *sioc,
1328 QCryptoTLSCreds *tlscreds,
1329 const char *tlsaclname,
1330 void (*close_fn)(NBDClient *))
1333 NBDClientNewData *data = g_new(NBDClientNewData, 1);
1335 client = g_malloc0(sizeof(NBDClient));
1336 client->refcount = 1;
1338 client->tlscreds = tlscreds;
1340 object_ref(OBJECT(client->tlscreds));
1342 client->tlsaclname = g_strdup(tlsaclname);
1343 client->sioc = sioc;
1344 object_ref(OBJECT(client->sioc));
1345 client->ioc = QIO_CHANNEL(sioc);
1346 object_ref(OBJECT(client->ioc));
1347 client->can_read = true;
1348 client->close = close_fn;
1350 data->client = client;
1351 data->co = qemu_coroutine_create(nbd_co_client_start, data);
1352 qemu_coroutine_enter(data->co);