2 * Copyright (C) 2016-2018 Red Hat, Inc.
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/export.h"
23 #include "qapi/error.h"
24 #include "qemu/queue.h"
26 #include "nbd-internal.h"
27 #include "qemu/units.h"
29 #define NBD_META_ID_BASE_ALLOCATION 0
30 #define NBD_META_ID_DIRTY_BITMAP 1
33 * NBD_MAX_BLOCK_STATUS_EXTENTS: 1 MiB of extents data. An empirical
34 * constant. If an increase is needed, note that the NBD protocol
35 * recommends no larger than 32 mb, so that the client won't consider
36 * the reply as a denial of service attack.
38 #define NBD_MAX_BLOCK_STATUS_EXTENTS (1 * MiB / 8)
40 static int system_errno_to_nbd_errno(int err)
61 #if ENOTSUP != EOPNOTSUPP
73 /* Definitions for opaque data types */
75 typedef struct NBDRequestData NBDRequestData;
77 struct NBDRequestData {
78 QSIMPLEQ_ENTRY(NBDRequestData) entry;
87 void (*close)(NBDExport *exp);
95 QTAILQ_HEAD(, NBDClient) clients;
96 QTAILQ_ENTRY(NBDExport) next;
100 BlockBackend *eject_notifier_blk;
101 Notifier eject_notifier;
103 BdrvDirtyBitmap *export_bitmap;
104 char *export_bitmap_context;
107 static QTAILQ_HEAD(, NBDExport) exports = QTAILQ_HEAD_INITIALIZER(exports);
108 static QTAILQ_HEAD(, NBDExport) closed_exports =
109 QTAILQ_HEAD_INITIALIZER(closed_exports);
111 /* NBDExportMetaContexts represents a list of contexts to be exported,
112 * as selected by NBD_OPT_SET_META_CONTEXT. Also used for
113 * NBD_OPT_LIST_META_CONTEXT. */
114 typedef struct NBDExportMetaContexts {
116 bool valid; /* means that negotiation of the option finished without
118 bool base_allocation; /* export base:allocation context (block status) */
119 bool bitmap; /* export qemu:dirty-bitmap:<export bitmap name> */
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;
137 QTAILQ_ENTRY(NBDClient) next;
141 uint32_t check_align; /* If non-zero, check for aligned client requests */
143 bool structured_reply;
144 NBDExportMetaContexts export_meta;
146 uint32_t opt; /* Current option being negotiated */
147 uint32_t optlen; /* remaining length of data in ioc for the option being
151 static void nbd_client_receive_next_request(NBDClient *client);
153 /* Basic flow for negotiation
180 static inline void set_be_option_rep(NBDOptionReply *rep, uint32_t option,
181 uint32_t type, uint32_t length)
183 stq_be_p(&rep->magic, NBD_REP_MAGIC);
184 stl_be_p(&rep->option, option);
185 stl_be_p(&rep->type, type);
186 stl_be_p(&rep->length, length);
189 /* Send a reply header, including length, but no payload.
190 * Return -errno on error, 0 on success. */
191 static int nbd_negotiate_send_rep_len(NBDClient *client, uint32_t type,
192 uint32_t len, Error **errp)
196 trace_nbd_negotiate_send_rep_len(client->opt, nbd_opt_lookup(client->opt),
197 type, nbd_rep_lookup(type), len);
199 assert(len < NBD_MAX_BUFFER_SIZE);
201 set_be_option_rep(&rep, client->opt, type, len);
202 return nbd_write(client->ioc, &rep, sizeof(rep), errp);
205 /* Send a reply header with default 0 length.
206 * Return -errno on error, 0 on success. */
207 static int nbd_negotiate_send_rep(NBDClient *client, uint32_t type,
210 return nbd_negotiate_send_rep_len(client, type, 0, errp);
213 /* Send an error reply.
214 * Return -errno on error, 0 on success. */
215 static int GCC_FMT_ATTR(4, 0)
216 nbd_negotiate_send_rep_verr(NBDClient *client, uint32_t type,
217 Error **errp, const char *fmt, va_list va)
220 g_autofree char *msg = NULL;
224 msg = g_strdup_vprintf(fmt, va);
226 assert(len < NBD_MAX_STRING_SIZE);
227 trace_nbd_negotiate_send_rep_err(msg);
228 ret = nbd_negotiate_send_rep_len(client, type, len, errp);
232 if (nbd_write(client->ioc, msg, len, errp) < 0) {
233 error_prepend(errp, "write failed (error message): ");
241 * Return a malloc'd copy of @name suitable for use in an error reply.
244 nbd_sanitize_name(const char *name)
246 if (strnlen(name, 80) < 80) {
247 return g_strdup(name);
249 /* XXX Should we also try to sanitize any control characters? */
250 return g_strdup_printf("%.80s...", name);
253 /* Send an error reply.
254 * Return -errno on error, 0 on success. */
255 static int GCC_FMT_ATTR(4, 5)
256 nbd_negotiate_send_rep_err(NBDClient *client, uint32_t type,
257 Error **errp, const char *fmt, ...)
263 ret = nbd_negotiate_send_rep_verr(client, type, errp, fmt, va);
268 /* Drop remainder of the current option, and send a reply with the
269 * given error type and message. Return -errno on read or write
270 * failure; or 0 if connection is still live. */
271 static int GCC_FMT_ATTR(4, 0)
272 nbd_opt_vdrop(NBDClient *client, uint32_t type, Error **errp,
273 const char *fmt, va_list va)
275 int ret = nbd_drop(client->ioc, client->optlen, errp);
279 ret = nbd_negotiate_send_rep_verr(client, type, errp, fmt, va);
284 static int GCC_FMT_ATTR(4, 5)
285 nbd_opt_drop(NBDClient *client, uint32_t type, Error **errp,
286 const char *fmt, ...)
292 ret = nbd_opt_vdrop(client, type, errp, fmt, va);
298 static int GCC_FMT_ATTR(3, 4)
299 nbd_opt_invalid(NBDClient *client, Error **errp, const char *fmt, ...)
305 ret = nbd_opt_vdrop(client, NBD_REP_ERR_INVALID, errp, fmt, va);
311 /* Read size bytes from the unparsed payload of the current option.
312 * Return -errno on I/O error, 0 if option was completely handled by
313 * sending a reply about inconsistent lengths, or 1 on success. */
314 static int nbd_opt_read(NBDClient *client, void *buffer, size_t size,
317 if (size > client->optlen) {
318 return nbd_opt_invalid(client, errp,
319 "Inconsistent lengths in option %s",
320 nbd_opt_lookup(client->opt));
322 client->optlen -= size;
323 return qio_channel_read_all(client->ioc, buffer, size, errp) < 0 ? -EIO : 1;
326 /* Drop size bytes from the unparsed payload of the current option.
327 * Return -errno on I/O error, 0 if option was completely handled by
328 * sending a reply about inconsistent lengths, or 1 on success. */
329 static int nbd_opt_skip(NBDClient *client, size_t size, Error **errp)
331 if (size > client->optlen) {
332 return nbd_opt_invalid(client, errp,
333 "Inconsistent lengths in option %s",
334 nbd_opt_lookup(client->opt));
336 client->optlen -= size;
337 return nbd_drop(client->ioc, size, errp) < 0 ? -EIO : 1;
342 * Read a string with the format:
343 * uint32_t len (<= NBD_MAX_STRING_SIZE)
344 * len bytes string (not 0-terminated)
346 * On success, @name will be allocated.
347 * If @length is non-null, it will be set to the actual string length.
349 * Return -errno on I/O error, 0 if option was completely handled by
350 * sending a reply about inconsistent lengths, or 1 on success.
352 static int nbd_opt_read_name(NBDClient *client, char **name, uint32_t *length,
357 g_autofree char *local_name = NULL;
360 ret = nbd_opt_read(client, &len, sizeof(len), errp);
364 len = cpu_to_be32(len);
366 if (len > NBD_MAX_STRING_SIZE) {
367 return nbd_opt_invalid(client, errp,
368 "Invalid name length: %" PRIu32, len);
371 local_name = g_malloc(len + 1);
372 ret = nbd_opt_read(client, local_name, len, errp);
376 local_name[len] = '\0';
381 *name = g_steal_pointer(&local_name);
386 /* Send a single NBD_REP_SERVER reply to NBD_OPT_LIST, including payload.
387 * Return -errno on error, 0 on success. */
388 static int nbd_negotiate_send_rep_list(NBDClient *client, NBDExport *exp,
392 size_t name_len, desc_len;
394 const char *name = exp->name ? exp->name : "";
395 const char *desc = exp->description ? exp->description : "";
396 QIOChannel *ioc = client->ioc;
399 trace_nbd_negotiate_send_rep_list(name, desc);
400 name_len = strlen(name);
401 desc_len = strlen(desc);
402 assert(name_len <= NBD_MAX_STRING_SIZE && desc_len <= NBD_MAX_STRING_SIZE);
403 len = name_len + desc_len + sizeof(len);
404 ret = nbd_negotiate_send_rep_len(client, NBD_REP_SERVER, len, errp);
409 len = cpu_to_be32(name_len);
410 if (nbd_write(ioc, &len, sizeof(len), errp) < 0) {
411 error_prepend(errp, "write failed (name length): ");
415 if (nbd_write(ioc, name, name_len, errp) < 0) {
416 error_prepend(errp, "write failed (name buffer): ");
420 if (nbd_write(ioc, desc, desc_len, errp) < 0) {
421 error_prepend(errp, "write failed (description buffer): ");
428 /* Process the NBD_OPT_LIST command, with a potential series of replies.
429 * Return -errno on error, 0 on success. */
430 static int nbd_negotiate_handle_list(NBDClient *client, Error **errp)
433 assert(client->opt == NBD_OPT_LIST);
435 /* For each export, send a NBD_REP_SERVER reply. */
436 QTAILQ_FOREACH(exp, &exports, next) {
437 if (nbd_negotiate_send_rep_list(client, exp, errp)) {
441 /* Finish with a NBD_REP_ACK. */
442 return nbd_negotiate_send_rep(client, NBD_REP_ACK, errp);
445 static void nbd_check_meta_export(NBDClient *client)
447 client->export_meta.valid &= client->exp == client->export_meta.exp;
450 /* Send a reply to NBD_OPT_EXPORT_NAME.
451 * Return -errno on error, 0 on success. */
452 static int nbd_negotiate_handle_export_name(NBDClient *client, bool no_zeroes,
456 g_autofree char *name = NULL;
457 char buf[NBD_REPLY_EXPORT_NAME_SIZE] = "";
463 [20 .. xx] export name (length bytes)
466 [ 8 .. 9] export flags
467 [10 .. 133] reserved (0) [unless no_zeroes]
469 trace_nbd_negotiate_handle_export_name();
470 if (client->optlen > NBD_MAX_STRING_SIZE) {
471 error_setg(errp, "Bad length received");
474 name = g_malloc(client->optlen + 1);
475 if (nbd_read(client->ioc, name, client->optlen, "export name", errp) < 0) {
478 name[client->optlen] = '\0';
481 trace_nbd_negotiate_handle_export_name_request(name);
483 client->exp = nbd_export_find(name);
485 error_setg(errp, "export not found");
489 myflags = client->exp->nbdflags;
490 if (client->structured_reply) {
491 myflags |= NBD_FLAG_SEND_DF;
493 trace_nbd_negotiate_new_style_size_flags(client->exp->size, myflags);
494 stq_be_p(buf, client->exp->size);
495 stw_be_p(buf + 8, myflags);
496 len = no_zeroes ? 10 : sizeof(buf);
497 ret = nbd_write(client->ioc, buf, len, errp);
499 error_prepend(errp, "write failed: ");
503 QTAILQ_INSERT_TAIL(&client->exp->clients, client, next);
504 nbd_export_get(client->exp);
505 nbd_check_meta_export(client);
510 /* Send a single NBD_REP_INFO, with a buffer @buf of @length bytes.
511 * The buffer does NOT include the info type prefix.
512 * Return -errno on error, 0 if ready to send more. */
513 static int nbd_negotiate_send_info(NBDClient *client,
514 uint16_t info, uint32_t length, void *buf,
519 trace_nbd_negotiate_send_info(info, nbd_info_lookup(info), length);
520 rc = nbd_negotiate_send_rep_len(client, NBD_REP_INFO,
521 sizeof(info) + length, errp);
525 info = cpu_to_be16(info);
526 if (nbd_write(client->ioc, &info, sizeof(info), errp) < 0) {
529 if (nbd_write(client->ioc, buf, length, errp) < 0) {
535 /* nbd_reject_length: Handle any unexpected payload.
536 * @fatal requests that we quit talking to the client, even if we are able
537 * to successfully send an error reply.
539 * -errno transmission error occurred or @fatal was requested, errp is set
540 * 0 error message successfully sent to client, errp is not set
542 static int nbd_reject_length(NBDClient *client, bool fatal, Error **errp)
546 assert(client->optlen);
547 ret = nbd_opt_invalid(client, errp, "option '%s' has unexpected length",
548 nbd_opt_lookup(client->opt));
550 error_setg(errp, "option '%s' has unexpected length",
551 nbd_opt_lookup(client->opt));
557 /* Handle NBD_OPT_INFO and NBD_OPT_GO.
558 * Return -errno on error, 0 if ready for next option, and 1 to move
559 * into transmission phase. */
560 static int nbd_negotiate_handle_info(NBDClient *client, Error **errp)
563 g_autofree char *name = NULL;
568 bool sendname = false;
569 bool blocksize = false;
571 char buf[sizeof(uint64_t) + sizeof(uint16_t)];
572 uint32_t check_align = 0;
576 4 bytes: L, name length (can be 0)
578 2 bytes: N, number of requests (can be 0)
579 N * 2 bytes: N requests
581 rc = nbd_opt_read_name(client, &name, &namelen, errp);
585 trace_nbd_negotiate_handle_export_name_request(name);
587 rc = nbd_opt_read(client, &requests, sizeof(requests), errp);
591 requests = be16_to_cpu(requests);
592 trace_nbd_negotiate_handle_info_requests(requests);
594 rc = nbd_opt_read(client, &request, sizeof(request), errp);
598 request = be16_to_cpu(request);
599 trace_nbd_negotiate_handle_info_request(request,
600 nbd_info_lookup(request));
601 /* We care about NBD_INFO_NAME and NBD_INFO_BLOCK_SIZE;
602 * everything else is either a request we don't know or
603 * something we send regardless of request */
608 case NBD_INFO_BLOCK_SIZE:
613 if (client->optlen) {
614 return nbd_reject_length(client, false, errp);
617 exp = nbd_export_find(name);
619 g_autofree char *sane_name = nbd_sanitize_name(name);
621 return nbd_negotiate_send_rep_err(client, NBD_REP_ERR_UNKNOWN,
622 errp, "export '%s' not present",
626 /* Don't bother sending NBD_INFO_NAME unless client requested it */
628 rc = nbd_negotiate_send_info(client, NBD_INFO_NAME, namelen, name,
635 /* Send NBD_INFO_DESCRIPTION only if available, regardless of
637 if (exp->description) {
638 size_t len = strlen(exp->description);
640 assert(len <= NBD_MAX_STRING_SIZE);
641 rc = nbd_negotiate_send_info(client, NBD_INFO_DESCRIPTION,
642 len, exp->description, errp);
648 /* Send NBD_INFO_BLOCK_SIZE always, but tweak the minimum size
649 * according to whether the client requested it, and according to
650 * whether this is OPT_INFO or OPT_GO. */
651 /* minimum - 1 for back-compat, or actual if client will obey it. */
652 if (client->opt == NBD_OPT_INFO || blocksize) {
653 check_align = sizes[0] = blk_get_request_alignment(exp->blk);
657 assert(sizes[0] <= NBD_MAX_BUFFER_SIZE);
658 /* preferred - Hard-code to 4096 for now.
659 * TODO: is blk_bs(blk)->bl.opt_transfer appropriate? */
660 sizes[1] = MAX(4096, sizes[0]);
661 /* maximum - At most 32M, but smaller as appropriate. */
662 sizes[2] = MIN(blk_get_max_transfer(exp->blk), NBD_MAX_BUFFER_SIZE);
663 trace_nbd_negotiate_handle_info_block_size(sizes[0], sizes[1], sizes[2]);
664 sizes[0] = cpu_to_be32(sizes[0]);
665 sizes[1] = cpu_to_be32(sizes[1]);
666 sizes[2] = cpu_to_be32(sizes[2]);
667 rc = nbd_negotiate_send_info(client, NBD_INFO_BLOCK_SIZE,
668 sizeof(sizes), sizes, errp);
673 /* Send NBD_INFO_EXPORT always */
674 myflags = exp->nbdflags;
675 if (client->structured_reply) {
676 myflags |= NBD_FLAG_SEND_DF;
678 trace_nbd_negotiate_new_style_size_flags(exp->size, myflags);
679 stq_be_p(buf, exp->size);
680 stw_be_p(buf + 8, myflags);
681 rc = nbd_negotiate_send_info(client, NBD_INFO_EXPORT,
682 sizeof(buf), buf, errp);
688 * If the client is just asking for NBD_OPT_INFO, but forgot to
689 * request block sizes in a situation that would impact
690 * performance, then return an error. But for NBD_OPT_GO, we
691 * tolerate all clients, regardless of alignments.
693 if (client->opt == NBD_OPT_INFO && !blocksize &&
694 blk_get_request_alignment(exp->blk) > 1) {
695 return nbd_negotiate_send_rep_err(client,
696 NBD_REP_ERR_BLOCK_SIZE_REQD,
698 "request NBD_INFO_BLOCK_SIZE to "
703 rc = nbd_negotiate_send_rep(client, NBD_REP_ACK, errp);
708 if (client->opt == NBD_OPT_GO) {
710 client->check_align = check_align;
711 QTAILQ_INSERT_TAIL(&client->exp->clients, client, next);
712 nbd_export_get(client->exp);
713 nbd_check_meta_export(client);
720 /* Handle NBD_OPT_STARTTLS. Return NULL to drop connection, or else the
721 * new channel for all further (now-encrypted) communication. */
722 static QIOChannel *nbd_negotiate_handle_starttls(NBDClient *client,
727 struct NBDTLSHandshakeData data = { 0 };
729 assert(client->opt == NBD_OPT_STARTTLS);
731 trace_nbd_negotiate_handle_starttls();
734 if (nbd_negotiate_send_rep(client, NBD_REP_ACK, errp) < 0) {
738 tioc = qio_channel_tls_new_server(ioc,
746 qio_channel_set_name(QIO_CHANNEL(tioc), "nbd-server-tls");
747 trace_nbd_negotiate_handle_starttls_handshake();
748 data.loop = g_main_loop_new(g_main_context_default(), FALSE);
749 qio_channel_tls_handshake(tioc,
755 if (!data.complete) {
756 g_main_loop_run(data.loop);
758 g_main_loop_unref(data.loop);
760 object_unref(OBJECT(tioc));
761 error_propagate(errp, data.error);
765 return QIO_CHANNEL(tioc);
768 /* nbd_negotiate_send_meta_context
770 * Send one chunk of reply to NBD_OPT_{LIST,SET}_META_CONTEXT
772 * For NBD_OPT_LIST_META_CONTEXT @context_id is ignored, 0 is used instead.
774 static int nbd_negotiate_send_meta_context(NBDClient *client,
779 NBDOptionReplyMetaContext opt;
780 struct iovec iov[] = {
781 {.iov_base = &opt, .iov_len = sizeof(opt)},
782 {.iov_base = (void *)context, .iov_len = strlen(context)}
785 assert(iov[1].iov_len <= NBD_MAX_STRING_SIZE);
786 if (client->opt == NBD_OPT_LIST_META_CONTEXT) {
790 trace_nbd_negotiate_meta_query_reply(context, context_id);
791 set_be_option_rep(&opt.h, client->opt, NBD_REP_META_CONTEXT,
792 sizeof(opt) - sizeof(opt.h) + iov[1].iov_len);
793 stl_be_p(&opt.context_id, context_id);
795 return qio_channel_writev_all(client->ioc, iov, 2, errp) < 0 ? -EIO : 0;
798 /* Read strlen(@pattern) bytes, and set @match to true if they match @pattern.
799 * @match is never set to false.
801 * Return -errno on I/O error, 0 if option was completely handled by
802 * sending a reply about inconsistent lengths, or 1 on success.
804 * Note: return code = 1 doesn't mean that we've read exactly @pattern.
805 * It only means that there are no errors.
807 static int nbd_meta_pattern(NBDClient *client, const char *pattern, bool *match,
812 size_t len = strlen(pattern);
816 query = g_malloc(len);
817 ret = nbd_opt_read(client, query, len, errp);
823 if (strncmp(query, pattern, len) == 0) {
824 trace_nbd_negotiate_meta_query_parse(pattern);
827 trace_nbd_negotiate_meta_query_skip("pattern not matched");
835 * Read @len bytes, and set @match to true if they match @pattern, or if @len
836 * is 0 and the client is performing _LIST_. @match is never set to false.
838 * Return -errno on I/O error, 0 if option was completely handled by
839 * sending a reply about inconsistent lengths, or 1 on success.
841 * Note: return code = 1 doesn't mean that we've read exactly @pattern.
842 * It only means that there are no errors.
844 static int nbd_meta_empty_or_pattern(NBDClient *client, const char *pattern,
845 uint32_t len, bool *match, Error **errp)
848 if (client->opt == NBD_OPT_LIST_META_CONTEXT) {
851 trace_nbd_negotiate_meta_query_parse("empty");
855 if (len != strlen(pattern)) {
856 trace_nbd_negotiate_meta_query_skip("different lengths");
857 return nbd_opt_skip(client, len, errp);
860 return nbd_meta_pattern(client, pattern, match, errp);
863 /* nbd_meta_base_query
865 * Handle queries to 'base' namespace. For now, only the base:allocation
866 * context is available. 'len' is the amount of text remaining to be read from
867 * the current name, after the 'base:' portion has been stripped.
869 * Return -errno on I/O error, 0 if option was completely handled by
870 * sending a reply about inconsistent lengths, or 1 on success.
872 static int nbd_meta_base_query(NBDClient *client, NBDExportMetaContexts *meta,
873 uint32_t len, Error **errp)
875 return nbd_meta_empty_or_pattern(client, "allocation", len,
876 &meta->base_allocation, errp);
879 /* nbd_meta_bitmap_query
881 * Handle query to 'qemu:' namespace.
882 * @len is the amount of text remaining to be read from the current name, after
883 * the 'qemu:' portion has been stripped.
885 * Return -errno on I/O error, 0 if option was completely handled by
886 * sending a reply about inconsistent lengths, or 1 on success. */
887 static int nbd_meta_qemu_query(NBDClient *client, NBDExportMetaContexts *meta,
888 uint32_t len, Error **errp)
890 bool dirty_bitmap = false;
891 size_t dirty_bitmap_len = strlen("dirty-bitmap:");
894 if (!meta->exp->export_bitmap) {
895 trace_nbd_negotiate_meta_query_skip("no dirty-bitmap exported");
896 return nbd_opt_skip(client, len, errp);
900 if (client->opt == NBD_OPT_LIST_META_CONTEXT) {
903 trace_nbd_negotiate_meta_query_parse("empty");
907 if (len < dirty_bitmap_len) {
908 trace_nbd_negotiate_meta_query_skip("not dirty-bitmap:");
909 return nbd_opt_skip(client, len, errp);
912 len -= dirty_bitmap_len;
913 ret = nbd_meta_pattern(client, "dirty-bitmap:", &dirty_bitmap, errp);
918 trace_nbd_negotiate_meta_query_skip("not dirty-bitmap:");
919 return nbd_opt_skip(client, len, errp);
922 trace_nbd_negotiate_meta_query_parse("dirty-bitmap:");
924 return nbd_meta_empty_or_pattern(
925 client, meta->exp->export_bitmap_context +
926 strlen("qemu:dirty_bitmap:"), len, &meta->bitmap, errp);
929 /* nbd_negotiate_meta_query
931 * Parse namespace name and call corresponding function to parse body of the
934 * The only supported namespaces are 'base' and 'qemu'.
936 * The function aims not wasting time and memory to read long unknown namespace
939 * Return -errno on I/O error, 0 if option was completely handled by
940 * sending a reply about inconsistent lengths, or 1 on success. */
941 static int nbd_negotiate_meta_query(NBDClient *client,
942 NBDExportMetaContexts *meta, Error **errp)
945 * Both 'qemu' and 'base' namespaces have length = 5 including a
946 * colon. If another length namespace is later introduced, this
947 * should certainly be refactored.
954 ret = nbd_opt_read(client, &len, sizeof(len), errp);
958 len = cpu_to_be32(len);
960 if (len > NBD_MAX_STRING_SIZE) {
961 trace_nbd_negotiate_meta_query_skip("length too long");
962 return nbd_opt_skip(client, len, errp);
965 trace_nbd_negotiate_meta_query_skip("length too short");
966 return nbd_opt_skip(client, len, errp);
970 ret = nbd_opt_read(client, ns, ns_len, errp);
975 if (!strncmp(ns, "base:", ns_len)) {
976 trace_nbd_negotiate_meta_query_parse("base:");
977 return nbd_meta_base_query(client, meta, len, errp);
978 } else if (!strncmp(ns, "qemu:", ns_len)) {
979 trace_nbd_negotiate_meta_query_parse("qemu:");
980 return nbd_meta_qemu_query(client, meta, len, errp);
983 trace_nbd_negotiate_meta_query_skip("unknown namespace");
984 return nbd_opt_skip(client, len, errp);
987 /* nbd_negotiate_meta_queries
988 * Handle NBD_OPT_LIST_META_CONTEXT and NBD_OPT_SET_META_CONTEXT
990 * Return -errno on I/O error, or 0 if option was completely handled. */
991 static int nbd_negotiate_meta_queries(NBDClient *client,
992 NBDExportMetaContexts *meta, Error **errp)
995 g_autofree char *export_name = NULL;
996 NBDExportMetaContexts local_meta;
1000 if (!client->structured_reply) {
1001 return nbd_opt_invalid(client, errp,
1002 "request option '%s' when structured reply "
1003 "is not negotiated",
1004 nbd_opt_lookup(client->opt));
1007 if (client->opt == NBD_OPT_LIST_META_CONTEXT) {
1008 /* Only change the caller's meta on SET. */
1012 memset(meta, 0, sizeof(*meta));
1014 ret = nbd_opt_read_name(client, &export_name, NULL, errp);
1019 meta->exp = nbd_export_find(export_name);
1020 if (meta->exp == NULL) {
1021 g_autofree char *sane_name = nbd_sanitize_name(export_name);
1023 return nbd_opt_drop(client, NBD_REP_ERR_UNKNOWN, errp,
1024 "export '%s' not present", sane_name);
1027 ret = nbd_opt_read(client, &nb_queries, sizeof(nb_queries), errp);
1031 nb_queries = cpu_to_be32(nb_queries);
1032 trace_nbd_negotiate_meta_context(nbd_opt_lookup(client->opt),
1033 export_name, nb_queries);
1035 if (client->opt == NBD_OPT_LIST_META_CONTEXT && !nb_queries) {
1036 /* enable all known contexts */
1037 meta->base_allocation = true;
1038 meta->bitmap = !!meta->exp->export_bitmap;
1040 for (i = 0; i < nb_queries; ++i) {
1041 ret = nbd_negotiate_meta_query(client, meta, errp);
1048 if (meta->base_allocation) {
1049 ret = nbd_negotiate_send_meta_context(client, "base:allocation",
1050 NBD_META_ID_BASE_ALLOCATION,
1058 ret = nbd_negotiate_send_meta_context(client,
1059 meta->exp->export_bitmap_context,
1060 NBD_META_ID_DIRTY_BITMAP,
1067 ret = nbd_negotiate_send_rep(client, NBD_REP_ACK, errp);
1075 /* nbd_negotiate_options
1076 * Process all NBD_OPT_* client option commands, during fixed newstyle
1079 * -errno on error, errp is set
1080 * 0 on successful negotiation, errp is not set
1081 * 1 if client sent NBD_OPT_ABORT, i.e. on valid disconnect,
1084 static int nbd_negotiate_options(NBDClient *client, Error **errp)
1087 bool fixedNewstyle = false;
1088 bool no_zeroes = false;
1091 [ 0 .. 3] client flags
1093 Then we loop until NBD_OPT_EXPORT_NAME or NBD_OPT_GO:
1094 [ 0 .. 7] NBD_OPTS_MAGIC
1095 [ 8 .. 11] NBD option
1096 [12 .. 15] Data length
1099 [ 0 .. 7] NBD_OPTS_MAGIC
1100 [ 8 .. 11] Second NBD option
1101 [12 .. 15] Data length
1105 if (nbd_read32(client->ioc, &flags, "flags", errp) < 0) {
1108 trace_nbd_negotiate_options_flags(flags);
1109 if (flags & NBD_FLAG_C_FIXED_NEWSTYLE) {
1110 fixedNewstyle = true;
1111 flags &= ~NBD_FLAG_C_FIXED_NEWSTYLE;
1113 if (flags & NBD_FLAG_C_NO_ZEROES) {
1115 flags &= ~NBD_FLAG_C_NO_ZEROES;
1118 error_setg(errp, "Unknown client flags 0x%" PRIx32 " received", flags);
1124 uint32_t option, length;
1127 if (nbd_read64(client->ioc, &magic, "opts magic", errp) < 0) {
1130 trace_nbd_negotiate_options_check_magic(magic);
1131 if (magic != NBD_OPTS_MAGIC) {
1132 error_setg(errp, "Bad magic received");
1136 if (nbd_read32(client->ioc, &option, "option", errp) < 0) {
1139 client->opt = option;
1141 if (nbd_read32(client->ioc, &length, "option length", errp) < 0) {
1144 assert(!client->optlen);
1145 client->optlen = length;
1147 if (length > NBD_MAX_BUFFER_SIZE) {
1148 error_setg(errp, "len (%" PRIu32" ) is larger than max len (%u)",
1149 length, NBD_MAX_BUFFER_SIZE);
1153 trace_nbd_negotiate_options_check_option(option,
1154 nbd_opt_lookup(option));
1155 if (client->tlscreds &&
1156 client->ioc == (QIOChannel *)client->sioc) {
1158 if (!fixedNewstyle) {
1159 error_setg(errp, "Unsupported option 0x%" PRIx32, option);
1163 case NBD_OPT_STARTTLS:
1165 /* Unconditionally drop the connection if the client
1166 * can't start a TLS negotiation correctly */
1167 return nbd_reject_length(client, true, errp);
1169 tioc = nbd_negotiate_handle_starttls(client, errp);
1174 object_unref(OBJECT(client->ioc));
1175 client->ioc = QIO_CHANNEL(tioc);
1178 case NBD_OPT_EXPORT_NAME:
1179 /* No way to return an error to client, so drop connection */
1180 error_setg(errp, "Option 0x%x not permitted before TLS",
1185 /* Let the client keep trying, unless they asked to
1186 * quit. Always try to give an error back to the
1187 * client; but when replying to OPT_ABORT, be aware
1188 * that the client may hang up before receiving the
1189 * error, in which case we are fine ignoring the
1190 * resulting EPIPE. */
1191 ret = nbd_opt_drop(client, NBD_REP_ERR_TLS_REQD,
1192 option == NBD_OPT_ABORT ? NULL : errp,
1194 " not permitted before TLS", option);
1195 if (option == NBD_OPT_ABORT) {
1200 } else if (fixedNewstyle) {
1204 ret = nbd_reject_length(client, false, errp);
1206 ret = nbd_negotiate_handle_list(client, errp);
1211 /* NBD spec says we must try to reply before
1212 * disconnecting, but that we must also tolerate
1213 * guests that don't wait for our reply. */
1214 nbd_negotiate_send_rep(client, NBD_REP_ACK, NULL);
1217 case NBD_OPT_EXPORT_NAME:
1218 return nbd_negotiate_handle_export_name(client, no_zeroes,
1223 ret = nbd_negotiate_handle_info(client, errp);
1225 assert(option == NBD_OPT_GO);
1230 case NBD_OPT_STARTTLS:
1232 ret = nbd_reject_length(client, false, errp);
1233 } else if (client->tlscreds) {
1234 ret = nbd_negotiate_send_rep_err(client,
1235 NBD_REP_ERR_INVALID, errp,
1236 "TLS already enabled");
1238 ret = nbd_negotiate_send_rep_err(client,
1239 NBD_REP_ERR_POLICY, errp,
1240 "TLS not configured");
1244 case NBD_OPT_STRUCTURED_REPLY:
1246 ret = nbd_reject_length(client, false, errp);
1247 } else if (client->structured_reply) {
1248 ret = nbd_negotiate_send_rep_err(
1249 client, NBD_REP_ERR_INVALID, errp,
1250 "structured reply already negotiated");
1252 ret = nbd_negotiate_send_rep(client, NBD_REP_ACK, errp);
1253 client->structured_reply = true;
1257 case NBD_OPT_LIST_META_CONTEXT:
1258 case NBD_OPT_SET_META_CONTEXT:
1259 ret = nbd_negotiate_meta_queries(client, &client->export_meta,
1264 ret = nbd_opt_drop(client, NBD_REP_ERR_UNSUP, errp,
1265 "Unsupported option %" PRIu32 " (%s)",
1266 option, nbd_opt_lookup(option));
1271 * If broken new-style we should drop the connection
1272 * for anything except NBD_OPT_EXPORT_NAME
1275 case NBD_OPT_EXPORT_NAME:
1276 return nbd_negotiate_handle_export_name(client, no_zeroes,
1280 error_setg(errp, "Unsupported option %" PRIu32 " (%s)",
1281 option, nbd_opt_lookup(option));
1293 * -errno on error, errp is set
1294 * 0 on successful negotiation, errp is not set
1295 * 1 if client sent NBD_OPT_ABORT, i.e. on valid disconnect,
1298 static coroutine_fn int nbd_negotiate(NBDClient *client, Error **errp)
1301 char buf[NBD_OLDSTYLE_NEGOTIATE_SIZE] = "";
1304 /* Old style negotiation header, no room for options
1305 [ 0 .. 7] passwd ("NBDMAGIC")
1306 [ 8 .. 15] magic (NBD_CLIENT_MAGIC)
1308 [24 .. 27] export flags (zero-extended)
1309 [28 .. 151] reserved (0)
1311 New style negotiation header, client can send options
1312 [ 0 .. 7] passwd ("NBDMAGIC")
1313 [ 8 .. 15] magic (NBD_OPTS_MAGIC)
1314 [16 .. 17] server flags (0)
1315 ....options sent, ending in NBD_OPT_EXPORT_NAME or NBD_OPT_GO....
1318 qio_channel_set_blocking(client->ioc, false, NULL);
1320 trace_nbd_negotiate_begin();
1321 memcpy(buf, "NBDMAGIC", 8);
1323 stq_be_p(buf + 8, NBD_OPTS_MAGIC);
1324 stw_be_p(buf + 16, NBD_FLAG_FIXED_NEWSTYLE | NBD_FLAG_NO_ZEROES);
1326 if (nbd_write(client->ioc, buf, 18, errp) < 0) {
1327 error_prepend(errp, "write failed: ");
1330 ret = nbd_negotiate_options(client, errp);
1333 error_prepend(errp, "option negotiation failed: ");
1338 /* Attach the channel to the same AioContext as the export */
1339 if (client->exp && client->exp->ctx) {
1340 qio_channel_attach_aio_context(client->ioc, client->exp->ctx);
1343 assert(!client->optlen);
1344 trace_nbd_negotiate_success();
1349 static int nbd_receive_request(QIOChannel *ioc, NBDRequest *request,
1352 uint8_t buf[NBD_REQUEST_SIZE];
1356 ret = nbd_read(ioc, buf, sizeof(buf), "request", errp);
1362 [ 0 .. 3] magic (NBD_REQUEST_MAGIC)
1363 [ 4 .. 5] flags (NBD_CMD_FLAG_FUA, ...)
1364 [ 6 .. 7] type (NBD_CMD_READ, ...)
1370 magic = ldl_be_p(buf);
1371 request->flags = lduw_be_p(buf + 4);
1372 request->type = lduw_be_p(buf + 6);
1373 request->handle = ldq_be_p(buf + 8);
1374 request->from = ldq_be_p(buf + 16);
1375 request->len = ldl_be_p(buf + 24);
1377 trace_nbd_receive_request(magic, request->flags, request->type,
1378 request->from, request->len);
1380 if (magic != NBD_REQUEST_MAGIC) {
1381 error_setg(errp, "invalid magic (got 0x%" PRIx32 ")", magic);
1387 #define MAX_NBD_REQUESTS 16
1389 void nbd_client_get(NBDClient *client)
1394 void nbd_client_put(NBDClient *client)
1396 if (--client->refcount == 0) {
1397 /* The last reference should be dropped by client->close,
1398 * which is called by client_close.
1400 assert(client->closing);
1402 qio_channel_detach_aio_context(client->ioc);
1403 object_unref(OBJECT(client->sioc));
1404 object_unref(OBJECT(client->ioc));
1405 if (client->tlscreds) {
1406 object_unref(OBJECT(client->tlscreds));
1408 g_free(client->tlsauthz);
1410 QTAILQ_REMOVE(&client->exp->clients, client, next);
1411 nbd_export_put(client->exp);
1417 static void client_close(NBDClient *client, bool negotiated)
1419 if (client->closing) {
1423 client->closing = true;
1425 /* Force requests to finish. They will drop their own references,
1426 * then we'll close the socket and free the NBDClient.
1428 qio_channel_shutdown(client->ioc, QIO_CHANNEL_SHUTDOWN_BOTH,
1431 /* Also tell the client, so that they release their reference. */
1432 if (client->close_fn) {
1433 client->close_fn(client, negotiated);
1437 static NBDRequestData *nbd_request_get(NBDClient *client)
1439 NBDRequestData *req;
1441 assert(client->nb_requests <= MAX_NBD_REQUESTS - 1);
1442 client->nb_requests++;
1444 req = g_new0(NBDRequestData, 1);
1445 nbd_client_get(client);
1446 req->client = client;
1450 static void nbd_request_put(NBDRequestData *req)
1452 NBDClient *client = req->client;
1455 qemu_vfree(req->data);
1459 client->nb_requests--;
1460 nbd_client_receive_next_request(client);
1462 nbd_client_put(client);
1465 static void blk_aio_attached(AioContext *ctx, void *opaque)
1467 NBDExport *exp = opaque;
1470 trace_nbd_blk_aio_attached(exp->name, ctx);
1474 QTAILQ_FOREACH(client, &exp->clients, next) {
1475 qio_channel_attach_aio_context(client->ioc, ctx);
1476 if (client->recv_coroutine) {
1477 aio_co_schedule(ctx, client->recv_coroutine);
1479 if (client->send_coroutine) {
1480 aio_co_schedule(ctx, client->send_coroutine);
1485 static void blk_aio_detach(void *opaque)
1487 NBDExport *exp = opaque;
1490 trace_nbd_blk_aio_detach(exp->name, exp->ctx);
1492 QTAILQ_FOREACH(client, &exp->clients, next) {
1493 qio_channel_detach_aio_context(client->ioc);
1499 static void nbd_eject_notifier(Notifier *n, void *data)
1501 NBDExport *exp = container_of(n, NBDExport, eject_notifier);
1502 AioContext *aio_context;
1504 aio_context = exp->ctx;
1505 aio_context_acquire(aio_context);
1506 nbd_export_close(exp);
1507 aio_context_release(aio_context);
1510 NBDExport *nbd_export_new(BlockDriverState *bs, uint64_t dev_offset,
1511 uint64_t size, const char *name, const char *desc,
1512 const char *bitmap, bool readonly, bool shared,
1513 void (*close)(NBDExport *), bool writethrough,
1514 BlockBackend *on_eject_blk, Error **errp)
1522 exp = g_new0(NBDExport, 1);
1523 exp->common = (BlockExport) {
1524 .drv = &blk_exp_nbd,
1528 * NBD exports are used for non-shared storage migration. Make sure
1529 * that BDRV_O_INACTIVE is cleared and the image is ready for write
1530 * access since the export could be available before migration handover.
1531 * ctx was acquired in the caller.
1533 assert(name && strlen(name) <= NBD_MAX_STRING_SIZE);
1534 ctx = bdrv_get_aio_context(bs);
1535 bdrv_invalidate_cache(bs, NULL);
1537 /* Don't allow resize while the NBD server is running, otherwise we don't
1538 * care what happens with the node. */
1539 perm = BLK_PERM_CONSISTENT_READ;
1541 perm |= BLK_PERM_WRITE;
1543 blk = blk_new(ctx, perm,
1544 BLK_PERM_CONSISTENT_READ | BLK_PERM_WRITE_UNCHANGED |
1545 BLK_PERM_WRITE | BLK_PERM_GRAPH_MOD);
1546 ret = blk_insert_bs(blk, bs, errp);
1550 blk_set_enable_write_cache(blk, !writethrough);
1551 blk_set_allow_aio_context_change(blk, true);
1554 QTAILQ_INIT(&exp->clients);
1556 assert(dev_offset <= INT64_MAX);
1557 exp->dev_offset = dev_offset;
1558 exp->name = g_strdup(name);
1559 assert(!desc || strlen(desc) <= NBD_MAX_STRING_SIZE);
1560 exp->description = g_strdup(desc);
1561 exp->nbdflags = (NBD_FLAG_HAS_FLAGS | NBD_FLAG_SEND_FLUSH |
1562 NBD_FLAG_SEND_FUA | NBD_FLAG_SEND_CACHE);
1564 exp->nbdflags |= NBD_FLAG_READ_ONLY;
1566 exp->nbdflags |= NBD_FLAG_CAN_MULTI_CONN;
1569 exp->nbdflags |= (NBD_FLAG_SEND_TRIM | NBD_FLAG_SEND_WRITE_ZEROES |
1570 NBD_FLAG_SEND_FAST_ZERO);
1572 assert(size <= INT64_MAX - dev_offset);
1573 exp->size = QEMU_ALIGN_DOWN(size, BDRV_SECTOR_SIZE);
1576 BdrvDirtyBitmap *bm = NULL;
1579 bm = bdrv_find_dirty_bitmap(bs, bitmap);
1584 bs = bdrv_filter_or_cow_bs(bs);
1588 error_setg(errp, "Bitmap '%s' is not found", bitmap);
1592 if (bdrv_dirty_bitmap_check(bm, BDRV_BITMAP_ALLOW_RO, errp)) {
1596 if (readonly && bdrv_is_writable(bs) &&
1597 bdrv_dirty_bitmap_enabled(bm)) {
1599 "Enabled bitmap '%s' incompatible with readonly export",
1604 bdrv_dirty_bitmap_set_busy(bm, true);
1605 exp->export_bitmap = bm;
1606 assert(strlen(bitmap) <= BDRV_BITMAP_MAX_NAME_SIZE);
1607 exp->export_bitmap_context = g_strdup_printf("qemu:dirty-bitmap:%s",
1609 assert(strlen(exp->export_bitmap_context) < NBD_MAX_STRING_SIZE);
1614 blk_add_aio_context_notifier(blk, blk_aio_attached, blk_aio_detach, exp);
1617 blk_ref(on_eject_blk);
1618 exp->eject_notifier_blk = on_eject_blk;
1619 exp->eject_notifier.notify = nbd_eject_notifier;
1620 blk_add_remove_bs_notifier(on_eject_blk, &exp->eject_notifier);
1622 QTAILQ_INSERT_TAIL(&exports, exp, next);
1623 nbd_export_get(exp);
1629 g_free(exp->description);
1634 NBDExport *nbd_export_find(const char *name)
1637 QTAILQ_FOREACH(exp, &exports, next) {
1638 if (strcmp(name, exp->name) == 0) {
1647 nbd_export_aio_context(NBDExport *exp)
1652 void nbd_export_close(NBDExport *exp)
1654 NBDClient *client, *next;
1656 nbd_export_get(exp);
1658 * TODO: Should we expand QMP NbdServerRemoveNode enum to allow a
1659 * close mode that stops advertising the export to new clients but
1660 * still permits existing clients to run to completion? Because of
1661 * that possibility, nbd_export_close() can be called more than
1662 * once on an export.
1664 QTAILQ_FOREACH_SAFE(client, &exp->clients, next, next) {
1665 client_close(client, true);
1668 nbd_export_put(exp);
1671 QTAILQ_REMOVE(&exports, exp, next);
1672 QTAILQ_INSERT_TAIL(&closed_exports, exp, next);
1674 g_free(exp->description);
1675 exp->description = NULL;
1676 nbd_export_put(exp);
1679 void nbd_export_remove(NBDExport *exp, NbdServerRemoveMode mode, Error **errp)
1682 if (mode == NBD_SERVER_REMOVE_MODE_HARD || QTAILQ_EMPTY(&exp->clients)) {
1683 nbd_export_close(exp);
1687 assert(mode == NBD_SERVER_REMOVE_MODE_SAFE);
1689 error_setg(errp, "export '%s' still in use", exp->name);
1690 error_append_hint(errp, "Use mode='hard' to force client disconnect\n");
1693 void nbd_export_get(NBDExport *exp)
1695 assert(exp->refcount > 0);
1699 void nbd_export_put(NBDExport *exp)
1701 assert(exp->refcount > 0);
1702 if (exp->refcount == 1) {
1703 nbd_export_close(exp);
1706 /* nbd_export_close() may theoretically reduce refcount to 0. It may happen
1707 * if someone calls nbd_export_put() on named export not through
1708 * nbd_export_set_name() when refcount is 1. So, let's assert that
1711 assert(exp->refcount > 0);
1712 if (--exp->refcount == 0) {
1713 assert(exp->name == NULL);
1714 assert(exp->description == NULL);
1721 if (exp->eject_notifier_blk) {
1722 notifier_remove(&exp->eject_notifier);
1723 blk_unref(exp->eject_notifier_blk);
1725 blk_remove_aio_context_notifier(exp->blk, blk_aio_attached,
1726 blk_aio_detach, exp);
1727 blk_unref(exp->blk);
1731 if (exp->export_bitmap) {
1732 bdrv_dirty_bitmap_set_busy(exp->export_bitmap, false);
1733 g_free(exp->export_bitmap_context);
1736 QTAILQ_REMOVE(&closed_exports, exp, next);
1742 const BlockExportDriver blk_exp_nbd = {
1743 .type = BLOCK_EXPORT_TYPE_NBD,
1744 .create = nbd_export_create,
1747 void nbd_export_close_all(void)
1749 NBDExport *exp, *next;
1750 AioContext *aio_context;
1752 QTAILQ_FOREACH_SAFE(exp, &exports, next, next) {
1753 aio_context = exp->ctx;
1754 aio_context_acquire(aio_context);
1755 nbd_export_close(exp);
1756 aio_context_release(aio_context);
1759 AIO_WAIT_WHILE(NULL, !(QTAILQ_EMPTY(&exports) &&
1760 QTAILQ_EMPTY(&closed_exports)));
1763 static int coroutine_fn nbd_co_send_iov(NBDClient *client, struct iovec *iov,
1764 unsigned niov, Error **errp)
1768 g_assert(qemu_in_coroutine());
1769 qemu_co_mutex_lock(&client->send_lock);
1770 client->send_coroutine = qemu_coroutine_self();
1772 ret = qio_channel_writev_all(client->ioc, iov, niov, errp) < 0 ? -EIO : 0;
1774 client->send_coroutine = NULL;
1775 qemu_co_mutex_unlock(&client->send_lock);
1780 static inline void set_be_simple_reply(NBDSimpleReply *reply, uint64_t error,
1783 stl_be_p(&reply->magic, NBD_SIMPLE_REPLY_MAGIC);
1784 stl_be_p(&reply->error, error);
1785 stq_be_p(&reply->handle, handle);
1788 static int nbd_co_send_simple_reply(NBDClient *client,
1795 NBDSimpleReply reply;
1796 int nbd_err = system_errno_to_nbd_errno(error);
1797 struct iovec iov[] = {
1798 {.iov_base = &reply, .iov_len = sizeof(reply)},
1799 {.iov_base = data, .iov_len = len}
1802 trace_nbd_co_send_simple_reply(handle, nbd_err, nbd_err_lookup(nbd_err),
1804 set_be_simple_reply(&reply, nbd_err, handle);
1806 return nbd_co_send_iov(client, iov, len ? 2 : 1, errp);
1809 static inline void set_be_chunk(NBDStructuredReplyChunk *chunk, uint16_t flags,
1810 uint16_t type, uint64_t handle, uint32_t length)
1812 stl_be_p(&chunk->magic, NBD_STRUCTURED_REPLY_MAGIC);
1813 stw_be_p(&chunk->flags, flags);
1814 stw_be_p(&chunk->type, type);
1815 stq_be_p(&chunk->handle, handle);
1816 stl_be_p(&chunk->length, length);
1819 static int coroutine_fn nbd_co_send_structured_done(NBDClient *client,
1823 NBDStructuredReplyChunk chunk;
1824 struct iovec iov[] = {
1825 {.iov_base = &chunk, .iov_len = sizeof(chunk)},
1828 trace_nbd_co_send_structured_done(handle);
1829 set_be_chunk(&chunk, NBD_REPLY_FLAG_DONE, NBD_REPLY_TYPE_NONE, handle, 0);
1831 return nbd_co_send_iov(client, iov, 1, errp);
1834 static int coroutine_fn nbd_co_send_structured_read(NBDClient *client,
1842 NBDStructuredReadData chunk;
1843 struct iovec iov[] = {
1844 {.iov_base = &chunk, .iov_len = sizeof(chunk)},
1845 {.iov_base = data, .iov_len = size}
1849 trace_nbd_co_send_structured_read(handle, offset, data, size);
1850 set_be_chunk(&chunk.h, final ? NBD_REPLY_FLAG_DONE : 0,
1851 NBD_REPLY_TYPE_OFFSET_DATA, handle,
1852 sizeof(chunk) - sizeof(chunk.h) + size);
1853 stq_be_p(&chunk.offset, offset);
1855 return nbd_co_send_iov(client, iov, 2, errp);
1858 static int coroutine_fn nbd_co_send_structured_error(NBDClient *client,
1864 NBDStructuredError chunk;
1865 int nbd_err = system_errno_to_nbd_errno(error);
1866 struct iovec iov[] = {
1867 {.iov_base = &chunk, .iov_len = sizeof(chunk)},
1868 {.iov_base = (char *)msg, .iov_len = msg ? strlen(msg) : 0},
1872 trace_nbd_co_send_structured_error(handle, nbd_err,
1873 nbd_err_lookup(nbd_err), msg ? msg : "");
1874 set_be_chunk(&chunk.h, NBD_REPLY_FLAG_DONE, NBD_REPLY_TYPE_ERROR, handle,
1875 sizeof(chunk) - sizeof(chunk.h) + iov[1].iov_len);
1876 stl_be_p(&chunk.error, nbd_err);
1877 stw_be_p(&chunk.message_length, iov[1].iov_len);
1879 return nbd_co_send_iov(client, iov, 1 + !!iov[1].iov_len, errp);
1882 /* Do a sparse read and send the structured reply to the client.
1883 * Returns -errno if sending fails. bdrv_block_status_above() failure is
1884 * reported to the client, at which point this function succeeds.
1886 static int coroutine_fn nbd_co_send_sparse_read(NBDClient *client,
1894 NBDExport *exp = client->exp;
1895 size_t progress = 0;
1897 while (progress < size) {
1899 int status = bdrv_block_status_above(blk_bs(exp->blk), NULL,
1901 size - progress, &pnum, NULL,
1906 char *msg = g_strdup_printf("unable to check for holes: %s",
1909 ret = nbd_co_send_structured_error(client, handle, -status, msg,
1914 assert(pnum && pnum <= size - progress);
1915 final = progress + pnum == size;
1916 if (status & BDRV_BLOCK_ZERO) {
1917 NBDStructuredReadHole chunk;
1918 struct iovec iov[] = {
1919 {.iov_base = &chunk, .iov_len = sizeof(chunk)},
1922 trace_nbd_co_send_structured_read_hole(handle, offset + progress,
1924 set_be_chunk(&chunk.h, final ? NBD_REPLY_FLAG_DONE : 0,
1925 NBD_REPLY_TYPE_OFFSET_HOLE,
1926 handle, sizeof(chunk) - sizeof(chunk.h));
1927 stq_be_p(&chunk.offset, offset + progress);
1928 stl_be_p(&chunk.length, pnum);
1929 ret = nbd_co_send_iov(client, iov, 1, errp);
1931 ret = blk_pread(exp->blk, offset + progress + exp->dev_offset,
1932 data + progress, pnum);
1934 error_setg_errno(errp, -ret, "reading from file failed");
1937 ret = nbd_co_send_structured_read(client, handle, offset + progress,
1938 data + progress, pnum, final,
1950 typedef struct NBDExtentArray {
1952 unsigned int nb_alloc;
1954 uint64_t total_length;
1956 bool converted_to_be;
1959 static NBDExtentArray *nbd_extent_array_new(unsigned int nb_alloc)
1961 NBDExtentArray *ea = g_new0(NBDExtentArray, 1);
1963 ea->nb_alloc = nb_alloc;
1964 ea->extents = g_new(NBDExtent, nb_alloc);
1970 static void nbd_extent_array_free(NBDExtentArray *ea)
1972 g_free(ea->extents);
1975 G_DEFINE_AUTOPTR_CLEANUP_FUNC(NBDExtentArray, nbd_extent_array_free);
1977 /* Further modifications of the array after conversion are abandoned */
1978 static void nbd_extent_array_convert_to_be(NBDExtentArray *ea)
1982 assert(!ea->converted_to_be);
1983 ea->can_add = false;
1984 ea->converted_to_be = true;
1986 for (i = 0; i < ea->count; i++) {
1987 ea->extents[i].flags = cpu_to_be32(ea->extents[i].flags);
1988 ea->extents[i].length = cpu_to_be32(ea->extents[i].length);
1993 * Add extent to NBDExtentArray. If extent can't be added (no available space),
1995 * For safety, when returning -1 for the first time, .can_add is set to false,
1996 * further call to nbd_extent_array_add() will crash.
1997 * (to avoid the situation, when after failing to add an extent (returned -1),
1998 * user miss this failure and add another extent, which is successfully added
1999 * (array is full, but new extent may be squashed into the last one), then we
2000 * have invalid array with skipped extent)
2002 static int nbd_extent_array_add(NBDExtentArray *ea,
2003 uint32_t length, uint32_t flags)
2005 assert(ea->can_add);
2011 /* Extend previous extent if flags are the same */
2012 if (ea->count > 0 && flags == ea->extents[ea->count - 1].flags) {
2013 uint64_t sum = (uint64_t)length + ea->extents[ea->count - 1].length;
2015 if (sum <= UINT32_MAX) {
2016 ea->extents[ea->count - 1].length = sum;
2017 ea->total_length += length;
2022 if (ea->count >= ea->nb_alloc) {
2023 ea->can_add = false;
2027 ea->total_length += length;
2028 ea->extents[ea->count] = (NBDExtent) {.length = length, .flags = flags};
2034 static int blockstatus_to_extents(BlockDriverState *bs, uint64_t offset,
2035 uint64_t bytes, NBDExtentArray *ea)
2040 int ret = bdrv_block_status_above(bs, NULL, offset, bytes, &num,
2047 flags = (ret & BDRV_BLOCK_ALLOCATED ? 0 : NBD_STATE_HOLE) |
2048 (ret & BDRV_BLOCK_ZERO ? NBD_STATE_ZERO : 0);
2050 if (nbd_extent_array_add(ea, num, flags) < 0) {
2062 * nbd_co_send_extents
2064 * @ea is converted to BE by the function
2065 * @last controls whether NBD_REPLY_FLAG_DONE is sent.
2067 static int nbd_co_send_extents(NBDClient *client, uint64_t handle,
2069 bool last, uint32_t context_id, Error **errp)
2071 NBDStructuredMeta chunk;
2072 struct iovec iov[] = {
2073 {.iov_base = &chunk, .iov_len = sizeof(chunk)},
2074 {.iov_base = ea->extents, .iov_len = ea->count * sizeof(ea->extents[0])}
2077 nbd_extent_array_convert_to_be(ea);
2079 trace_nbd_co_send_extents(handle, ea->count, context_id, ea->total_length,
2081 set_be_chunk(&chunk.h, last ? NBD_REPLY_FLAG_DONE : 0,
2082 NBD_REPLY_TYPE_BLOCK_STATUS,
2083 handle, sizeof(chunk) - sizeof(chunk.h) + iov[1].iov_len);
2084 stl_be_p(&chunk.context_id, context_id);
2086 return nbd_co_send_iov(client, iov, 2, errp);
2089 /* Get block status from the exported device and send it to the client */
2090 static int nbd_co_send_block_status(NBDClient *client, uint64_t handle,
2091 BlockDriverState *bs, uint64_t offset,
2092 uint32_t length, bool dont_fragment,
2093 bool last, uint32_t context_id,
2097 unsigned int nb_extents = dont_fragment ? 1 : NBD_MAX_BLOCK_STATUS_EXTENTS;
2098 g_autoptr(NBDExtentArray) ea = nbd_extent_array_new(nb_extents);
2100 ret = blockstatus_to_extents(bs, offset, length, ea);
2102 return nbd_co_send_structured_error(
2103 client, handle, -ret, "can't get block status", errp);
2106 return nbd_co_send_extents(client, handle, ea, last, context_id, errp);
2109 /* Populate @ea from a dirty bitmap. */
2110 static void bitmap_to_extents(BdrvDirtyBitmap *bitmap,
2111 uint64_t offset, uint64_t length,
2114 int64_t start, dirty_start, dirty_count;
2115 int64_t end = offset + length;
2118 bdrv_dirty_bitmap_lock(bitmap);
2120 for (start = offset;
2121 bdrv_dirty_bitmap_next_dirty_area(bitmap, start, end, INT32_MAX,
2122 &dirty_start, &dirty_count);
2123 start = dirty_start + dirty_count)
2125 if ((nbd_extent_array_add(es, dirty_start - start, 0) < 0) ||
2126 (nbd_extent_array_add(es, dirty_count, NBD_STATE_DIRTY) < 0))
2134 /* last non dirty extent */
2135 nbd_extent_array_add(es, end - start, 0);
2138 bdrv_dirty_bitmap_unlock(bitmap);
2141 static int nbd_co_send_bitmap(NBDClient *client, uint64_t handle,
2142 BdrvDirtyBitmap *bitmap, uint64_t offset,
2143 uint32_t length, bool dont_fragment, bool last,
2144 uint32_t context_id, Error **errp)
2146 unsigned int nb_extents = dont_fragment ? 1 : NBD_MAX_BLOCK_STATUS_EXTENTS;
2147 g_autoptr(NBDExtentArray) ea = nbd_extent_array_new(nb_extents);
2149 bitmap_to_extents(bitmap, offset, length, ea);
2151 return nbd_co_send_extents(client, handle, ea, last, context_id, errp);
2154 /* nbd_co_receive_request
2155 * Collect a client request. Return 0 if request looks valid, -EIO to drop
2156 * connection right away, and any other negative value to report an error to
2157 * the client (although the caller may still need to disconnect after reporting
2160 static int nbd_co_receive_request(NBDRequestData *req, NBDRequest *request,
2163 NBDClient *client = req->client;
2166 g_assert(qemu_in_coroutine());
2167 assert(client->recv_coroutine == qemu_coroutine_self());
2168 if (nbd_receive_request(client->ioc, request, errp) < 0) {
2172 trace_nbd_co_receive_request_decode_type(request->handle, request->type,
2173 nbd_cmd_lookup(request->type));
2175 if (request->type != NBD_CMD_WRITE) {
2176 /* No payload, we are ready to read the next request. */
2177 req->complete = true;
2180 if (request->type == NBD_CMD_DISC) {
2181 /* Special case: we're going to disconnect without a reply,
2182 * whether or not flags, from, or len are bogus */
2186 if (request->type == NBD_CMD_READ || request->type == NBD_CMD_WRITE ||
2187 request->type == NBD_CMD_CACHE)
2189 if (request->len > NBD_MAX_BUFFER_SIZE) {
2190 error_setg(errp, "len (%" PRIu32" ) is larger than max len (%u)",
2191 request->len, NBD_MAX_BUFFER_SIZE);
2195 if (request->type != NBD_CMD_CACHE) {
2196 req->data = blk_try_blockalign(client->exp->blk, request->len);
2197 if (req->data == NULL) {
2198 error_setg(errp, "No memory");
2204 if (request->type == NBD_CMD_WRITE) {
2205 if (nbd_read(client->ioc, req->data, request->len, "CMD_WRITE data",
2210 req->complete = true;
2212 trace_nbd_co_receive_request_payload_received(request->handle,
2216 /* Sanity checks. */
2217 if (client->exp->nbdflags & NBD_FLAG_READ_ONLY &&
2218 (request->type == NBD_CMD_WRITE ||
2219 request->type == NBD_CMD_WRITE_ZEROES ||
2220 request->type == NBD_CMD_TRIM)) {
2221 error_setg(errp, "Export is read-only");
2224 if (request->from > client->exp->size ||
2225 request->len > client->exp->size - request->from) {
2226 error_setg(errp, "operation past EOF; From: %" PRIu64 ", Len: %" PRIu32
2227 ", Size: %" PRIu64, request->from, request->len,
2229 return (request->type == NBD_CMD_WRITE ||
2230 request->type == NBD_CMD_WRITE_ZEROES) ? -ENOSPC : -EINVAL;
2232 if (client->check_align && !QEMU_IS_ALIGNED(request->from | request->len,
2233 client->check_align)) {
2235 * The block layer gracefully handles unaligned requests, but
2236 * it's still worth tracing client non-compliance
2238 trace_nbd_co_receive_align_compliance(nbd_cmd_lookup(request->type),
2241 client->check_align);
2243 valid_flags = NBD_CMD_FLAG_FUA;
2244 if (request->type == NBD_CMD_READ && client->structured_reply) {
2245 valid_flags |= NBD_CMD_FLAG_DF;
2246 } else if (request->type == NBD_CMD_WRITE_ZEROES) {
2247 valid_flags |= NBD_CMD_FLAG_NO_HOLE | NBD_CMD_FLAG_FAST_ZERO;
2248 } else if (request->type == NBD_CMD_BLOCK_STATUS) {
2249 valid_flags |= NBD_CMD_FLAG_REQ_ONE;
2251 if (request->flags & ~valid_flags) {
2252 error_setg(errp, "unsupported flags for command %s (got 0x%x)",
2253 nbd_cmd_lookup(request->type), request->flags);
2260 /* Send simple reply without a payload, or a structured error
2261 * @error_msg is ignored if @ret >= 0
2262 * Returns 0 if connection is still live, -errno on failure to talk to client
2264 static coroutine_fn int nbd_send_generic_reply(NBDClient *client,
2267 const char *error_msg,
2270 if (client->structured_reply && ret < 0) {
2271 return nbd_co_send_structured_error(client, handle, -ret, error_msg,
2274 return nbd_co_send_simple_reply(client, handle, ret < 0 ? -ret : 0,
2279 /* Handle NBD_CMD_READ request.
2280 * Return -errno if sending fails. Other errors are reported directly to the
2281 * client as an error reply. */
2282 static coroutine_fn int nbd_do_cmd_read(NBDClient *client, NBDRequest *request,
2283 uint8_t *data, Error **errp)
2286 NBDExport *exp = client->exp;
2288 assert(request->type == NBD_CMD_READ);
2290 /* XXX: NBD Protocol only documents use of FUA with WRITE */
2291 if (request->flags & NBD_CMD_FLAG_FUA) {
2292 ret = blk_co_flush(exp->blk);
2294 return nbd_send_generic_reply(client, request->handle, ret,
2295 "flush failed", errp);
2299 if (client->structured_reply && !(request->flags & NBD_CMD_FLAG_DF) &&
2302 return nbd_co_send_sparse_read(client, request->handle, request->from,
2303 data, request->len, errp);
2306 ret = blk_pread(exp->blk, request->from + exp->dev_offset, data,
2309 return nbd_send_generic_reply(client, request->handle, ret,
2310 "reading from file failed", errp);
2313 if (client->structured_reply) {
2315 return nbd_co_send_structured_read(client, request->handle,
2316 request->from, data,
2317 request->len, true, errp);
2319 return nbd_co_send_structured_done(client, request->handle, errp);
2322 return nbd_co_send_simple_reply(client, request->handle, 0,
2323 data, request->len, errp);
2330 * Handle NBD_CMD_CACHE request.
2331 * Return -errno if sending fails. Other errors are reported directly to the
2332 * client as an error reply.
2334 static coroutine_fn int nbd_do_cmd_cache(NBDClient *client, NBDRequest *request,
2338 NBDExport *exp = client->exp;
2340 assert(request->type == NBD_CMD_CACHE);
2342 ret = blk_co_preadv(exp->blk, request->from + exp->dev_offset, request->len,
2343 NULL, BDRV_REQ_COPY_ON_READ | BDRV_REQ_PREFETCH);
2345 return nbd_send_generic_reply(client, request->handle, ret,
2346 "caching data failed", errp);
2349 /* Handle NBD request.
2350 * Return -errno if sending fails. Other errors are reported directly to the
2351 * client as an error reply. */
2352 static coroutine_fn int nbd_handle_request(NBDClient *client,
2353 NBDRequest *request,
2354 uint8_t *data, Error **errp)
2358 NBDExport *exp = client->exp;
2361 switch (request->type) {
2363 return nbd_do_cmd_cache(client, request, errp);
2366 return nbd_do_cmd_read(client, request, data, errp);
2370 if (request->flags & NBD_CMD_FLAG_FUA) {
2371 flags |= BDRV_REQ_FUA;
2373 ret = blk_pwrite(exp->blk, request->from + exp->dev_offset,
2374 data, request->len, flags);
2375 return nbd_send_generic_reply(client, request->handle, ret,
2376 "writing to file failed", errp);
2378 case NBD_CMD_WRITE_ZEROES:
2380 if (request->flags & NBD_CMD_FLAG_FUA) {
2381 flags |= BDRV_REQ_FUA;
2383 if (!(request->flags & NBD_CMD_FLAG_NO_HOLE)) {
2384 flags |= BDRV_REQ_MAY_UNMAP;
2386 if (request->flags & NBD_CMD_FLAG_FAST_ZERO) {
2387 flags |= BDRV_REQ_NO_FALLBACK;
2390 /* FIXME simplify this when blk_pwrite_zeroes switches to 64-bit */
2391 while (ret >= 0 && request->len) {
2392 int align = client->check_align ?: 1;
2393 int len = MIN(request->len, QEMU_ALIGN_DOWN(BDRV_REQUEST_MAX_BYTES,
2395 ret = blk_pwrite_zeroes(exp->blk, request->from + exp->dev_offset,
2397 request->len -= len;
2398 request->from += len;
2400 return nbd_send_generic_reply(client, request->handle, ret,
2401 "writing to file failed", errp);
2404 /* unreachable, thanks to special case in nbd_co_receive_request() */
2408 ret = blk_co_flush(exp->blk);
2409 return nbd_send_generic_reply(client, request->handle, ret,
2410 "flush failed", errp);
2414 /* FIXME simplify this when blk_co_pdiscard switches to 64-bit */
2415 while (ret >= 0 && request->len) {
2416 int align = client->check_align ?: 1;
2417 int len = MIN(request->len, QEMU_ALIGN_DOWN(BDRV_REQUEST_MAX_BYTES,
2419 ret = blk_co_pdiscard(exp->blk, request->from + exp->dev_offset,
2421 request->len -= len;
2422 request->from += len;
2424 if (ret >= 0 && request->flags & NBD_CMD_FLAG_FUA) {
2425 ret = blk_co_flush(exp->blk);
2427 return nbd_send_generic_reply(client, request->handle, ret,
2428 "discard failed", errp);
2430 case NBD_CMD_BLOCK_STATUS:
2431 if (!request->len) {
2432 return nbd_send_generic_reply(client, request->handle, -EINVAL,
2433 "need non-zero length", errp);
2435 if (client->export_meta.valid &&
2436 (client->export_meta.base_allocation ||
2437 client->export_meta.bitmap))
2439 bool dont_fragment = request->flags & NBD_CMD_FLAG_REQ_ONE;
2441 if (client->export_meta.base_allocation) {
2442 ret = nbd_co_send_block_status(client, request->handle,
2443 blk_bs(exp->blk), request->from,
2444 request->len, dont_fragment,
2445 !client->export_meta.bitmap,
2446 NBD_META_ID_BASE_ALLOCATION,
2453 if (client->export_meta.bitmap) {
2454 ret = nbd_co_send_bitmap(client, request->handle,
2455 client->exp->export_bitmap,
2456 request->from, request->len,
2458 true, NBD_META_ID_DIRTY_BITMAP, errp);
2466 return nbd_send_generic_reply(client, request->handle, -EINVAL,
2467 "CMD_BLOCK_STATUS not negotiated",
2472 msg = g_strdup_printf("invalid request type (%" PRIu32 ") received",
2474 ret = nbd_send_generic_reply(client, request->handle, -EINVAL, msg,
2481 /* Owns a reference to the NBDClient passed as opaque. */
2482 static coroutine_fn void nbd_trip(void *opaque)
2484 NBDClient *client = opaque;
2485 NBDRequestData *req;
2486 NBDRequest request = { 0 }; /* GCC thinks it can be used uninitialized */
2488 Error *local_err = NULL;
2491 if (client->closing) {
2492 nbd_client_put(client);
2496 req = nbd_request_get(client);
2497 ret = nbd_co_receive_request(req, &request, &local_err);
2498 client->recv_coroutine = NULL;
2500 if (client->closing) {
2502 * The client may be closed when we are blocked in
2503 * nbd_co_receive_request()
2508 nbd_client_receive_next_request(client);
2514 /* It wans't -EIO, so, according to nbd_co_receive_request()
2515 * semantics, we should return the error to the client. */
2516 Error *export_err = local_err;
2519 ret = nbd_send_generic_reply(client, request.handle, -EINVAL,
2520 error_get_pretty(export_err), &local_err);
2521 error_free(export_err);
2523 ret = nbd_handle_request(client, &request, req->data, &local_err);
2526 error_prepend(&local_err, "Failed to send reply: ");
2530 /* We must disconnect after NBD_CMD_WRITE if we did not
2533 if (!req->complete) {
2534 error_setg(&local_err, "Request handling failed in intermediate state");
2539 nbd_request_put(req);
2540 nbd_client_put(client);
2545 error_reportf_err(local_err, "Disconnect client, due to: ");
2547 nbd_request_put(req);
2548 client_close(client, true);
2549 nbd_client_put(client);
2552 static void nbd_client_receive_next_request(NBDClient *client)
2554 if (!client->recv_coroutine && client->nb_requests < MAX_NBD_REQUESTS) {
2555 nbd_client_get(client);
2556 client->recv_coroutine = qemu_coroutine_create(nbd_trip, client);
2557 aio_co_schedule(client->exp->ctx, client->recv_coroutine);
2561 static coroutine_fn void nbd_co_client_start(void *opaque)
2563 NBDClient *client = opaque;
2564 Error *local_err = NULL;
2566 qemu_co_mutex_init(&client->send_lock);
2568 if (nbd_negotiate(client, &local_err)) {
2570 error_report_err(local_err);
2572 client_close(client, false);
2576 nbd_client_receive_next_request(client);
2580 * Create a new client listener using the given channel @sioc.
2581 * Begin servicing it in a coroutine. When the connection closes, call
2582 * @close_fn with an indication of whether the client completed negotiation.
2584 void nbd_client_new(QIOChannelSocket *sioc,
2585 QCryptoTLSCreds *tlscreds,
2586 const char *tlsauthz,
2587 void (*close_fn)(NBDClient *, bool))
2592 client = g_new0(NBDClient, 1);
2593 client->refcount = 1;
2594 client->tlscreds = tlscreds;
2596 object_ref(OBJECT(client->tlscreds));
2598 client->tlsauthz = g_strdup(tlsauthz);
2599 client->sioc = sioc;
2600 object_ref(OBJECT(client->sioc));
2601 client->ioc = QIO_CHANNEL(sioc);
2602 object_ref(OBJECT(client->ioc));
2603 client->close_fn = close_fn;
2605 co = qemu_coroutine_create(nbd_co_client_start, client);
2606 qemu_coroutine_enter(co);