2 * Copyright (C) 2016 Red Hat, Inc.
3 * Copyright (C) 2005 Anthony Liguori <anthony@codemonkey.ws>
5 * Network Block Device Server Side
7 * This program is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; under version 2 of the License.
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License
17 * along with this program; if not, see <http://www.gnu.org/licenses/>.
20 #include "qemu/osdep.h"
21 #include "qapi/error.h"
22 #include "nbd-internal.h"
24 static int system_errno_to_nbd_errno(int err
)
50 /* Definitions for opaque data types */
52 typedef struct NBDRequestData NBDRequestData
;
54 struct NBDRequestData
{
55 QSIMPLEQ_ENTRY(NBDRequestData
) entry
;
63 void (*close
)(NBDExport
*exp
);
71 QTAILQ_HEAD(, NBDClient
) clients
;
72 QTAILQ_ENTRY(NBDExport
) next
;
76 BlockBackend
*eject_notifier_blk
;
77 Notifier eject_notifier
;
80 static QTAILQ_HEAD(, NBDExport
) exports
= QTAILQ_HEAD_INITIALIZER(exports
);
84 void (*close
)(NBDClient
*client
);
88 QCryptoTLSCreds
*tlscreds
;
90 QIOChannelSocket
*sioc
; /* The underlying data channel */
91 QIOChannel
*ioc
; /* The current I/O channel which may differ (eg TLS) */
93 Coroutine
*recv_coroutine
;
96 Coroutine
*send_coroutine
;
98 QTAILQ_ENTRY(NBDClient
) next
;
103 /* That's all folks */
105 static void nbd_client_receive_next_request(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 /* Send a reply header, including length, but no payload.
199 * Return -errno on error, 0 on success. */
200 static int nbd_negotiate_send_rep_len(QIOChannel
*ioc
, uint32_t type
,
201 uint32_t opt
, uint32_t len
)
205 TRACE("Reply opt=%" PRIx32
" type=%" PRIx32
" len=%" PRIu32
,
208 magic
= cpu_to_be64(NBD_REP_MAGIC
);
209 if (nbd_negotiate_write(ioc
, &magic
, sizeof(magic
)) != sizeof(magic
)) {
210 LOG("write failed (rep magic)");
213 opt
= cpu_to_be32(opt
);
214 if (nbd_negotiate_write(ioc
, &opt
, sizeof(opt
)) != sizeof(opt
)) {
215 LOG("write failed (rep opt)");
218 type
= cpu_to_be32(type
);
219 if (nbd_negotiate_write(ioc
, &type
, sizeof(type
)) != sizeof(type
)) {
220 LOG("write failed (rep type)");
223 len
= cpu_to_be32(len
);
224 if (nbd_negotiate_write(ioc
, &len
, sizeof(len
)) != sizeof(len
)) {
225 LOG("write failed (rep data length)");
231 /* Send a reply header with default 0 length.
232 * Return -errno on error, 0 on success. */
233 static int nbd_negotiate_send_rep(QIOChannel
*ioc
, uint32_t type
, uint32_t opt
)
235 return nbd_negotiate_send_rep_len(ioc
, type
, opt
, 0);
238 /* Send an error reply.
239 * Return -errno on error, 0 on success. */
240 static int GCC_FMT_ATTR(4, 5)
241 nbd_negotiate_send_rep_err(QIOChannel
*ioc
, uint32_t type
,
242 uint32_t opt
, const char *fmt
, ...)
250 msg
= g_strdup_vprintf(fmt
, va
);
254 TRACE("sending error message \"%s\"", msg
);
255 ret
= nbd_negotiate_send_rep_len(ioc
, type
, opt
, len
);
259 if (nbd_negotiate_write(ioc
, msg
, len
) != len
) {
260 LOG("write failed (error message)");
270 /* Send a single NBD_REP_SERVER reply to NBD_OPT_LIST, including payload.
271 * Return -errno on error, 0 on success. */
272 static int nbd_negotiate_send_rep_list(QIOChannel
*ioc
, NBDExport
*exp
)
274 size_t name_len
, desc_len
;
276 const char *name
= exp
->name
? exp
->name
: "";
277 const char *desc
= exp
->description
? exp
->description
: "";
280 TRACE("Advertising export name '%s' description '%s'", name
, desc
);
281 name_len
= strlen(name
);
282 desc_len
= strlen(desc
);
283 len
= name_len
+ desc_len
+ sizeof(len
);
284 rc
= nbd_negotiate_send_rep_len(ioc
, NBD_REP_SERVER
, NBD_OPT_LIST
, len
);
289 len
= cpu_to_be32(name_len
);
290 if (nbd_negotiate_write(ioc
, &len
, sizeof(len
)) != sizeof(len
)) {
291 LOG("write failed (name length)");
294 if (nbd_negotiate_write(ioc
, name
, name_len
) != name_len
) {
295 LOG("write failed (name buffer)");
298 if (nbd_negotiate_write(ioc
, desc
, desc_len
) != desc_len
) {
299 LOG("write failed (description buffer)");
305 /* Process the NBD_OPT_LIST command, with a potential series of replies.
306 * Return -errno on error, 0 on success. */
307 static int nbd_negotiate_handle_list(NBDClient
*client
, uint32_t length
)
312 if (nbd_negotiate_drop_sync(client
->ioc
, length
) != length
) {
315 return nbd_negotiate_send_rep_err(client
->ioc
,
316 NBD_REP_ERR_INVALID
, NBD_OPT_LIST
,
317 "OPT_LIST should not have length");
320 /* For each export, send a NBD_REP_SERVER reply. */
321 QTAILQ_FOREACH(exp
, &exports
, next
) {
322 if (nbd_negotiate_send_rep_list(client
->ioc
, exp
)) {
326 /* Finish with a NBD_REP_ACK. */
327 return nbd_negotiate_send_rep(client
->ioc
, NBD_REP_ACK
, NBD_OPT_LIST
);
330 static int nbd_negotiate_handle_export_name(NBDClient
*client
, uint32_t length
)
333 char name
[NBD_MAX_NAME_SIZE
+ 1];
336 [20 .. xx] export name (length bytes)
338 TRACE("Checking length");
339 if (length
>= sizeof(name
)) {
340 LOG("Bad length received");
343 if (nbd_negotiate_read(client
->ioc
, name
, length
) != length
) {
349 TRACE("Client requested export '%s'", name
);
351 client
->exp
= nbd_export_find(name
);
353 LOG("export not found");
357 QTAILQ_INSERT_TAIL(&client
->exp
->clients
, client
, next
);
358 nbd_export_get(client
->exp
);
364 /* Handle NBD_OPT_STARTTLS. Return NULL to drop connection, or else the
365 * new channel for all further (now-encrypted) communication. */
366 static QIOChannel
*nbd_negotiate_handle_starttls(NBDClient
*client
,
371 struct NBDTLSHandshakeData data
= { 0 };
373 TRACE("Setting up TLS");
376 if (nbd_negotiate_drop_sync(ioc
, length
) != length
) {
379 nbd_negotiate_send_rep_err(ioc
, NBD_REP_ERR_INVALID
, NBD_OPT_STARTTLS
,
380 "OPT_STARTTLS should not have length");
384 if (nbd_negotiate_send_rep(client
->ioc
, NBD_REP_ACK
,
385 NBD_OPT_STARTTLS
) < 0) {
389 tioc
= qio_channel_tls_new_server(ioc
,
397 qio_channel_set_name(QIO_CHANNEL(tioc
), "nbd-server-tls");
398 TRACE("Starting TLS handshake");
399 data
.loop
= g_main_loop_new(g_main_context_default(), FALSE
);
400 qio_channel_tls_handshake(tioc
,
405 if (!data
.complete
) {
406 g_main_loop_run(data
.loop
);
408 g_main_loop_unref(data
.loop
);
410 object_unref(OBJECT(tioc
));
411 error_free(data
.error
);
415 return QIO_CHANNEL(tioc
);
419 /* Process all NBD_OPT_* client option commands.
420 * Return -errno on error, 0 on success. */
421 static int nbd_negotiate_options(NBDClient
*client
)
424 bool fixedNewstyle
= false;
427 [ 0 .. 3] client flags
429 [ 0 .. 7] NBD_OPTS_MAGIC
430 [ 8 .. 11] NBD option
431 [12 .. 15] Data length
434 [ 0 .. 7] NBD_OPTS_MAGIC
435 [ 8 .. 11] Second NBD option
436 [12 .. 15] Data length
440 if (nbd_negotiate_read(client
->ioc
, &flags
, sizeof(flags
)) !=
445 TRACE("Checking client flags");
446 be32_to_cpus(&flags
);
447 if (flags
& NBD_FLAG_C_FIXED_NEWSTYLE
) {
448 TRACE("Client supports fixed newstyle handshake");
449 fixedNewstyle
= true;
450 flags
&= ~NBD_FLAG_C_FIXED_NEWSTYLE
;
452 if (flags
& NBD_FLAG_C_NO_ZEROES
) {
453 TRACE("Client supports no zeroes at handshake end");
454 client
->no_zeroes
= true;
455 flags
&= ~NBD_FLAG_C_NO_ZEROES
;
458 TRACE("Unknown client flags 0x%" PRIx32
" received", flags
);
464 uint32_t clientflags
, length
;
467 if (nbd_negotiate_read(client
->ioc
, &magic
, sizeof(magic
)) !=
472 TRACE("Checking opts magic");
473 if (magic
!= be64_to_cpu(NBD_OPTS_MAGIC
)) {
474 LOG("Bad magic received");
478 if (nbd_negotiate_read(client
->ioc
, &clientflags
,
479 sizeof(clientflags
)) != sizeof(clientflags
)) {
483 clientflags
= be32_to_cpu(clientflags
);
485 if (nbd_negotiate_read(client
->ioc
, &length
, sizeof(length
)) !=
490 length
= be32_to_cpu(length
);
492 TRACE("Checking option 0x%" PRIx32
, clientflags
);
493 if (client
->tlscreds
&&
494 client
->ioc
== (QIOChannel
*)client
->sioc
) {
496 if (!fixedNewstyle
) {
497 TRACE("Unsupported option 0x%" PRIx32
, clientflags
);
500 switch (clientflags
) {
501 case NBD_OPT_STARTTLS
:
502 tioc
= nbd_negotiate_handle_starttls(client
, length
);
506 object_unref(OBJECT(client
->ioc
));
507 client
->ioc
= QIO_CHANNEL(tioc
);
510 case NBD_OPT_EXPORT_NAME
:
511 /* No way to return an error to client, so drop connection */
512 TRACE("Option 0x%x not permitted before TLS", clientflags
);
516 if (nbd_negotiate_drop_sync(client
->ioc
, length
) != length
) {
519 ret
= nbd_negotiate_send_rep_err(client
->ioc
,
520 NBD_REP_ERR_TLS_REQD
,
523 "not permitted before TLS",
528 /* Let the client keep trying, unless they asked to quit */
529 if (clientflags
== NBD_OPT_ABORT
) {
534 } else if (fixedNewstyle
) {
535 switch (clientflags
) {
537 ret
= nbd_negotiate_handle_list(client
, length
);
544 /* NBD spec says we must try to reply before
545 * disconnecting, but that we must also tolerate
546 * guests that don't wait for our reply. */
547 nbd_negotiate_send_rep(client
->ioc
, NBD_REP_ACK
, clientflags
);
550 case NBD_OPT_EXPORT_NAME
:
551 return nbd_negotiate_handle_export_name(client
, length
);
553 case NBD_OPT_STARTTLS
:
554 if (nbd_negotiate_drop_sync(client
->ioc
, length
) != length
) {
557 if (client
->tlscreds
) {
558 ret
= nbd_negotiate_send_rep_err(client
->ioc
,
561 "TLS already enabled");
563 ret
= nbd_negotiate_send_rep_err(client
->ioc
,
566 "TLS not configured");
573 if (nbd_negotiate_drop_sync(client
->ioc
, length
) != length
) {
576 ret
= nbd_negotiate_send_rep_err(client
->ioc
,
579 "Unsupported option 0x%"
589 * If broken new-style we should drop the connection
590 * for anything except NBD_OPT_EXPORT_NAME
592 switch (clientflags
) {
593 case NBD_OPT_EXPORT_NAME
:
594 return nbd_negotiate_handle_export_name(client
, length
);
597 TRACE("Unsupported option 0x%" PRIx32
, clientflags
);
609 static coroutine_fn
int nbd_negotiate(NBDClientNewData
*data
)
611 NBDClient
*client
= data
->client
;
612 char buf
[8 + 8 + 8 + 128];
614 const uint16_t myflags
= (NBD_FLAG_HAS_FLAGS
| NBD_FLAG_SEND_TRIM
|
615 NBD_FLAG_SEND_FLUSH
| NBD_FLAG_SEND_FUA
|
616 NBD_FLAG_SEND_WRITE_ZEROES
);
620 /* Old style negotiation header without options
621 [ 0 .. 7] passwd ("NBDMAGIC")
622 [ 8 .. 15] magic (NBD_CLIENT_MAGIC)
624 [24 .. 25] server flags (0)
625 [26 .. 27] export flags
626 [28 .. 151] reserved (0)
628 New style negotiation header with options
629 [ 0 .. 7] passwd ("NBDMAGIC")
630 [ 8 .. 15] magic (NBD_OPTS_MAGIC)
631 [16 .. 17] server flags (0)
634 [26 .. 27] export flags
635 [28 .. 151] reserved (0, omit if no_zeroes)
638 qio_channel_set_blocking(client
->ioc
, false, NULL
);
641 TRACE("Beginning negotiation.");
642 memset(buf
, 0, sizeof(buf
));
643 memcpy(buf
, "NBDMAGIC", 8);
645 oldStyle
= client
->exp
!= NULL
&& !client
->tlscreds
;
647 TRACE("advertising size %" PRIu64
" and flags %x",
648 client
->exp
->size
, client
->exp
->nbdflags
| myflags
);
649 stq_be_p(buf
+ 8, NBD_CLIENT_MAGIC
);
650 stq_be_p(buf
+ 16, client
->exp
->size
);
651 stw_be_p(buf
+ 26, client
->exp
->nbdflags
| myflags
);
653 stq_be_p(buf
+ 8, NBD_OPTS_MAGIC
);
654 stw_be_p(buf
+ 16, NBD_FLAG_FIXED_NEWSTYLE
| NBD_FLAG_NO_ZEROES
);
658 if (client
->tlscreds
) {
659 TRACE("TLS cannot be enabled with oldstyle protocol");
662 if (nbd_negotiate_write(client
->ioc
, buf
, sizeof(buf
)) != sizeof(buf
)) {
667 if (nbd_negotiate_write(client
->ioc
, buf
, 18) != 18) {
671 rc
= nbd_negotiate_options(client
);
673 LOG("option negotiation failed");
677 TRACE("advertising size %" PRIu64
" and flags %x",
678 client
->exp
->size
, client
->exp
->nbdflags
| myflags
);
679 stq_be_p(buf
+ 18, client
->exp
->size
);
680 stw_be_p(buf
+ 26, client
->exp
->nbdflags
| myflags
);
681 len
= client
->no_zeroes
? 10 : sizeof(buf
) - 18;
682 if (nbd_negotiate_write(client
->ioc
, buf
+ 18, len
) != len
) {
688 TRACE("Negotiation succeeded.");
694 static ssize_t
nbd_receive_request(QIOChannel
*ioc
, NBDRequest
*request
)
696 uint8_t buf
[NBD_REQUEST_SIZE
];
700 ret
= read_sync(ioc
, buf
, sizeof(buf
));
705 if (ret
!= sizeof(buf
)) {
711 [ 0 .. 3] magic (NBD_REQUEST_MAGIC)
712 [ 4 .. 5] flags (NBD_CMD_FLAG_FUA, ...)
713 [ 6 .. 7] type (NBD_CMD_READ, ...)
719 magic
= ldl_be_p(buf
);
720 request
->flags
= lduw_be_p(buf
+ 4);
721 request
->type
= lduw_be_p(buf
+ 6);
722 request
->handle
= ldq_be_p(buf
+ 8);
723 request
->from
= ldq_be_p(buf
+ 16);
724 request
->len
= ldl_be_p(buf
+ 24);
726 TRACE("Got request: { magic = 0x%" PRIx32
", .flags = %" PRIx16
727 ", .type = %" PRIx16
", from = %" PRIu64
", len = %" PRIu32
" }",
728 magic
, request
->flags
, request
->type
, request
->from
, request
->len
);
730 if (magic
!= NBD_REQUEST_MAGIC
) {
731 LOG("invalid magic (got 0x%" PRIx32
")", magic
);
737 static ssize_t
nbd_send_reply(QIOChannel
*ioc
, NBDReply
*reply
)
739 uint8_t buf
[NBD_REPLY_SIZE
];
742 reply
->error
= system_errno_to_nbd_errno(reply
->error
);
744 TRACE("Sending response to client: { .error = %" PRId32
745 ", handle = %" PRIu64
" }",
746 reply
->error
, reply
->handle
);
749 [ 0 .. 3] magic (NBD_REPLY_MAGIC)
750 [ 4 .. 7] error (0 == no error)
753 stl_be_p(buf
, NBD_REPLY_MAGIC
);
754 stl_be_p(buf
+ 4, reply
->error
);
755 stq_be_p(buf
+ 8, reply
->handle
);
757 ret
= write_sync(ioc
, buf
, sizeof(buf
));
762 if (ret
!= sizeof(buf
)) {
763 LOG("writing to socket failed");
769 #define MAX_NBD_REQUESTS 16
771 void nbd_client_get(NBDClient
*client
)
776 void nbd_client_put(NBDClient
*client
)
778 if (--client
->refcount
== 0) {
779 /* The last reference should be dropped by client->close,
780 * which is called by client_close.
782 assert(client
->closing
);
784 qio_channel_detach_aio_context(client
->ioc
);
785 object_unref(OBJECT(client
->sioc
));
786 object_unref(OBJECT(client
->ioc
));
787 if (client
->tlscreds
) {
788 object_unref(OBJECT(client
->tlscreds
));
790 g_free(client
->tlsaclname
);
792 QTAILQ_REMOVE(&client
->exp
->clients
, client
, next
);
793 nbd_export_put(client
->exp
);
799 static void client_close(NBDClient
*client
)
801 if (client
->closing
) {
805 client
->closing
= true;
807 /* Force requests to finish. They will drop their own references,
808 * then we'll close the socket and free the NBDClient.
810 qio_channel_shutdown(client
->ioc
, QIO_CHANNEL_SHUTDOWN_BOTH
,
813 /* Also tell the client, so that they release their reference. */
815 client
->close(client
);
819 static NBDRequestData
*nbd_request_get(NBDClient
*client
)
823 assert(client
->nb_requests
<= MAX_NBD_REQUESTS
- 1);
824 client
->nb_requests
++;
826 req
= g_new0(NBDRequestData
, 1);
827 nbd_client_get(client
);
828 req
->client
= client
;
832 static void nbd_request_put(NBDRequestData
*req
)
834 NBDClient
*client
= req
->client
;
837 qemu_vfree(req
->data
);
841 client
->nb_requests
--;
842 nbd_client_receive_next_request(client
);
844 nbd_client_put(client
);
847 static void blk_aio_attached(AioContext
*ctx
, void *opaque
)
849 NBDExport
*exp
= opaque
;
852 TRACE("Export %s: Attaching clients to AIO context %p\n", exp
->name
, ctx
);
856 QTAILQ_FOREACH(client
, &exp
->clients
, next
) {
857 qio_channel_attach_aio_context(client
->ioc
, ctx
);
858 if (client
->recv_coroutine
) {
859 aio_co_schedule(ctx
, client
->recv_coroutine
);
861 if (client
->send_coroutine
) {
862 aio_co_schedule(ctx
, client
->send_coroutine
);
867 static void blk_aio_detach(void *opaque
)
869 NBDExport
*exp
= opaque
;
872 TRACE("Export %s: Detaching clients from AIO context %p\n", exp
->name
, exp
->ctx
);
874 QTAILQ_FOREACH(client
, &exp
->clients
, next
) {
875 qio_channel_detach_aio_context(client
->ioc
);
881 static void nbd_eject_notifier(Notifier
*n
, void *data
)
883 NBDExport
*exp
= container_of(n
, NBDExport
, eject_notifier
);
884 nbd_export_close(exp
);
887 NBDExport
*nbd_export_new(BlockDriverState
*bs
, off_t dev_offset
, off_t size
,
888 uint16_t nbdflags
, void (*close
)(NBDExport
*),
889 bool writethrough
, BlockBackend
*on_eject_blk
,
893 NBDExport
*exp
= g_malloc0(sizeof(NBDExport
));
897 /* Don't allow resize while the NBD server is running, otherwise we don't
898 * care what happens with the node. */
899 perm
= BLK_PERM_CONSISTENT_READ
;
900 if ((nbdflags
& NBD_FLAG_READ_ONLY
) == 0) {
901 perm
|= BLK_PERM_WRITE
;
903 blk
= blk_new(perm
, BLK_PERM_CONSISTENT_READ
| BLK_PERM_WRITE_UNCHANGED
|
904 BLK_PERM_WRITE
| BLK_PERM_GRAPH_MOD
);
905 ret
= blk_insert_bs(blk
, bs
, errp
);
909 blk_set_enable_write_cache(blk
, !writethrough
);
912 QTAILQ_INIT(&exp
->clients
);
914 exp
->dev_offset
= dev_offset
;
915 exp
->nbdflags
= nbdflags
;
916 exp
->size
= size
< 0 ? blk_getlength(blk
) : size
;
918 error_setg_errno(errp
, -exp
->size
,
919 "Failed to determine the NBD export's length");
922 exp
->size
-= exp
->size
% BDRV_SECTOR_SIZE
;
925 exp
->ctx
= blk_get_aio_context(blk
);
926 blk_add_aio_context_notifier(blk
, blk_aio_attached
, blk_aio_detach
, exp
);
929 blk_ref(on_eject_blk
);
930 exp
->eject_notifier_blk
= on_eject_blk
;
931 exp
->eject_notifier
.notify
= nbd_eject_notifier
;
932 blk_add_remove_bs_notifier(on_eject_blk
, &exp
->eject_notifier
);
936 * NBD exports are used for non-shared storage migration. Make sure
937 * that BDRV_O_INACTIVE is cleared and the image is ready for write
938 * access since the export could be available before migration handover.
940 aio_context_acquire(exp
->ctx
);
941 blk_invalidate_cache(blk
, NULL
);
942 aio_context_release(exp
->ctx
);
951 NBDExport
*nbd_export_find(const char *name
)
954 QTAILQ_FOREACH(exp
, &exports
, next
) {
955 if (strcmp(name
, exp
->name
) == 0) {
963 void nbd_export_set_name(NBDExport
*exp
, const char *name
)
965 if (exp
->name
== name
) {
970 if (exp
->name
!= NULL
) {
973 QTAILQ_REMOVE(&exports
, exp
, next
);
978 exp
->name
= g_strdup(name
);
979 QTAILQ_INSERT_TAIL(&exports
, exp
, next
);
984 void nbd_export_set_description(NBDExport
*exp
, const char *description
)
986 g_free(exp
->description
);
987 exp
->description
= g_strdup(description
);
990 void nbd_export_close(NBDExport
*exp
)
992 NBDClient
*client
, *next
;
995 QTAILQ_FOREACH_SAFE(client
, &exp
->clients
, next
, next
) {
996 client_close(client
);
998 nbd_export_set_name(exp
, NULL
);
999 nbd_export_set_description(exp
, NULL
);
1000 nbd_export_put(exp
);
1003 void nbd_export_get(NBDExport
*exp
)
1005 assert(exp
->refcount
> 0);
1009 void nbd_export_put(NBDExport
*exp
)
1011 assert(exp
->refcount
> 0);
1012 if (exp
->refcount
== 1) {
1013 nbd_export_close(exp
);
1016 if (--exp
->refcount
== 0) {
1017 assert(exp
->name
== NULL
);
1018 assert(exp
->description
== NULL
);
1025 if (exp
->eject_notifier_blk
) {
1026 notifier_remove(&exp
->eject_notifier
);
1027 blk_unref(exp
->eject_notifier_blk
);
1029 blk_remove_aio_context_notifier(exp
->blk
, blk_aio_attached
,
1030 blk_aio_detach
, exp
);
1031 blk_unref(exp
->blk
);
1039 BlockBackend
*nbd_export_get_blockdev(NBDExport
*exp
)
1044 void nbd_export_close_all(void)
1046 NBDExport
*exp
, *next
;
1048 QTAILQ_FOREACH_SAFE(exp
, &exports
, next
, next
) {
1049 nbd_export_close(exp
);
1053 static ssize_t
nbd_co_send_reply(NBDRequestData
*req
, NBDReply
*reply
,
1056 NBDClient
*client
= req
->client
;
1059 g_assert(qemu_in_coroutine());
1060 qemu_co_mutex_lock(&client
->send_lock
);
1061 client
->send_coroutine
= qemu_coroutine_self();
1064 rc
= nbd_send_reply(client
->ioc
, reply
);
1066 qio_channel_set_cork(client
->ioc
, true);
1067 rc
= nbd_send_reply(client
->ioc
, reply
);
1069 ret
= write_sync(client
->ioc
, req
->data
, len
);
1074 qio_channel_set_cork(client
->ioc
, false);
1077 client
->send_coroutine
= NULL
;
1078 qemu_co_mutex_unlock(&client
->send_lock
);
1082 /* Collect a client request. Return 0 if request looks valid, -EAGAIN
1083 * to keep trying the collection, -EIO to drop connection right away,
1084 * and any other negative value to report an error to the client
1085 * (although the caller may still need to disconnect after reporting
1087 static ssize_t
nbd_co_receive_request(NBDRequestData
*req
,
1088 NBDRequest
*request
)
1090 NBDClient
*client
= req
->client
;
1093 g_assert(qemu_in_coroutine());
1094 assert(client
->recv_coroutine
== qemu_coroutine_self());
1095 rc
= nbd_receive_request(client
->ioc
, request
);
1097 if (rc
!= -EAGAIN
) {
1103 TRACE("Decoding type");
1105 if (request
->type
!= NBD_CMD_WRITE
) {
1106 /* No payload, we are ready to read the next request. */
1107 req
->complete
= true;
1110 if (request
->type
== NBD_CMD_DISC
) {
1111 /* Special case: we're going to disconnect without a reply,
1112 * whether or not flags, from, or len are bogus */
1113 TRACE("Request type is DISCONNECT");
1118 /* Check for sanity in the parameters, part 1. Defer as many
1119 * checks as possible until after reading any NBD_CMD_WRITE
1120 * payload, so we can try and keep the connection alive. */
1121 if ((request
->from
+ request
->len
) < request
->from
) {
1122 LOG("integer overflow detected, you're probably being attacked");
1127 if (request
->type
== NBD_CMD_READ
|| request
->type
== NBD_CMD_WRITE
) {
1128 if (request
->len
> NBD_MAX_BUFFER_SIZE
) {
1129 LOG("len (%" PRIu32
" ) is larger than max len (%u)",
1130 request
->len
, NBD_MAX_BUFFER_SIZE
);
1135 req
->data
= blk_try_blockalign(client
->exp
->blk
, request
->len
);
1136 if (req
->data
== NULL
) {
1141 if (request
->type
== NBD_CMD_WRITE
) {
1142 TRACE("Reading %" PRIu32
" byte(s)", request
->len
);
1144 if (read_sync(client
->ioc
, req
->data
, request
->len
) != request
->len
) {
1145 LOG("reading from socket failed");
1149 req
->complete
= true;
1152 /* Sanity checks, part 2. */
1153 if (request
->from
+ request
->len
> client
->exp
->size
) {
1154 LOG("operation past EOF; From: %" PRIu64
", Len: %" PRIu32
1155 ", Size: %" PRIu64
, request
->from
, request
->len
,
1156 (uint64_t)client
->exp
->size
);
1157 rc
= request
->type
== NBD_CMD_WRITE
? -ENOSPC
: -EINVAL
;
1160 if (request
->flags
& ~(NBD_CMD_FLAG_FUA
| NBD_CMD_FLAG_NO_HOLE
)) {
1161 LOG("unsupported flags (got 0x%x)", request
->flags
);
1165 if (request
->type
!= NBD_CMD_WRITE_ZEROES
&&
1166 (request
->flags
& NBD_CMD_FLAG_NO_HOLE
)) {
1167 LOG("unexpected flags (got 0x%x)", request
->flags
);
1175 client
->recv_coroutine
= NULL
;
1176 nbd_client_receive_next_request(client
);
1181 /* Owns a reference to the NBDClient passed as opaque. */
1182 static coroutine_fn
void nbd_trip(void *opaque
)
1184 NBDClient
*client
= opaque
;
1185 NBDExport
*exp
= client
->exp
;
1186 NBDRequestData
*req
;
1187 NBDRequest request
= { 0 }; /* GCC thinks it can be used uninitialized */
1192 TRACE("Reading request.");
1193 if (client
->closing
) {
1194 nbd_client_put(client
);
1198 req
= nbd_request_get(client
);
1199 ret
= nbd_co_receive_request(req
, &request
);
1200 if (ret
== -EAGAIN
) {
1207 reply
.handle
= request
.handle
;
1215 if (client
->closing
) {
1217 * The client may be closed when we are blocked in
1218 * nbd_co_receive_request()
1223 switch (request
.type
) {
1225 TRACE("Request type is READ");
1227 /* XXX: NBD Protocol only documents use of FUA with WRITE */
1228 if (request
.flags
& NBD_CMD_FLAG_FUA
) {
1229 ret
= blk_co_flush(exp
->blk
);
1231 LOG("flush failed");
1237 ret
= blk_pread(exp
->blk
, request
.from
+ exp
->dev_offset
,
1238 req
->data
, request
.len
);
1240 LOG("reading from file failed");
1245 TRACE("Read %" PRIu32
" byte(s)", request
.len
);
1246 if (nbd_co_send_reply(req
, &reply
, request
.len
) < 0)
1250 TRACE("Request type is WRITE");
1252 if (exp
->nbdflags
& NBD_FLAG_READ_ONLY
) {
1253 TRACE("Server is read-only, return error");
1254 reply
.error
= EROFS
;
1258 TRACE("Writing to device");
1261 if (request
.flags
& NBD_CMD_FLAG_FUA
) {
1262 flags
|= BDRV_REQ_FUA
;
1264 ret
= blk_pwrite(exp
->blk
, request
.from
+ exp
->dev_offset
,
1265 req
->data
, request
.len
, flags
);
1267 LOG("writing to file failed");
1272 if (nbd_co_send_reply(req
, &reply
, 0) < 0) {
1277 case NBD_CMD_WRITE_ZEROES
:
1278 TRACE("Request type is WRITE_ZEROES");
1280 if (exp
->nbdflags
& NBD_FLAG_READ_ONLY
) {
1281 TRACE("Server is read-only, return error");
1282 reply
.error
= EROFS
;
1286 TRACE("Writing to device");
1289 if (request
.flags
& NBD_CMD_FLAG_FUA
) {
1290 flags
|= BDRV_REQ_FUA
;
1292 if (!(request
.flags
& NBD_CMD_FLAG_NO_HOLE
)) {
1293 flags
|= BDRV_REQ_MAY_UNMAP
;
1295 ret
= blk_pwrite_zeroes(exp
->blk
, request
.from
+ exp
->dev_offset
,
1296 request
.len
, flags
);
1298 LOG("writing to file failed");
1303 if (nbd_co_send_reply(req
, &reply
, 0) < 0) {
1309 /* unreachable, thanks to special case in nbd_co_receive_request() */
1313 TRACE("Request type is FLUSH");
1315 ret
= blk_co_flush(exp
->blk
);
1317 LOG("flush failed");
1320 if (nbd_co_send_reply(req
, &reply
, 0) < 0) {
1325 TRACE("Request type is TRIM");
1326 ret
= blk_co_pdiscard(exp
->blk
, request
.from
+ exp
->dev_offset
,
1329 LOG("discard failed");
1332 if (nbd_co_send_reply(req
, &reply
, 0) < 0) {
1337 LOG("invalid request type (%" PRIu32
") received", request
.type
);
1338 reply
.error
= EINVAL
;
1340 /* We must disconnect after NBD_CMD_WRITE if we did not
1343 if (nbd_co_send_reply(req
, &reply
, 0) < 0 || !req
->complete
) {
1349 TRACE("Request/Reply complete");
1352 nbd_request_put(req
);
1353 nbd_client_put(client
);
1357 nbd_request_put(req
);
1358 client_close(client
);
1359 nbd_client_put(client
);
1362 static void nbd_client_receive_next_request(NBDClient
*client
)
1364 if (!client
->recv_coroutine
&& client
->nb_requests
< MAX_NBD_REQUESTS
) {
1365 nbd_client_get(client
);
1366 client
->recv_coroutine
= qemu_coroutine_create(nbd_trip
, client
);
1367 aio_co_schedule(client
->exp
->ctx
, client
->recv_coroutine
);
1371 static coroutine_fn
void nbd_co_client_start(void *opaque
)
1373 NBDClientNewData
*data
= opaque
;
1374 NBDClient
*client
= data
->client
;
1375 NBDExport
*exp
= client
->exp
;
1378 nbd_export_get(exp
);
1380 if (nbd_negotiate(data
)) {
1381 client_close(client
);
1384 qemu_co_mutex_init(&client
->send_lock
);
1387 QTAILQ_INSERT_TAIL(&exp
->clients
, client
, next
);
1390 nbd_client_receive_next_request(client
);
1396 void nbd_client_new(NBDExport
*exp
,
1397 QIOChannelSocket
*sioc
,
1398 QCryptoTLSCreds
*tlscreds
,
1399 const char *tlsaclname
,
1400 void (*close_fn
)(NBDClient
*))
1403 NBDClientNewData
*data
= g_new(NBDClientNewData
, 1);
1405 client
= g_malloc0(sizeof(NBDClient
));
1406 client
->refcount
= 1;
1408 client
->tlscreds
= tlscreds
;
1410 object_ref(OBJECT(client
->tlscreds
));
1412 client
->tlsaclname
= g_strdup(tlsaclname
);
1413 client
->sioc
= sioc
;
1414 object_ref(OBJECT(client
->sioc
));
1415 client
->ioc
= QIO_CHANNEL(sioc
);
1416 object_ref(OBJECT(client
->ioc
));
1417 client
->close
= close_fn
;
1419 data
->client
= client
;
1420 data
->co
= qemu_coroutine_create(nbd_co_client_start
, data
);
1421 qemu_coroutine_enter(data
->co
);