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"
22 #include "block/block_int.h"
23 #include "block/export.h"
24 #include "block/dirty-bitmap.h"
25 #include "qapi/error.h"
26 #include "qemu/queue.h"
28 #include "nbd-internal.h"
29 #include "qemu/units.h"
30 #include "qemu/memalign.h"
32 #define NBD_META_ID_BASE_ALLOCATION 0
33 #define NBD_META_ID_ALLOCATION_DEPTH 1
34 /* Dirty bitmaps use 'NBD_META_ID_DIRTY_BITMAP + i', so keep this id last. */
35 #define NBD_META_ID_DIRTY_BITMAP 2
38 * NBD_MAX_BLOCK_STATUS_EXTENTS: 1 MiB of extents data. An empirical
39 * constant. If an increase is needed, note that the NBD protocol
40 * recommends no larger than 32 mb, so that the client won't consider
41 * the reply as a denial of service attack.
43 #define NBD_MAX_BLOCK_STATUS_EXTENTS (1 * MiB / 8)
45 static int system_errno_to_nbd_errno(int err
)
66 #if ENOTSUP != EOPNOTSUPP
78 /* Definitions for opaque data types */
80 typedef struct NBDRequestData NBDRequestData
;
82 struct NBDRequestData
{
95 QTAILQ_HEAD(, NBDClient
) clients
;
96 QTAILQ_ENTRY(NBDExport
) next
;
98 BlockBackend
*eject_notifier_blk
;
99 Notifier eject_notifier
;
101 bool allocation_depth
;
102 BdrvDirtyBitmap
**export_bitmaps
;
103 size_t nr_export_bitmaps
;
106 static QTAILQ_HEAD(, NBDExport
) exports
= QTAILQ_HEAD_INITIALIZER(exports
);
108 /* NBDExportMetaContexts represents a list of contexts to be exported,
109 * as selected by NBD_OPT_SET_META_CONTEXT. Also used for
110 * NBD_OPT_LIST_META_CONTEXT. */
111 typedef struct NBDExportMetaContexts
{
113 size_t count
; /* number of negotiated contexts */
114 bool base_allocation
; /* export base:allocation context (block status) */
115 bool allocation_depth
; /* export qemu:allocation-depth */
117 * export qemu:dirty-bitmap:<export bitmap name>,
118 * sized by exp->nr_export_bitmaps
120 } NBDExportMetaContexts
;
124 void (*close_fn
)(NBDClient
*client
, bool negotiated
);
127 QCryptoTLSCreds
*tlscreds
;
129 QIOChannelSocket
*sioc
; /* The underlying data channel */
130 QIOChannel
*ioc
; /* The current I/O channel which may differ (eg TLS) */
132 Coroutine
*recv_coroutine
;
135 Coroutine
*send_coroutine
;
140 QTAILQ_ENTRY(NBDClient
) next
;
144 uint32_t check_align
; /* If non-zero, check for aligned client requests */
147 NBDExportMetaContexts export_meta
;
149 uint32_t opt
; /* Current option being negotiated */
150 uint32_t optlen
; /* remaining length of data in ioc for the option being
154 static void nbd_client_receive_next_request(NBDClient
*client
);
156 /* Basic flow for negotiation
183 static inline void set_be_option_rep(NBDOptionReply
*rep
, uint32_t option
,
184 uint32_t type
, uint32_t length
)
186 stq_be_p(&rep
->magic
, NBD_REP_MAGIC
);
187 stl_be_p(&rep
->option
, option
);
188 stl_be_p(&rep
->type
, type
);
189 stl_be_p(&rep
->length
, length
);
192 /* Send a reply header, including length, but no payload.
193 * Return -errno on error, 0 on success. */
194 static int nbd_negotiate_send_rep_len(NBDClient
*client
, uint32_t type
,
195 uint32_t len
, Error
**errp
)
199 trace_nbd_negotiate_send_rep_len(client
->opt
, nbd_opt_lookup(client
->opt
),
200 type
, nbd_rep_lookup(type
), len
);
202 assert(len
< NBD_MAX_BUFFER_SIZE
);
204 set_be_option_rep(&rep
, client
->opt
, type
, len
);
205 return nbd_write(client
->ioc
, &rep
, sizeof(rep
), errp
);
208 /* Send a reply header with default 0 length.
209 * Return -errno on error, 0 on success. */
210 static int nbd_negotiate_send_rep(NBDClient
*client
, uint32_t type
,
213 return nbd_negotiate_send_rep_len(client
, type
, 0, errp
);
216 /* Send an error reply.
217 * Return -errno on error, 0 on success. */
218 static int G_GNUC_PRINTF(4, 0)
219 nbd_negotiate_send_rep_verr(NBDClient
*client
, uint32_t type
,
220 Error
**errp
, const char *fmt
, va_list va
)
223 g_autofree
char *msg
= NULL
;
227 msg
= g_strdup_vprintf(fmt
, va
);
229 assert(len
< NBD_MAX_STRING_SIZE
);
230 trace_nbd_negotiate_send_rep_err(msg
);
231 ret
= nbd_negotiate_send_rep_len(client
, type
, len
, errp
);
235 if (nbd_write(client
->ioc
, msg
, len
, errp
) < 0) {
236 error_prepend(errp
, "write failed (error message): ");
244 * Return a malloc'd copy of @name suitable for use in an error reply.
247 nbd_sanitize_name(const char *name
)
249 if (strnlen(name
, 80) < 80) {
250 return g_strdup(name
);
252 /* XXX Should we also try to sanitize any control characters? */
253 return g_strdup_printf("%.80s...", name
);
256 /* Send an error reply.
257 * Return -errno on error, 0 on success. */
258 static int G_GNUC_PRINTF(4, 5)
259 nbd_negotiate_send_rep_err(NBDClient
*client
, uint32_t type
,
260 Error
**errp
, const char *fmt
, ...)
266 ret
= nbd_negotiate_send_rep_verr(client
, type
, errp
, fmt
, va
);
271 /* Drop remainder of the current option, and send a reply with the
272 * given error type and message. Return -errno on read or write
273 * failure; or 0 if connection is still live. */
274 static int G_GNUC_PRINTF(4, 0)
275 nbd_opt_vdrop(NBDClient
*client
, uint32_t type
, Error
**errp
,
276 const char *fmt
, va_list va
)
278 int ret
= nbd_drop(client
->ioc
, client
->optlen
, errp
);
282 ret
= nbd_negotiate_send_rep_verr(client
, type
, errp
, fmt
, va
);
287 static int G_GNUC_PRINTF(4, 5)
288 nbd_opt_drop(NBDClient
*client
, uint32_t type
, Error
**errp
,
289 const char *fmt
, ...)
295 ret
= nbd_opt_vdrop(client
, type
, errp
, fmt
, va
);
301 static int G_GNUC_PRINTF(3, 4)
302 nbd_opt_invalid(NBDClient
*client
, Error
**errp
, const char *fmt
, ...)
308 ret
= nbd_opt_vdrop(client
, NBD_REP_ERR_INVALID
, errp
, fmt
, va
);
314 /* Read size bytes from the unparsed payload of the current option.
315 * If @check_nul, require that no NUL bytes appear in buffer.
316 * Return -errno on I/O error, 0 if option was completely handled by
317 * sending a reply about inconsistent lengths, or 1 on success. */
318 static int nbd_opt_read(NBDClient
*client
, void *buffer
, size_t size
,
319 bool check_nul
, Error
**errp
)
321 if (size
> client
->optlen
) {
322 return nbd_opt_invalid(client
, errp
,
323 "Inconsistent lengths in option %s",
324 nbd_opt_lookup(client
->opt
));
326 client
->optlen
-= size
;
327 if (qio_channel_read_all(client
->ioc
, buffer
, size
, errp
) < 0) {
331 if (check_nul
&& strnlen(buffer
, size
) != size
) {
332 return nbd_opt_invalid(client
, errp
,
333 "Unexpected embedded NUL in option %s",
334 nbd_opt_lookup(client
->opt
));
339 /* Drop size bytes from the unparsed payload of the current option.
340 * Return -errno on I/O error, 0 if option was completely handled by
341 * sending a reply about inconsistent lengths, or 1 on success. */
342 static int nbd_opt_skip(NBDClient
*client
, size_t size
, Error
**errp
)
344 if (size
> client
->optlen
) {
345 return nbd_opt_invalid(client
, errp
,
346 "Inconsistent lengths in option %s",
347 nbd_opt_lookup(client
->opt
));
349 client
->optlen
-= size
;
350 return nbd_drop(client
->ioc
, size
, errp
) < 0 ? -EIO
: 1;
355 * Read a string with the format:
356 * uint32_t len (<= NBD_MAX_STRING_SIZE)
357 * len bytes string (not 0-terminated)
359 * On success, @name will be allocated.
360 * If @length is non-null, it will be set to the actual string length.
362 * Return -errno on I/O error, 0 if option was completely handled by
363 * sending a reply about inconsistent lengths, or 1 on success.
365 static int nbd_opt_read_name(NBDClient
*client
, char **name
, uint32_t *length
,
370 g_autofree
char *local_name
= NULL
;
373 ret
= nbd_opt_read(client
, &len
, sizeof(len
), false, errp
);
377 len
= cpu_to_be32(len
);
379 if (len
> NBD_MAX_STRING_SIZE
) {
380 return nbd_opt_invalid(client
, errp
,
381 "Invalid name length: %" PRIu32
, len
);
384 local_name
= g_malloc(len
+ 1);
385 ret
= nbd_opt_read(client
, local_name
, len
, true, errp
);
389 local_name
[len
] = '\0';
394 *name
= g_steal_pointer(&local_name
);
399 /* Send a single NBD_REP_SERVER reply to NBD_OPT_LIST, including payload.
400 * Return -errno on error, 0 on success. */
401 static int nbd_negotiate_send_rep_list(NBDClient
*client
, NBDExport
*exp
,
405 size_t name_len
, desc_len
;
407 const char *name
= exp
->name
? exp
->name
: "";
408 const char *desc
= exp
->description
? exp
->description
: "";
409 QIOChannel
*ioc
= client
->ioc
;
412 trace_nbd_negotiate_send_rep_list(name
, desc
);
413 name_len
= strlen(name
);
414 desc_len
= strlen(desc
);
415 assert(name_len
<= NBD_MAX_STRING_SIZE
&& desc_len
<= NBD_MAX_STRING_SIZE
);
416 len
= name_len
+ desc_len
+ sizeof(len
);
417 ret
= nbd_negotiate_send_rep_len(client
, NBD_REP_SERVER
, len
, errp
);
422 len
= cpu_to_be32(name_len
);
423 if (nbd_write(ioc
, &len
, sizeof(len
), errp
) < 0) {
424 error_prepend(errp
, "write failed (name length): ");
428 if (nbd_write(ioc
, name
, name_len
, errp
) < 0) {
429 error_prepend(errp
, "write failed (name buffer): ");
433 if (nbd_write(ioc
, desc
, desc_len
, errp
) < 0) {
434 error_prepend(errp
, "write failed (description buffer): ");
441 /* Process the NBD_OPT_LIST command, with a potential series of replies.
442 * Return -errno on error, 0 on success. */
443 static int nbd_negotiate_handle_list(NBDClient
*client
, Error
**errp
)
446 assert(client
->opt
== NBD_OPT_LIST
);
448 /* For each export, send a NBD_REP_SERVER reply. */
449 QTAILQ_FOREACH(exp
, &exports
, next
) {
450 if (nbd_negotiate_send_rep_list(client
, exp
, errp
)) {
454 /* Finish with a NBD_REP_ACK. */
455 return nbd_negotiate_send_rep(client
, NBD_REP_ACK
, errp
);
458 static void nbd_check_meta_export(NBDClient
*client
)
460 if (client
->exp
!= client
->export_meta
.exp
) {
461 client
->export_meta
.count
= 0;
465 /* Send a reply to NBD_OPT_EXPORT_NAME.
466 * Return -errno on error, 0 on success. */
467 static int nbd_negotiate_handle_export_name(NBDClient
*client
, bool no_zeroes
,
471 g_autofree
char *name
= NULL
;
472 char buf
[NBD_REPLY_EXPORT_NAME_SIZE
] = "";
478 [20 .. xx] export name (length bytes)
481 [ 8 .. 9] export flags
482 [10 .. 133] reserved (0) [unless no_zeroes]
484 trace_nbd_negotiate_handle_export_name();
485 if (client
->optlen
> NBD_MAX_STRING_SIZE
) {
486 error_setg(errp
, "Bad length received");
489 name
= g_malloc(client
->optlen
+ 1);
490 if (nbd_read(client
->ioc
, name
, client
->optlen
, "export name", errp
) < 0) {
493 name
[client
->optlen
] = '\0';
496 trace_nbd_negotiate_handle_export_name_request(name
);
498 client
->exp
= nbd_export_find(name
);
500 error_setg(errp
, "export not found");
504 myflags
= client
->exp
->nbdflags
;
505 if (client
->mode
>= NBD_MODE_STRUCTURED
) {
506 myflags
|= NBD_FLAG_SEND_DF
;
508 trace_nbd_negotiate_new_style_size_flags(client
->exp
->size
, myflags
);
509 stq_be_p(buf
, client
->exp
->size
);
510 stw_be_p(buf
+ 8, myflags
);
511 len
= no_zeroes
? 10 : sizeof(buf
);
512 ret
= nbd_write(client
->ioc
, buf
, len
, errp
);
514 error_prepend(errp
, "write failed: ");
518 QTAILQ_INSERT_TAIL(&client
->exp
->clients
, client
, next
);
519 blk_exp_ref(&client
->exp
->common
);
520 nbd_check_meta_export(client
);
525 /* Send a single NBD_REP_INFO, with a buffer @buf of @length bytes.
526 * The buffer does NOT include the info type prefix.
527 * Return -errno on error, 0 if ready to send more. */
528 static int nbd_negotiate_send_info(NBDClient
*client
,
529 uint16_t info
, uint32_t length
, void *buf
,
534 trace_nbd_negotiate_send_info(info
, nbd_info_lookup(info
), length
);
535 rc
= nbd_negotiate_send_rep_len(client
, NBD_REP_INFO
,
536 sizeof(info
) + length
, errp
);
540 info
= cpu_to_be16(info
);
541 if (nbd_write(client
->ioc
, &info
, sizeof(info
), errp
) < 0) {
544 if (nbd_write(client
->ioc
, buf
, length
, errp
) < 0) {
550 /* nbd_reject_length: Handle any unexpected payload.
551 * @fatal requests that we quit talking to the client, even if we are able
552 * to successfully send an error reply.
554 * -errno transmission error occurred or @fatal was requested, errp is set
555 * 0 error message successfully sent to client, errp is not set
557 static int nbd_reject_length(NBDClient
*client
, bool fatal
, Error
**errp
)
561 assert(client
->optlen
);
562 ret
= nbd_opt_invalid(client
, errp
, "option '%s' has unexpected length",
563 nbd_opt_lookup(client
->opt
));
565 error_setg(errp
, "option '%s' has unexpected length",
566 nbd_opt_lookup(client
->opt
));
572 /* Handle NBD_OPT_INFO and NBD_OPT_GO.
573 * Return -errno on error, 0 if ready for next option, and 1 to move
574 * into transmission phase. */
575 static int nbd_negotiate_handle_info(NBDClient
*client
, Error
**errp
)
578 g_autofree
char *name
= NULL
;
582 uint32_t namelen
= 0;
583 bool sendname
= false;
584 bool blocksize
= false;
586 char buf
[sizeof(uint64_t) + sizeof(uint16_t)];
587 uint32_t check_align
= 0;
591 4 bytes: L, name length (can be 0)
593 2 bytes: N, number of requests (can be 0)
594 N * 2 bytes: N requests
596 rc
= nbd_opt_read_name(client
, &name
, &namelen
, errp
);
600 trace_nbd_negotiate_handle_export_name_request(name
);
602 rc
= nbd_opt_read(client
, &requests
, sizeof(requests
), false, errp
);
606 requests
= be16_to_cpu(requests
);
607 trace_nbd_negotiate_handle_info_requests(requests
);
609 rc
= nbd_opt_read(client
, &request
, sizeof(request
), false, errp
);
613 request
= be16_to_cpu(request
);
614 trace_nbd_negotiate_handle_info_request(request
,
615 nbd_info_lookup(request
));
616 /* We care about NBD_INFO_NAME and NBD_INFO_BLOCK_SIZE;
617 * everything else is either a request we don't know or
618 * something we send regardless of request */
623 case NBD_INFO_BLOCK_SIZE
:
628 if (client
->optlen
) {
629 return nbd_reject_length(client
, false, errp
);
632 exp
= nbd_export_find(name
);
634 g_autofree
char *sane_name
= nbd_sanitize_name(name
);
636 return nbd_negotiate_send_rep_err(client
, NBD_REP_ERR_UNKNOWN
,
637 errp
, "export '%s' not present",
641 /* Don't bother sending NBD_INFO_NAME unless client requested it */
643 rc
= nbd_negotiate_send_info(client
, NBD_INFO_NAME
, namelen
, name
,
650 /* Send NBD_INFO_DESCRIPTION only if available, regardless of
652 if (exp
->description
) {
653 size_t len
= strlen(exp
->description
);
655 assert(len
<= NBD_MAX_STRING_SIZE
);
656 rc
= nbd_negotiate_send_info(client
, NBD_INFO_DESCRIPTION
,
657 len
, exp
->description
, errp
);
663 /* Send NBD_INFO_BLOCK_SIZE always, but tweak the minimum size
664 * according to whether the client requested it, and according to
665 * whether this is OPT_INFO or OPT_GO. */
666 /* minimum - 1 for back-compat, or actual if client will obey it. */
667 if (client
->opt
== NBD_OPT_INFO
|| blocksize
) {
668 check_align
= sizes
[0] = blk_get_request_alignment(exp
->common
.blk
);
672 assert(sizes
[0] <= NBD_MAX_BUFFER_SIZE
);
673 /* preferred - Hard-code to 4096 for now.
674 * TODO: is blk_bs(blk)->bl.opt_transfer appropriate? */
675 sizes
[1] = MAX(4096, sizes
[0]);
676 /* maximum - At most 32M, but smaller as appropriate. */
677 sizes
[2] = MIN(blk_get_max_transfer(exp
->common
.blk
), NBD_MAX_BUFFER_SIZE
);
678 trace_nbd_negotiate_handle_info_block_size(sizes
[0], sizes
[1], sizes
[2]);
679 sizes
[0] = cpu_to_be32(sizes
[0]);
680 sizes
[1] = cpu_to_be32(sizes
[1]);
681 sizes
[2] = cpu_to_be32(sizes
[2]);
682 rc
= nbd_negotiate_send_info(client
, NBD_INFO_BLOCK_SIZE
,
683 sizeof(sizes
), sizes
, errp
);
688 /* Send NBD_INFO_EXPORT always */
689 myflags
= exp
->nbdflags
;
690 if (client
->mode
>= NBD_MODE_STRUCTURED
) {
691 myflags
|= NBD_FLAG_SEND_DF
;
693 trace_nbd_negotiate_new_style_size_flags(exp
->size
, myflags
);
694 stq_be_p(buf
, exp
->size
);
695 stw_be_p(buf
+ 8, myflags
);
696 rc
= nbd_negotiate_send_info(client
, NBD_INFO_EXPORT
,
697 sizeof(buf
), buf
, errp
);
703 * If the client is just asking for NBD_OPT_INFO, but forgot to
704 * request block sizes in a situation that would impact
705 * performance, then return an error. But for NBD_OPT_GO, we
706 * tolerate all clients, regardless of alignments.
708 if (client
->opt
== NBD_OPT_INFO
&& !blocksize
&&
709 blk_get_request_alignment(exp
->common
.blk
) > 1) {
710 return nbd_negotiate_send_rep_err(client
,
711 NBD_REP_ERR_BLOCK_SIZE_REQD
,
713 "request NBD_INFO_BLOCK_SIZE to "
718 rc
= nbd_negotiate_send_rep(client
, NBD_REP_ACK
, errp
);
723 if (client
->opt
== NBD_OPT_GO
) {
725 client
->check_align
= check_align
;
726 QTAILQ_INSERT_TAIL(&client
->exp
->clients
, client
, next
);
727 blk_exp_ref(&client
->exp
->common
);
728 nbd_check_meta_export(client
);
735 /* Handle NBD_OPT_STARTTLS. Return NULL to drop connection, or else the
736 * new channel for all further (now-encrypted) communication. */
737 static QIOChannel
*nbd_negotiate_handle_starttls(NBDClient
*client
,
742 struct NBDTLSHandshakeData data
= { 0 };
744 assert(client
->opt
== NBD_OPT_STARTTLS
);
746 trace_nbd_negotiate_handle_starttls();
749 if (nbd_negotiate_send_rep(client
, NBD_REP_ACK
, errp
) < 0) {
753 tioc
= qio_channel_tls_new_server(ioc
,
761 qio_channel_set_name(QIO_CHANNEL(tioc
), "nbd-server-tls");
762 trace_nbd_negotiate_handle_starttls_handshake();
763 data
.loop
= g_main_loop_new(g_main_context_default(), FALSE
);
764 qio_channel_tls_handshake(tioc
,
770 if (!data
.complete
) {
771 g_main_loop_run(data
.loop
);
773 g_main_loop_unref(data
.loop
);
775 object_unref(OBJECT(tioc
));
776 error_propagate(errp
, data
.error
);
780 return QIO_CHANNEL(tioc
);
783 /* nbd_negotiate_send_meta_context
785 * Send one chunk of reply to NBD_OPT_{LIST,SET}_META_CONTEXT
787 * For NBD_OPT_LIST_META_CONTEXT @context_id is ignored, 0 is used instead.
789 static int nbd_negotiate_send_meta_context(NBDClient
*client
,
794 NBDOptionReplyMetaContext opt
;
795 struct iovec iov
[] = {
796 {.iov_base
= &opt
, .iov_len
= sizeof(opt
)},
797 {.iov_base
= (void *)context
, .iov_len
= strlen(context
)}
800 assert(iov
[1].iov_len
<= NBD_MAX_STRING_SIZE
);
801 if (client
->opt
== NBD_OPT_LIST_META_CONTEXT
) {
805 trace_nbd_negotiate_meta_query_reply(context
, context_id
);
806 set_be_option_rep(&opt
.h
, client
->opt
, NBD_REP_META_CONTEXT
,
807 sizeof(opt
) - sizeof(opt
.h
) + iov
[1].iov_len
);
808 stl_be_p(&opt
.context_id
, context_id
);
810 return qio_channel_writev_all(client
->ioc
, iov
, 2, errp
) < 0 ? -EIO
: 0;
814 * Return true if @query matches @pattern, or if @query is empty when
815 * the @client is performing _LIST_.
817 static bool nbd_meta_empty_or_pattern(NBDClient
*client
, const char *pattern
,
821 trace_nbd_negotiate_meta_query_parse("empty");
822 return client
->opt
== NBD_OPT_LIST_META_CONTEXT
;
824 if (strcmp(query
, pattern
) == 0) {
825 trace_nbd_negotiate_meta_query_parse(pattern
);
828 trace_nbd_negotiate_meta_query_skip("pattern not matched");
833 * Return true and adjust @str in place if it begins with @prefix.
835 static bool nbd_strshift(const char **str
, const char *prefix
)
837 size_t len
= strlen(prefix
);
839 if (strncmp(*str
, prefix
, len
) == 0) {
846 /* nbd_meta_base_query
848 * Handle queries to 'base' namespace. For now, only the base:allocation
849 * context is available. Return true if @query has been handled.
851 static bool nbd_meta_base_query(NBDClient
*client
, NBDExportMetaContexts
*meta
,
854 if (!nbd_strshift(&query
, "base:")) {
857 trace_nbd_negotiate_meta_query_parse("base:");
859 if (nbd_meta_empty_or_pattern(client
, "allocation", query
)) {
860 meta
->base_allocation
= true;
865 /* nbd_meta_qemu_query
867 * Handle queries to 'qemu' namespace. For now, only the qemu:dirty-bitmap:
868 * and qemu:allocation-depth contexts are available. Return true if @query
871 static bool nbd_meta_qemu_query(NBDClient
*client
, NBDExportMetaContexts
*meta
,
876 if (!nbd_strshift(&query
, "qemu:")) {
879 trace_nbd_negotiate_meta_query_parse("qemu:");
882 if (client
->opt
== NBD_OPT_LIST_META_CONTEXT
) {
883 meta
->allocation_depth
= meta
->exp
->allocation_depth
;
884 if (meta
->exp
->nr_export_bitmaps
) {
885 memset(meta
->bitmaps
, 1, meta
->exp
->nr_export_bitmaps
);
888 trace_nbd_negotiate_meta_query_parse("empty");
892 if (strcmp(query
, "allocation-depth") == 0) {
893 trace_nbd_negotiate_meta_query_parse("allocation-depth");
894 meta
->allocation_depth
= meta
->exp
->allocation_depth
;
898 if (nbd_strshift(&query
, "dirty-bitmap:")) {
899 trace_nbd_negotiate_meta_query_parse("dirty-bitmap:");
901 if (client
->opt
== NBD_OPT_LIST_META_CONTEXT
&&
902 meta
->exp
->nr_export_bitmaps
) {
903 memset(meta
->bitmaps
, 1, meta
->exp
->nr_export_bitmaps
);
905 trace_nbd_negotiate_meta_query_parse("empty");
909 for (i
= 0; i
< meta
->exp
->nr_export_bitmaps
; i
++) {
912 bm_name
= bdrv_dirty_bitmap_name(meta
->exp
->export_bitmaps
[i
]);
913 if (strcmp(bm_name
, query
) == 0) {
914 meta
->bitmaps
[i
] = true;
915 trace_nbd_negotiate_meta_query_parse(query
);
919 trace_nbd_negotiate_meta_query_skip("no dirty-bitmap match");
923 trace_nbd_negotiate_meta_query_skip("unknown qemu context");
927 /* nbd_negotiate_meta_query
929 * Parse namespace name and call corresponding function to parse body of the
932 * The only supported namespaces are 'base' and 'qemu'.
934 * Return -errno on I/O error, 0 if option was completely handled by
935 * sending a reply about inconsistent lengths, or 1 on success. */
936 static int nbd_negotiate_meta_query(NBDClient
*client
,
937 NBDExportMetaContexts
*meta
, Error
**errp
)
940 g_autofree
char *query
= NULL
;
943 ret
= nbd_opt_read(client
, &len
, sizeof(len
), false, errp
);
947 len
= cpu_to_be32(len
);
949 if (len
> NBD_MAX_STRING_SIZE
) {
950 trace_nbd_negotiate_meta_query_skip("length too long");
951 return nbd_opt_skip(client
, len
, errp
);
954 query
= g_malloc(len
+ 1);
955 ret
= nbd_opt_read(client
, query
, len
, true, errp
);
961 if (nbd_meta_base_query(client
, meta
, query
)) {
964 if (nbd_meta_qemu_query(client
, meta
, query
)) {
968 trace_nbd_negotiate_meta_query_skip("unknown namespace");
972 /* nbd_negotiate_meta_queries
973 * Handle NBD_OPT_LIST_META_CONTEXT and NBD_OPT_SET_META_CONTEXT
975 * Return -errno on I/O error, or 0 if option was completely handled. */
976 static int nbd_negotiate_meta_queries(NBDClient
*client
,
977 NBDExportMetaContexts
*meta
, Error
**errp
)
980 g_autofree
char *export_name
= NULL
;
981 /* Mark unused to work around https://bugs.llvm.org/show_bug.cgi?id=3888 */
982 g_autofree G_GNUC_UNUSED
bool *bitmaps
= NULL
;
983 NBDExportMetaContexts local_meta
= {0};
988 if (client
->opt
== NBD_OPT_SET_META_CONTEXT
&&
989 client
->mode
< NBD_MODE_STRUCTURED
) {
990 return nbd_opt_invalid(client
, errp
,
991 "request option '%s' when structured reply "
993 nbd_opt_lookup(client
->opt
));
996 if (client
->opt
== NBD_OPT_LIST_META_CONTEXT
) {
997 /* Only change the caller's meta on SET. */
1001 g_free(meta
->bitmaps
);
1002 memset(meta
, 0, sizeof(*meta
));
1004 ret
= nbd_opt_read_name(client
, &export_name
, NULL
, errp
);
1009 meta
->exp
= nbd_export_find(export_name
);
1010 if (meta
->exp
== NULL
) {
1011 g_autofree
char *sane_name
= nbd_sanitize_name(export_name
);
1013 return nbd_opt_drop(client
, NBD_REP_ERR_UNKNOWN
, errp
,
1014 "export '%s' not present", sane_name
);
1016 meta
->bitmaps
= g_new0(bool, meta
->exp
->nr_export_bitmaps
);
1017 if (client
->opt
== NBD_OPT_LIST_META_CONTEXT
) {
1018 bitmaps
= meta
->bitmaps
;
1021 ret
= nbd_opt_read(client
, &nb_queries
, sizeof(nb_queries
), false, errp
);
1025 nb_queries
= cpu_to_be32(nb_queries
);
1026 trace_nbd_negotiate_meta_context(nbd_opt_lookup(client
->opt
),
1027 export_name
, nb_queries
);
1029 if (client
->opt
== NBD_OPT_LIST_META_CONTEXT
&& !nb_queries
) {
1030 /* enable all known contexts */
1031 meta
->base_allocation
= true;
1032 meta
->allocation_depth
= meta
->exp
->allocation_depth
;
1033 if (meta
->exp
->nr_export_bitmaps
) {
1034 memset(meta
->bitmaps
, 1, meta
->exp
->nr_export_bitmaps
);
1037 for (i
= 0; i
< nb_queries
; ++i
) {
1038 ret
= nbd_negotiate_meta_query(client
, meta
, errp
);
1045 if (meta
->base_allocation
) {
1046 ret
= nbd_negotiate_send_meta_context(client
, "base:allocation",
1047 NBD_META_ID_BASE_ALLOCATION
,
1055 if (meta
->allocation_depth
) {
1056 ret
= nbd_negotiate_send_meta_context(client
, "qemu:allocation-depth",
1057 NBD_META_ID_ALLOCATION_DEPTH
,
1065 for (i
= 0; i
< meta
->exp
->nr_export_bitmaps
; i
++) {
1066 const char *bm_name
;
1067 g_autofree
char *context
= NULL
;
1069 if (!meta
->bitmaps
[i
]) {
1073 bm_name
= bdrv_dirty_bitmap_name(meta
->exp
->export_bitmaps
[i
]);
1074 context
= g_strdup_printf("qemu:dirty-bitmap:%s", bm_name
);
1076 ret
= nbd_negotiate_send_meta_context(client
, context
,
1077 NBD_META_ID_DIRTY_BITMAP
+ i
,
1085 ret
= nbd_negotiate_send_rep(client
, NBD_REP_ACK
, errp
);
1087 meta
->count
= count
;
1093 /* nbd_negotiate_options
1094 * Process all NBD_OPT_* client option commands, during fixed newstyle
1097 * -errno on error, errp is set
1098 * 0 on successful negotiation, errp is not set
1099 * 1 if client sent NBD_OPT_ABORT, i.e. on valid disconnect,
1102 static int nbd_negotiate_options(NBDClient
*client
, Error
**errp
)
1105 bool fixedNewstyle
= false;
1106 bool no_zeroes
= false;
1109 [ 0 .. 3] client flags
1111 Then we loop until NBD_OPT_EXPORT_NAME or NBD_OPT_GO:
1112 [ 0 .. 7] NBD_OPTS_MAGIC
1113 [ 8 .. 11] NBD option
1114 [12 .. 15] Data length
1117 [ 0 .. 7] NBD_OPTS_MAGIC
1118 [ 8 .. 11] Second NBD option
1119 [12 .. 15] Data length
1123 if (nbd_read32(client
->ioc
, &flags
, "flags", errp
) < 0) {
1126 client
->mode
= NBD_MODE_EXPORT_NAME
;
1127 trace_nbd_negotiate_options_flags(flags
);
1128 if (flags
& NBD_FLAG_C_FIXED_NEWSTYLE
) {
1129 fixedNewstyle
= true;
1130 flags
&= ~NBD_FLAG_C_FIXED_NEWSTYLE
;
1131 client
->mode
= NBD_MODE_SIMPLE
;
1133 if (flags
& NBD_FLAG_C_NO_ZEROES
) {
1135 flags
&= ~NBD_FLAG_C_NO_ZEROES
;
1138 error_setg(errp
, "Unknown client flags 0x%" PRIx32
" received", flags
);
1144 uint32_t option
, length
;
1147 if (nbd_read64(client
->ioc
, &magic
, "opts magic", errp
) < 0) {
1150 trace_nbd_negotiate_options_check_magic(magic
);
1151 if (magic
!= NBD_OPTS_MAGIC
) {
1152 error_setg(errp
, "Bad magic received");
1156 if (nbd_read32(client
->ioc
, &option
, "option", errp
) < 0) {
1159 client
->opt
= option
;
1161 if (nbd_read32(client
->ioc
, &length
, "option length", errp
) < 0) {
1164 assert(!client
->optlen
);
1165 client
->optlen
= length
;
1167 if (length
> NBD_MAX_BUFFER_SIZE
) {
1168 error_setg(errp
, "len (%" PRIu32
") is larger than max len (%u)",
1169 length
, NBD_MAX_BUFFER_SIZE
);
1173 trace_nbd_negotiate_options_check_option(option
,
1174 nbd_opt_lookup(option
));
1175 if (client
->tlscreds
&&
1176 client
->ioc
== (QIOChannel
*)client
->sioc
) {
1178 if (!fixedNewstyle
) {
1179 error_setg(errp
, "Unsupported option 0x%" PRIx32
, option
);
1183 case NBD_OPT_STARTTLS
:
1185 /* Unconditionally drop the connection if the client
1186 * can't start a TLS negotiation correctly */
1187 return nbd_reject_length(client
, true, errp
);
1189 tioc
= nbd_negotiate_handle_starttls(client
, errp
);
1194 object_unref(OBJECT(client
->ioc
));
1198 case NBD_OPT_EXPORT_NAME
:
1199 /* No way to return an error to client, so drop connection */
1200 error_setg(errp
, "Option 0x%x not permitted before TLS",
1205 /* Let the client keep trying, unless they asked to
1206 * quit. Always try to give an error back to the
1207 * client; but when replying to OPT_ABORT, be aware
1208 * that the client may hang up before receiving the
1209 * error, in which case we are fine ignoring the
1210 * resulting EPIPE. */
1211 ret
= nbd_opt_drop(client
, NBD_REP_ERR_TLS_REQD
,
1212 option
== NBD_OPT_ABORT
? NULL
: errp
,
1214 " not permitted before TLS", option
);
1215 if (option
== NBD_OPT_ABORT
) {
1220 } else if (fixedNewstyle
) {
1224 ret
= nbd_reject_length(client
, false, errp
);
1226 ret
= nbd_negotiate_handle_list(client
, errp
);
1231 /* NBD spec says we must try to reply before
1232 * disconnecting, but that we must also tolerate
1233 * guests that don't wait for our reply. */
1234 nbd_negotiate_send_rep(client
, NBD_REP_ACK
, NULL
);
1237 case NBD_OPT_EXPORT_NAME
:
1238 return nbd_negotiate_handle_export_name(client
, no_zeroes
,
1243 ret
= nbd_negotiate_handle_info(client
, errp
);
1245 assert(option
== NBD_OPT_GO
);
1250 case NBD_OPT_STARTTLS
:
1252 ret
= nbd_reject_length(client
, false, errp
);
1253 } else if (client
->tlscreds
) {
1254 ret
= nbd_negotiate_send_rep_err(client
,
1255 NBD_REP_ERR_INVALID
, errp
,
1256 "TLS already enabled");
1258 ret
= nbd_negotiate_send_rep_err(client
,
1259 NBD_REP_ERR_POLICY
, errp
,
1260 "TLS not configured");
1264 case NBD_OPT_STRUCTURED_REPLY
:
1266 ret
= nbd_reject_length(client
, false, errp
);
1267 } else if (client
->mode
>= NBD_MODE_STRUCTURED
) {
1268 ret
= nbd_negotiate_send_rep_err(
1269 client
, NBD_REP_ERR_INVALID
, errp
,
1270 "structured reply already negotiated");
1272 ret
= nbd_negotiate_send_rep(client
, NBD_REP_ACK
, errp
);
1273 client
->mode
= NBD_MODE_STRUCTURED
;
1277 case NBD_OPT_LIST_META_CONTEXT
:
1278 case NBD_OPT_SET_META_CONTEXT
:
1279 ret
= nbd_negotiate_meta_queries(client
, &client
->export_meta
,
1284 ret
= nbd_opt_drop(client
, NBD_REP_ERR_UNSUP
, errp
,
1285 "Unsupported option %" PRIu32
" (%s)",
1286 option
, nbd_opt_lookup(option
));
1291 * If broken new-style we should drop the connection
1292 * for anything except NBD_OPT_EXPORT_NAME
1295 case NBD_OPT_EXPORT_NAME
:
1296 return nbd_negotiate_handle_export_name(client
, no_zeroes
,
1300 error_setg(errp
, "Unsupported option %" PRIu32
" (%s)",
1301 option
, nbd_opt_lookup(option
));
1313 * -errno on error, errp is set
1314 * 0 on successful negotiation, errp is not set
1315 * 1 if client sent NBD_OPT_ABORT, i.e. on valid disconnect,
1318 static coroutine_fn
int nbd_negotiate(NBDClient
*client
, Error
**errp
)
1321 char buf
[NBD_OLDSTYLE_NEGOTIATE_SIZE
] = "";
1324 /* Old style negotiation header, no room for options
1325 [ 0 .. 7] passwd ("NBDMAGIC")
1326 [ 8 .. 15] magic (NBD_CLIENT_MAGIC)
1328 [24 .. 27] export flags (zero-extended)
1329 [28 .. 151] reserved (0)
1331 New style negotiation header, client can send options
1332 [ 0 .. 7] passwd ("NBDMAGIC")
1333 [ 8 .. 15] magic (NBD_OPTS_MAGIC)
1334 [16 .. 17] server flags (0)
1335 ....options sent, ending in NBD_OPT_EXPORT_NAME or NBD_OPT_GO....
1338 qio_channel_set_blocking(client
->ioc
, false, NULL
);
1339 qio_channel_set_follow_coroutine_ctx(client
->ioc
, true);
1341 trace_nbd_negotiate_begin();
1342 memcpy(buf
, "NBDMAGIC", 8);
1344 stq_be_p(buf
+ 8, NBD_OPTS_MAGIC
);
1345 stw_be_p(buf
+ 16, NBD_FLAG_FIXED_NEWSTYLE
| NBD_FLAG_NO_ZEROES
);
1347 if (nbd_write(client
->ioc
, buf
, 18, errp
) < 0) {
1348 error_prepend(errp
, "write failed: ");
1351 ret
= nbd_negotiate_options(client
, errp
);
1354 error_prepend(errp
, "option negotiation failed: ");
1359 assert(!client
->optlen
);
1360 trace_nbd_negotiate_success();
1366 * Tries to read @size bytes from @ioc. This is a local implementation of
1367 * qio_channel_readv_all_eof. We have it here because we need it to be
1368 * interruptible and to know when the coroutine is yielding.
1369 * Returns 1 on success
1370 * 0 on eof, when no data was read (errp is not set)
1371 * negative errno on failure (errp is set)
1373 static inline int coroutine_fn
1374 nbd_read_eof(NBDClient
*client
, void *buffer
, size_t size
, Error
**errp
)
1376 bool partial
= false;
1380 struct iovec iov
= { .iov_base
= buffer
, .iov_len
= size
};
1383 len
= qio_channel_readv(client
->ioc
, &iov
, 1, errp
);
1384 if (len
== QIO_CHANNEL_ERR_BLOCK
) {
1385 client
->read_yielding
= true;
1386 qio_channel_yield(client
->ioc
, G_IO_IN
);
1387 client
->read_yielding
= false;
1388 if (client
->quiescing
) {
1392 } else if (len
< 0) {
1394 } else if (len
== 0) {
1397 "Unexpected end-of-file before all bytes were read");
1406 buffer
= (uint8_t *) buffer
+ len
;
1411 static int coroutine_fn
nbd_receive_request(NBDClient
*client
, NBDRequest
*request
,
1414 uint8_t buf
[NBD_REQUEST_SIZE
];
1418 ret
= nbd_read_eof(client
, buf
, sizeof(buf
), errp
);
1427 [ 0 .. 3] magic (NBD_REQUEST_MAGIC)
1428 [ 4 .. 5] flags (NBD_CMD_FLAG_FUA, ...)
1429 [ 6 .. 7] type (NBD_CMD_READ, ...)
1435 magic
= ldl_be_p(buf
);
1436 request
->flags
= lduw_be_p(buf
+ 4);
1437 request
->type
= lduw_be_p(buf
+ 6);
1438 request
->cookie
= ldq_be_p(buf
+ 8);
1439 request
->from
= ldq_be_p(buf
+ 16);
1440 request
->len
= (uint32_t)ldl_be_p(buf
+ 24); /* widen 32 to 64 bits */
1442 trace_nbd_receive_request(magic
, request
->flags
, request
->type
,
1443 request
->from
, request
->len
);
1445 if (magic
!= NBD_REQUEST_MAGIC
) {
1446 error_setg(errp
, "invalid magic (got 0x%" PRIx32
")", magic
);
1452 #define MAX_NBD_REQUESTS 16
1454 void nbd_client_get(NBDClient
*client
)
1459 void nbd_client_put(NBDClient
*client
)
1461 if (--client
->refcount
== 0) {
1462 /* The last reference should be dropped by client->close,
1463 * which is called by client_close.
1465 assert(client
->closing
);
1467 object_unref(OBJECT(client
->sioc
));
1468 object_unref(OBJECT(client
->ioc
));
1469 if (client
->tlscreds
) {
1470 object_unref(OBJECT(client
->tlscreds
));
1472 g_free(client
->tlsauthz
);
1474 QTAILQ_REMOVE(&client
->exp
->clients
, client
, next
);
1475 blk_exp_unref(&client
->exp
->common
);
1477 g_free(client
->export_meta
.bitmaps
);
1482 static void client_close(NBDClient
*client
, bool negotiated
)
1484 if (client
->closing
) {
1488 client
->closing
= true;
1490 /* Force requests to finish. They will drop their own references,
1491 * then we'll close the socket and free the NBDClient.
1493 qio_channel_shutdown(client
->ioc
, QIO_CHANNEL_SHUTDOWN_BOTH
,
1496 /* Also tell the client, so that they release their reference. */
1497 if (client
->close_fn
) {
1498 client
->close_fn(client
, negotiated
);
1502 static NBDRequestData
*nbd_request_get(NBDClient
*client
)
1504 NBDRequestData
*req
;
1506 assert(client
->nb_requests
<= MAX_NBD_REQUESTS
- 1);
1507 client
->nb_requests
++;
1509 req
= g_new0(NBDRequestData
, 1);
1510 nbd_client_get(client
);
1511 req
->client
= client
;
1515 static void nbd_request_put(NBDRequestData
*req
)
1517 NBDClient
*client
= req
->client
;
1520 qemu_vfree(req
->data
);
1524 client
->nb_requests
--;
1526 if (client
->quiescing
&& client
->nb_requests
== 0) {
1530 nbd_client_receive_next_request(client
);
1532 nbd_client_put(client
);
1535 static void blk_aio_attached(AioContext
*ctx
, void *opaque
)
1537 NBDExport
*exp
= opaque
;
1540 trace_nbd_blk_aio_attached(exp
->name
, ctx
);
1542 exp
->common
.ctx
= ctx
;
1544 QTAILQ_FOREACH(client
, &exp
->clients
, next
) {
1545 assert(client
->nb_requests
== 0);
1546 assert(client
->recv_coroutine
== NULL
);
1547 assert(client
->send_coroutine
== NULL
);
1551 static void blk_aio_detach(void *opaque
)
1553 NBDExport
*exp
= opaque
;
1555 trace_nbd_blk_aio_detach(exp
->name
, exp
->common
.ctx
);
1557 exp
->common
.ctx
= NULL
;
1560 static void nbd_drained_begin(void *opaque
)
1562 NBDExport
*exp
= opaque
;
1565 QTAILQ_FOREACH(client
, &exp
->clients
, next
) {
1566 client
->quiescing
= true;
1570 static void nbd_drained_end(void *opaque
)
1572 NBDExport
*exp
= opaque
;
1575 QTAILQ_FOREACH(client
, &exp
->clients
, next
) {
1576 client
->quiescing
= false;
1577 nbd_client_receive_next_request(client
);
1581 static bool nbd_drained_poll(void *opaque
)
1583 NBDExport
*exp
= opaque
;
1586 QTAILQ_FOREACH(client
, &exp
->clients
, next
) {
1587 if (client
->nb_requests
!= 0) {
1589 * If there's a coroutine waiting for a request on nbd_read_eof()
1590 * enter it here so we don't depend on the client to wake it up.
1592 if (client
->recv_coroutine
!= NULL
&& client
->read_yielding
) {
1593 qio_channel_wake_read(client
->ioc
);
1603 static void nbd_eject_notifier(Notifier
*n
, void *data
)
1605 NBDExport
*exp
= container_of(n
, NBDExport
, eject_notifier
);
1607 blk_exp_request_shutdown(&exp
->common
);
1610 void nbd_export_set_on_eject_blk(BlockExport
*exp
, BlockBackend
*blk
)
1612 NBDExport
*nbd_exp
= container_of(exp
, NBDExport
, common
);
1613 assert(exp
->drv
== &blk_exp_nbd
);
1614 assert(nbd_exp
->eject_notifier_blk
== NULL
);
1617 nbd_exp
->eject_notifier_blk
= blk
;
1618 nbd_exp
->eject_notifier
.notify
= nbd_eject_notifier
;
1619 blk_add_remove_bs_notifier(blk
, &nbd_exp
->eject_notifier
);
1622 static const BlockDevOps nbd_block_ops
= {
1623 .drained_begin
= nbd_drained_begin
,
1624 .drained_end
= nbd_drained_end
,
1625 .drained_poll
= nbd_drained_poll
,
1628 static int nbd_export_create(BlockExport
*blk_exp
, BlockExportOptions
*exp_args
,
1631 NBDExport
*exp
= container_of(blk_exp
, NBDExport
, common
);
1632 BlockExportOptionsNbd
*arg
= &exp_args
->u
.nbd
;
1633 const char *name
= arg
->name
?: exp_args
->node_name
;
1634 BlockBackend
*blk
= blk_exp
->blk
;
1636 uint64_t perm
, shared_perm
;
1637 bool readonly
= !exp_args
->writable
;
1638 BlockDirtyBitmapOrStrList
*bitmaps
;
1642 assert(exp_args
->type
== BLOCK_EXPORT_TYPE_NBD
);
1644 if (!nbd_server_is_running()) {
1645 error_setg(errp
, "NBD server not running");
1649 if (strlen(name
) > NBD_MAX_STRING_SIZE
) {
1650 error_setg(errp
, "export name '%s' too long", name
);
1654 if (arg
->description
&& strlen(arg
->description
) > NBD_MAX_STRING_SIZE
) {
1655 error_setg(errp
, "description '%s' too long", arg
->description
);
1659 if (nbd_export_find(name
)) {
1660 error_setg(errp
, "NBD server already has export named '%s'", name
);
1664 size
= blk_getlength(blk
);
1666 error_setg_errno(errp
, -size
,
1667 "Failed to determine the NBD export's length");
1671 /* Don't allow resize while the NBD server is running, otherwise we don't
1672 * care what happens with the node. */
1673 blk_get_perm(blk
, &perm
, &shared_perm
);
1674 ret
= blk_set_perm(blk
, perm
, shared_perm
& ~BLK_PERM_RESIZE
, errp
);
1679 QTAILQ_INIT(&exp
->clients
);
1680 exp
->name
= g_strdup(name
);
1681 exp
->description
= g_strdup(arg
->description
);
1682 exp
->nbdflags
= (NBD_FLAG_HAS_FLAGS
| NBD_FLAG_SEND_FLUSH
|
1683 NBD_FLAG_SEND_FUA
| NBD_FLAG_SEND_CACHE
);
1685 if (nbd_server_max_connections() != 1) {
1686 exp
->nbdflags
|= NBD_FLAG_CAN_MULTI_CONN
;
1689 exp
->nbdflags
|= NBD_FLAG_READ_ONLY
;
1691 exp
->nbdflags
|= (NBD_FLAG_SEND_TRIM
| NBD_FLAG_SEND_WRITE_ZEROES
|
1692 NBD_FLAG_SEND_FAST_ZERO
);
1694 exp
->size
= QEMU_ALIGN_DOWN(size
, BDRV_SECTOR_SIZE
);
1696 for (bitmaps
= arg
->bitmaps
; bitmaps
; bitmaps
= bitmaps
->next
) {
1697 exp
->nr_export_bitmaps
++;
1699 exp
->export_bitmaps
= g_new0(BdrvDirtyBitmap
*, exp
->nr_export_bitmaps
);
1700 for (i
= 0, bitmaps
= arg
->bitmaps
; bitmaps
;
1701 i
++, bitmaps
= bitmaps
->next
)
1704 BlockDriverState
*bs
= blk_bs(blk
);
1705 BdrvDirtyBitmap
*bm
= NULL
;
1707 switch (bitmaps
->value
->type
) {
1709 bitmap
= bitmaps
->value
->u
.local
;
1711 bm
= bdrv_find_dirty_bitmap(bs
, bitmap
);
1716 bs
= bdrv_filter_or_cow_bs(bs
);
1721 error_setg(errp
, "Bitmap '%s' is not found",
1722 bitmaps
->value
->u
.local
);
1726 if (readonly
&& bdrv_is_writable(bs
) &&
1727 bdrv_dirty_bitmap_enabled(bm
)) {
1729 error_setg(errp
, "Enabled bitmap '%s' incompatible with "
1730 "readonly export", bitmap
);
1735 bitmap
= bitmaps
->value
->u
.external
.name
;
1736 bm
= block_dirty_bitmap_lookup(bitmaps
->value
->u
.external
.node
,
1737 bitmap
, NULL
, errp
);
1749 if (bdrv_dirty_bitmap_check(bm
, BDRV_BITMAP_ALLOW_RO
, errp
)) {
1754 exp
->export_bitmaps
[i
] = bm
;
1755 assert(strlen(bitmap
) <= BDRV_BITMAP_MAX_NAME_SIZE
);
1758 /* Mark bitmaps busy in a separate loop, to simplify roll-back concerns. */
1759 for (i
= 0; i
< exp
->nr_export_bitmaps
; i
++) {
1760 bdrv_dirty_bitmap_set_busy(exp
->export_bitmaps
[i
], true);
1763 exp
->allocation_depth
= arg
->allocation_depth
;
1766 * We need to inhibit request queuing in the block layer to ensure we can
1767 * be properly quiesced when entering a drained section, as our coroutines
1768 * servicing pending requests might enter blk_pread().
1770 blk_set_disable_request_queuing(blk
, true);
1772 blk_add_aio_context_notifier(blk
, blk_aio_attached
, blk_aio_detach
, exp
);
1774 blk_set_dev_ops(blk
, &nbd_block_ops
, exp
);
1776 QTAILQ_INSERT_TAIL(&exports
, exp
, next
);
1781 g_free(exp
->export_bitmaps
);
1783 g_free(exp
->description
);
1787 NBDExport
*nbd_export_find(const char *name
)
1790 QTAILQ_FOREACH(exp
, &exports
, next
) {
1791 if (strcmp(name
, exp
->name
) == 0) {
1800 nbd_export_aio_context(NBDExport
*exp
)
1802 return exp
->common
.ctx
;
1805 static void nbd_export_request_shutdown(BlockExport
*blk_exp
)
1807 NBDExport
*exp
= container_of(blk_exp
, NBDExport
, common
);
1808 NBDClient
*client
, *next
;
1810 blk_exp_ref(&exp
->common
);
1812 * TODO: Should we expand QMP NbdServerRemoveNode enum to allow a
1813 * close mode that stops advertising the export to new clients but
1814 * still permits existing clients to run to completion? Because of
1815 * that possibility, nbd_export_close() can be called more than
1816 * once on an export.
1818 QTAILQ_FOREACH_SAFE(client
, &exp
->clients
, next
, next
) {
1819 client_close(client
, true);
1824 QTAILQ_REMOVE(&exports
, exp
, next
);
1826 blk_exp_unref(&exp
->common
);
1829 static void nbd_export_delete(BlockExport
*blk_exp
)
1832 NBDExport
*exp
= container_of(blk_exp
, NBDExport
, common
);
1834 assert(exp
->name
== NULL
);
1835 assert(QTAILQ_EMPTY(&exp
->clients
));
1837 g_free(exp
->description
);
1838 exp
->description
= NULL
;
1840 if (exp
->eject_notifier_blk
) {
1841 notifier_remove(&exp
->eject_notifier
);
1842 blk_unref(exp
->eject_notifier_blk
);
1844 blk_remove_aio_context_notifier(exp
->common
.blk
, blk_aio_attached
,
1845 blk_aio_detach
, exp
);
1846 blk_set_disable_request_queuing(exp
->common
.blk
, false);
1848 for (i
= 0; i
< exp
->nr_export_bitmaps
; i
++) {
1849 bdrv_dirty_bitmap_set_busy(exp
->export_bitmaps
[i
], false);
1853 const BlockExportDriver blk_exp_nbd
= {
1854 .type
= BLOCK_EXPORT_TYPE_NBD
,
1855 .instance_size
= sizeof(NBDExport
),
1856 .create
= nbd_export_create
,
1857 .delete = nbd_export_delete
,
1858 .request_shutdown
= nbd_export_request_shutdown
,
1861 static int coroutine_fn
nbd_co_send_iov(NBDClient
*client
, struct iovec
*iov
,
1862 unsigned niov
, Error
**errp
)
1866 g_assert(qemu_in_coroutine());
1867 qemu_co_mutex_lock(&client
->send_lock
);
1868 client
->send_coroutine
= qemu_coroutine_self();
1870 ret
= qio_channel_writev_all(client
->ioc
, iov
, niov
, errp
) < 0 ? -EIO
: 0;
1872 client
->send_coroutine
= NULL
;
1873 qemu_co_mutex_unlock(&client
->send_lock
);
1878 static inline void set_be_simple_reply(NBDSimpleReply
*reply
, uint64_t error
,
1881 stl_be_p(&reply
->magic
, NBD_SIMPLE_REPLY_MAGIC
);
1882 stl_be_p(&reply
->error
, error
);
1883 stq_be_p(&reply
->cookie
, cookie
);
1886 static int coroutine_fn
nbd_co_send_simple_reply(NBDClient
*client
,
1887 NBDRequest
*request
,
1893 NBDSimpleReply reply
;
1894 int nbd_err
= system_errno_to_nbd_errno(error
);
1895 struct iovec iov
[] = {
1896 {.iov_base
= &reply
, .iov_len
= sizeof(reply
)},
1897 {.iov_base
= data
, .iov_len
= len
}
1900 assert(!len
|| !nbd_err
);
1901 assert(len
<= NBD_MAX_BUFFER_SIZE
);
1902 assert(client
->mode
< NBD_MODE_STRUCTURED
||
1903 (client
->mode
== NBD_MODE_STRUCTURED
&&
1904 request
->type
!= NBD_CMD_READ
));
1905 trace_nbd_co_send_simple_reply(request
->cookie
, nbd_err
,
1906 nbd_err_lookup(nbd_err
), len
);
1907 set_be_simple_reply(&reply
, nbd_err
, request
->cookie
);
1909 return nbd_co_send_iov(client
, iov
, 2, errp
);
1913 * Prepare the header of a reply chunk for network transmission.
1915 * On input, @iov is partially initialized: iov[0].iov_base must point
1916 * to an uninitialized NBDReply, while the remaining @niov elements
1917 * (if any) must be ready for transmission. This function then
1918 * populates iov[0] for transmission.
1920 static inline void set_be_chunk(NBDClient
*client
, struct iovec
*iov
,
1921 size_t niov
, uint16_t flags
, uint16_t type
,
1922 NBDRequest
*request
)
1924 /* TODO - handle structured vs. extended replies */
1925 NBDStructuredReplyChunk
*chunk
= iov
->iov_base
;
1926 size_t i
, length
= 0;
1928 for (i
= 1; i
< niov
; i
++) {
1929 length
+= iov
[i
].iov_len
;
1931 assert(length
<= NBD_MAX_BUFFER_SIZE
+ sizeof(NBDStructuredReadData
));
1933 iov
[0].iov_len
= sizeof(*chunk
);
1934 stl_be_p(&chunk
->magic
, NBD_STRUCTURED_REPLY_MAGIC
);
1935 stw_be_p(&chunk
->flags
, flags
);
1936 stw_be_p(&chunk
->type
, type
);
1937 stq_be_p(&chunk
->cookie
, request
->cookie
);
1938 stl_be_p(&chunk
->length
, length
);
1941 static int coroutine_fn
nbd_co_send_chunk_done(NBDClient
*client
,
1942 NBDRequest
*request
,
1946 struct iovec iov
[] = {
1950 trace_nbd_co_send_chunk_done(request
->cookie
);
1951 set_be_chunk(client
, iov
, 1, NBD_REPLY_FLAG_DONE
,
1952 NBD_REPLY_TYPE_NONE
, request
);
1953 return nbd_co_send_iov(client
, iov
, 1, errp
);
1956 static int coroutine_fn
nbd_co_send_chunk_read(NBDClient
*client
,
1957 NBDRequest
*request
,
1965 NBDStructuredReadData chunk
;
1966 struct iovec iov
[] = {
1968 {.iov_base
= &chunk
, .iov_len
= sizeof(chunk
)},
1969 {.iov_base
= data
, .iov_len
= size
}
1972 assert(size
&& size
<= NBD_MAX_BUFFER_SIZE
);
1973 trace_nbd_co_send_chunk_read(request
->cookie
, offset
, data
, size
);
1974 set_be_chunk(client
, iov
, 3, final
? NBD_REPLY_FLAG_DONE
: 0,
1975 NBD_REPLY_TYPE_OFFSET_DATA
, request
);
1976 stq_be_p(&chunk
.offset
, offset
);
1978 return nbd_co_send_iov(client
, iov
, 3, errp
);
1981 static int coroutine_fn
nbd_co_send_chunk_error(NBDClient
*client
,
1982 NBDRequest
*request
,
1988 NBDStructuredError chunk
;
1989 int nbd_err
= system_errno_to_nbd_errno(error
);
1990 struct iovec iov
[] = {
1992 {.iov_base
= &chunk
, .iov_len
= sizeof(chunk
)},
1993 {.iov_base
= (char *)msg
, .iov_len
= msg
? strlen(msg
) : 0},
1997 trace_nbd_co_send_chunk_error(request
->cookie
, nbd_err
,
1998 nbd_err_lookup(nbd_err
), msg
? msg
: "");
1999 set_be_chunk(client
, iov
, 3, NBD_REPLY_FLAG_DONE
,
2000 NBD_REPLY_TYPE_ERROR
, request
);
2001 stl_be_p(&chunk
.error
, nbd_err
);
2002 stw_be_p(&chunk
.message_length
, iov
[2].iov_len
);
2004 return nbd_co_send_iov(client
, iov
, 3, errp
);
2007 /* Do a sparse read and send the structured reply to the client.
2008 * Returns -errno if sending fails. blk_co_block_status_above() failure is
2009 * reported to the client, at which point this function succeeds.
2011 static int coroutine_fn
nbd_co_send_sparse_read(NBDClient
*client
,
2012 NBDRequest
*request
,
2019 NBDExport
*exp
= client
->exp
;
2020 size_t progress
= 0;
2022 assert(size
<= NBD_MAX_BUFFER_SIZE
);
2023 while (progress
< size
) {
2025 int status
= blk_co_block_status_above(exp
->common
.blk
, NULL
,
2027 size
- progress
, &pnum
, NULL
,
2032 char *msg
= g_strdup_printf("unable to check for holes: %s",
2035 ret
= nbd_co_send_chunk_error(client
, request
, -status
, msg
, errp
);
2039 assert(pnum
&& pnum
<= size
- progress
);
2040 final
= progress
+ pnum
== size
;
2041 if (status
& BDRV_BLOCK_ZERO
) {
2043 NBDStructuredReadHole chunk
;
2044 struct iovec iov
[] = {
2046 {.iov_base
= &chunk
, .iov_len
= sizeof(chunk
)},
2049 trace_nbd_co_send_chunk_read_hole(request
->cookie
,
2050 offset
+ progress
, pnum
);
2051 set_be_chunk(client
, iov
, 2,
2052 final
? NBD_REPLY_FLAG_DONE
: 0,
2053 NBD_REPLY_TYPE_OFFSET_HOLE
, request
);
2054 stq_be_p(&chunk
.offset
, offset
+ progress
);
2055 stl_be_p(&chunk
.length
, pnum
);
2056 ret
= nbd_co_send_iov(client
, iov
, 2, errp
);
2058 ret
= blk_co_pread(exp
->common
.blk
, offset
+ progress
, pnum
,
2059 data
+ progress
, 0);
2061 error_setg_errno(errp
, -ret
, "reading from file failed");
2064 ret
= nbd_co_send_chunk_read(client
, request
, offset
+ progress
,
2065 data
+ progress
, pnum
, final
, errp
);
2076 typedef struct NBDExtentArray
{
2077 NBDExtent32
*extents
;
2078 unsigned int nb_alloc
;
2080 uint64_t total_length
;
2082 bool converted_to_be
;
2085 static NBDExtentArray
*nbd_extent_array_new(unsigned int nb_alloc
)
2087 NBDExtentArray
*ea
= g_new0(NBDExtentArray
, 1);
2089 ea
->nb_alloc
= nb_alloc
;
2090 ea
->extents
= g_new(NBDExtent32
, nb_alloc
);
2096 static void nbd_extent_array_free(NBDExtentArray
*ea
)
2098 g_free(ea
->extents
);
2101 G_DEFINE_AUTOPTR_CLEANUP_FUNC(NBDExtentArray
, nbd_extent_array_free
)
2103 /* Further modifications of the array after conversion are abandoned */
2104 static void nbd_extent_array_convert_to_be(NBDExtentArray
*ea
)
2108 assert(!ea
->converted_to_be
);
2109 ea
->can_add
= false;
2110 ea
->converted_to_be
= true;
2112 for (i
= 0; i
< ea
->count
; i
++) {
2113 ea
->extents
[i
].flags
= cpu_to_be32(ea
->extents
[i
].flags
);
2114 ea
->extents
[i
].length
= cpu_to_be32(ea
->extents
[i
].length
);
2119 * Add extent to NBDExtentArray. If extent can't be added (no available space),
2121 * For safety, when returning -1 for the first time, .can_add is set to false,
2122 * and further calls to nbd_extent_array_add() will crash.
2123 * (this avoids the situation where a caller ignores failure to add one extent,
2124 * where adding another extent that would squash into the last array entry
2125 * would result in an incorrect range reported to the client)
2127 static int nbd_extent_array_add(NBDExtentArray
*ea
,
2128 uint32_t length
, uint32_t flags
)
2130 assert(ea
->can_add
);
2136 /* Extend previous extent if flags are the same */
2137 if (ea
->count
> 0 && flags
== ea
->extents
[ea
->count
- 1].flags
) {
2138 uint64_t sum
= (uint64_t)length
+ ea
->extents
[ea
->count
- 1].length
;
2140 if (sum
<= UINT32_MAX
) {
2141 ea
->extents
[ea
->count
- 1].length
= sum
;
2142 ea
->total_length
+= length
;
2147 if (ea
->count
>= ea
->nb_alloc
) {
2148 ea
->can_add
= false;
2152 ea
->total_length
+= length
;
2153 ea
->extents
[ea
->count
] = (NBDExtent32
) {.length
= length
, .flags
= flags
};
2159 static int coroutine_fn
blockstatus_to_extents(BlockBackend
*blk
,
2160 uint64_t offset
, uint64_t bytes
,
2166 int ret
= blk_co_block_status_above(blk
, NULL
, offset
, bytes
, &num
,
2173 flags
= (ret
& BDRV_BLOCK_DATA
? 0 : NBD_STATE_HOLE
) |
2174 (ret
& BDRV_BLOCK_ZERO
? NBD_STATE_ZERO
: 0);
2176 if (nbd_extent_array_add(ea
, num
, flags
) < 0) {
2187 static int coroutine_fn
blockalloc_to_extents(BlockBackend
*blk
,
2188 uint64_t offset
, uint64_t bytes
,
2193 int ret
= blk_co_is_allocated_above(blk
, NULL
, false, offset
, bytes
,
2200 if (nbd_extent_array_add(ea
, num
, ret
) < 0) {
2212 * nbd_co_send_extents
2214 * @ea is converted to BE by the function
2215 * @last controls whether NBD_REPLY_FLAG_DONE is sent.
2217 static int coroutine_fn
2218 nbd_co_send_extents(NBDClient
*client
, NBDRequest
*request
, NBDExtentArray
*ea
,
2219 bool last
, uint32_t context_id
, Error
**errp
)
2222 NBDStructuredMeta chunk
;
2223 struct iovec iov
[] = {
2225 {.iov_base
= &chunk
, .iov_len
= sizeof(chunk
)},
2226 {.iov_base
= ea
->extents
, .iov_len
= ea
->count
* sizeof(ea
->extents
[0])}
2229 nbd_extent_array_convert_to_be(ea
);
2231 trace_nbd_co_send_extents(request
->cookie
, ea
->count
, context_id
,
2232 ea
->total_length
, last
);
2233 set_be_chunk(client
, iov
, 3, last
? NBD_REPLY_FLAG_DONE
: 0,
2234 NBD_REPLY_TYPE_BLOCK_STATUS
, request
);
2235 stl_be_p(&chunk
.context_id
, context_id
);
2237 return nbd_co_send_iov(client
, iov
, 3, errp
);
2240 /* Get block status from the exported device and send it to the client */
2242 coroutine_fn
nbd_co_send_block_status(NBDClient
*client
, NBDRequest
*request
,
2243 BlockBackend
*blk
, uint64_t offset
,
2244 uint32_t length
, bool dont_fragment
,
2245 bool last
, uint32_t context_id
,
2249 unsigned int nb_extents
= dont_fragment
? 1 : NBD_MAX_BLOCK_STATUS_EXTENTS
;
2250 g_autoptr(NBDExtentArray
) ea
= nbd_extent_array_new(nb_extents
);
2252 if (context_id
== NBD_META_ID_BASE_ALLOCATION
) {
2253 ret
= blockstatus_to_extents(blk
, offset
, length
, ea
);
2255 ret
= blockalloc_to_extents(blk
, offset
, length
, ea
);
2258 return nbd_co_send_chunk_error(client
, request
, -ret
,
2259 "can't get block status", errp
);
2262 return nbd_co_send_extents(client
, request
, ea
, last
, context_id
, errp
);
2265 /* Populate @ea from a dirty bitmap. */
2266 static void bitmap_to_extents(BdrvDirtyBitmap
*bitmap
,
2267 uint64_t offset
, uint64_t length
,
2270 int64_t start
, dirty_start
, dirty_count
;
2271 int64_t end
= offset
+ length
;
2274 bdrv_dirty_bitmap_lock(bitmap
);
2276 for (start
= offset
;
2277 bdrv_dirty_bitmap_next_dirty_area(bitmap
, start
, end
, INT32_MAX
,
2278 &dirty_start
, &dirty_count
);
2279 start
= dirty_start
+ dirty_count
)
2281 if ((nbd_extent_array_add(es
, dirty_start
- start
, 0) < 0) ||
2282 (nbd_extent_array_add(es
, dirty_count
, NBD_STATE_DIRTY
) < 0))
2290 /* last non dirty extent, nothing to do if array is now full */
2291 (void) nbd_extent_array_add(es
, end
- start
, 0);
2294 bdrv_dirty_bitmap_unlock(bitmap
);
2297 static int coroutine_fn
nbd_co_send_bitmap(NBDClient
*client
,
2298 NBDRequest
*request
,
2299 BdrvDirtyBitmap
*bitmap
,
2301 uint32_t length
, bool dont_fragment
,
2302 bool last
, uint32_t context_id
,
2305 unsigned int nb_extents
= dont_fragment
? 1 : NBD_MAX_BLOCK_STATUS_EXTENTS
;
2306 g_autoptr(NBDExtentArray
) ea
= nbd_extent_array_new(nb_extents
);
2308 bitmap_to_extents(bitmap
, offset
, length
, ea
);
2310 return nbd_co_send_extents(client
, request
, ea
, last
, context_id
, errp
);
2313 /* nbd_co_receive_request
2314 * Collect a client request. Return 0 if request looks valid, -EIO to drop
2315 * connection right away, -EAGAIN to indicate we were interrupted and the
2316 * channel should be quiesced, and any other negative value to report an error
2317 * to the client (although the caller may still need to disconnect after
2318 * reporting the error).
2320 static int coroutine_fn
nbd_co_receive_request(NBDRequestData
*req
,
2321 NBDRequest
*request
,
2324 NBDClient
*client
= req
->client
;
2325 bool check_length
= false;
2326 bool check_rofs
= false;
2327 bool allocate_buffer
= false;
2328 unsigned payload_len
= 0;
2329 int valid_flags
= NBD_CMD_FLAG_FUA
;
2332 g_assert(qemu_in_coroutine());
2333 assert(client
->recv_coroutine
== qemu_coroutine_self());
2334 ret
= nbd_receive_request(client
, request
, errp
);
2339 trace_nbd_co_receive_request_decode_type(request
->cookie
, request
->type
,
2340 nbd_cmd_lookup(request
->type
));
2341 switch (request
->type
) {
2343 /* Special case: we're going to disconnect without a reply,
2344 * whether or not flags, from, or len are bogus */
2345 req
->complete
= true;
2349 if (client
->mode
>= NBD_MODE_STRUCTURED
) {
2350 valid_flags
|= NBD_CMD_FLAG_DF
;
2352 check_length
= true;
2353 allocate_buffer
= true;
2357 payload_len
= request
->len
;
2358 check_length
= true;
2359 allocate_buffer
= true;
2371 check_length
= true;
2374 case NBD_CMD_WRITE_ZEROES
:
2375 valid_flags
|= NBD_CMD_FLAG_NO_HOLE
| NBD_CMD_FLAG_FAST_ZERO
;
2379 case NBD_CMD_BLOCK_STATUS
:
2380 valid_flags
|= NBD_CMD_FLAG_REQ_ONE
;
2384 /* Unrecognized, will fail later */
2388 /* Payload and buffer handling. */
2390 req
->complete
= true;
2392 if (check_length
&& request
->len
> NBD_MAX_BUFFER_SIZE
) {
2393 /* READ, WRITE, CACHE */
2394 error_setg(errp
, "len (%" PRIu64
") is larger than max len (%u)",
2395 request
->len
, NBD_MAX_BUFFER_SIZE
);
2398 if (allocate_buffer
) {
2400 req
->data
= blk_try_blockalign(client
->exp
->common
.blk
,
2402 if (req
->data
== NULL
) {
2403 error_setg(errp
, "No memory");
2410 ret
= nbd_read(client
->ioc
, req
->data
, payload_len
,
2411 "CMD_WRITE data", errp
);
2415 req
->complete
= true;
2416 trace_nbd_co_receive_request_payload_received(request
->cookie
,
2420 /* Sanity checks. */
2421 if (client
->exp
->nbdflags
& NBD_FLAG_READ_ONLY
&& check_rofs
) {
2422 /* WRITE, TRIM, WRITE_ZEROES */
2423 error_setg(errp
, "Export is read-only");
2426 if (request
->from
> client
->exp
->size
||
2427 request
->len
> client
->exp
->size
- request
->from
) {
2428 error_setg(errp
, "operation past EOF; From: %" PRIu64
", Len: %" PRIu64
2429 ", Size: %" PRIu64
, request
->from
, request
->len
,
2431 return (request
->type
== NBD_CMD_WRITE
||
2432 request
->type
== NBD_CMD_WRITE_ZEROES
) ? -ENOSPC
: -EINVAL
;
2434 if (client
->check_align
&& !QEMU_IS_ALIGNED(request
->from
| request
->len
,
2435 client
->check_align
)) {
2437 * The block layer gracefully handles unaligned requests, but
2438 * it's still worth tracing client non-compliance
2440 trace_nbd_co_receive_align_compliance(nbd_cmd_lookup(request
->type
),
2443 client
->check_align
);
2445 if (request
->flags
& ~valid_flags
) {
2446 error_setg(errp
, "unsupported flags for command %s (got 0x%x)",
2447 nbd_cmd_lookup(request
->type
), request
->flags
);
2454 /* Send simple reply without a payload, or a structured error
2455 * @error_msg is ignored if @ret >= 0
2456 * Returns 0 if connection is still live, -errno on failure to talk to client
2458 static coroutine_fn
int nbd_send_generic_reply(NBDClient
*client
,
2459 NBDRequest
*request
,
2461 const char *error_msg
,
2464 if (client
->mode
>= NBD_MODE_STRUCTURED
&& ret
< 0) {
2465 return nbd_co_send_chunk_error(client
, request
, -ret
, error_msg
, errp
);
2467 return nbd_co_send_simple_reply(client
, request
, ret
< 0 ? -ret
: 0,
2472 /* Handle NBD_CMD_READ request.
2473 * Return -errno if sending fails. Other errors are reported directly to the
2474 * client as an error reply. */
2475 static coroutine_fn
int nbd_do_cmd_read(NBDClient
*client
, NBDRequest
*request
,
2476 uint8_t *data
, Error
**errp
)
2479 NBDExport
*exp
= client
->exp
;
2481 assert(request
->type
== NBD_CMD_READ
);
2482 assert(request
->len
<= NBD_MAX_BUFFER_SIZE
);
2484 /* XXX: NBD Protocol only documents use of FUA with WRITE */
2485 if (request
->flags
& NBD_CMD_FLAG_FUA
) {
2486 ret
= blk_co_flush(exp
->common
.blk
);
2488 return nbd_send_generic_reply(client
, request
, ret
,
2489 "flush failed", errp
);
2493 if (client
->mode
>= NBD_MODE_STRUCTURED
&&
2494 !(request
->flags
& NBD_CMD_FLAG_DF
) && request
->len
)
2496 return nbd_co_send_sparse_read(client
, request
, request
->from
,
2497 data
, request
->len
, errp
);
2500 ret
= blk_co_pread(exp
->common
.blk
, request
->from
, request
->len
, data
, 0);
2502 return nbd_send_generic_reply(client
, request
, ret
,
2503 "reading from file failed", errp
);
2506 if (client
->mode
>= NBD_MODE_STRUCTURED
) {
2508 return nbd_co_send_chunk_read(client
, request
, request
->from
, data
,
2509 request
->len
, true, errp
);
2511 return nbd_co_send_chunk_done(client
, request
, errp
);
2514 return nbd_co_send_simple_reply(client
, request
, 0,
2515 data
, request
->len
, errp
);
2522 * Handle NBD_CMD_CACHE request.
2523 * Return -errno if sending fails. Other errors are reported directly to the
2524 * client as an error reply.
2526 static coroutine_fn
int nbd_do_cmd_cache(NBDClient
*client
, NBDRequest
*request
,
2530 NBDExport
*exp
= client
->exp
;
2532 assert(request
->type
== NBD_CMD_CACHE
);
2533 assert(request
->len
<= NBD_MAX_BUFFER_SIZE
);
2535 ret
= blk_co_preadv(exp
->common
.blk
, request
->from
, request
->len
,
2536 NULL
, BDRV_REQ_COPY_ON_READ
| BDRV_REQ_PREFETCH
);
2538 return nbd_send_generic_reply(client
, request
, ret
,
2539 "caching data failed", errp
);
2542 /* Handle NBD request.
2543 * Return -errno if sending fails. Other errors are reported directly to the
2544 * client as an error reply. */
2545 static coroutine_fn
int nbd_handle_request(NBDClient
*client
,
2546 NBDRequest
*request
,
2547 uint8_t *data
, Error
**errp
)
2551 NBDExport
*exp
= client
->exp
;
2555 switch (request
->type
) {
2557 return nbd_do_cmd_cache(client
, request
, errp
);
2560 return nbd_do_cmd_read(client
, request
, data
, errp
);
2564 if (request
->flags
& NBD_CMD_FLAG_FUA
) {
2565 flags
|= BDRV_REQ_FUA
;
2567 assert(request
->len
<= NBD_MAX_BUFFER_SIZE
);
2568 ret
= blk_co_pwrite(exp
->common
.blk
, request
->from
, request
->len
, data
,
2570 return nbd_send_generic_reply(client
, request
, ret
,
2571 "writing to file failed", errp
);
2573 case NBD_CMD_WRITE_ZEROES
:
2575 if (request
->flags
& NBD_CMD_FLAG_FUA
) {
2576 flags
|= BDRV_REQ_FUA
;
2578 if (!(request
->flags
& NBD_CMD_FLAG_NO_HOLE
)) {
2579 flags
|= BDRV_REQ_MAY_UNMAP
;
2581 if (request
->flags
& NBD_CMD_FLAG_FAST_ZERO
) {
2582 flags
|= BDRV_REQ_NO_FALLBACK
;
2584 ret
= blk_co_pwrite_zeroes(exp
->common
.blk
, request
->from
, request
->len
,
2586 return nbd_send_generic_reply(client
, request
, ret
,
2587 "writing to file failed", errp
);
2590 /* unreachable, thanks to special case in nbd_co_receive_request() */
2594 ret
= blk_co_flush(exp
->common
.blk
);
2595 return nbd_send_generic_reply(client
, request
, ret
,
2596 "flush failed", errp
);
2599 ret
= blk_co_pdiscard(exp
->common
.blk
, request
->from
, request
->len
);
2600 if (ret
>= 0 && request
->flags
& NBD_CMD_FLAG_FUA
) {
2601 ret
= blk_co_flush(exp
->common
.blk
);
2603 return nbd_send_generic_reply(client
, request
, ret
,
2604 "discard failed", errp
);
2606 case NBD_CMD_BLOCK_STATUS
:
2607 if (!request
->len
) {
2608 return nbd_send_generic_reply(client
, request
, -EINVAL
,
2609 "need non-zero length", errp
);
2611 assert(request
->len
<= UINT32_MAX
);
2612 if (client
->export_meta
.count
) {
2613 bool dont_fragment
= request
->flags
& NBD_CMD_FLAG_REQ_ONE
;
2614 int contexts_remaining
= client
->export_meta
.count
;
2616 if (client
->export_meta
.base_allocation
) {
2617 ret
= nbd_co_send_block_status(client
, request
,
2620 request
->len
, dont_fragment
,
2621 !--contexts_remaining
,
2622 NBD_META_ID_BASE_ALLOCATION
,
2629 if (client
->export_meta
.allocation_depth
) {
2630 ret
= nbd_co_send_block_status(client
, request
,
2632 request
->from
, request
->len
,
2634 !--contexts_remaining
,
2635 NBD_META_ID_ALLOCATION_DEPTH
,
2642 for (i
= 0; i
< client
->exp
->nr_export_bitmaps
; i
++) {
2643 if (!client
->export_meta
.bitmaps
[i
]) {
2646 ret
= nbd_co_send_bitmap(client
, request
,
2647 client
->exp
->export_bitmaps
[i
],
2648 request
->from
, request
->len
,
2649 dont_fragment
, !--contexts_remaining
,
2650 NBD_META_ID_DIRTY_BITMAP
+ i
, errp
);
2656 assert(!contexts_remaining
);
2660 return nbd_send_generic_reply(client
, request
, -EINVAL
,
2661 "CMD_BLOCK_STATUS not negotiated",
2666 msg
= g_strdup_printf("invalid request type (%" PRIu32
") received",
2668 ret
= nbd_send_generic_reply(client
, request
, -EINVAL
, msg
,
2675 /* Owns a reference to the NBDClient passed as opaque. */
2676 static coroutine_fn
void nbd_trip(void *opaque
)
2678 NBDClient
*client
= opaque
;
2679 NBDRequestData
*req
;
2680 NBDRequest request
= { 0 }; /* GCC thinks it can be used uninitialized */
2682 Error
*local_err
= NULL
;
2685 if (client
->closing
) {
2686 nbd_client_put(client
);
2690 if (client
->quiescing
) {
2692 * We're switching between AIO contexts. Don't attempt to receive a new
2693 * request and kick the main context which may be waiting for us.
2695 nbd_client_put(client
);
2696 client
->recv_coroutine
= NULL
;
2701 req
= nbd_request_get(client
);
2702 ret
= nbd_co_receive_request(req
, &request
, &local_err
);
2703 client
->recv_coroutine
= NULL
;
2705 if (client
->closing
) {
2707 * The client may be closed when we are blocked in
2708 * nbd_co_receive_request()
2713 if (ret
== -EAGAIN
) {
2714 assert(client
->quiescing
);
2718 nbd_client_receive_next_request(client
);
2723 qio_channel_set_cork(client
->ioc
, true);
2726 /* It wasn't -EIO, so, according to nbd_co_receive_request()
2727 * semantics, we should return the error to the client. */
2728 Error
*export_err
= local_err
;
2731 ret
= nbd_send_generic_reply(client
, &request
, -EINVAL
,
2732 error_get_pretty(export_err
), &local_err
);
2733 error_free(export_err
);
2735 ret
= nbd_handle_request(client
, &request
, req
->data
, &local_err
);
2738 error_prepend(&local_err
, "Failed to send reply: ");
2742 /* We must disconnect after NBD_CMD_WRITE if we did not
2745 if (!req
->complete
) {
2746 error_setg(&local_err
, "Request handling failed in intermediate state");
2750 qio_channel_set_cork(client
->ioc
, false);
2752 nbd_request_put(req
);
2753 nbd_client_put(client
);
2758 error_reportf_err(local_err
, "Disconnect client, due to: ");
2760 nbd_request_put(req
);
2761 client_close(client
, true);
2762 nbd_client_put(client
);
2765 static void nbd_client_receive_next_request(NBDClient
*client
)
2767 if (!client
->recv_coroutine
&& client
->nb_requests
< MAX_NBD_REQUESTS
&&
2768 !client
->quiescing
) {
2769 nbd_client_get(client
);
2770 client
->recv_coroutine
= qemu_coroutine_create(nbd_trip
, client
);
2771 aio_co_schedule(client
->exp
->common
.ctx
, client
->recv_coroutine
);
2775 static coroutine_fn
void nbd_co_client_start(void *opaque
)
2777 NBDClient
*client
= opaque
;
2778 Error
*local_err
= NULL
;
2780 qemu_co_mutex_init(&client
->send_lock
);
2782 if (nbd_negotiate(client
, &local_err
)) {
2784 error_report_err(local_err
);
2786 client_close(client
, false);
2790 nbd_client_receive_next_request(client
);
2794 * Create a new client listener using the given channel @sioc.
2795 * Begin servicing it in a coroutine. When the connection closes, call
2796 * @close_fn with an indication of whether the client completed negotiation.
2798 void nbd_client_new(QIOChannelSocket
*sioc
,
2799 QCryptoTLSCreds
*tlscreds
,
2800 const char *tlsauthz
,
2801 void (*close_fn
)(NBDClient
*, bool))
2806 client
= g_new0(NBDClient
, 1);
2807 client
->refcount
= 1;
2808 client
->tlscreds
= tlscreds
;
2810 object_ref(OBJECT(client
->tlscreds
));
2812 client
->tlsauthz
= g_strdup(tlsauthz
);
2813 client
->sioc
= sioc
;
2814 qio_channel_set_delay(QIO_CHANNEL(sioc
), false);
2815 object_ref(OBJECT(client
->sioc
));
2816 client
->ioc
= QIO_CHANNEL(sioc
);
2817 object_ref(OBJECT(client
->ioc
));
2818 client
->close_fn
= close_fn
;
2820 co
= qemu_coroutine_create(nbd_co_client_start
, client
);
2821 qemu_coroutine_enter(co
);