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_fn
)(NBDClient
*client
, bool negotiated
);
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 /* Basic flow for negotiation
134 /* Send a reply header, including length, but no payload.
135 * Return -errno on error, 0 on success. */
136 static int nbd_negotiate_send_rep_len(QIOChannel
*ioc
, uint32_t type
,
137 uint32_t opt
, uint32_t len
, Error
**errp
)
141 TRACE("Reply opt=%" PRIx32
" type=%" PRIx32
" len=%" PRIu32
,
144 magic
= cpu_to_be64(NBD_REP_MAGIC
);
145 if (nbd_write(ioc
, &magic
, sizeof(magic
), errp
) < 0) {
146 error_prepend(errp
, "write failed (rep magic): ");
150 opt
= cpu_to_be32(opt
);
151 if (nbd_write(ioc
, &opt
, sizeof(opt
), errp
) < 0) {
152 error_prepend(errp
, "write failed (rep opt): ");
156 type
= cpu_to_be32(type
);
157 if (nbd_write(ioc
, &type
, sizeof(type
), errp
) < 0) {
158 error_prepend(errp
, "write failed (rep type): ");
162 len
= cpu_to_be32(len
);
163 if (nbd_write(ioc
, &len
, sizeof(len
), errp
) < 0) {
164 error_prepend(errp
, "write failed (rep data length): ");
170 /* Send a reply header with default 0 length.
171 * Return -errno on error, 0 on success. */
172 static int nbd_negotiate_send_rep(QIOChannel
*ioc
, uint32_t type
, uint32_t opt
,
175 return nbd_negotiate_send_rep_len(ioc
, type
, opt
, 0, errp
);
178 /* Send an error reply.
179 * Return -errno on error, 0 on success. */
180 static int GCC_FMT_ATTR(5, 6)
181 nbd_negotiate_send_rep_err(QIOChannel
*ioc
, uint32_t type
,
182 uint32_t opt
, Error
**errp
, const char *fmt
, ...)
190 msg
= g_strdup_vprintf(fmt
, va
);
194 TRACE("sending error message \"%s\"", msg
);
195 ret
= nbd_negotiate_send_rep_len(ioc
, type
, opt
, len
, errp
);
199 if (nbd_write(ioc
, msg
, len
, errp
) < 0) {
200 error_prepend(errp
, "write failed (error message): ");
211 /* Send a single NBD_REP_SERVER reply to NBD_OPT_LIST, including payload.
212 * Return -errno on error, 0 on success. */
213 static int nbd_negotiate_send_rep_list(QIOChannel
*ioc
, NBDExport
*exp
,
216 size_t name_len
, desc_len
;
218 const char *name
= exp
->name
? exp
->name
: "";
219 const char *desc
= exp
->description
? exp
->description
: "";
222 TRACE("Advertising export name '%s' description '%s'", name
, desc
);
223 name_len
= strlen(name
);
224 desc_len
= strlen(desc
);
225 len
= name_len
+ desc_len
+ sizeof(len
);
226 ret
= nbd_negotiate_send_rep_len(ioc
, NBD_REP_SERVER
, NBD_OPT_LIST
, len
,
232 len
= cpu_to_be32(name_len
);
233 if (nbd_write(ioc
, &len
, sizeof(len
), errp
) < 0) {
234 error_prepend(errp
, "write failed (name length): ");
238 if (nbd_write(ioc
, name
, name_len
, errp
) < 0) {
239 error_prepend(errp
, "write failed (name buffer): ");
243 if (nbd_write(ioc
, desc
, desc_len
, errp
) < 0) {
244 error_prepend(errp
, "write failed (description buffer): ");
251 /* Process the NBD_OPT_LIST command, with a potential series of replies.
252 * Return -errno on error, 0 on success. */
253 static int nbd_negotiate_handle_list(NBDClient
*client
, uint32_t length
,
259 if (nbd_drop(client
->ioc
, length
, errp
) < 0) {
262 return nbd_negotiate_send_rep_err(client
->ioc
,
263 NBD_REP_ERR_INVALID
, NBD_OPT_LIST
,
265 "OPT_LIST should not have length");
268 /* For each export, send a NBD_REP_SERVER reply. */
269 QTAILQ_FOREACH(exp
, &exports
, next
) {
270 if (nbd_negotiate_send_rep_list(client
->ioc
, exp
, errp
)) {
274 /* Finish with a NBD_REP_ACK. */
275 return nbd_negotiate_send_rep(client
->ioc
, NBD_REP_ACK
, NBD_OPT_LIST
, errp
);
278 static int nbd_negotiate_handle_export_name(NBDClient
*client
, uint32_t length
,
281 char name
[NBD_MAX_NAME_SIZE
+ 1];
284 [20 .. xx] export name (length bytes)
286 TRACE("Checking length");
287 if (length
>= sizeof(name
)) {
288 error_setg(errp
, "Bad length received");
291 if (nbd_read(client
->ioc
, name
, length
, errp
) < 0) {
292 error_prepend(errp
, "read failed: ");
297 TRACE("Client requested export '%s'", name
);
299 client
->exp
= nbd_export_find(name
);
301 error_setg(errp
, "export not found");
305 QTAILQ_INSERT_TAIL(&client
->exp
->clients
, client
, next
);
306 nbd_export_get(client
->exp
);
311 /* Handle NBD_OPT_STARTTLS. Return NULL to drop connection, or else the
312 * new channel for all further (now-encrypted) communication. */
313 static QIOChannel
*nbd_negotiate_handle_starttls(NBDClient
*client
,
319 struct NBDTLSHandshakeData data
= { 0 };
321 TRACE("Setting up TLS");
324 if (nbd_drop(ioc
, length
, errp
) < 0) {
327 nbd_negotiate_send_rep_err(ioc
, NBD_REP_ERR_INVALID
, NBD_OPT_STARTTLS
,
329 "OPT_STARTTLS should not have length");
333 if (nbd_negotiate_send_rep(client
->ioc
, NBD_REP_ACK
,
334 NBD_OPT_STARTTLS
, errp
) < 0) {
338 tioc
= qio_channel_tls_new_server(ioc
,
346 qio_channel_set_name(QIO_CHANNEL(tioc
), "nbd-server-tls");
347 TRACE("Starting TLS handshake");
348 data
.loop
= g_main_loop_new(g_main_context_default(), FALSE
);
349 qio_channel_tls_handshake(tioc
,
354 if (!data
.complete
) {
355 g_main_loop_run(data
.loop
);
357 g_main_loop_unref(data
.loop
);
359 object_unref(OBJECT(tioc
));
360 error_propagate(errp
, data
.error
);
364 return QIO_CHANNEL(tioc
);
367 /* nbd_negotiate_options
368 * Process all NBD_OPT_* client option commands.
370 * -errno on error, errp is set
371 * 0 on successful negotiation, errp is not set
372 * 1 if client sent NBD_OPT_ABORT, i.e. on valid disconnect,
375 static int nbd_negotiate_options(NBDClient
*client
, Error
**errp
)
378 bool fixedNewstyle
= false;
379 Error
*local_err
= NULL
;
382 [ 0 .. 3] client flags
384 [ 0 .. 7] NBD_OPTS_MAGIC
385 [ 8 .. 11] NBD option
386 [12 .. 15] Data length
389 [ 0 .. 7] NBD_OPTS_MAGIC
390 [ 8 .. 11] Second NBD option
391 [12 .. 15] Data length
395 if (nbd_read(client
->ioc
, &flags
, sizeof(flags
), errp
) < 0) {
396 error_prepend(errp
, "read failed: ");
399 TRACE("Checking client flags");
400 be32_to_cpus(&flags
);
401 if (flags
& NBD_FLAG_C_FIXED_NEWSTYLE
) {
402 TRACE("Client supports fixed newstyle handshake");
403 fixedNewstyle
= true;
404 flags
&= ~NBD_FLAG_C_FIXED_NEWSTYLE
;
406 if (flags
& NBD_FLAG_C_NO_ZEROES
) {
407 TRACE("Client supports no zeroes at handshake end");
408 client
->no_zeroes
= true;
409 flags
&= ~NBD_FLAG_C_NO_ZEROES
;
412 error_setg(errp
, "Unknown client flags 0x%" PRIx32
" received", flags
);
418 uint32_t clientflags
, length
;
421 if (nbd_read(client
->ioc
, &magic
, sizeof(magic
), errp
) < 0) {
422 error_prepend(errp
, "read failed: ");
425 TRACE("Checking opts magic");
426 if (magic
!= be64_to_cpu(NBD_OPTS_MAGIC
)) {
427 error_setg(errp
, "Bad magic received");
431 if (nbd_read(client
->ioc
, &clientflags
,
432 sizeof(clientflags
), errp
) < 0) {
433 error_prepend(errp
, "read failed: ");
436 clientflags
= be32_to_cpu(clientflags
);
438 if (nbd_read(client
->ioc
, &length
, sizeof(length
), errp
) < 0) {
439 error_prepend(errp
, "read failed: ");
442 length
= be32_to_cpu(length
);
444 TRACE("Checking option 0x%" PRIx32
, clientflags
);
445 if (client
->tlscreds
&&
446 client
->ioc
== (QIOChannel
*)client
->sioc
) {
448 if (!fixedNewstyle
) {
449 error_setg(errp
, "Unsupported option 0x%" PRIx32
, clientflags
);
452 switch (clientflags
) {
453 case NBD_OPT_STARTTLS
:
454 tioc
= nbd_negotiate_handle_starttls(client
, length
, errp
);
458 object_unref(OBJECT(client
->ioc
));
459 client
->ioc
= QIO_CHANNEL(tioc
);
462 case NBD_OPT_EXPORT_NAME
:
463 /* No way to return an error to client, so drop connection */
464 error_setg(errp
, "Option 0x%x not permitted before TLS",
469 if (nbd_drop(client
->ioc
, length
, errp
) < 0) {
472 ret
= nbd_negotiate_send_rep_err(client
->ioc
,
473 NBD_REP_ERR_TLS_REQD
,
476 "not permitted before TLS",
481 /* Let the client keep trying, unless they asked to quit */
482 if (clientflags
== NBD_OPT_ABORT
) {
487 } else if (fixedNewstyle
) {
488 switch (clientflags
) {
490 ret
= nbd_negotiate_handle_list(client
, length
, errp
);
497 /* NBD spec says we must try to reply before
498 * disconnecting, but that we must also tolerate
499 * guests that don't wait for our reply. */
500 nbd_negotiate_send_rep(client
->ioc
, NBD_REP_ACK
, clientflags
,
503 if (local_err
!= NULL
) {
504 TRACE("Reply to NBD_OPT_ABORT request failed: %s",
505 error_get_pretty(local_err
));
506 error_free(local_err
);
511 case NBD_OPT_EXPORT_NAME
:
512 return nbd_negotiate_handle_export_name(client
, length
, errp
);
514 case NBD_OPT_STARTTLS
:
515 if (nbd_drop(client
->ioc
, length
, errp
) < 0) {
518 if (client
->tlscreds
) {
519 ret
= nbd_negotiate_send_rep_err(client
->ioc
,
522 "TLS already enabled");
524 ret
= nbd_negotiate_send_rep_err(client
->ioc
,
527 "TLS not configured");
534 if (nbd_drop(client
->ioc
, length
, errp
) < 0) {
537 ret
= nbd_negotiate_send_rep_err(client
->ioc
,
540 "Unsupported option 0x%"
550 * If broken new-style we should drop the connection
551 * for anything except NBD_OPT_EXPORT_NAME
553 switch (clientflags
) {
554 case NBD_OPT_EXPORT_NAME
:
555 return nbd_negotiate_handle_export_name(client
, length
, errp
);
558 error_setg(errp
, "Unsupported option 0x%" PRIx32
, clientflags
);
567 * -errno on error, errp is set
568 * 0 on successful negotiation, errp is not set
569 * 1 if client sent NBD_OPT_ABORT, i.e. on valid disconnect,
572 static coroutine_fn
int nbd_negotiate(NBDClient
*client
, Error
**errp
)
574 char buf
[8 + 8 + 8 + 128];
576 const uint16_t myflags
= (NBD_FLAG_HAS_FLAGS
| NBD_FLAG_SEND_TRIM
|
577 NBD_FLAG_SEND_FLUSH
| NBD_FLAG_SEND_FUA
|
578 NBD_FLAG_SEND_WRITE_ZEROES
);
582 /* Old style negotiation header without options
583 [ 0 .. 7] passwd ("NBDMAGIC")
584 [ 8 .. 15] magic (NBD_CLIENT_MAGIC)
586 [24 .. 25] server flags (0)
587 [26 .. 27] export flags
588 [28 .. 151] reserved (0)
590 New style negotiation header with options
591 [ 0 .. 7] passwd ("NBDMAGIC")
592 [ 8 .. 15] magic (NBD_OPTS_MAGIC)
593 [16 .. 17] server flags (0)
596 [26 .. 27] export flags
597 [28 .. 151] reserved (0, omit if no_zeroes)
600 qio_channel_set_blocking(client
->ioc
, false, NULL
);
602 TRACE("Beginning negotiation.");
603 memset(buf
, 0, sizeof(buf
));
604 memcpy(buf
, "NBDMAGIC", 8);
606 oldStyle
= client
->exp
!= NULL
&& !client
->tlscreds
;
608 TRACE("advertising size %" PRIu64
" and flags %x",
609 client
->exp
->size
, client
->exp
->nbdflags
| myflags
);
610 stq_be_p(buf
+ 8, NBD_CLIENT_MAGIC
);
611 stq_be_p(buf
+ 16, client
->exp
->size
);
612 stw_be_p(buf
+ 26, client
->exp
->nbdflags
| myflags
);
614 if (nbd_write(client
->ioc
, buf
, sizeof(buf
), errp
) < 0) {
615 error_prepend(errp
, "write failed: ");
619 stq_be_p(buf
+ 8, NBD_OPTS_MAGIC
);
620 stw_be_p(buf
+ 16, NBD_FLAG_FIXED_NEWSTYLE
| NBD_FLAG_NO_ZEROES
);
622 if (nbd_write(client
->ioc
, buf
, 18, errp
) < 0) {
623 error_prepend(errp
, "write failed: ");
626 ret
= nbd_negotiate_options(client
, errp
);
629 error_prepend(errp
, "option negotiation failed: ");
634 TRACE("advertising size %" PRIu64
" and flags %x",
635 client
->exp
->size
, client
->exp
->nbdflags
| myflags
);
636 stq_be_p(buf
+ 18, client
->exp
->size
);
637 stw_be_p(buf
+ 26, client
->exp
->nbdflags
| myflags
);
638 len
= client
->no_zeroes
? 10 : sizeof(buf
) - 18;
639 ret
= nbd_write(client
->ioc
, buf
+ 18, len
, errp
);
641 error_prepend(errp
, "write failed: ");
646 TRACE("Negotiation succeeded.");
651 static int nbd_receive_request(QIOChannel
*ioc
, NBDRequest
*request
,
654 uint8_t buf
[NBD_REQUEST_SIZE
];
658 ret
= nbd_read(ioc
, buf
, sizeof(buf
), errp
);
664 [ 0 .. 3] magic (NBD_REQUEST_MAGIC)
665 [ 4 .. 5] flags (NBD_CMD_FLAG_FUA, ...)
666 [ 6 .. 7] type (NBD_CMD_READ, ...)
672 magic
= ldl_be_p(buf
);
673 request
->flags
= lduw_be_p(buf
+ 4);
674 request
->type
= lduw_be_p(buf
+ 6);
675 request
->handle
= ldq_be_p(buf
+ 8);
676 request
->from
= ldq_be_p(buf
+ 16);
677 request
->len
= ldl_be_p(buf
+ 24);
679 TRACE("Got request: { magic = 0x%" PRIx32
", .flags = %" PRIx16
680 ", .type = %" PRIx16
", from = %" PRIu64
", len = %" PRIu32
" }",
681 magic
, request
->flags
, request
->type
, request
->from
, request
->len
);
683 if (magic
!= NBD_REQUEST_MAGIC
) {
684 error_setg(errp
, "invalid magic (got 0x%" PRIx32
")", magic
);
690 static int nbd_send_reply(QIOChannel
*ioc
, NBDReply
*reply
, Error
**errp
)
692 uint8_t buf
[NBD_REPLY_SIZE
];
694 reply
->error
= system_errno_to_nbd_errno(reply
->error
);
696 TRACE("Sending response to client: { .error = %" PRId32
697 ", handle = %" PRIu64
" }",
698 reply
->error
, reply
->handle
);
701 [ 0 .. 3] magic (NBD_REPLY_MAGIC)
702 [ 4 .. 7] error (0 == no error)
705 stl_be_p(buf
, NBD_REPLY_MAGIC
);
706 stl_be_p(buf
+ 4, reply
->error
);
707 stq_be_p(buf
+ 8, reply
->handle
);
709 return nbd_write(ioc
, buf
, sizeof(buf
), errp
);
712 #define MAX_NBD_REQUESTS 16
714 void nbd_client_get(NBDClient
*client
)
719 void nbd_client_put(NBDClient
*client
)
721 if (--client
->refcount
== 0) {
722 /* The last reference should be dropped by client->close,
723 * which is called by client_close.
725 assert(client
->closing
);
727 qio_channel_detach_aio_context(client
->ioc
);
728 object_unref(OBJECT(client
->sioc
));
729 object_unref(OBJECT(client
->ioc
));
730 if (client
->tlscreds
) {
731 object_unref(OBJECT(client
->tlscreds
));
733 g_free(client
->tlsaclname
);
735 QTAILQ_REMOVE(&client
->exp
->clients
, client
, next
);
736 nbd_export_put(client
->exp
);
742 static void client_close(NBDClient
*client
, bool negotiated
)
744 if (client
->closing
) {
748 client
->closing
= true;
750 /* Force requests to finish. They will drop their own references,
751 * then we'll close the socket and free the NBDClient.
753 qio_channel_shutdown(client
->ioc
, QIO_CHANNEL_SHUTDOWN_BOTH
,
756 /* Also tell the client, so that they release their reference. */
757 if (client
->close_fn
) {
758 client
->close_fn(client
, negotiated
);
762 static NBDRequestData
*nbd_request_get(NBDClient
*client
)
766 assert(client
->nb_requests
<= MAX_NBD_REQUESTS
- 1);
767 client
->nb_requests
++;
769 req
= g_new0(NBDRequestData
, 1);
770 nbd_client_get(client
);
771 req
->client
= client
;
775 static void nbd_request_put(NBDRequestData
*req
)
777 NBDClient
*client
= req
->client
;
780 qemu_vfree(req
->data
);
784 client
->nb_requests
--;
785 nbd_client_receive_next_request(client
);
787 nbd_client_put(client
);
790 static void blk_aio_attached(AioContext
*ctx
, void *opaque
)
792 NBDExport
*exp
= opaque
;
795 TRACE("Export %s: Attaching clients to AIO context %p\n", exp
->name
, ctx
);
799 QTAILQ_FOREACH(client
, &exp
->clients
, next
) {
800 qio_channel_attach_aio_context(client
->ioc
, ctx
);
801 if (client
->recv_coroutine
) {
802 aio_co_schedule(ctx
, client
->recv_coroutine
);
804 if (client
->send_coroutine
) {
805 aio_co_schedule(ctx
, client
->send_coroutine
);
810 static void blk_aio_detach(void *opaque
)
812 NBDExport
*exp
= opaque
;
815 TRACE("Export %s: Detaching clients from AIO context %p\n", exp
->name
, exp
->ctx
);
817 QTAILQ_FOREACH(client
, &exp
->clients
, next
) {
818 qio_channel_detach_aio_context(client
->ioc
);
824 static void nbd_eject_notifier(Notifier
*n
, void *data
)
826 NBDExport
*exp
= container_of(n
, NBDExport
, eject_notifier
);
827 nbd_export_close(exp
);
830 NBDExport
*nbd_export_new(BlockDriverState
*bs
, off_t dev_offset
, off_t size
,
831 uint16_t nbdflags
, void (*close
)(NBDExport
*),
832 bool writethrough
, BlockBackend
*on_eject_blk
,
836 NBDExport
*exp
= g_malloc0(sizeof(NBDExport
));
840 /* Don't allow resize while the NBD server is running, otherwise we don't
841 * care what happens with the node. */
842 perm
= BLK_PERM_CONSISTENT_READ
;
843 if ((nbdflags
& NBD_FLAG_READ_ONLY
) == 0) {
844 perm
|= BLK_PERM_WRITE
;
846 blk
= blk_new(perm
, BLK_PERM_CONSISTENT_READ
| BLK_PERM_WRITE_UNCHANGED
|
847 BLK_PERM_WRITE
| BLK_PERM_GRAPH_MOD
);
848 ret
= blk_insert_bs(blk
, bs
, errp
);
852 blk_set_enable_write_cache(blk
, !writethrough
);
855 QTAILQ_INIT(&exp
->clients
);
857 exp
->dev_offset
= dev_offset
;
858 exp
->nbdflags
= nbdflags
;
859 exp
->size
= size
< 0 ? blk_getlength(blk
) : size
;
861 error_setg_errno(errp
, -exp
->size
,
862 "Failed to determine the NBD export's length");
865 exp
->size
-= exp
->size
% BDRV_SECTOR_SIZE
;
868 exp
->ctx
= blk_get_aio_context(blk
);
869 blk_add_aio_context_notifier(blk
, blk_aio_attached
, blk_aio_detach
, exp
);
872 blk_ref(on_eject_blk
);
873 exp
->eject_notifier_blk
= on_eject_blk
;
874 exp
->eject_notifier
.notify
= nbd_eject_notifier
;
875 blk_add_remove_bs_notifier(on_eject_blk
, &exp
->eject_notifier
);
879 * NBD exports are used for non-shared storage migration. Make sure
880 * that BDRV_O_INACTIVE is cleared and the image is ready for write
881 * access since the export could be available before migration handover.
883 aio_context_acquire(exp
->ctx
);
884 blk_invalidate_cache(blk
, NULL
);
885 aio_context_release(exp
->ctx
);
894 NBDExport
*nbd_export_find(const char *name
)
897 QTAILQ_FOREACH(exp
, &exports
, next
) {
898 if (strcmp(name
, exp
->name
) == 0) {
906 void nbd_export_set_name(NBDExport
*exp
, const char *name
)
908 if (exp
->name
== name
) {
913 if (exp
->name
!= NULL
) {
916 QTAILQ_REMOVE(&exports
, exp
, next
);
921 exp
->name
= g_strdup(name
);
922 QTAILQ_INSERT_TAIL(&exports
, exp
, next
);
927 void nbd_export_set_description(NBDExport
*exp
, const char *description
)
929 g_free(exp
->description
);
930 exp
->description
= g_strdup(description
);
933 void nbd_export_close(NBDExport
*exp
)
935 NBDClient
*client
, *next
;
938 QTAILQ_FOREACH_SAFE(client
, &exp
->clients
, next
, next
) {
939 client_close(client
, true);
941 nbd_export_set_name(exp
, NULL
);
942 nbd_export_set_description(exp
, NULL
);
946 void nbd_export_get(NBDExport
*exp
)
948 assert(exp
->refcount
> 0);
952 void nbd_export_put(NBDExport
*exp
)
954 assert(exp
->refcount
> 0);
955 if (exp
->refcount
== 1) {
956 nbd_export_close(exp
);
959 if (--exp
->refcount
== 0) {
960 assert(exp
->name
== NULL
);
961 assert(exp
->description
== NULL
);
968 if (exp
->eject_notifier_blk
) {
969 notifier_remove(&exp
->eject_notifier
);
970 blk_unref(exp
->eject_notifier_blk
);
972 blk_remove_aio_context_notifier(exp
->blk
, blk_aio_attached
,
973 blk_aio_detach
, exp
);
982 BlockBackend
*nbd_export_get_blockdev(NBDExport
*exp
)
987 void nbd_export_close_all(void)
989 NBDExport
*exp
, *next
;
991 QTAILQ_FOREACH_SAFE(exp
, &exports
, next
, next
) {
992 nbd_export_close(exp
);
996 static int nbd_co_send_reply(NBDRequestData
*req
, NBDReply
*reply
, int len
,
999 NBDClient
*client
= req
->client
;
1002 g_assert(qemu_in_coroutine());
1003 qemu_co_mutex_lock(&client
->send_lock
);
1004 client
->send_coroutine
= qemu_coroutine_self();
1007 ret
= nbd_send_reply(client
->ioc
, reply
, errp
);
1009 qio_channel_set_cork(client
->ioc
, true);
1010 ret
= nbd_send_reply(client
->ioc
, reply
, errp
);
1012 ret
= nbd_write(client
->ioc
, req
->data
, len
, errp
);
1017 qio_channel_set_cork(client
->ioc
, false);
1020 client
->send_coroutine
= NULL
;
1021 qemu_co_mutex_unlock(&client
->send_lock
);
1025 /* nbd_co_receive_request
1026 * Collect a client request. Return 0 if request looks valid, -EIO to drop
1027 * connection right away, and any other negative value to report an error to
1028 * the client (although the caller may still need to disconnect after reporting
1031 static int nbd_co_receive_request(NBDRequestData
*req
, NBDRequest
*request
,
1034 NBDClient
*client
= req
->client
;
1036 g_assert(qemu_in_coroutine());
1037 assert(client
->recv_coroutine
== qemu_coroutine_self());
1038 if (nbd_receive_request(client
->ioc
, request
, errp
) < 0) {
1042 TRACE("Decoding type");
1044 if (request
->type
!= NBD_CMD_WRITE
) {
1045 /* No payload, we are ready to read the next request. */
1046 req
->complete
= true;
1049 if (request
->type
== NBD_CMD_DISC
) {
1050 /* Special case: we're going to disconnect without a reply,
1051 * whether or not flags, from, or len are bogus */
1052 TRACE("Request type is DISCONNECT");
1056 /* Check for sanity in the parameters, part 1. Defer as many
1057 * checks as possible until after reading any NBD_CMD_WRITE
1058 * payload, so we can try and keep the connection alive. */
1059 if ((request
->from
+ request
->len
) < request
->from
) {
1061 "integer overflow detected, you're probably being attacked");
1065 if (request
->type
== NBD_CMD_READ
|| request
->type
== NBD_CMD_WRITE
) {
1066 if (request
->len
> NBD_MAX_BUFFER_SIZE
) {
1067 error_setg(errp
, "len (%" PRIu32
" ) is larger than max len (%u)",
1068 request
->len
, NBD_MAX_BUFFER_SIZE
);
1072 req
->data
= blk_try_blockalign(client
->exp
->blk
, request
->len
);
1073 if (req
->data
== NULL
) {
1074 error_setg(errp
, "No memory");
1078 if (request
->type
== NBD_CMD_WRITE
) {
1079 TRACE("Reading %" PRIu32
" byte(s)", request
->len
);
1081 if (nbd_read(client
->ioc
, req
->data
, request
->len
, errp
) < 0) {
1082 error_prepend(errp
, "reading from socket failed: ");
1085 req
->complete
= true;
1088 /* Sanity checks, part 2. */
1089 if (request
->from
+ request
->len
> client
->exp
->size
) {
1090 error_setg(errp
, "operation past EOF; From: %" PRIu64
", Len: %" PRIu32
1091 ", Size: %" PRIu64
, request
->from
, request
->len
,
1092 (uint64_t)client
->exp
->size
);
1093 return request
->type
== NBD_CMD_WRITE
? -ENOSPC
: -EINVAL
;
1095 if (request
->flags
& ~(NBD_CMD_FLAG_FUA
| NBD_CMD_FLAG_NO_HOLE
)) {
1096 error_setg(errp
, "unsupported flags (got 0x%x)", request
->flags
);
1099 if (request
->type
!= NBD_CMD_WRITE_ZEROES
&&
1100 (request
->flags
& NBD_CMD_FLAG_NO_HOLE
)) {
1101 error_setg(errp
, "unexpected flags (got 0x%x)", request
->flags
);
1108 /* Owns a reference to the NBDClient passed as opaque. */
1109 static coroutine_fn
void nbd_trip(void *opaque
)
1111 NBDClient
*client
= opaque
;
1112 NBDExport
*exp
= client
->exp
;
1113 NBDRequestData
*req
;
1114 NBDRequest request
= { 0 }; /* GCC thinks it can be used uninitialized */
1118 int reply_data_len
= 0;
1119 Error
*local_err
= NULL
;
1121 TRACE("Reading request.");
1122 if (client
->closing
) {
1123 nbd_client_put(client
);
1127 req
= nbd_request_get(client
);
1128 ret
= nbd_co_receive_request(req
, &request
, &local_err
);
1129 client
->recv_coroutine
= NULL
;
1130 nbd_client_receive_next_request(client
);
1135 reply
.handle
= request
.handle
;
1143 if (client
->closing
) {
1145 * The client may be closed when we are blocked in
1146 * nbd_co_receive_request()
1151 switch (request
.type
) {
1153 TRACE("Request type is READ");
1155 /* XXX: NBD Protocol only documents use of FUA with WRITE */
1156 if (request
.flags
& NBD_CMD_FLAG_FUA
) {
1157 ret
= blk_co_flush(exp
->blk
);
1159 error_setg_errno(&local_err
, -ret
, "flush failed");
1165 ret
= blk_pread(exp
->blk
, request
.from
+ exp
->dev_offset
,
1166 req
->data
, request
.len
);
1168 error_setg_errno(&local_err
, -ret
, "reading from file failed");
1173 reply_data_len
= request
.len
;
1174 TRACE("Read %" PRIu32
" byte(s)", request
.len
);
1178 TRACE("Request type is WRITE");
1180 if (exp
->nbdflags
& NBD_FLAG_READ_ONLY
) {
1181 TRACE("Server is read-only, return error");
1182 reply
.error
= EROFS
;
1186 TRACE("Writing to device");
1189 if (request
.flags
& NBD_CMD_FLAG_FUA
) {
1190 flags
|= BDRV_REQ_FUA
;
1192 ret
= blk_pwrite(exp
->blk
, request
.from
+ exp
->dev_offset
,
1193 req
->data
, request
.len
, flags
);
1195 error_setg_errno(&local_err
, -ret
, "writing to file failed");
1200 case NBD_CMD_WRITE_ZEROES
:
1201 TRACE("Request type is WRITE_ZEROES");
1203 if (exp
->nbdflags
& NBD_FLAG_READ_ONLY
) {
1204 error_setg(&local_err
, "Server is read-only, return error");
1205 reply
.error
= EROFS
;
1209 TRACE("Writing to device");
1212 if (request
.flags
& NBD_CMD_FLAG_FUA
) {
1213 flags
|= BDRV_REQ_FUA
;
1215 if (!(request
.flags
& NBD_CMD_FLAG_NO_HOLE
)) {
1216 flags
|= BDRV_REQ_MAY_UNMAP
;
1218 ret
= blk_pwrite_zeroes(exp
->blk
, request
.from
+ exp
->dev_offset
,
1219 request
.len
, flags
);
1221 error_setg_errno(&local_err
, -ret
, "writing to file failed");
1227 /* unreachable, thanks to special case in nbd_co_receive_request() */
1231 TRACE("Request type is FLUSH");
1233 ret
= blk_co_flush(exp
->blk
);
1235 error_setg_errno(&local_err
, -ret
, "flush failed");
1241 TRACE("Request type is TRIM");
1242 ret
= blk_co_pdiscard(exp
->blk
, request
.from
+ exp
->dev_offset
,
1245 error_setg_errno(&local_err
, -ret
, "discard failed");
1251 error_setg(&local_err
, "invalid request type (%" PRIu32
") received",
1253 reply
.error
= EINVAL
;
1258 /* If we are here local_err is not fatal error, already stored in
1260 error_report_err(local_err
);
1264 if (nbd_co_send_reply(req
, &reply
, reply_data_len
, &local_err
) < 0) {
1265 error_prepend(&local_err
, "Failed to send reply: ");
1269 /* We must disconnect after NBD_CMD_WRITE if we did not
1272 if (!req
->complete
) {
1273 error_setg(&local_err
, "Request handling failed in intermediate state");
1277 TRACE("Request/Reply complete");
1280 nbd_request_put(req
);
1281 nbd_client_put(client
);
1286 error_reportf_err(local_err
, "Disconnect client, due to: ");
1288 nbd_request_put(req
);
1289 client_close(client
, true);
1290 nbd_client_put(client
);
1293 static void nbd_client_receive_next_request(NBDClient
*client
)
1295 if (!client
->recv_coroutine
&& client
->nb_requests
< MAX_NBD_REQUESTS
) {
1296 nbd_client_get(client
);
1297 client
->recv_coroutine
= qemu_coroutine_create(nbd_trip
, client
);
1298 aio_co_schedule(client
->exp
->ctx
, client
->recv_coroutine
);
1302 static coroutine_fn
void nbd_co_client_start(void *opaque
)
1304 NBDClient
*client
= opaque
;
1305 NBDExport
*exp
= client
->exp
;
1306 Error
*local_err
= NULL
;
1309 nbd_export_get(exp
);
1310 QTAILQ_INSERT_TAIL(&exp
->clients
, client
, next
);
1312 qemu_co_mutex_init(&client
->send_lock
);
1314 if (nbd_negotiate(client
, &local_err
)) {
1316 error_report_err(local_err
);
1318 client_close(client
, false);
1322 nbd_client_receive_next_request(client
);
1326 * Create a new client listener on the given export @exp, using the
1327 * given channel @sioc. Begin servicing it in a coroutine. When the
1328 * connection closes, call @close_fn with an indication of whether the
1329 * client completed negotiation.
1331 void nbd_client_new(NBDExport
*exp
,
1332 QIOChannelSocket
*sioc
,
1333 QCryptoTLSCreds
*tlscreds
,
1334 const char *tlsaclname
,
1335 void (*close_fn
)(NBDClient
*, bool))
1340 client
= g_malloc0(sizeof(NBDClient
));
1341 client
->refcount
= 1;
1343 client
->tlscreds
= tlscreds
;
1345 object_ref(OBJECT(client
->tlscreds
));
1347 client
->tlsaclname
= g_strdup(tlsaclname
);
1348 client
->sioc
= sioc
;
1349 object_ref(OBJECT(client
->sioc
));
1350 client
->ioc
= QIO_CHANNEL(sioc
);
1351 object_ref(OBJECT(client
->ioc
));
1352 client
->close_fn
= close_fn
;
1354 co
= qemu_coroutine_create(nbd_co_client_start
, client
);
1355 qemu_coroutine_enter(co
);