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
;
100 QTAILQ_ENTRY(NBDClient
) next
;
105 /* That's all folks */
107 static void nbd_set_handlers(NBDClient
*client
);
108 static void nbd_unset_handlers(NBDClient
*client
);
109 static void nbd_update_can_read(NBDClient
*client
);
111 static gboolean
nbd_negotiate_continue(QIOChannel
*ioc
,
112 GIOCondition condition
,
115 qemu_coroutine_enter(opaque
);
119 static ssize_t
nbd_negotiate_read(QIOChannel
*ioc
, void *buffer
, size_t size
)
124 assert(qemu_in_coroutine());
125 /* Negotiation are always in main loop. */
126 watch
= qio_channel_add_watch(ioc
,
128 nbd_negotiate_continue
,
129 qemu_coroutine_self(),
131 ret
= read_sync(ioc
, buffer
, size
);
132 g_source_remove(watch
);
137 static ssize_t
nbd_negotiate_write(QIOChannel
*ioc
, const void *buffer
,
143 assert(qemu_in_coroutine());
144 /* Negotiation are always in main loop. */
145 watch
= qio_channel_add_watch(ioc
,
147 nbd_negotiate_continue
,
148 qemu_coroutine_self(),
150 ret
= write_sync(ioc
, buffer
, size
);
151 g_source_remove(watch
);
155 static ssize_t
nbd_negotiate_drop_sync(QIOChannel
*ioc
, size_t size
)
157 ssize_t ret
, dropped
= size
;
158 uint8_t *buffer
= g_malloc(MIN(65536, size
));
161 ret
= nbd_negotiate_read(ioc
, buffer
, MIN(65536, size
));
175 /* Basic flow for negotiation
202 /* Send a reply header, including length, but no payload.
203 * Return -errno on error, 0 on success. */
204 static int nbd_negotiate_send_rep_len(QIOChannel
*ioc
, uint32_t type
,
205 uint32_t opt
, uint32_t len
)
209 TRACE("Reply opt=%" PRIx32
" type=%" PRIx32
" len=%" PRIu32
,
212 magic
= cpu_to_be64(NBD_REP_MAGIC
);
213 if (nbd_negotiate_write(ioc
, &magic
, sizeof(magic
)) != sizeof(magic
)) {
214 LOG("write failed (rep magic)");
217 opt
= cpu_to_be32(opt
);
218 if (nbd_negotiate_write(ioc
, &opt
, sizeof(opt
)) != sizeof(opt
)) {
219 LOG("write failed (rep opt)");
222 type
= cpu_to_be32(type
);
223 if (nbd_negotiate_write(ioc
, &type
, sizeof(type
)) != sizeof(type
)) {
224 LOG("write failed (rep type)");
227 len
= cpu_to_be32(len
);
228 if (nbd_negotiate_write(ioc
, &len
, sizeof(len
)) != sizeof(len
)) {
229 LOG("write failed (rep data length)");
235 /* Send a reply header with default 0 length.
236 * Return -errno on error, 0 on success. */
237 static int nbd_negotiate_send_rep(QIOChannel
*ioc
, uint32_t type
, uint32_t opt
)
239 return nbd_negotiate_send_rep_len(ioc
, type
, opt
, 0);
242 /* Send an error reply.
243 * Return -errno on error, 0 on success. */
244 static int GCC_FMT_ATTR(4, 5)
245 nbd_negotiate_send_rep_err(QIOChannel
*ioc
, uint32_t type
,
246 uint32_t opt
, const char *fmt
, ...)
254 msg
= g_strdup_vprintf(fmt
, va
);
258 TRACE("sending error message \"%s\"", msg
);
259 ret
= nbd_negotiate_send_rep_len(ioc
, type
, opt
, len
);
263 if (nbd_negotiate_write(ioc
, msg
, len
) != len
) {
264 LOG("write failed (error message)");
274 /* Send a single NBD_REP_SERVER reply to NBD_OPT_LIST, including payload.
275 * Return -errno on error, 0 on success. */
276 static int nbd_negotiate_send_rep_list(QIOChannel
*ioc
, NBDExport
*exp
)
278 size_t name_len
, desc_len
;
280 const char *name
= exp
->name
? exp
->name
: "";
281 const char *desc
= exp
->description
? exp
->description
: "";
284 TRACE("Advertising export name '%s' description '%s'", name
, desc
);
285 name_len
= strlen(name
);
286 desc_len
= strlen(desc
);
287 len
= name_len
+ desc_len
+ sizeof(len
);
288 rc
= nbd_negotiate_send_rep_len(ioc
, NBD_REP_SERVER
, NBD_OPT_LIST
, len
);
293 len
= cpu_to_be32(name_len
);
294 if (nbd_negotiate_write(ioc
, &len
, sizeof(len
)) != sizeof(len
)) {
295 LOG("write failed (name length)");
298 if (nbd_negotiate_write(ioc
, name
, name_len
) != name_len
) {
299 LOG("write failed (name buffer)");
302 if (nbd_negotiate_write(ioc
, desc
, desc_len
) != desc_len
) {
303 LOG("write failed (description buffer)");
309 /* Process the NBD_OPT_LIST command, with a potential series of replies.
310 * Return -errno on error, 0 on success. */
311 static int nbd_negotiate_handle_list(NBDClient
*client
, uint32_t length
)
316 if (nbd_negotiate_drop_sync(client
->ioc
, length
) != length
) {
319 return nbd_negotiate_send_rep_err(client
->ioc
,
320 NBD_REP_ERR_INVALID
, NBD_OPT_LIST
,
321 "OPT_LIST should not have length");
324 /* For each export, send a NBD_REP_SERVER reply. */
325 QTAILQ_FOREACH(exp
, &exports
, next
) {
326 if (nbd_negotiate_send_rep_list(client
->ioc
, exp
)) {
330 /* Finish with a NBD_REP_ACK. */
331 return nbd_negotiate_send_rep(client
->ioc
, NBD_REP_ACK
, NBD_OPT_LIST
);
334 static int nbd_negotiate_handle_export_name(NBDClient
*client
, uint32_t length
)
337 char name
[NBD_MAX_NAME_SIZE
+ 1];
340 [20 .. xx] export name (length bytes)
342 TRACE("Checking length");
343 if (length
>= sizeof(name
)) {
344 LOG("Bad length received");
347 if (nbd_negotiate_read(client
->ioc
, name
, length
) != length
) {
353 TRACE("Client requested export '%s'", name
);
355 client
->exp
= nbd_export_find(name
);
357 LOG("export not found");
361 QTAILQ_INSERT_TAIL(&client
->exp
->clients
, client
, next
);
362 nbd_export_get(client
->exp
);
368 /* Handle NBD_OPT_STARTTLS. Return NULL to drop connection, or else the
369 * new channel for all further (now-encrypted) communication. */
370 static QIOChannel
*nbd_negotiate_handle_starttls(NBDClient
*client
,
375 struct NBDTLSHandshakeData data
= { 0 };
377 TRACE("Setting up TLS");
380 if (nbd_negotiate_drop_sync(ioc
, length
) != length
) {
383 nbd_negotiate_send_rep_err(ioc
, NBD_REP_ERR_INVALID
, NBD_OPT_STARTTLS
,
384 "OPT_STARTTLS should not have length");
388 if (nbd_negotiate_send_rep(client
->ioc
, NBD_REP_ACK
,
389 NBD_OPT_STARTTLS
) < 0) {
393 tioc
= qio_channel_tls_new_server(ioc
,
401 qio_channel_set_name(QIO_CHANNEL(tioc
), "nbd-server-tls");
402 TRACE("Starting TLS handshake");
403 data
.loop
= g_main_loop_new(g_main_context_default(), FALSE
);
404 qio_channel_tls_handshake(tioc
,
409 if (!data
.complete
) {
410 g_main_loop_run(data
.loop
);
412 g_main_loop_unref(data
.loop
);
414 object_unref(OBJECT(tioc
));
415 error_free(data
.error
);
419 return QIO_CHANNEL(tioc
);
423 /* Process all NBD_OPT_* client option commands.
424 * Return -errno on error, 0 on success. */
425 static int nbd_negotiate_options(NBDClient
*client
)
428 bool fixedNewstyle
= false;
431 [ 0 .. 3] client flags
433 [ 0 .. 7] NBD_OPTS_MAGIC
434 [ 8 .. 11] NBD option
435 [12 .. 15] Data length
438 [ 0 .. 7] NBD_OPTS_MAGIC
439 [ 8 .. 11] Second NBD option
440 [12 .. 15] Data length
444 if (nbd_negotiate_read(client
->ioc
, &flags
, sizeof(flags
)) !=
449 TRACE("Checking client flags");
450 be32_to_cpus(&flags
);
451 if (flags
& NBD_FLAG_C_FIXED_NEWSTYLE
) {
452 TRACE("Client supports fixed newstyle handshake");
453 fixedNewstyle
= true;
454 flags
&= ~NBD_FLAG_C_FIXED_NEWSTYLE
;
456 if (flags
& NBD_FLAG_C_NO_ZEROES
) {
457 TRACE("Client supports no zeroes at handshake end");
458 client
->no_zeroes
= true;
459 flags
&= ~NBD_FLAG_C_NO_ZEROES
;
462 TRACE("Unknown client flags 0x%" PRIx32
" received", flags
);
468 uint32_t clientflags
, length
;
471 if (nbd_negotiate_read(client
->ioc
, &magic
, sizeof(magic
)) !=
476 TRACE("Checking opts magic");
477 if (magic
!= be64_to_cpu(NBD_OPTS_MAGIC
)) {
478 LOG("Bad magic received");
482 if (nbd_negotiate_read(client
->ioc
, &clientflags
,
483 sizeof(clientflags
)) != sizeof(clientflags
)) {
487 clientflags
= be32_to_cpu(clientflags
);
489 if (nbd_negotiate_read(client
->ioc
, &length
, sizeof(length
)) !=
494 length
= be32_to_cpu(length
);
496 TRACE("Checking option 0x%" PRIx32
, clientflags
);
497 if (client
->tlscreds
&&
498 client
->ioc
== (QIOChannel
*)client
->sioc
) {
500 if (!fixedNewstyle
) {
501 TRACE("Unsupported option 0x%" PRIx32
, clientflags
);
504 switch (clientflags
) {
505 case NBD_OPT_STARTTLS
:
506 tioc
= nbd_negotiate_handle_starttls(client
, length
);
510 object_unref(OBJECT(client
->ioc
));
511 client
->ioc
= QIO_CHANNEL(tioc
);
514 case NBD_OPT_EXPORT_NAME
:
515 /* No way to return an error to client, so drop connection */
516 TRACE("Option 0x%x not permitted before TLS", clientflags
);
520 if (nbd_negotiate_drop_sync(client
->ioc
, length
) != length
) {
523 ret
= nbd_negotiate_send_rep_err(client
->ioc
,
524 NBD_REP_ERR_TLS_REQD
,
527 "not permitted before TLS",
532 /* Let the client keep trying, unless they asked to quit */
533 if (clientflags
== NBD_OPT_ABORT
) {
538 } else if (fixedNewstyle
) {
539 switch (clientflags
) {
541 ret
= nbd_negotiate_handle_list(client
, length
);
548 /* NBD spec says we must try to reply before
549 * disconnecting, but that we must also tolerate
550 * guests that don't wait for our reply. */
551 nbd_negotiate_send_rep(client
->ioc
, NBD_REP_ACK
, clientflags
);
554 case NBD_OPT_EXPORT_NAME
:
555 return nbd_negotiate_handle_export_name(client
, length
);
557 case NBD_OPT_STARTTLS
:
558 if (nbd_negotiate_drop_sync(client
->ioc
, length
) != length
) {
561 if (client
->tlscreds
) {
562 ret
= nbd_negotiate_send_rep_err(client
->ioc
,
565 "TLS already enabled");
567 ret
= nbd_negotiate_send_rep_err(client
->ioc
,
570 "TLS not configured");
577 if (nbd_negotiate_drop_sync(client
->ioc
, length
) != length
) {
580 ret
= nbd_negotiate_send_rep_err(client
->ioc
,
583 "Unsupported option 0x%"
593 * If broken new-style we should drop the connection
594 * for anything except NBD_OPT_EXPORT_NAME
596 switch (clientflags
) {
597 case NBD_OPT_EXPORT_NAME
:
598 return nbd_negotiate_handle_export_name(client
, length
);
601 TRACE("Unsupported option 0x%" PRIx32
, clientflags
);
613 static coroutine_fn
int nbd_negotiate(NBDClientNewData
*data
)
615 NBDClient
*client
= data
->client
;
616 char buf
[8 + 8 + 8 + 128];
618 const uint16_t myflags
= (NBD_FLAG_HAS_FLAGS
| NBD_FLAG_SEND_TRIM
|
619 NBD_FLAG_SEND_FLUSH
| NBD_FLAG_SEND_FUA
|
620 NBD_FLAG_SEND_WRITE_ZEROES
);
624 /* Old style negotiation header without options
625 [ 0 .. 7] passwd ("NBDMAGIC")
626 [ 8 .. 15] magic (NBD_CLIENT_MAGIC)
628 [24 .. 25] server flags (0)
629 [26 .. 27] export flags
630 [28 .. 151] reserved (0)
632 New style negotiation header with options
633 [ 0 .. 7] passwd ("NBDMAGIC")
634 [ 8 .. 15] magic (NBD_OPTS_MAGIC)
635 [16 .. 17] server flags (0)
638 [26 .. 27] export flags
639 [28 .. 151] reserved (0, omit if no_zeroes)
642 qio_channel_set_blocking(client
->ioc
, false, NULL
);
645 TRACE("Beginning negotiation.");
646 memset(buf
, 0, sizeof(buf
));
647 memcpy(buf
, "NBDMAGIC", 8);
649 oldStyle
= client
->exp
!= NULL
&& !client
->tlscreds
;
651 TRACE("advertising size %" PRIu64
" and flags %x",
652 client
->exp
->size
, client
->exp
->nbdflags
| myflags
);
653 stq_be_p(buf
+ 8, NBD_CLIENT_MAGIC
);
654 stq_be_p(buf
+ 16, client
->exp
->size
);
655 stw_be_p(buf
+ 26, client
->exp
->nbdflags
| myflags
);
657 stq_be_p(buf
+ 8, NBD_OPTS_MAGIC
);
658 stw_be_p(buf
+ 16, NBD_FLAG_FIXED_NEWSTYLE
| NBD_FLAG_NO_ZEROES
);
662 if (client
->tlscreds
) {
663 TRACE("TLS cannot be enabled with oldstyle protocol");
666 if (nbd_negotiate_write(client
->ioc
, buf
, sizeof(buf
)) != sizeof(buf
)) {
671 if (nbd_negotiate_write(client
->ioc
, buf
, 18) != 18) {
675 rc
= nbd_negotiate_options(client
);
677 LOG("option negotiation failed");
681 TRACE("advertising size %" PRIu64
" and flags %x",
682 client
->exp
->size
, client
->exp
->nbdflags
| myflags
);
683 stq_be_p(buf
+ 18, client
->exp
->size
);
684 stw_be_p(buf
+ 26, client
->exp
->nbdflags
| myflags
);
685 len
= client
->no_zeroes
? 10 : sizeof(buf
) - 18;
686 if (nbd_negotiate_write(client
->ioc
, buf
+ 18, len
) != len
) {
692 TRACE("Negotiation succeeded.");
698 static ssize_t
nbd_receive_request(QIOChannel
*ioc
, NBDRequest
*request
)
700 uint8_t buf
[NBD_REQUEST_SIZE
];
704 ret
= read_sync(ioc
, buf
, sizeof(buf
));
709 if (ret
!= sizeof(buf
)) {
715 [ 0 .. 3] magic (NBD_REQUEST_MAGIC)
716 [ 4 .. 5] flags (NBD_CMD_FLAG_FUA, ...)
717 [ 6 .. 7] type (NBD_CMD_READ, ...)
723 magic
= ldl_be_p(buf
);
724 request
->flags
= lduw_be_p(buf
+ 4);
725 request
->type
= lduw_be_p(buf
+ 6);
726 request
->handle
= ldq_be_p(buf
+ 8);
727 request
->from
= ldq_be_p(buf
+ 16);
728 request
->len
= ldl_be_p(buf
+ 24);
730 TRACE("Got request: { magic = 0x%" PRIx32
", .flags = %" PRIx16
731 ", .type = %" PRIx16
", from = %" PRIu64
", len = %" PRIu32
" }",
732 magic
, request
->flags
, request
->type
, request
->from
, request
->len
);
734 if (magic
!= NBD_REQUEST_MAGIC
) {
735 LOG("invalid magic (got 0x%" PRIx32
")", magic
);
741 static ssize_t
nbd_send_reply(QIOChannel
*ioc
, NBDReply
*reply
)
743 uint8_t buf
[NBD_REPLY_SIZE
];
746 reply
->error
= system_errno_to_nbd_errno(reply
->error
);
748 TRACE("Sending response to client: { .error = %" PRId32
749 ", handle = %" PRIu64
" }",
750 reply
->error
, reply
->handle
);
753 [ 0 .. 3] magic (NBD_REPLY_MAGIC)
754 [ 4 .. 7] error (0 == no error)
757 stl_be_p(buf
, NBD_REPLY_MAGIC
);
758 stl_be_p(buf
+ 4, reply
->error
);
759 stq_be_p(buf
+ 8, reply
->handle
);
761 ret
= write_sync(ioc
, buf
, sizeof(buf
));
766 if (ret
!= sizeof(buf
)) {
767 LOG("writing to socket failed");
773 #define MAX_NBD_REQUESTS 16
775 void nbd_client_get(NBDClient
*client
)
780 void nbd_client_put(NBDClient
*client
)
782 if (--client
->refcount
== 0) {
783 /* The last reference should be dropped by client->close,
784 * which is called by client_close.
786 assert(client
->closing
);
788 nbd_unset_handlers(client
);
789 object_unref(OBJECT(client
->sioc
));
790 object_unref(OBJECT(client
->ioc
));
791 if (client
->tlscreds
) {
792 object_unref(OBJECT(client
->tlscreds
));
794 g_free(client
->tlsaclname
);
796 QTAILQ_REMOVE(&client
->exp
->clients
, client
, next
);
797 nbd_export_put(client
->exp
);
803 static void client_close(NBDClient
*client
)
805 if (client
->closing
) {
809 client
->closing
= true;
811 /* Force requests to finish. They will drop their own references,
812 * then we'll close the socket and free the NBDClient.
814 qio_channel_shutdown(client
->ioc
, QIO_CHANNEL_SHUTDOWN_BOTH
,
817 /* Also tell the client, so that they release their reference. */
819 client
->close(client
);
823 static NBDRequestData
*nbd_request_get(NBDClient
*client
)
827 assert(client
->nb_requests
<= MAX_NBD_REQUESTS
- 1);
828 client
->nb_requests
++;
829 nbd_update_can_read(client
);
831 req
= g_new0(NBDRequestData
, 1);
832 nbd_client_get(client
);
833 req
->client
= client
;
837 static void nbd_request_put(NBDRequestData
*req
)
839 NBDClient
*client
= req
->client
;
842 qemu_vfree(req
->data
);
846 client
->nb_requests
--;
847 nbd_update_can_read(client
);
848 nbd_client_put(client
);
851 static void blk_aio_attached(AioContext
*ctx
, void *opaque
)
853 NBDExport
*exp
= opaque
;
856 TRACE("Export %s: Attaching clients to AIO context %p\n", exp
->name
, ctx
);
860 QTAILQ_FOREACH(client
, &exp
->clients
, next
) {
861 nbd_set_handlers(client
);
865 static void blk_aio_detach(void *opaque
)
867 NBDExport
*exp
= opaque
;
870 TRACE("Export %s: Detaching clients from AIO context %p\n", exp
->name
, exp
->ctx
);
872 QTAILQ_FOREACH(client
, &exp
->clients
, next
) {
873 nbd_unset_handlers(client
);
879 static void nbd_eject_notifier(Notifier
*n
, void *data
)
881 NBDExport
*exp
= container_of(n
, NBDExport
, eject_notifier
);
882 nbd_export_close(exp
);
885 NBDExport
*nbd_export_new(BlockDriverState
*bs
, off_t dev_offset
, off_t size
,
886 uint16_t nbdflags
, void (*close
)(NBDExport
*),
887 bool writethrough
, BlockBackend
*on_eject_blk
,
891 NBDExport
*exp
= g_malloc0(sizeof(NBDExport
));
894 blk_insert_bs(blk
, bs
);
895 blk_set_enable_write_cache(blk
, !writethrough
);
898 QTAILQ_INIT(&exp
->clients
);
900 exp
->dev_offset
= dev_offset
;
901 exp
->nbdflags
= nbdflags
;
902 exp
->size
= size
< 0 ? blk_getlength(blk
) : size
;
904 error_setg_errno(errp
, -exp
->size
,
905 "Failed to determine the NBD export's length");
908 exp
->size
-= exp
->size
% BDRV_SECTOR_SIZE
;
911 exp
->ctx
= blk_get_aio_context(blk
);
912 blk_add_aio_context_notifier(blk
, blk_aio_attached
, blk_aio_detach
, exp
);
915 blk_ref(on_eject_blk
);
916 exp
->eject_notifier_blk
= on_eject_blk
;
917 exp
->eject_notifier
.notify
= nbd_eject_notifier
;
918 blk_add_remove_bs_notifier(on_eject_blk
, &exp
->eject_notifier
);
922 * NBD exports are used for non-shared storage migration. Make sure
923 * that BDRV_O_INACTIVE is cleared and the image is ready for write
924 * access since the export could be available before migration handover.
926 aio_context_acquire(exp
->ctx
);
927 blk_invalidate_cache(blk
, NULL
);
928 aio_context_release(exp
->ctx
);
937 NBDExport
*nbd_export_find(const char *name
)
940 QTAILQ_FOREACH(exp
, &exports
, next
) {
941 if (strcmp(name
, exp
->name
) == 0) {
949 void nbd_export_set_name(NBDExport
*exp
, const char *name
)
951 if (exp
->name
== name
) {
956 if (exp
->name
!= NULL
) {
959 QTAILQ_REMOVE(&exports
, exp
, next
);
964 exp
->name
= g_strdup(name
);
965 QTAILQ_INSERT_TAIL(&exports
, exp
, next
);
970 void nbd_export_set_description(NBDExport
*exp
, const char *description
)
972 g_free(exp
->description
);
973 exp
->description
= g_strdup(description
);
976 void nbd_export_close(NBDExport
*exp
)
978 NBDClient
*client
, *next
;
981 QTAILQ_FOREACH_SAFE(client
, &exp
->clients
, next
, next
) {
982 client_close(client
);
984 nbd_export_set_name(exp
, NULL
);
985 nbd_export_set_description(exp
, NULL
);
989 void nbd_export_get(NBDExport
*exp
)
991 assert(exp
->refcount
> 0);
995 void nbd_export_put(NBDExport
*exp
)
997 assert(exp
->refcount
> 0);
998 if (exp
->refcount
== 1) {
999 nbd_export_close(exp
);
1002 if (--exp
->refcount
== 0) {
1003 assert(exp
->name
== NULL
);
1004 assert(exp
->description
== NULL
);
1011 if (exp
->eject_notifier_blk
) {
1012 notifier_remove(&exp
->eject_notifier
);
1013 blk_unref(exp
->eject_notifier_blk
);
1015 blk_remove_aio_context_notifier(exp
->blk
, blk_aio_attached
,
1016 blk_aio_detach
, exp
);
1017 blk_unref(exp
->blk
);
1025 BlockBackend
*nbd_export_get_blockdev(NBDExport
*exp
)
1030 void nbd_export_close_all(void)
1032 NBDExport
*exp
, *next
;
1034 QTAILQ_FOREACH_SAFE(exp
, &exports
, next
, next
) {
1035 nbd_export_close(exp
);
1039 static ssize_t
nbd_co_send_reply(NBDRequestData
*req
, NBDReply
*reply
,
1042 NBDClient
*client
= req
->client
;
1045 g_assert(qemu_in_coroutine());
1046 qemu_co_mutex_lock(&client
->send_lock
);
1047 client
->send_coroutine
= qemu_coroutine_self();
1048 nbd_set_handlers(client
);
1051 rc
= nbd_send_reply(client
->ioc
, reply
);
1053 qio_channel_set_cork(client
->ioc
, true);
1054 rc
= nbd_send_reply(client
->ioc
, reply
);
1056 ret
= write_sync(client
->ioc
, req
->data
, len
);
1061 qio_channel_set_cork(client
->ioc
, false);
1064 client
->send_coroutine
= NULL
;
1065 nbd_set_handlers(client
);
1066 qemu_co_mutex_unlock(&client
->send_lock
);
1070 /* Collect a client request. Return 0 if request looks valid, -EAGAIN
1071 * to keep trying the collection, -EIO to drop connection right away,
1072 * and any other negative value to report an error to the client
1073 * (although the caller may still need to disconnect after reporting
1075 static ssize_t
nbd_co_receive_request(NBDRequestData
*req
,
1076 NBDRequest
*request
)
1078 NBDClient
*client
= req
->client
;
1081 g_assert(qemu_in_coroutine());
1082 client
->recv_coroutine
= qemu_coroutine_self();
1083 nbd_update_can_read(client
);
1085 rc
= nbd_receive_request(client
->ioc
, request
);
1087 if (rc
!= -EAGAIN
) {
1093 TRACE("Decoding type");
1095 if (request
->type
!= NBD_CMD_WRITE
) {
1096 /* No payload, we are ready to read the next request. */
1097 req
->complete
= true;
1100 if (request
->type
== NBD_CMD_DISC
) {
1101 /* Special case: we're going to disconnect without a reply,
1102 * whether or not flags, from, or len are bogus */
1103 TRACE("Request type is DISCONNECT");
1108 /* Check for sanity in the parameters, part 1. Defer as many
1109 * checks as possible until after reading any NBD_CMD_WRITE
1110 * payload, so we can try and keep the connection alive. */
1111 if ((request
->from
+ request
->len
) < request
->from
) {
1112 LOG("integer overflow detected, you're probably being attacked");
1117 if (request
->type
== NBD_CMD_READ
|| request
->type
== NBD_CMD_WRITE
) {
1118 if (request
->len
> NBD_MAX_BUFFER_SIZE
) {
1119 LOG("len (%" PRIu32
" ) is larger than max len (%u)",
1120 request
->len
, NBD_MAX_BUFFER_SIZE
);
1125 req
->data
= blk_try_blockalign(client
->exp
->blk
, request
->len
);
1126 if (req
->data
== NULL
) {
1131 if (request
->type
== NBD_CMD_WRITE
) {
1132 TRACE("Reading %" PRIu32
" byte(s)", request
->len
);
1134 if (read_sync(client
->ioc
, req
->data
, request
->len
) != request
->len
) {
1135 LOG("reading from socket failed");
1139 req
->complete
= true;
1142 /* Sanity checks, part 2. */
1143 if (request
->from
+ request
->len
> client
->exp
->size
) {
1144 LOG("operation past EOF; From: %" PRIu64
", Len: %" PRIu32
1145 ", Size: %" PRIu64
, request
->from
, request
->len
,
1146 (uint64_t)client
->exp
->size
);
1147 rc
= request
->type
== NBD_CMD_WRITE
? -ENOSPC
: -EINVAL
;
1150 if (request
->flags
& ~(NBD_CMD_FLAG_FUA
| NBD_CMD_FLAG_NO_HOLE
)) {
1151 LOG("unsupported flags (got 0x%x)", request
->flags
);
1155 if (request
->type
!= NBD_CMD_WRITE_ZEROES
&&
1156 (request
->flags
& NBD_CMD_FLAG_NO_HOLE
)) {
1157 LOG("unexpected flags (got 0x%x)", request
->flags
);
1165 client
->recv_coroutine
= NULL
;
1166 nbd_update_can_read(client
);
1171 static void nbd_trip(void *opaque
)
1173 NBDClient
*client
= opaque
;
1174 NBDExport
*exp
= client
->exp
;
1175 NBDRequestData
*req
;
1181 TRACE("Reading request.");
1182 if (client
->closing
) {
1186 req
= nbd_request_get(client
);
1187 ret
= nbd_co_receive_request(req
, &request
);
1188 if (ret
== -EAGAIN
) {
1195 reply
.handle
= request
.handle
;
1203 if (client
->closing
) {
1205 * The client may be closed when we are blocked in
1206 * nbd_co_receive_request()
1211 switch (request
.type
) {
1213 TRACE("Request type is READ");
1215 /* XXX: NBD Protocol only documents use of FUA with WRITE */
1216 if (request
.flags
& NBD_CMD_FLAG_FUA
) {
1217 ret
= blk_co_flush(exp
->blk
);
1219 LOG("flush failed");
1225 ret
= blk_pread(exp
->blk
, request
.from
+ exp
->dev_offset
,
1226 req
->data
, request
.len
);
1228 LOG("reading from file failed");
1233 TRACE("Read %" PRIu32
" byte(s)", request
.len
);
1234 if (nbd_co_send_reply(req
, &reply
, request
.len
) < 0)
1238 TRACE("Request type is WRITE");
1240 if (exp
->nbdflags
& NBD_FLAG_READ_ONLY
) {
1241 TRACE("Server is read-only, return error");
1242 reply
.error
= EROFS
;
1246 TRACE("Writing to device");
1249 if (request
.flags
& NBD_CMD_FLAG_FUA
) {
1250 flags
|= BDRV_REQ_FUA
;
1252 ret
= blk_pwrite(exp
->blk
, request
.from
+ exp
->dev_offset
,
1253 req
->data
, request
.len
, flags
);
1255 LOG("writing to file failed");
1260 if (nbd_co_send_reply(req
, &reply
, 0) < 0) {
1265 case NBD_CMD_WRITE_ZEROES
:
1266 TRACE("Request type is WRITE_ZEROES");
1268 if (exp
->nbdflags
& NBD_FLAG_READ_ONLY
) {
1269 TRACE("Server is read-only, return error");
1270 reply
.error
= EROFS
;
1274 TRACE("Writing to device");
1277 if (request
.flags
& NBD_CMD_FLAG_FUA
) {
1278 flags
|= BDRV_REQ_FUA
;
1280 if (!(request
.flags
& NBD_CMD_FLAG_NO_HOLE
)) {
1281 flags
|= BDRV_REQ_MAY_UNMAP
;
1283 ret
= blk_pwrite_zeroes(exp
->blk
, request
.from
+ exp
->dev_offset
,
1284 request
.len
, flags
);
1286 LOG("writing to file failed");
1291 if (nbd_co_send_reply(req
, &reply
, 0) < 0) {
1297 /* unreachable, thanks to special case in nbd_co_receive_request() */
1301 TRACE("Request type is FLUSH");
1303 ret
= blk_co_flush(exp
->blk
);
1305 LOG("flush failed");
1308 if (nbd_co_send_reply(req
, &reply
, 0) < 0) {
1313 TRACE("Request type is TRIM");
1314 ret
= blk_co_pdiscard(exp
->blk
, request
.from
+ exp
->dev_offset
,
1317 LOG("discard failed");
1320 if (nbd_co_send_reply(req
, &reply
, 0) < 0) {
1325 LOG("invalid request type (%" PRIu32
") received", request
.type
);
1326 reply
.error
= EINVAL
;
1328 /* We must disconnect after NBD_CMD_WRITE if we did not
1331 if (nbd_co_send_reply(req
, &reply
, 0) < 0 || !req
->complete
) {
1337 TRACE("Request/Reply complete");
1340 nbd_request_put(req
);
1344 nbd_request_put(req
);
1345 client_close(client
);
1348 static void nbd_read(void *opaque
)
1350 NBDClient
*client
= opaque
;
1352 if (client
->recv_coroutine
) {
1353 qemu_coroutine_enter(client
->recv_coroutine
);
1355 qemu_coroutine_enter(qemu_coroutine_create(nbd_trip
, client
));
1359 static void nbd_restart_write(void *opaque
)
1361 NBDClient
*client
= opaque
;
1363 qemu_coroutine_enter(client
->send_coroutine
);
1366 static void nbd_set_handlers(NBDClient
*client
)
1368 if (client
->exp
&& client
->exp
->ctx
) {
1369 aio_set_fd_handler(client
->exp
->ctx
, client
->sioc
->fd
,
1371 client
->can_read
? nbd_read
: NULL
,
1372 client
->send_coroutine
? nbd_restart_write
: NULL
,
1377 static void nbd_unset_handlers(NBDClient
*client
)
1379 if (client
->exp
&& client
->exp
->ctx
) {
1380 aio_set_fd_handler(client
->exp
->ctx
, client
->sioc
->fd
,
1381 true, NULL
, NULL
, NULL
);
1385 static void nbd_update_can_read(NBDClient
*client
)
1387 bool can_read
= client
->recv_coroutine
||
1388 client
->nb_requests
< MAX_NBD_REQUESTS
;
1390 if (can_read
!= client
->can_read
) {
1391 client
->can_read
= can_read
;
1392 nbd_set_handlers(client
);
1394 /* There is no need to invoke aio_notify(), since aio_set_fd_handler()
1395 * in nbd_set_handlers() will have taken care of that */
1399 static coroutine_fn
void nbd_co_client_start(void *opaque
)
1401 NBDClientNewData
*data
= opaque
;
1402 NBDClient
*client
= data
->client
;
1403 NBDExport
*exp
= client
->exp
;
1406 nbd_export_get(exp
);
1408 if (nbd_negotiate(data
)) {
1409 client_close(client
);
1412 qemu_co_mutex_init(&client
->send_lock
);
1413 nbd_set_handlers(client
);
1416 QTAILQ_INSERT_TAIL(&exp
->clients
, client
, next
);
1422 void nbd_client_new(NBDExport
*exp
,
1423 QIOChannelSocket
*sioc
,
1424 QCryptoTLSCreds
*tlscreds
,
1425 const char *tlsaclname
,
1426 void (*close_fn
)(NBDClient
*))
1429 NBDClientNewData
*data
= g_new(NBDClientNewData
, 1);
1431 client
= g_malloc0(sizeof(NBDClient
));
1432 client
->refcount
= 1;
1434 client
->tlscreds
= tlscreds
;
1436 object_ref(OBJECT(client
->tlscreds
));
1438 client
->tlsaclname
= g_strdup(tlsaclname
);
1439 client
->sioc
= sioc
;
1440 object_ref(OBJECT(client
->sioc
));
1441 client
->ioc
= QIO_CHANNEL(sioc
);
1442 object_ref(OBJECT(client
->ioc
));
1443 client
->can_read
= true;
1444 client
->close
= close_fn
;
1446 data
->client
= client
;
1447 data
->co
= qemu_coroutine_create(nbd_co_client_start
, data
);
1448 qemu_coroutine_enter(data
->co
);