MAINTAINERS: Add an entry for OpenSBI firmware
[qemu/ar7.git] / nbd / server.c
blob5357f588f05aaae2ffb3701b7f3e305abc6d40e7
1 /*
2 * Copyright (C) 2016-2018 Red Hat, Inc.
3 * Copyright (C) 2005 Anthony Liguori <anthony@codemonkey.ws>
5 * Network Block Device Server Side
7 * This program is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; under version 2 of the License.
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License
17 * along with this program; if not, see <http://www.gnu.org/licenses/>.
20 #include "qemu/osdep.h"
21 #include "qapi/error.h"
22 #include "qemu/queue.h"
23 #include "trace.h"
24 #include "nbd-internal.h"
25 #include "qemu/units.h"
27 #define NBD_META_ID_BASE_ALLOCATION 0
28 #define NBD_META_ID_DIRTY_BITMAP 1
31 * NBD_MAX_BLOCK_STATUS_EXTENTS: 1 MiB of extents data. An empirical
32 * constant. If an increase is needed, note that the NBD protocol
33 * recommends no larger than 32 mb, so that the client won't consider
34 * the reply as a denial of service attack.
36 #define NBD_MAX_BLOCK_STATUS_EXTENTS (1 * MiB / 8)
38 static int system_errno_to_nbd_errno(int err)
40 switch (err) {
41 case 0:
42 return NBD_SUCCESS;
43 case EPERM:
44 case EROFS:
45 return NBD_EPERM;
46 case EIO:
47 return NBD_EIO;
48 case ENOMEM:
49 return NBD_ENOMEM;
50 #ifdef EDQUOT
51 case EDQUOT:
52 #endif
53 case EFBIG:
54 case ENOSPC:
55 return NBD_ENOSPC;
56 case EOVERFLOW:
57 return NBD_EOVERFLOW;
58 case ENOTSUP:
59 #if ENOTSUP != EOPNOTSUPP
60 case EOPNOTSUPP:
61 #endif
62 return NBD_ENOTSUP;
63 case ESHUTDOWN:
64 return NBD_ESHUTDOWN;
65 case EINVAL:
66 default:
67 return NBD_EINVAL;
71 /* Definitions for opaque data types */
73 typedef struct NBDRequestData NBDRequestData;
75 struct NBDRequestData {
76 QSIMPLEQ_ENTRY(NBDRequestData) entry;
77 NBDClient *client;
78 uint8_t *data;
79 bool complete;
82 struct NBDExport {
83 int refcount;
84 void (*close)(NBDExport *exp);
86 BlockBackend *blk;
87 char *name;
88 char *description;
89 uint64_t dev_offset;
90 uint64_t size;
91 uint16_t nbdflags;
92 QTAILQ_HEAD(, NBDClient) clients;
93 QTAILQ_ENTRY(NBDExport) next;
95 AioContext *ctx;
97 BlockBackend *eject_notifier_blk;
98 Notifier eject_notifier;
100 BdrvDirtyBitmap *export_bitmap;
101 char *export_bitmap_context;
104 static QTAILQ_HEAD(, NBDExport) exports = QTAILQ_HEAD_INITIALIZER(exports);
106 /* NBDExportMetaContexts represents a list of contexts to be exported,
107 * as selected by NBD_OPT_SET_META_CONTEXT. Also used for
108 * NBD_OPT_LIST_META_CONTEXT. */
109 typedef struct NBDExportMetaContexts {
110 NBDExport *exp;
111 bool valid; /* means that negotiation of the option finished without
112 errors */
113 bool base_allocation; /* export base:allocation context (block status) */
114 bool bitmap; /* export qemu:dirty-bitmap:<export bitmap name> */
115 } NBDExportMetaContexts;
117 struct NBDClient {
118 int refcount;
119 void (*close_fn)(NBDClient *client, bool negotiated);
121 NBDExport *exp;
122 QCryptoTLSCreds *tlscreds;
123 char *tlsauthz;
124 QIOChannelSocket *sioc; /* The underlying data channel */
125 QIOChannel *ioc; /* The current I/O channel which may differ (eg TLS) */
127 Coroutine *recv_coroutine;
129 CoMutex send_lock;
130 Coroutine *send_coroutine;
132 QTAILQ_ENTRY(NBDClient) next;
133 int nb_requests;
134 bool closing;
136 uint32_t check_align; /* If non-zero, check for aligned client requests */
138 bool structured_reply;
139 NBDExportMetaContexts export_meta;
141 uint32_t opt; /* Current option being negotiated */
142 uint32_t optlen; /* remaining length of data in ioc for the option being
143 negotiated now */
146 static void nbd_client_receive_next_request(NBDClient *client);
148 /* Basic flow for negotiation
150 Server Client
151 Negotiate
155 Server Client
156 Negotiate #1
157 Option
158 Negotiate #2
160 ----
162 followed by
164 Server Client
165 Request
166 Response
167 Request
168 Response
171 Request (type == 2)
175 static inline void set_be_option_rep(NBDOptionReply *rep, uint32_t option,
176 uint32_t type, uint32_t length)
178 stq_be_p(&rep->magic, NBD_REP_MAGIC);
179 stl_be_p(&rep->option, option);
180 stl_be_p(&rep->type, type);
181 stl_be_p(&rep->length, length);
184 /* Send a reply header, including length, but no payload.
185 * Return -errno on error, 0 on success. */
186 static int nbd_negotiate_send_rep_len(NBDClient *client, uint32_t type,
187 uint32_t len, Error **errp)
189 NBDOptionReply rep;
191 trace_nbd_negotiate_send_rep_len(client->opt, nbd_opt_lookup(client->opt),
192 type, nbd_rep_lookup(type), len);
194 assert(len < NBD_MAX_BUFFER_SIZE);
196 set_be_option_rep(&rep, client->opt, type, len);
197 return nbd_write(client->ioc, &rep, sizeof(rep), errp);
200 /* Send a reply header with default 0 length.
201 * Return -errno on error, 0 on success. */
202 static int nbd_negotiate_send_rep(NBDClient *client, uint32_t type,
203 Error **errp)
205 return nbd_negotiate_send_rep_len(client, type, 0, errp);
208 /* Send an error reply.
209 * Return -errno on error, 0 on success. */
210 static int GCC_FMT_ATTR(4, 0)
211 nbd_negotiate_send_rep_verr(NBDClient *client, uint32_t type,
212 Error **errp, const char *fmt, va_list va)
214 ERRP_GUARD();
215 g_autofree char *msg = NULL;
216 int ret;
217 size_t len;
219 msg = g_strdup_vprintf(fmt, va);
220 len = strlen(msg);
221 assert(len < NBD_MAX_STRING_SIZE);
222 trace_nbd_negotiate_send_rep_err(msg);
223 ret = nbd_negotiate_send_rep_len(client, type, len, errp);
224 if (ret < 0) {
225 return ret;
227 if (nbd_write(client->ioc, msg, len, errp) < 0) {
228 error_prepend(errp, "write failed (error message): ");
229 return -EIO;
232 return 0;
236 * Return a malloc'd copy of @name suitable for use in an error reply.
238 static char *
239 nbd_sanitize_name(const char *name)
241 if (strnlen(name, 80) < 80) {
242 return g_strdup(name);
244 /* XXX Should we also try to sanitize any control characters? */
245 return g_strdup_printf("%.80s...", name);
248 /* Send an error reply.
249 * Return -errno on error, 0 on success. */
250 static int GCC_FMT_ATTR(4, 5)
251 nbd_negotiate_send_rep_err(NBDClient *client, uint32_t type,
252 Error **errp, const char *fmt, ...)
254 va_list va;
255 int ret;
257 va_start(va, fmt);
258 ret = nbd_negotiate_send_rep_verr(client, type, errp, fmt, va);
259 va_end(va);
260 return ret;
263 /* Drop remainder of the current option, and send a reply with the
264 * given error type and message. Return -errno on read or write
265 * failure; or 0 if connection is still live. */
266 static int GCC_FMT_ATTR(4, 0)
267 nbd_opt_vdrop(NBDClient *client, uint32_t type, Error **errp,
268 const char *fmt, va_list va)
270 int ret = nbd_drop(client->ioc, client->optlen, errp);
272 client->optlen = 0;
273 if (!ret) {
274 ret = nbd_negotiate_send_rep_verr(client, type, errp, fmt, va);
276 return ret;
279 static int GCC_FMT_ATTR(4, 5)
280 nbd_opt_drop(NBDClient *client, uint32_t type, Error **errp,
281 const char *fmt, ...)
283 int ret;
284 va_list va;
286 va_start(va, fmt);
287 ret = nbd_opt_vdrop(client, type, errp, fmt, va);
288 va_end(va);
290 return ret;
293 static int GCC_FMT_ATTR(3, 4)
294 nbd_opt_invalid(NBDClient *client, Error **errp, const char *fmt, ...)
296 int ret;
297 va_list va;
299 va_start(va, fmt);
300 ret = nbd_opt_vdrop(client, NBD_REP_ERR_INVALID, errp, fmt, va);
301 va_end(va);
303 return ret;
306 /* Read size bytes from the unparsed payload of the current option.
307 * Return -errno on I/O error, 0 if option was completely handled by
308 * sending a reply about inconsistent lengths, or 1 on success. */
309 static int nbd_opt_read(NBDClient *client, void *buffer, size_t size,
310 Error **errp)
312 if (size > client->optlen) {
313 return nbd_opt_invalid(client, errp,
314 "Inconsistent lengths in option %s",
315 nbd_opt_lookup(client->opt));
317 client->optlen -= size;
318 return qio_channel_read_all(client->ioc, buffer, size, errp) < 0 ? -EIO : 1;
321 /* Drop size bytes from the unparsed payload of the current option.
322 * Return -errno on I/O error, 0 if option was completely handled by
323 * sending a reply about inconsistent lengths, or 1 on success. */
324 static int nbd_opt_skip(NBDClient *client, size_t size, Error **errp)
326 if (size > client->optlen) {
327 return nbd_opt_invalid(client, errp,
328 "Inconsistent lengths in option %s",
329 nbd_opt_lookup(client->opt));
331 client->optlen -= size;
332 return nbd_drop(client->ioc, size, errp) < 0 ? -EIO : 1;
335 /* nbd_opt_read_name
337 * Read a string with the format:
338 * uint32_t len (<= NBD_MAX_STRING_SIZE)
339 * len bytes string (not 0-terminated)
341 * On success, @name will be allocated.
342 * If @length is non-null, it will be set to the actual string length.
344 * Return -errno on I/O error, 0 if option was completely handled by
345 * sending a reply about inconsistent lengths, or 1 on success.
347 static int nbd_opt_read_name(NBDClient *client, char **name, uint32_t *length,
348 Error **errp)
350 int ret;
351 uint32_t len;
352 g_autofree char *local_name = NULL;
354 *name = NULL;
355 ret = nbd_opt_read(client, &len, sizeof(len), errp);
356 if (ret <= 0) {
357 return ret;
359 len = cpu_to_be32(len);
361 if (len > NBD_MAX_STRING_SIZE) {
362 return nbd_opt_invalid(client, errp,
363 "Invalid name length: %" PRIu32, len);
366 local_name = g_malloc(len + 1);
367 ret = nbd_opt_read(client, local_name, len, errp);
368 if (ret <= 0) {
369 return ret;
371 local_name[len] = '\0';
373 if (length) {
374 *length = len;
376 *name = g_steal_pointer(&local_name);
378 return 1;
381 /* Send a single NBD_REP_SERVER reply to NBD_OPT_LIST, including payload.
382 * Return -errno on error, 0 on success. */
383 static int nbd_negotiate_send_rep_list(NBDClient *client, NBDExport *exp,
384 Error **errp)
386 ERRP_GUARD();
387 size_t name_len, desc_len;
388 uint32_t len;
389 const char *name = exp->name ? exp->name : "";
390 const char *desc = exp->description ? exp->description : "";
391 QIOChannel *ioc = client->ioc;
392 int ret;
394 trace_nbd_negotiate_send_rep_list(name, desc);
395 name_len = strlen(name);
396 desc_len = strlen(desc);
397 assert(name_len <= NBD_MAX_STRING_SIZE && desc_len <= NBD_MAX_STRING_SIZE);
398 len = name_len + desc_len + sizeof(len);
399 ret = nbd_negotiate_send_rep_len(client, NBD_REP_SERVER, len, errp);
400 if (ret < 0) {
401 return ret;
404 len = cpu_to_be32(name_len);
405 if (nbd_write(ioc, &len, sizeof(len), errp) < 0) {
406 error_prepend(errp, "write failed (name length): ");
407 return -EINVAL;
410 if (nbd_write(ioc, name, name_len, errp) < 0) {
411 error_prepend(errp, "write failed (name buffer): ");
412 return -EINVAL;
415 if (nbd_write(ioc, desc, desc_len, errp) < 0) {
416 error_prepend(errp, "write failed (description buffer): ");
417 return -EINVAL;
420 return 0;
423 /* Process the NBD_OPT_LIST command, with a potential series of replies.
424 * Return -errno on error, 0 on success. */
425 static int nbd_negotiate_handle_list(NBDClient *client, Error **errp)
427 NBDExport *exp;
428 assert(client->opt == NBD_OPT_LIST);
430 /* For each export, send a NBD_REP_SERVER reply. */
431 QTAILQ_FOREACH(exp, &exports, next) {
432 if (nbd_negotiate_send_rep_list(client, exp, errp)) {
433 return -EINVAL;
436 /* Finish with a NBD_REP_ACK. */
437 return nbd_negotiate_send_rep(client, NBD_REP_ACK, errp);
440 static void nbd_check_meta_export(NBDClient *client)
442 client->export_meta.valid &= client->exp == client->export_meta.exp;
445 /* Send a reply to NBD_OPT_EXPORT_NAME.
446 * Return -errno on error, 0 on success. */
447 static int nbd_negotiate_handle_export_name(NBDClient *client, bool no_zeroes,
448 Error **errp)
450 ERRP_GUARD();
451 g_autofree char *name = NULL;
452 char buf[NBD_REPLY_EXPORT_NAME_SIZE] = "";
453 size_t len;
454 int ret;
455 uint16_t myflags;
457 /* Client sends:
458 [20 .. xx] export name (length bytes)
459 Server replies:
460 [ 0 .. 7] size
461 [ 8 .. 9] export flags
462 [10 .. 133] reserved (0) [unless no_zeroes]
464 trace_nbd_negotiate_handle_export_name();
465 if (client->optlen > NBD_MAX_STRING_SIZE) {
466 error_setg(errp, "Bad length received");
467 return -EINVAL;
469 name = g_malloc(client->optlen + 1);
470 if (nbd_read(client->ioc, name, client->optlen, "export name", errp) < 0) {
471 return -EIO;
473 name[client->optlen] = '\0';
474 client->optlen = 0;
476 trace_nbd_negotiate_handle_export_name_request(name);
478 client->exp = nbd_export_find(name);
479 if (!client->exp) {
480 error_setg(errp, "export not found");
481 return -EINVAL;
484 myflags = client->exp->nbdflags;
485 if (client->structured_reply) {
486 myflags |= NBD_FLAG_SEND_DF;
488 trace_nbd_negotiate_new_style_size_flags(client->exp->size, myflags);
489 stq_be_p(buf, client->exp->size);
490 stw_be_p(buf + 8, myflags);
491 len = no_zeroes ? 10 : sizeof(buf);
492 ret = nbd_write(client->ioc, buf, len, errp);
493 if (ret < 0) {
494 error_prepend(errp, "write failed: ");
495 return ret;
498 QTAILQ_INSERT_TAIL(&client->exp->clients, client, next);
499 nbd_export_get(client->exp);
500 nbd_check_meta_export(client);
502 return 0;
505 /* Send a single NBD_REP_INFO, with a buffer @buf of @length bytes.
506 * The buffer does NOT include the info type prefix.
507 * Return -errno on error, 0 if ready to send more. */
508 static int nbd_negotiate_send_info(NBDClient *client,
509 uint16_t info, uint32_t length, void *buf,
510 Error **errp)
512 int rc;
514 trace_nbd_negotiate_send_info(info, nbd_info_lookup(info), length);
515 rc = nbd_negotiate_send_rep_len(client, NBD_REP_INFO,
516 sizeof(info) + length, errp);
517 if (rc < 0) {
518 return rc;
520 info = cpu_to_be16(info);
521 if (nbd_write(client->ioc, &info, sizeof(info), errp) < 0) {
522 return -EIO;
524 if (nbd_write(client->ioc, buf, length, errp) < 0) {
525 return -EIO;
527 return 0;
530 /* nbd_reject_length: Handle any unexpected payload.
531 * @fatal requests that we quit talking to the client, even if we are able
532 * to successfully send an error reply.
533 * Return:
534 * -errno transmission error occurred or @fatal was requested, errp is set
535 * 0 error message successfully sent to client, errp is not set
537 static int nbd_reject_length(NBDClient *client, bool fatal, Error **errp)
539 int ret;
541 assert(client->optlen);
542 ret = nbd_opt_invalid(client, errp, "option '%s' has unexpected length",
543 nbd_opt_lookup(client->opt));
544 if (fatal && !ret) {
545 error_setg(errp, "option '%s' has unexpected length",
546 nbd_opt_lookup(client->opt));
547 return -EINVAL;
549 return ret;
552 /* Handle NBD_OPT_INFO and NBD_OPT_GO.
553 * Return -errno on error, 0 if ready for next option, and 1 to move
554 * into transmission phase. */
555 static int nbd_negotiate_handle_info(NBDClient *client, Error **errp)
557 int rc;
558 g_autofree char *name = NULL;
559 NBDExport *exp;
560 uint16_t requests;
561 uint16_t request;
562 uint32_t namelen;
563 bool sendname = false;
564 bool blocksize = false;
565 uint32_t sizes[3];
566 char buf[sizeof(uint64_t) + sizeof(uint16_t)];
567 uint32_t check_align = 0;
568 uint16_t myflags;
570 /* Client sends:
571 4 bytes: L, name length (can be 0)
572 L bytes: export name
573 2 bytes: N, number of requests (can be 0)
574 N * 2 bytes: N requests
576 rc = nbd_opt_read_name(client, &name, &namelen, errp);
577 if (rc <= 0) {
578 return rc;
580 trace_nbd_negotiate_handle_export_name_request(name);
582 rc = nbd_opt_read(client, &requests, sizeof(requests), errp);
583 if (rc <= 0) {
584 return rc;
586 requests = be16_to_cpu(requests);
587 trace_nbd_negotiate_handle_info_requests(requests);
588 while (requests--) {
589 rc = nbd_opt_read(client, &request, sizeof(request), errp);
590 if (rc <= 0) {
591 return rc;
593 request = be16_to_cpu(request);
594 trace_nbd_negotiate_handle_info_request(request,
595 nbd_info_lookup(request));
596 /* We care about NBD_INFO_NAME and NBD_INFO_BLOCK_SIZE;
597 * everything else is either a request we don't know or
598 * something we send regardless of request */
599 switch (request) {
600 case NBD_INFO_NAME:
601 sendname = true;
602 break;
603 case NBD_INFO_BLOCK_SIZE:
604 blocksize = true;
605 break;
608 if (client->optlen) {
609 return nbd_reject_length(client, false, errp);
612 exp = nbd_export_find(name);
613 if (!exp) {
614 g_autofree char *sane_name = nbd_sanitize_name(name);
616 return nbd_negotiate_send_rep_err(client, NBD_REP_ERR_UNKNOWN,
617 errp, "export '%s' not present",
618 sane_name);
621 /* Don't bother sending NBD_INFO_NAME unless client requested it */
622 if (sendname) {
623 rc = nbd_negotiate_send_info(client, NBD_INFO_NAME, namelen, name,
624 errp);
625 if (rc < 0) {
626 return rc;
630 /* Send NBD_INFO_DESCRIPTION only if available, regardless of
631 * client request */
632 if (exp->description) {
633 size_t len = strlen(exp->description);
635 assert(len <= NBD_MAX_STRING_SIZE);
636 rc = nbd_negotiate_send_info(client, NBD_INFO_DESCRIPTION,
637 len, exp->description, errp);
638 if (rc < 0) {
639 return rc;
643 /* Send NBD_INFO_BLOCK_SIZE always, but tweak the minimum size
644 * according to whether the client requested it, and according to
645 * whether this is OPT_INFO or OPT_GO. */
646 /* minimum - 1 for back-compat, or actual if client will obey it. */
647 if (client->opt == NBD_OPT_INFO || blocksize) {
648 check_align = sizes[0] = blk_get_request_alignment(exp->blk);
649 } else {
650 sizes[0] = 1;
652 assert(sizes[0] <= NBD_MAX_BUFFER_SIZE);
653 /* preferred - Hard-code to 4096 for now.
654 * TODO: is blk_bs(blk)->bl.opt_transfer appropriate? */
655 sizes[1] = MAX(4096, sizes[0]);
656 /* maximum - At most 32M, but smaller as appropriate. */
657 sizes[2] = MIN(blk_get_max_transfer(exp->blk), NBD_MAX_BUFFER_SIZE);
658 trace_nbd_negotiate_handle_info_block_size(sizes[0], sizes[1], sizes[2]);
659 sizes[0] = cpu_to_be32(sizes[0]);
660 sizes[1] = cpu_to_be32(sizes[1]);
661 sizes[2] = cpu_to_be32(sizes[2]);
662 rc = nbd_negotiate_send_info(client, NBD_INFO_BLOCK_SIZE,
663 sizeof(sizes), sizes, errp);
664 if (rc < 0) {
665 return rc;
668 /* Send NBD_INFO_EXPORT always */
669 myflags = exp->nbdflags;
670 if (client->structured_reply) {
671 myflags |= NBD_FLAG_SEND_DF;
673 trace_nbd_negotiate_new_style_size_flags(exp->size, myflags);
674 stq_be_p(buf, exp->size);
675 stw_be_p(buf + 8, myflags);
676 rc = nbd_negotiate_send_info(client, NBD_INFO_EXPORT,
677 sizeof(buf), buf, errp);
678 if (rc < 0) {
679 return rc;
683 * If the client is just asking for NBD_OPT_INFO, but forgot to
684 * request block sizes in a situation that would impact
685 * performance, then return an error. But for NBD_OPT_GO, we
686 * tolerate all clients, regardless of alignments.
688 if (client->opt == NBD_OPT_INFO && !blocksize &&
689 blk_get_request_alignment(exp->blk) > 1) {
690 return nbd_negotiate_send_rep_err(client,
691 NBD_REP_ERR_BLOCK_SIZE_REQD,
692 errp,
693 "request NBD_INFO_BLOCK_SIZE to "
694 "use this export");
697 /* Final reply */
698 rc = nbd_negotiate_send_rep(client, NBD_REP_ACK, errp);
699 if (rc < 0) {
700 return rc;
703 if (client->opt == NBD_OPT_GO) {
704 client->exp = exp;
705 client->check_align = check_align;
706 QTAILQ_INSERT_TAIL(&client->exp->clients, client, next);
707 nbd_export_get(client->exp);
708 nbd_check_meta_export(client);
709 rc = 1;
711 return rc;
715 /* Handle NBD_OPT_STARTTLS. Return NULL to drop connection, or else the
716 * new channel for all further (now-encrypted) communication. */
717 static QIOChannel *nbd_negotiate_handle_starttls(NBDClient *client,
718 Error **errp)
720 QIOChannel *ioc;
721 QIOChannelTLS *tioc;
722 struct NBDTLSHandshakeData data = { 0 };
724 assert(client->opt == NBD_OPT_STARTTLS);
726 trace_nbd_negotiate_handle_starttls();
727 ioc = client->ioc;
729 if (nbd_negotiate_send_rep(client, NBD_REP_ACK, errp) < 0) {
730 return NULL;
733 tioc = qio_channel_tls_new_server(ioc,
734 client->tlscreds,
735 client->tlsauthz,
736 errp);
737 if (!tioc) {
738 return NULL;
741 qio_channel_set_name(QIO_CHANNEL(tioc), "nbd-server-tls");
742 trace_nbd_negotiate_handle_starttls_handshake();
743 data.loop = g_main_loop_new(g_main_context_default(), FALSE);
744 qio_channel_tls_handshake(tioc,
745 nbd_tls_handshake,
746 &data,
747 NULL,
748 NULL);
750 if (!data.complete) {
751 g_main_loop_run(data.loop);
753 g_main_loop_unref(data.loop);
754 if (data.error) {
755 object_unref(OBJECT(tioc));
756 error_propagate(errp, data.error);
757 return NULL;
760 return QIO_CHANNEL(tioc);
763 /* nbd_negotiate_send_meta_context
765 * Send one chunk of reply to NBD_OPT_{LIST,SET}_META_CONTEXT
767 * For NBD_OPT_LIST_META_CONTEXT @context_id is ignored, 0 is used instead.
769 static int nbd_negotiate_send_meta_context(NBDClient *client,
770 const char *context,
771 uint32_t context_id,
772 Error **errp)
774 NBDOptionReplyMetaContext opt;
775 struct iovec iov[] = {
776 {.iov_base = &opt, .iov_len = sizeof(opt)},
777 {.iov_base = (void *)context, .iov_len = strlen(context)}
780 assert(iov[1].iov_len <= NBD_MAX_STRING_SIZE);
781 if (client->opt == NBD_OPT_LIST_META_CONTEXT) {
782 context_id = 0;
785 trace_nbd_negotiate_meta_query_reply(context, context_id);
786 set_be_option_rep(&opt.h, client->opt, NBD_REP_META_CONTEXT,
787 sizeof(opt) - sizeof(opt.h) + iov[1].iov_len);
788 stl_be_p(&opt.context_id, context_id);
790 return qio_channel_writev_all(client->ioc, iov, 2, errp) < 0 ? -EIO : 0;
793 /* Read strlen(@pattern) bytes, and set @match to true if they match @pattern.
794 * @match is never set to false.
796 * Return -errno on I/O error, 0 if option was completely handled by
797 * sending a reply about inconsistent lengths, or 1 on success.
799 * Note: return code = 1 doesn't mean that we've read exactly @pattern.
800 * It only means that there are no errors.
802 static int nbd_meta_pattern(NBDClient *client, const char *pattern, bool *match,
803 Error **errp)
805 int ret;
806 char *query;
807 size_t len = strlen(pattern);
809 assert(len);
811 query = g_malloc(len);
812 ret = nbd_opt_read(client, query, len, errp);
813 if (ret <= 0) {
814 g_free(query);
815 return ret;
818 if (strncmp(query, pattern, len) == 0) {
819 trace_nbd_negotiate_meta_query_parse(pattern);
820 *match = true;
821 } else {
822 trace_nbd_negotiate_meta_query_skip("pattern not matched");
824 g_free(query);
826 return 1;
830 * Read @len bytes, and set @match to true if they match @pattern, or if @len
831 * is 0 and the client is performing _LIST_. @match is never set to false.
833 * Return -errno on I/O error, 0 if option was completely handled by
834 * sending a reply about inconsistent lengths, or 1 on success.
836 * Note: return code = 1 doesn't mean that we've read exactly @pattern.
837 * It only means that there are no errors.
839 static int nbd_meta_empty_or_pattern(NBDClient *client, const char *pattern,
840 uint32_t len, bool *match, Error **errp)
842 if (len == 0) {
843 if (client->opt == NBD_OPT_LIST_META_CONTEXT) {
844 *match = true;
846 trace_nbd_negotiate_meta_query_parse("empty");
847 return 1;
850 if (len != strlen(pattern)) {
851 trace_nbd_negotiate_meta_query_skip("different lengths");
852 return nbd_opt_skip(client, len, errp);
855 return nbd_meta_pattern(client, pattern, match, errp);
858 /* nbd_meta_base_query
860 * Handle queries to 'base' namespace. For now, only the base:allocation
861 * context is available. 'len' is the amount of text remaining to be read from
862 * the current name, after the 'base:' portion has been stripped.
864 * Return -errno on I/O error, 0 if option was completely handled by
865 * sending a reply about inconsistent lengths, or 1 on success.
867 static int nbd_meta_base_query(NBDClient *client, NBDExportMetaContexts *meta,
868 uint32_t len, Error **errp)
870 return nbd_meta_empty_or_pattern(client, "allocation", len,
871 &meta->base_allocation, errp);
874 /* nbd_meta_bitmap_query
876 * Handle query to 'qemu:' namespace.
877 * @len is the amount of text remaining to be read from the current name, after
878 * the 'qemu:' portion has been stripped.
880 * Return -errno on I/O error, 0 if option was completely handled by
881 * sending a reply about inconsistent lengths, or 1 on success. */
882 static int nbd_meta_qemu_query(NBDClient *client, NBDExportMetaContexts *meta,
883 uint32_t len, Error **errp)
885 bool dirty_bitmap = false;
886 size_t dirty_bitmap_len = strlen("dirty-bitmap:");
887 int ret;
889 if (!meta->exp->export_bitmap) {
890 trace_nbd_negotiate_meta_query_skip("no dirty-bitmap exported");
891 return nbd_opt_skip(client, len, errp);
894 if (len == 0) {
895 if (client->opt == NBD_OPT_LIST_META_CONTEXT) {
896 meta->bitmap = true;
898 trace_nbd_negotiate_meta_query_parse("empty");
899 return 1;
902 if (len < dirty_bitmap_len) {
903 trace_nbd_negotiate_meta_query_skip("not dirty-bitmap:");
904 return nbd_opt_skip(client, len, errp);
907 len -= dirty_bitmap_len;
908 ret = nbd_meta_pattern(client, "dirty-bitmap:", &dirty_bitmap, errp);
909 if (ret <= 0) {
910 return ret;
912 if (!dirty_bitmap) {
913 trace_nbd_negotiate_meta_query_skip("not dirty-bitmap:");
914 return nbd_opt_skip(client, len, errp);
917 trace_nbd_negotiate_meta_query_parse("dirty-bitmap:");
919 return nbd_meta_empty_or_pattern(
920 client, meta->exp->export_bitmap_context +
921 strlen("qemu:dirty_bitmap:"), len, &meta->bitmap, errp);
924 /* nbd_negotiate_meta_query
926 * Parse namespace name and call corresponding function to parse body of the
927 * query.
929 * The only supported namespaces are 'base' and 'qemu'.
931 * The function aims not wasting time and memory to read long unknown namespace
932 * names.
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 * Both 'qemu' and 'base' namespaces have length = 5 including a
941 * colon. If another length namespace is later introduced, this
942 * should certainly be refactored.
944 int ret;
945 size_t ns_len = 5;
946 char ns[5];
947 uint32_t len;
949 ret = nbd_opt_read(client, &len, sizeof(len), errp);
950 if (ret <= 0) {
951 return ret;
953 len = cpu_to_be32(len);
955 if (len > NBD_MAX_STRING_SIZE) {
956 trace_nbd_negotiate_meta_query_skip("length too long");
957 return nbd_opt_skip(client, len, errp);
959 if (len < ns_len) {
960 trace_nbd_negotiate_meta_query_skip("length too short");
961 return nbd_opt_skip(client, len, errp);
964 len -= ns_len;
965 ret = nbd_opt_read(client, ns, ns_len, errp);
966 if (ret <= 0) {
967 return ret;
970 if (!strncmp(ns, "base:", ns_len)) {
971 trace_nbd_negotiate_meta_query_parse("base:");
972 return nbd_meta_base_query(client, meta, len, errp);
973 } else if (!strncmp(ns, "qemu:", ns_len)) {
974 trace_nbd_negotiate_meta_query_parse("qemu:");
975 return nbd_meta_qemu_query(client, meta, len, errp);
978 trace_nbd_negotiate_meta_query_skip("unknown namespace");
979 return nbd_opt_skip(client, len, errp);
982 /* nbd_negotiate_meta_queries
983 * Handle NBD_OPT_LIST_META_CONTEXT and NBD_OPT_SET_META_CONTEXT
985 * Return -errno on I/O error, or 0 if option was completely handled. */
986 static int nbd_negotiate_meta_queries(NBDClient *client,
987 NBDExportMetaContexts *meta, Error **errp)
989 int ret;
990 g_autofree char *export_name = NULL;
991 NBDExportMetaContexts local_meta;
992 uint32_t nb_queries;
993 int i;
995 if (!client->structured_reply) {
996 return nbd_opt_invalid(client, errp,
997 "request option '%s' when structured reply "
998 "is not negotiated",
999 nbd_opt_lookup(client->opt));
1002 if (client->opt == NBD_OPT_LIST_META_CONTEXT) {
1003 /* Only change the caller's meta on SET. */
1004 meta = &local_meta;
1007 memset(meta, 0, sizeof(*meta));
1009 ret = nbd_opt_read_name(client, &export_name, NULL, errp);
1010 if (ret <= 0) {
1011 return ret;
1014 meta->exp = nbd_export_find(export_name);
1015 if (meta->exp == NULL) {
1016 g_autofree char *sane_name = nbd_sanitize_name(export_name);
1018 return nbd_opt_drop(client, NBD_REP_ERR_UNKNOWN, errp,
1019 "export '%s' not present", sane_name);
1022 ret = nbd_opt_read(client, &nb_queries, sizeof(nb_queries), errp);
1023 if (ret <= 0) {
1024 return ret;
1026 nb_queries = cpu_to_be32(nb_queries);
1027 trace_nbd_negotiate_meta_context(nbd_opt_lookup(client->opt),
1028 export_name, nb_queries);
1030 if (client->opt == NBD_OPT_LIST_META_CONTEXT && !nb_queries) {
1031 /* enable all known contexts */
1032 meta->base_allocation = true;
1033 meta->bitmap = !!meta->exp->export_bitmap;
1034 } else {
1035 for (i = 0; i < nb_queries; ++i) {
1036 ret = nbd_negotiate_meta_query(client, meta, errp);
1037 if (ret <= 0) {
1038 return ret;
1043 if (meta->base_allocation) {
1044 ret = nbd_negotiate_send_meta_context(client, "base:allocation",
1045 NBD_META_ID_BASE_ALLOCATION,
1046 errp);
1047 if (ret < 0) {
1048 return ret;
1052 if (meta->bitmap) {
1053 ret = nbd_negotiate_send_meta_context(client,
1054 meta->exp->export_bitmap_context,
1055 NBD_META_ID_DIRTY_BITMAP,
1056 errp);
1057 if (ret < 0) {
1058 return ret;
1062 ret = nbd_negotiate_send_rep(client, NBD_REP_ACK, errp);
1063 if (ret == 0) {
1064 meta->valid = true;
1067 return ret;
1070 /* nbd_negotiate_options
1071 * Process all NBD_OPT_* client option commands, during fixed newstyle
1072 * negotiation.
1073 * Return:
1074 * -errno on error, errp is set
1075 * 0 on successful negotiation, errp is not set
1076 * 1 if client sent NBD_OPT_ABORT, i.e. on valid disconnect,
1077 * errp is not set
1079 static int nbd_negotiate_options(NBDClient *client, Error **errp)
1081 uint32_t flags;
1082 bool fixedNewstyle = false;
1083 bool no_zeroes = false;
1085 /* Client sends:
1086 [ 0 .. 3] client flags
1088 Then we loop until NBD_OPT_EXPORT_NAME or NBD_OPT_GO:
1089 [ 0 .. 7] NBD_OPTS_MAGIC
1090 [ 8 .. 11] NBD option
1091 [12 .. 15] Data length
1092 ... Rest of request
1094 [ 0 .. 7] NBD_OPTS_MAGIC
1095 [ 8 .. 11] Second NBD option
1096 [12 .. 15] Data length
1097 ... Rest of request
1100 if (nbd_read32(client->ioc, &flags, "flags", errp) < 0) {
1101 return -EIO;
1103 trace_nbd_negotiate_options_flags(flags);
1104 if (flags & NBD_FLAG_C_FIXED_NEWSTYLE) {
1105 fixedNewstyle = true;
1106 flags &= ~NBD_FLAG_C_FIXED_NEWSTYLE;
1108 if (flags & NBD_FLAG_C_NO_ZEROES) {
1109 no_zeroes = true;
1110 flags &= ~NBD_FLAG_C_NO_ZEROES;
1112 if (flags != 0) {
1113 error_setg(errp, "Unknown client flags 0x%" PRIx32 " received", flags);
1114 return -EINVAL;
1117 while (1) {
1118 int ret;
1119 uint32_t option, length;
1120 uint64_t magic;
1122 if (nbd_read64(client->ioc, &magic, "opts magic", errp) < 0) {
1123 return -EINVAL;
1125 trace_nbd_negotiate_options_check_magic(magic);
1126 if (magic != NBD_OPTS_MAGIC) {
1127 error_setg(errp, "Bad magic received");
1128 return -EINVAL;
1131 if (nbd_read32(client->ioc, &option, "option", errp) < 0) {
1132 return -EINVAL;
1134 client->opt = option;
1136 if (nbd_read32(client->ioc, &length, "option length", errp) < 0) {
1137 return -EINVAL;
1139 assert(!client->optlen);
1140 client->optlen = length;
1142 if (length > NBD_MAX_BUFFER_SIZE) {
1143 error_setg(errp, "len (%" PRIu32" ) is larger than max len (%u)",
1144 length, NBD_MAX_BUFFER_SIZE);
1145 return -EINVAL;
1148 trace_nbd_negotiate_options_check_option(option,
1149 nbd_opt_lookup(option));
1150 if (client->tlscreds &&
1151 client->ioc == (QIOChannel *)client->sioc) {
1152 QIOChannel *tioc;
1153 if (!fixedNewstyle) {
1154 error_setg(errp, "Unsupported option 0x%" PRIx32, option);
1155 return -EINVAL;
1157 switch (option) {
1158 case NBD_OPT_STARTTLS:
1159 if (length) {
1160 /* Unconditionally drop the connection if the client
1161 * can't start a TLS negotiation correctly */
1162 return nbd_reject_length(client, true, errp);
1164 tioc = nbd_negotiate_handle_starttls(client, errp);
1165 if (!tioc) {
1166 return -EIO;
1168 ret = 0;
1169 object_unref(OBJECT(client->ioc));
1170 client->ioc = QIO_CHANNEL(tioc);
1171 break;
1173 case NBD_OPT_EXPORT_NAME:
1174 /* No way to return an error to client, so drop connection */
1175 error_setg(errp, "Option 0x%x not permitted before TLS",
1176 option);
1177 return -EINVAL;
1179 default:
1180 /* Let the client keep trying, unless they asked to
1181 * quit. Always try to give an error back to the
1182 * client; but when replying to OPT_ABORT, be aware
1183 * that the client may hang up before receiving the
1184 * error, in which case we are fine ignoring the
1185 * resulting EPIPE. */
1186 ret = nbd_opt_drop(client, NBD_REP_ERR_TLS_REQD,
1187 option == NBD_OPT_ABORT ? NULL : errp,
1188 "Option 0x%" PRIx32
1189 " not permitted before TLS", option);
1190 if (option == NBD_OPT_ABORT) {
1191 return 1;
1193 break;
1195 } else if (fixedNewstyle) {
1196 switch (option) {
1197 case NBD_OPT_LIST:
1198 if (length) {
1199 ret = nbd_reject_length(client, false, errp);
1200 } else {
1201 ret = nbd_negotiate_handle_list(client, errp);
1203 break;
1205 case NBD_OPT_ABORT:
1206 /* NBD spec says we must try to reply before
1207 * disconnecting, but that we must also tolerate
1208 * guests that don't wait for our reply. */
1209 nbd_negotiate_send_rep(client, NBD_REP_ACK, NULL);
1210 return 1;
1212 case NBD_OPT_EXPORT_NAME:
1213 return nbd_negotiate_handle_export_name(client, no_zeroes,
1214 errp);
1216 case NBD_OPT_INFO:
1217 case NBD_OPT_GO:
1218 ret = nbd_negotiate_handle_info(client, errp);
1219 if (ret == 1) {
1220 assert(option == NBD_OPT_GO);
1221 return 0;
1223 break;
1225 case NBD_OPT_STARTTLS:
1226 if (length) {
1227 ret = nbd_reject_length(client, false, errp);
1228 } else if (client->tlscreds) {
1229 ret = nbd_negotiate_send_rep_err(client,
1230 NBD_REP_ERR_INVALID, errp,
1231 "TLS already enabled");
1232 } else {
1233 ret = nbd_negotiate_send_rep_err(client,
1234 NBD_REP_ERR_POLICY, errp,
1235 "TLS not configured");
1237 break;
1239 case NBD_OPT_STRUCTURED_REPLY:
1240 if (length) {
1241 ret = nbd_reject_length(client, false, errp);
1242 } else if (client->structured_reply) {
1243 ret = nbd_negotiate_send_rep_err(
1244 client, NBD_REP_ERR_INVALID, errp,
1245 "structured reply already negotiated");
1246 } else {
1247 ret = nbd_negotiate_send_rep(client, NBD_REP_ACK, errp);
1248 client->structured_reply = true;
1250 break;
1252 case NBD_OPT_LIST_META_CONTEXT:
1253 case NBD_OPT_SET_META_CONTEXT:
1254 ret = nbd_negotiate_meta_queries(client, &client->export_meta,
1255 errp);
1256 break;
1258 default:
1259 ret = nbd_opt_drop(client, NBD_REP_ERR_UNSUP, errp,
1260 "Unsupported option %" PRIu32 " (%s)",
1261 option, nbd_opt_lookup(option));
1262 break;
1264 } else {
1266 * If broken new-style we should drop the connection
1267 * for anything except NBD_OPT_EXPORT_NAME
1269 switch (option) {
1270 case NBD_OPT_EXPORT_NAME:
1271 return nbd_negotiate_handle_export_name(client, no_zeroes,
1272 errp);
1274 default:
1275 error_setg(errp, "Unsupported option %" PRIu32 " (%s)",
1276 option, nbd_opt_lookup(option));
1277 return -EINVAL;
1280 if (ret < 0) {
1281 return ret;
1286 /* nbd_negotiate
1287 * Return:
1288 * -errno on error, errp is set
1289 * 0 on successful negotiation, errp is not set
1290 * 1 if client sent NBD_OPT_ABORT, i.e. on valid disconnect,
1291 * errp is not set
1293 static coroutine_fn int nbd_negotiate(NBDClient *client, Error **errp)
1295 ERRP_GUARD();
1296 char buf[NBD_OLDSTYLE_NEGOTIATE_SIZE] = "";
1297 int ret;
1299 /* Old style negotiation header, no room for options
1300 [ 0 .. 7] passwd ("NBDMAGIC")
1301 [ 8 .. 15] magic (NBD_CLIENT_MAGIC)
1302 [16 .. 23] size
1303 [24 .. 27] export flags (zero-extended)
1304 [28 .. 151] reserved (0)
1306 New style negotiation header, client can send options
1307 [ 0 .. 7] passwd ("NBDMAGIC")
1308 [ 8 .. 15] magic (NBD_OPTS_MAGIC)
1309 [16 .. 17] server flags (0)
1310 ....options sent, ending in NBD_OPT_EXPORT_NAME or NBD_OPT_GO....
1313 qio_channel_set_blocking(client->ioc, false, NULL);
1315 trace_nbd_negotiate_begin();
1316 memcpy(buf, "NBDMAGIC", 8);
1318 stq_be_p(buf + 8, NBD_OPTS_MAGIC);
1319 stw_be_p(buf + 16, NBD_FLAG_FIXED_NEWSTYLE | NBD_FLAG_NO_ZEROES);
1321 if (nbd_write(client->ioc, buf, 18, errp) < 0) {
1322 error_prepend(errp, "write failed: ");
1323 return -EINVAL;
1325 ret = nbd_negotiate_options(client, errp);
1326 if (ret != 0) {
1327 if (ret < 0) {
1328 error_prepend(errp, "option negotiation failed: ");
1330 return ret;
1333 /* Attach the channel to the same AioContext as the export */
1334 if (client->exp && client->exp->ctx) {
1335 qio_channel_attach_aio_context(client->ioc, client->exp->ctx);
1338 assert(!client->optlen);
1339 trace_nbd_negotiate_success();
1341 return 0;
1344 static int nbd_receive_request(QIOChannel *ioc, NBDRequest *request,
1345 Error **errp)
1347 uint8_t buf[NBD_REQUEST_SIZE];
1348 uint32_t magic;
1349 int ret;
1351 ret = nbd_read(ioc, buf, sizeof(buf), "request", errp);
1352 if (ret < 0) {
1353 return ret;
1356 /* Request
1357 [ 0 .. 3] magic (NBD_REQUEST_MAGIC)
1358 [ 4 .. 5] flags (NBD_CMD_FLAG_FUA, ...)
1359 [ 6 .. 7] type (NBD_CMD_READ, ...)
1360 [ 8 .. 15] handle
1361 [16 .. 23] from
1362 [24 .. 27] len
1365 magic = ldl_be_p(buf);
1366 request->flags = lduw_be_p(buf + 4);
1367 request->type = lduw_be_p(buf + 6);
1368 request->handle = ldq_be_p(buf + 8);
1369 request->from = ldq_be_p(buf + 16);
1370 request->len = ldl_be_p(buf + 24);
1372 trace_nbd_receive_request(magic, request->flags, request->type,
1373 request->from, request->len);
1375 if (magic != NBD_REQUEST_MAGIC) {
1376 error_setg(errp, "invalid magic (got 0x%" PRIx32 ")", magic);
1377 return -EINVAL;
1379 return 0;
1382 #define MAX_NBD_REQUESTS 16
1384 void nbd_client_get(NBDClient *client)
1386 client->refcount++;
1389 void nbd_client_put(NBDClient *client)
1391 if (--client->refcount == 0) {
1392 /* The last reference should be dropped by client->close,
1393 * which is called by client_close.
1395 assert(client->closing);
1397 qio_channel_detach_aio_context(client->ioc);
1398 object_unref(OBJECT(client->sioc));
1399 object_unref(OBJECT(client->ioc));
1400 if (client->tlscreds) {
1401 object_unref(OBJECT(client->tlscreds));
1403 g_free(client->tlsauthz);
1404 if (client->exp) {
1405 QTAILQ_REMOVE(&client->exp->clients, client, next);
1406 nbd_export_put(client->exp);
1408 g_free(client);
1412 static void client_close(NBDClient *client, bool negotiated)
1414 if (client->closing) {
1415 return;
1418 client->closing = true;
1420 /* Force requests to finish. They will drop their own references,
1421 * then we'll close the socket and free the NBDClient.
1423 qio_channel_shutdown(client->ioc, QIO_CHANNEL_SHUTDOWN_BOTH,
1424 NULL);
1426 /* Also tell the client, so that they release their reference. */
1427 if (client->close_fn) {
1428 client->close_fn(client, negotiated);
1432 static NBDRequestData *nbd_request_get(NBDClient *client)
1434 NBDRequestData *req;
1436 assert(client->nb_requests <= MAX_NBD_REQUESTS - 1);
1437 client->nb_requests++;
1439 req = g_new0(NBDRequestData, 1);
1440 nbd_client_get(client);
1441 req->client = client;
1442 return req;
1445 static void nbd_request_put(NBDRequestData *req)
1447 NBDClient *client = req->client;
1449 if (req->data) {
1450 qemu_vfree(req->data);
1452 g_free(req);
1454 client->nb_requests--;
1455 nbd_client_receive_next_request(client);
1457 nbd_client_put(client);
1460 static void blk_aio_attached(AioContext *ctx, void *opaque)
1462 NBDExport *exp = opaque;
1463 NBDClient *client;
1465 trace_nbd_blk_aio_attached(exp->name, ctx);
1467 exp->ctx = ctx;
1469 QTAILQ_FOREACH(client, &exp->clients, next) {
1470 qio_channel_attach_aio_context(client->ioc, ctx);
1471 if (client->recv_coroutine) {
1472 aio_co_schedule(ctx, client->recv_coroutine);
1474 if (client->send_coroutine) {
1475 aio_co_schedule(ctx, client->send_coroutine);
1480 static void blk_aio_detach(void *opaque)
1482 NBDExport *exp = opaque;
1483 NBDClient *client;
1485 trace_nbd_blk_aio_detach(exp->name, exp->ctx);
1487 QTAILQ_FOREACH(client, &exp->clients, next) {
1488 qio_channel_detach_aio_context(client->ioc);
1491 exp->ctx = NULL;
1494 static void nbd_eject_notifier(Notifier *n, void *data)
1496 NBDExport *exp = container_of(n, NBDExport, eject_notifier);
1497 AioContext *aio_context;
1499 aio_context = exp->ctx;
1500 aio_context_acquire(aio_context);
1501 nbd_export_close(exp);
1502 aio_context_release(aio_context);
1505 NBDExport *nbd_export_new(BlockDriverState *bs, uint64_t dev_offset,
1506 uint64_t size, const char *name, const char *desc,
1507 const char *bitmap, bool readonly, bool shared,
1508 void (*close)(NBDExport *), bool writethrough,
1509 BlockBackend *on_eject_blk, Error **errp)
1511 AioContext *ctx;
1512 BlockBackend *blk;
1513 NBDExport *exp = g_new0(NBDExport, 1);
1514 uint64_t perm;
1515 int ret;
1518 * NBD exports are used for non-shared storage migration. Make sure
1519 * that BDRV_O_INACTIVE is cleared and the image is ready for write
1520 * access since the export could be available before migration handover.
1521 * ctx was acquired in the caller.
1523 assert(name && strlen(name) <= NBD_MAX_STRING_SIZE);
1524 ctx = bdrv_get_aio_context(bs);
1525 bdrv_invalidate_cache(bs, NULL);
1527 /* Don't allow resize while the NBD server is running, otherwise we don't
1528 * care what happens with the node. */
1529 perm = BLK_PERM_CONSISTENT_READ;
1530 if (!readonly) {
1531 perm |= BLK_PERM_WRITE;
1533 blk = blk_new(ctx, perm,
1534 BLK_PERM_CONSISTENT_READ | BLK_PERM_WRITE_UNCHANGED |
1535 BLK_PERM_WRITE | BLK_PERM_GRAPH_MOD);
1536 ret = blk_insert_bs(blk, bs, errp);
1537 if (ret < 0) {
1538 goto fail;
1540 blk_set_enable_write_cache(blk, !writethrough);
1541 blk_set_allow_aio_context_change(blk, true);
1543 exp->refcount = 1;
1544 QTAILQ_INIT(&exp->clients);
1545 exp->blk = blk;
1546 assert(dev_offset <= INT64_MAX);
1547 exp->dev_offset = dev_offset;
1548 exp->name = g_strdup(name);
1549 assert(!desc || strlen(desc) <= NBD_MAX_STRING_SIZE);
1550 exp->description = g_strdup(desc);
1551 exp->nbdflags = (NBD_FLAG_HAS_FLAGS | NBD_FLAG_SEND_FLUSH |
1552 NBD_FLAG_SEND_FUA | NBD_FLAG_SEND_CACHE);
1553 if (readonly) {
1554 exp->nbdflags |= NBD_FLAG_READ_ONLY;
1555 if (shared) {
1556 exp->nbdflags |= NBD_FLAG_CAN_MULTI_CONN;
1558 } else {
1559 exp->nbdflags |= (NBD_FLAG_SEND_TRIM | NBD_FLAG_SEND_WRITE_ZEROES |
1560 NBD_FLAG_SEND_FAST_ZERO);
1562 assert(size <= INT64_MAX - dev_offset);
1563 exp->size = QEMU_ALIGN_DOWN(size, BDRV_SECTOR_SIZE);
1565 if (bitmap) {
1566 BdrvDirtyBitmap *bm = NULL;
1568 while (true) {
1569 bm = bdrv_find_dirty_bitmap(bs, bitmap);
1570 if (bm != NULL || bs->backing == NULL) {
1571 break;
1574 bs = bs->backing->bs;
1577 if (bm == NULL) {
1578 error_setg(errp, "Bitmap '%s' is not found", bitmap);
1579 goto fail;
1582 if (bdrv_dirty_bitmap_check(bm, BDRV_BITMAP_ALLOW_RO, errp)) {
1583 goto fail;
1586 if (readonly && bdrv_is_writable(bs) &&
1587 bdrv_dirty_bitmap_enabled(bm)) {
1588 error_setg(errp,
1589 "Enabled bitmap '%s' incompatible with readonly export",
1590 bitmap);
1591 goto fail;
1594 bdrv_dirty_bitmap_set_busy(bm, true);
1595 exp->export_bitmap = bm;
1596 assert(strlen(bitmap) <= BDRV_BITMAP_MAX_NAME_SIZE);
1597 exp->export_bitmap_context = g_strdup_printf("qemu:dirty-bitmap:%s",
1598 bitmap);
1599 assert(strlen(exp->export_bitmap_context) < NBD_MAX_STRING_SIZE);
1602 exp->close = close;
1603 exp->ctx = ctx;
1604 blk_add_aio_context_notifier(blk, blk_aio_attached, blk_aio_detach, exp);
1606 if (on_eject_blk) {
1607 blk_ref(on_eject_blk);
1608 exp->eject_notifier_blk = on_eject_blk;
1609 exp->eject_notifier.notify = nbd_eject_notifier;
1610 blk_add_remove_bs_notifier(on_eject_blk, &exp->eject_notifier);
1612 QTAILQ_INSERT_TAIL(&exports, exp, next);
1613 nbd_export_get(exp);
1614 return exp;
1616 fail:
1617 blk_unref(blk);
1618 g_free(exp->name);
1619 g_free(exp->description);
1620 g_free(exp);
1621 return NULL;
1624 NBDExport *nbd_export_find(const char *name)
1626 NBDExport *exp;
1627 QTAILQ_FOREACH(exp, &exports, next) {
1628 if (strcmp(name, exp->name) == 0) {
1629 return exp;
1633 return NULL;
1636 AioContext *
1637 nbd_export_aio_context(NBDExport *exp)
1639 return exp->ctx;
1642 void nbd_export_close(NBDExport *exp)
1644 NBDClient *client, *next;
1646 nbd_export_get(exp);
1648 * TODO: Should we expand QMP NbdServerRemoveNode enum to allow a
1649 * close mode that stops advertising the export to new clients but
1650 * still permits existing clients to run to completion? Because of
1651 * that possibility, nbd_export_close() can be called more than
1652 * once on an export.
1654 QTAILQ_FOREACH_SAFE(client, &exp->clients, next, next) {
1655 client_close(client, true);
1657 if (exp->name) {
1658 nbd_export_put(exp);
1659 g_free(exp->name);
1660 exp->name = NULL;
1661 QTAILQ_REMOVE(&exports, exp, next);
1663 g_free(exp->description);
1664 exp->description = NULL;
1665 nbd_export_put(exp);
1668 void nbd_export_remove(NBDExport *exp, NbdServerRemoveMode mode, Error **errp)
1670 ERRP_GUARD();
1671 if (mode == NBD_SERVER_REMOVE_MODE_HARD || QTAILQ_EMPTY(&exp->clients)) {
1672 nbd_export_close(exp);
1673 return;
1676 assert(mode == NBD_SERVER_REMOVE_MODE_SAFE);
1678 error_setg(errp, "export '%s' still in use", exp->name);
1679 error_append_hint(errp, "Use mode='hard' to force client disconnect\n");
1682 void nbd_export_get(NBDExport *exp)
1684 assert(exp->refcount > 0);
1685 exp->refcount++;
1688 void nbd_export_put(NBDExport *exp)
1690 assert(exp->refcount > 0);
1691 if (exp->refcount == 1) {
1692 nbd_export_close(exp);
1695 /* nbd_export_close() may theoretically reduce refcount to 0. It may happen
1696 * if someone calls nbd_export_put() on named export not through
1697 * nbd_export_set_name() when refcount is 1. So, let's assert that
1698 * it is > 0.
1700 assert(exp->refcount > 0);
1701 if (--exp->refcount == 0) {
1702 assert(exp->name == NULL);
1703 assert(exp->description == NULL);
1705 if (exp->close) {
1706 exp->close(exp);
1709 if (exp->blk) {
1710 if (exp->eject_notifier_blk) {
1711 notifier_remove(&exp->eject_notifier);
1712 blk_unref(exp->eject_notifier_blk);
1714 blk_remove_aio_context_notifier(exp->blk, blk_aio_attached,
1715 blk_aio_detach, exp);
1716 blk_unref(exp->blk);
1717 exp->blk = NULL;
1720 if (exp->export_bitmap) {
1721 bdrv_dirty_bitmap_set_busy(exp->export_bitmap, false);
1722 g_free(exp->export_bitmap_context);
1725 g_free(exp);
1729 BlockBackend *nbd_export_get_blockdev(NBDExport *exp)
1731 return exp->blk;
1734 void nbd_export_close_all(void)
1736 NBDExport *exp, *next;
1737 AioContext *aio_context;
1739 QTAILQ_FOREACH_SAFE(exp, &exports, next, next) {
1740 aio_context = exp->ctx;
1741 aio_context_acquire(aio_context);
1742 nbd_export_close(exp);
1743 aio_context_release(aio_context);
1747 static int coroutine_fn nbd_co_send_iov(NBDClient *client, struct iovec *iov,
1748 unsigned niov, Error **errp)
1750 int ret;
1752 g_assert(qemu_in_coroutine());
1753 qemu_co_mutex_lock(&client->send_lock);
1754 client->send_coroutine = qemu_coroutine_self();
1756 ret = qio_channel_writev_all(client->ioc, iov, niov, errp) < 0 ? -EIO : 0;
1758 client->send_coroutine = NULL;
1759 qemu_co_mutex_unlock(&client->send_lock);
1761 return ret;
1764 static inline void set_be_simple_reply(NBDSimpleReply *reply, uint64_t error,
1765 uint64_t handle)
1767 stl_be_p(&reply->magic, NBD_SIMPLE_REPLY_MAGIC);
1768 stl_be_p(&reply->error, error);
1769 stq_be_p(&reply->handle, handle);
1772 static int nbd_co_send_simple_reply(NBDClient *client,
1773 uint64_t handle,
1774 uint32_t error,
1775 void *data,
1776 size_t len,
1777 Error **errp)
1779 NBDSimpleReply reply;
1780 int nbd_err = system_errno_to_nbd_errno(error);
1781 struct iovec iov[] = {
1782 {.iov_base = &reply, .iov_len = sizeof(reply)},
1783 {.iov_base = data, .iov_len = len}
1786 trace_nbd_co_send_simple_reply(handle, nbd_err, nbd_err_lookup(nbd_err),
1787 len);
1788 set_be_simple_reply(&reply, nbd_err, handle);
1790 return nbd_co_send_iov(client, iov, len ? 2 : 1, errp);
1793 static inline void set_be_chunk(NBDStructuredReplyChunk *chunk, uint16_t flags,
1794 uint16_t type, uint64_t handle, uint32_t length)
1796 stl_be_p(&chunk->magic, NBD_STRUCTURED_REPLY_MAGIC);
1797 stw_be_p(&chunk->flags, flags);
1798 stw_be_p(&chunk->type, type);
1799 stq_be_p(&chunk->handle, handle);
1800 stl_be_p(&chunk->length, length);
1803 static int coroutine_fn nbd_co_send_structured_done(NBDClient *client,
1804 uint64_t handle,
1805 Error **errp)
1807 NBDStructuredReplyChunk chunk;
1808 struct iovec iov[] = {
1809 {.iov_base = &chunk, .iov_len = sizeof(chunk)},
1812 trace_nbd_co_send_structured_done(handle);
1813 set_be_chunk(&chunk, NBD_REPLY_FLAG_DONE, NBD_REPLY_TYPE_NONE, handle, 0);
1815 return nbd_co_send_iov(client, iov, 1, errp);
1818 static int coroutine_fn nbd_co_send_structured_read(NBDClient *client,
1819 uint64_t handle,
1820 uint64_t offset,
1821 void *data,
1822 size_t size,
1823 bool final,
1824 Error **errp)
1826 NBDStructuredReadData chunk;
1827 struct iovec iov[] = {
1828 {.iov_base = &chunk, .iov_len = sizeof(chunk)},
1829 {.iov_base = data, .iov_len = size}
1832 assert(size);
1833 trace_nbd_co_send_structured_read(handle, offset, data, size);
1834 set_be_chunk(&chunk.h, final ? NBD_REPLY_FLAG_DONE : 0,
1835 NBD_REPLY_TYPE_OFFSET_DATA, handle,
1836 sizeof(chunk) - sizeof(chunk.h) + size);
1837 stq_be_p(&chunk.offset, offset);
1839 return nbd_co_send_iov(client, iov, 2, errp);
1842 static int coroutine_fn nbd_co_send_structured_error(NBDClient *client,
1843 uint64_t handle,
1844 uint32_t error,
1845 const char *msg,
1846 Error **errp)
1848 NBDStructuredError chunk;
1849 int nbd_err = system_errno_to_nbd_errno(error);
1850 struct iovec iov[] = {
1851 {.iov_base = &chunk, .iov_len = sizeof(chunk)},
1852 {.iov_base = (char *)msg, .iov_len = msg ? strlen(msg) : 0},
1855 assert(nbd_err);
1856 trace_nbd_co_send_structured_error(handle, nbd_err,
1857 nbd_err_lookup(nbd_err), msg ? msg : "");
1858 set_be_chunk(&chunk.h, NBD_REPLY_FLAG_DONE, NBD_REPLY_TYPE_ERROR, handle,
1859 sizeof(chunk) - sizeof(chunk.h) + iov[1].iov_len);
1860 stl_be_p(&chunk.error, nbd_err);
1861 stw_be_p(&chunk.message_length, iov[1].iov_len);
1863 return nbd_co_send_iov(client, iov, 1 + !!iov[1].iov_len, errp);
1866 /* Do a sparse read and send the structured reply to the client.
1867 * Returns -errno if sending fails. bdrv_block_status_above() failure is
1868 * reported to the client, at which point this function succeeds.
1870 static int coroutine_fn nbd_co_send_sparse_read(NBDClient *client,
1871 uint64_t handle,
1872 uint64_t offset,
1873 uint8_t *data,
1874 size_t size,
1875 Error **errp)
1877 int ret = 0;
1878 NBDExport *exp = client->exp;
1879 size_t progress = 0;
1881 while (progress < size) {
1882 int64_t pnum;
1883 int status = bdrv_block_status_above(blk_bs(exp->blk), NULL,
1884 offset + progress,
1885 size - progress, &pnum, NULL,
1886 NULL);
1887 bool final;
1889 if (status < 0) {
1890 char *msg = g_strdup_printf("unable to check for holes: %s",
1891 strerror(-status));
1893 ret = nbd_co_send_structured_error(client, handle, -status, msg,
1894 errp);
1895 g_free(msg);
1896 return ret;
1898 assert(pnum && pnum <= size - progress);
1899 final = progress + pnum == size;
1900 if (status & BDRV_BLOCK_ZERO) {
1901 NBDStructuredReadHole chunk;
1902 struct iovec iov[] = {
1903 {.iov_base = &chunk, .iov_len = sizeof(chunk)},
1906 trace_nbd_co_send_structured_read_hole(handle, offset + progress,
1907 pnum);
1908 set_be_chunk(&chunk.h, final ? NBD_REPLY_FLAG_DONE : 0,
1909 NBD_REPLY_TYPE_OFFSET_HOLE,
1910 handle, sizeof(chunk) - sizeof(chunk.h));
1911 stq_be_p(&chunk.offset, offset + progress);
1912 stl_be_p(&chunk.length, pnum);
1913 ret = nbd_co_send_iov(client, iov, 1, errp);
1914 } else {
1915 ret = blk_pread(exp->blk, offset + progress + exp->dev_offset,
1916 data + progress, pnum);
1917 if (ret < 0) {
1918 error_setg_errno(errp, -ret, "reading from file failed");
1919 break;
1921 ret = nbd_co_send_structured_read(client, handle, offset + progress,
1922 data + progress, pnum, final,
1923 errp);
1926 if (ret < 0) {
1927 break;
1929 progress += pnum;
1931 return ret;
1934 typedef struct NBDExtentArray {
1935 NBDExtent *extents;
1936 unsigned int nb_alloc;
1937 unsigned int count;
1938 uint64_t total_length;
1939 bool can_add;
1940 bool converted_to_be;
1941 } NBDExtentArray;
1943 static NBDExtentArray *nbd_extent_array_new(unsigned int nb_alloc)
1945 NBDExtentArray *ea = g_new0(NBDExtentArray, 1);
1947 ea->nb_alloc = nb_alloc;
1948 ea->extents = g_new(NBDExtent, nb_alloc);
1949 ea->can_add = true;
1951 return ea;
1954 static void nbd_extent_array_free(NBDExtentArray *ea)
1956 g_free(ea->extents);
1957 g_free(ea);
1959 G_DEFINE_AUTOPTR_CLEANUP_FUNC(NBDExtentArray, nbd_extent_array_free);
1961 /* Further modifications of the array after conversion are abandoned */
1962 static void nbd_extent_array_convert_to_be(NBDExtentArray *ea)
1964 int i;
1966 assert(!ea->converted_to_be);
1967 ea->can_add = false;
1968 ea->converted_to_be = true;
1970 for (i = 0; i < ea->count; i++) {
1971 ea->extents[i].flags = cpu_to_be32(ea->extents[i].flags);
1972 ea->extents[i].length = cpu_to_be32(ea->extents[i].length);
1977 * Add extent to NBDExtentArray. If extent can't be added (no available space),
1978 * return -1.
1979 * For safety, when returning -1 for the first time, .can_add is set to false,
1980 * further call to nbd_extent_array_add() will crash.
1981 * (to avoid the situation, when after failing to add an extent (returned -1),
1982 * user miss this failure and add another extent, which is successfully added
1983 * (array is full, but new extent may be squashed into the last one), then we
1984 * have invalid array with skipped extent)
1986 static int nbd_extent_array_add(NBDExtentArray *ea,
1987 uint32_t length, uint32_t flags)
1989 assert(ea->can_add);
1991 if (!length) {
1992 return 0;
1995 /* Extend previous extent if flags are the same */
1996 if (ea->count > 0 && flags == ea->extents[ea->count - 1].flags) {
1997 uint64_t sum = (uint64_t)length + ea->extents[ea->count - 1].length;
1999 if (sum <= UINT32_MAX) {
2000 ea->extents[ea->count - 1].length = sum;
2001 ea->total_length += length;
2002 return 0;
2006 if (ea->count >= ea->nb_alloc) {
2007 ea->can_add = false;
2008 return -1;
2011 ea->total_length += length;
2012 ea->extents[ea->count] = (NBDExtent) {.length = length, .flags = flags};
2013 ea->count++;
2015 return 0;
2018 static int blockstatus_to_extents(BlockDriverState *bs, uint64_t offset,
2019 uint64_t bytes, NBDExtentArray *ea)
2021 while (bytes) {
2022 uint32_t flags;
2023 int64_t num;
2024 int ret = bdrv_block_status_above(bs, NULL, offset, bytes, &num,
2025 NULL, NULL);
2027 if (ret < 0) {
2028 return ret;
2031 flags = (ret & BDRV_BLOCK_ALLOCATED ? 0 : NBD_STATE_HOLE) |
2032 (ret & BDRV_BLOCK_ZERO ? NBD_STATE_ZERO : 0);
2034 if (nbd_extent_array_add(ea, num, flags) < 0) {
2035 return 0;
2038 offset += num;
2039 bytes -= num;
2042 return 0;
2046 * nbd_co_send_extents
2048 * @ea is converted to BE by the function
2049 * @last controls whether NBD_REPLY_FLAG_DONE is sent.
2051 static int nbd_co_send_extents(NBDClient *client, uint64_t handle,
2052 NBDExtentArray *ea,
2053 bool last, uint32_t context_id, Error **errp)
2055 NBDStructuredMeta chunk;
2056 struct iovec iov[] = {
2057 {.iov_base = &chunk, .iov_len = sizeof(chunk)},
2058 {.iov_base = ea->extents, .iov_len = ea->count * sizeof(ea->extents[0])}
2061 nbd_extent_array_convert_to_be(ea);
2063 trace_nbd_co_send_extents(handle, ea->count, context_id, ea->total_length,
2064 last);
2065 set_be_chunk(&chunk.h, last ? NBD_REPLY_FLAG_DONE : 0,
2066 NBD_REPLY_TYPE_BLOCK_STATUS,
2067 handle, sizeof(chunk) - sizeof(chunk.h) + iov[1].iov_len);
2068 stl_be_p(&chunk.context_id, context_id);
2070 return nbd_co_send_iov(client, iov, 2, errp);
2073 /* Get block status from the exported device and send it to the client */
2074 static int nbd_co_send_block_status(NBDClient *client, uint64_t handle,
2075 BlockDriverState *bs, uint64_t offset,
2076 uint32_t length, bool dont_fragment,
2077 bool last, uint32_t context_id,
2078 Error **errp)
2080 int ret;
2081 unsigned int nb_extents = dont_fragment ? 1 : NBD_MAX_BLOCK_STATUS_EXTENTS;
2082 g_autoptr(NBDExtentArray) ea = nbd_extent_array_new(nb_extents);
2084 ret = blockstatus_to_extents(bs, offset, length, ea);
2085 if (ret < 0) {
2086 return nbd_co_send_structured_error(
2087 client, handle, -ret, "can't get block status", errp);
2090 return nbd_co_send_extents(client, handle, ea, last, context_id, errp);
2093 /* Populate @ea from a dirty bitmap. */
2094 static void bitmap_to_extents(BdrvDirtyBitmap *bitmap,
2095 uint64_t offset, uint64_t length,
2096 NBDExtentArray *es)
2098 int64_t start, dirty_start, dirty_count;
2099 int64_t end = offset + length;
2100 bool full = false;
2102 bdrv_dirty_bitmap_lock(bitmap);
2104 for (start = offset;
2105 bdrv_dirty_bitmap_next_dirty_area(bitmap, start, end, INT32_MAX,
2106 &dirty_start, &dirty_count);
2107 start = dirty_start + dirty_count)
2109 if ((nbd_extent_array_add(es, dirty_start - start, 0) < 0) ||
2110 (nbd_extent_array_add(es, dirty_count, NBD_STATE_DIRTY) < 0))
2112 full = true;
2113 break;
2117 if (!full) {
2118 /* last non dirty extent */
2119 nbd_extent_array_add(es, end - start, 0);
2122 bdrv_dirty_bitmap_unlock(bitmap);
2125 static int nbd_co_send_bitmap(NBDClient *client, uint64_t handle,
2126 BdrvDirtyBitmap *bitmap, uint64_t offset,
2127 uint32_t length, bool dont_fragment, bool last,
2128 uint32_t context_id, Error **errp)
2130 unsigned int nb_extents = dont_fragment ? 1 : NBD_MAX_BLOCK_STATUS_EXTENTS;
2131 g_autoptr(NBDExtentArray) ea = nbd_extent_array_new(nb_extents);
2133 bitmap_to_extents(bitmap, offset, length, ea);
2135 return nbd_co_send_extents(client, handle, ea, last, context_id, errp);
2138 /* nbd_co_receive_request
2139 * Collect a client request. Return 0 if request looks valid, -EIO to drop
2140 * connection right away, and any other negative value to report an error to
2141 * the client (although the caller may still need to disconnect after reporting
2142 * the error).
2144 static int nbd_co_receive_request(NBDRequestData *req, NBDRequest *request,
2145 Error **errp)
2147 NBDClient *client = req->client;
2148 int valid_flags;
2150 g_assert(qemu_in_coroutine());
2151 assert(client->recv_coroutine == qemu_coroutine_self());
2152 if (nbd_receive_request(client->ioc, request, errp) < 0) {
2153 return -EIO;
2156 trace_nbd_co_receive_request_decode_type(request->handle, request->type,
2157 nbd_cmd_lookup(request->type));
2159 if (request->type != NBD_CMD_WRITE) {
2160 /* No payload, we are ready to read the next request. */
2161 req->complete = true;
2164 if (request->type == NBD_CMD_DISC) {
2165 /* Special case: we're going to disconnect without a reply,
2166 * whether or not flags, from, or len are bogus */
2167 return -EIO;
2170 if (request->type == NBD_CMD_READ || request->type == NBD_CMD_WRITE ||
2171 request->type == NBD_CMD_CACHE)
2173 if (request->len > NBD_MAX_BUFFER_SIZE) {
2174 error_setg(errp, "len (%" PRIu32" ) is larger than max len (%u)",
2175 request->len, NBD_MAX_BUFFER_SIZE);
2176 return -EINVAL;
2179 if (request->type != NBD_CMD_CACHE) {
2180 req->data = blk_try_blockalign(client->exp->blk, request->len);
2181 if (req->data == NULL) {
2182 error_setg(errp, "No memory");
2183 return -ENOMEM;
2188 if (request->type == NBD_CMD_WRITE) {
2189 if (nbd_read(client->ioc, req->data, request->len, "CMD_WRITE data",
2190 errp) < 0)
2192 return -EIO;
2194 req->complete = true;
2196 trace_nbd_co_receive_request_payload_received(request->handle,
2197 request->len);
2200 /* Sanity checks. */
2201 if (client->exp->nbdflags & NBD_FLAG_READ_ONLY &&
2202 (request->type == NBD_CMD_WRITE ||
2203 request->type == NBD_CMD_WRITE_ZEROES ||
2204 request->type == NBD_CMD_TRIM)) {
2205 error_setg(errp, "Export is read-only");
2206 return -EROFS;
2208 if (request->from > client->exp->size ||
2209 request->len > client->exp->size - request->from) {
2210 error_setg(errp, "operation past EOF; From: %" PRIu64 ", Len: %" PRIu32
2211 ", Size: %" PRIu64, request->from, request->len,
2212 client->exp->size);
2213 return (request->type == NBD_CMD_WRITE ||
2214 request->type == NBD_CMD_WRITE_ZEROES) ? -ENOSPC : -EINVAL;
2216 if (client->check_align && !QEMU_IS_ALIGNED(request->from | request->len,
2217 client->check_align)) {
2219 * The block layer gracefully handles unaligned requests, but
2220 * it's still worth tracing client non-compliance
2222 trace_nbd_co_receive_align_compliance(nbd_cmd_lookup(request->type),
2223 request->from,
2224 request->len,
2225 client->check_align);
2227 valid_flags = NBD_CMD_FLAG_FUA;
2228 if (request->type == NBD_CMD_READ && client->structured_reply) {
2229 valid_flags |= NBD_CMD_FLAG_DF;
2230 } else if (request->type == NBD_CMD_WRITE_ZEROES) {
2231 valid_flags |= NBD_CMD_FLAG_NO_HOLE | NBD_CMD_FLAG_FAST_ZERO;
2232 } else if (request->type == NBD_CMD_BLOCK_STATUS) {
2233 valid_flags |= NBD_CMD_FLAG_REQ_ONE;
2235 if (request->flags & ~valid_flags) {
2236 error_setg(errp, "unsupported flags for command %s (got 0x%x)",
2237 nbd_cmd_lookup(request->type), request->flags);
2238 return -EINVAL;
2241 return 0;
2244 /* Send simple reply without a payload, or a structured error
2245 * @error_msg is ignored if @ret >= 0
2246 * Returns 0 if connection is still live, -errno on failure to talk to client
2248 static coroutine_fn int nbd_send_generic_reply(NBDClient *client,
2249 uint64_t handle,
2250 int ret,
2251 const char *error_msg,
2252 Error **errp)
2254 if (client->structured_reply && ret < 0) {
2255 return nbd_co_send_structured_error(client, handle, -ret, error_msg,
2256 errp);
2257 } else {
2258 return nbd_co_send_simple_reply(client, handle, ret < 0 ? -ret : 0,
2259 NULL, 0, errp);
2263 /* Handle NBD_CMD_READ request.
2264 * Return -errno if sending fails. Other errors are reported directly to the
2265 * client as an error reply. */
2266 static coroutine_fn int nbd_do_cmd_read(NBDClient *client, NBDRequest *request,
2267 uint8_t *data, Error **errp)
2269 int ret;
2270 NBDExport *exp = client->exp;
2272 assert(request->type == NBD_CMD_READ);
2274 /* XXX: NBD Protocol only documents use of FUA with WRITE */
2275 if (request->flags & NBD_CMD_FLAG_FUA) {
2276 ret = blk_co_flush(exp->blk);
2277 if (ret < 0) {
2278 return nbd_send_generic_reply(client, request->handle, ret,
2279 "flush failed", errp);
2283 if (client->structured_reply && !(request->flags & NBD_CMD_FLAG_DF) &&
2284 request->len)
2286 return nbd_co_send_sparse_read(client, request->handle, request->from,
2287 data, request->len, errp);
2290 ret = blk_pread(exp->blk, request->from + exp->dev_offset, data,
2291 request->len);
2292 if (ret < 0) {
2293 return nbd_send_generic_reply(client, request->handle, ret,
2294 "reading from file failed", errp);
2297 if (client->structured_reply) {
2298 if (request->len) {
2299 return nbd_co_send_structured_read(client, request->handle,
2300 request->from, data,
2301 request->len, true, errp);
2302 } else {
2303 return nbd_co_send_structured_done(client, request->handle, errp);
2305 } else {
2306 return nbd_co_send_simple_reply(client, request->handle, 0,
2307 data, request->len, errp);
2312 * nbd_do_cmd_cache
2314 * Handle NBD_CMD_CACHE request.
2315 * Return -errno if sending fails. Other errors are reported directly to the
2316 * client as an error reply.
2318 static coroutine_fn int nbd_do_cmd_cache(NBDClient *client, NBDRequest *request,
2319 Error **errp)
2321 int ret;
2322 NBDExport *exp = client->exp;
2324 assert(request->type == NBD_CMD_CACHE);
2326 ret = blk_co_preadv(exp->blk, request->from + exp->dev_offset, request->len,
2327 NULL, BDRV_REQ_COPY_ON_READ | BDRV_REQ_PREFETCH);
2329 return nbd_send_generic_reply(client, request->handle, ret,
2330 "caching data failed", errp);
2333 /* Handle NBD request.
2334 * Return -errno if sending fails. Other errors are reported directly to the
2335 * client as an error reply. */
2336 static coroutine_fn int nbd_handle_request(NBDClient *client,
2337 NBDRequest *request,
2338 uint8_t *data, Error **errp)
2340 int ret;
2341 int flags;
2342 NBDExport *exp = client->exp;
2343 char *msg;
2345 switch (request->type) {
2346 case NBD_CMD_CACHE:
2347 return nbd_do_cmd_cache(client, request, errp);
2349 case NBD_CMD_READ:
2350 return nbd_do_cmd_read(client, request, data, errp);
2352 case NBD_CMD_WRITE:
2353 flags = 0;
2354 if (request->flags & NBD_CMD_FLAG_FUA) {
2355 flags |= BDRV_REQ_FUA;
2357 ret = blk_pwrite(exp->blk, request->from + exp->dev_offset,
2358 data, request->len, flags);
2359 return nbd_send_generic_reply(client, request->handle, ret,
2360 "writing to file failed", errp);
2362 case NBD_CMD_WRITE_ZEROES:
2363 flags = 0;
2364 if (request->flags & NBD_CMD_FLAG_FUA) {
2365 flags |= BDRV_REQ_FUA;
2367 if (!(request->flags & NBD_CMD_FLAG_NO_HOLE)) {
2368 flags |= BDRV_REQ_MAY_UNMAP;
2370 if (request->flags & NBD_CMD_FLAG_FAST_ZERO) {
2371 flags |= BDRV_REQ_NO_FALLBACK;
2373 ret = blk_pwrite_zeroes(exp->blk, request->from + exp->dev_offset,
2374 request->len, flags);
2375 return nbd_send_generic_reply(client, request->handle, ret,
2376 "writing to file failed", errp);
2378 case NBD_CMD_DISC:
2379 /* unreachable, thanks to special case in nbd_co_receive_request() */
2380 abort();
2382 case NBD_CMD_FLUSH:
2383 ret = blk_co_flush(exp->blk);
2384 return nbd_send_generic_reply(client, request->handle, ret,
2385 "flush failed", errp);
2387 case NBD_CMD_TRIM:
2388 ret = blk_co_pdiscard(exp->blk, request->from + exp->dev_offset,
2389 request->len);
2390 if (ret == 0 && request->flags & NBD_CMD_FLAG_FUA) {
2391 ret = blk_co_flush(exp->blk);
2393 return nbd_send_generic_reply(client, request->handle, ret,
2394 "discard failed", errp);
2396 case NBD_CMD_BLOCK_STATUS:
2397 if (!request->len) {
2398 return nbd_send_generic_reply(client, request->handle, -EINVAL,
2399 "need non-zero length", errp);
2401 if (client->export_meta.valid &&
2402 (client->export_meta.base_allocation ||
2403 client->export_meta.bitmap))
2405 bool dont_fragment = request->flags & NBD_CMD_FLAG_REQ_ONE;
2407 if (client->export_meta.base_allocation) {
2408 ret = nbd_co_send_block_status(client, request->handle,
2409 blk_bs(exp->blk), request->from,
2410 request->len, dont_fragment,
2411 !client->export_meta.bitmap,
2412 NBD_META_ID_BASE_ALLOCATION,
2413 errp);
2414 if (ret < 0) {
2415 return ret;
2419 if (client->export_meta.bitmap) {
2420 ret = nbd_co_send_bitmap(client, request->handle,
2421 client->exp->export_bitmap,
2422 request->from, request->len,
2423 dont_fragment,
2424 true, NBD_META_ID_DIRTY_BITMAP, errp);
2425 if (ret < 0) {
2426 return ret;
2430 return 0;
2431 } else {
2432 return nbd_send_generic_reply(client, request->handle, -EINVAL,
2433 "CMD_BLOCK_STATUS not negotiated",
2434 errp);
2437 default:
2438 msg = g_strdup_printf("invalid request type (%" PRIu32 ") received",
2439 request->type);
2440 ret = nbd_send_generic_reply(client, request->handle, -EINVAL, msg,
2441 errp);
2442 g_free(msg);
2443 return ret;
2447 /* Owns a reference to the NBDClient passed as opaque. */
2448 static coroutine_fn void nbd_trip(void *opaque)
2450 NBDClient *client = opaque;
2451 NBDRequestData *req;
2452 NBDRequest request = { 0 }; /* GCC thinks it can be used uninitialized */
2453 int ret;
2454 Error *local_err = NULL;
2456 trace_nbd_trip();
2457 if (client->closing) {
2458 nbd_client_put(client);
2459 return;
2462 req = nbd_request_get(client);
2463 ret = nbd_co_receive_request(req, &request, &local_err);
2464 client->recv_coroutine = NULL;
2466 if (client->closing) {
2468 * The client may be closed when we are blocked in
2469 * nbd_co_receive_request()
2471 goto done;
2474 nbd_client_receive_next_request(client);
2475 if (ret == -EIO) {
2476 goto disconnect;
2479 if (ret < 0) {
2480 /* It wans't -EIO, so, according to nbd_co_receive_request()
2481 * semantics, we should return the error to the client. */
2482 Error *export_err = local_err;
2484 local_err = NULL;
2485 ret = nbd_send_generic_reply(client, request.handle, -EINVAL,
2486 error_get_pretty(export_err), &local_err);
2487 error_free(export_err);
2488 } else {
2489 ret = nbd_handle_request(client, &request, req->data, &local_err);
2491 if (ret < 0) {
2492 error_prepend(&local_err, "Failed to send reply: ");
2493 goto disconnect;
2496 /* We must disconnect after NBD_CMD_WRITE if we did not
2497 * read the payload.
2499 if (!req->complete) {
2500 error_setg(&local_err, "Request handling failed in intermediate state");
2501 goto disconnect;
2504 done:
2505 nbd_request_put(req);
2506 nbd_client_put(client);
2507 return;
2509 disconnect:
2510 if (local_err) {
2511 error_reportf_err(local_err, "Disconnect client, due to: ");
2513 nbd_request_put(req);
2514 client_close(client, true);
2515 nbd_client_put(client);
2518 static void nbd_client_receive_next_request(NBDClient *client)
2520 if (!client->recv_coroutine && client->nb_requests < MAX_NBD_REQUESTS) {
2521 nbd_client_get(client);
2522 client->recv_coroutine = qemu_coroutine_create(nbd_trip, client);
2523 aio_co_schedule(client->exp->ctx, client->recv_coroutine);
2527 static coroutine_fn void nbd_co_client_start(void *opaque)
2529 NBDClient *client = opaque;
2530 Error *local_err = NULL;
2532 qemu_co_mutex_init(&client->send_lock);
2534 if (nbd_negotiate(client, &local_err)) {
2535 if (local_err) {
2536 error_report_err(local_err);
2538 client_close(client, false);
2539 return;
2542 nbd_client_receive_next_request(client);
2546 * Create a new client listener using the given channel @sioc.
2547 * Begin servicing it in a coroutine. When the connection closes, call
2548 * @close_fn with an indication of whether the client completed negotiation.
2550 void nbd_client_new(QIOChannelSocket *sioc,
2551 QCryptoTLSCreds *tlscreds,
2552 const char *tlsauthz,
2553 void (*close_fn)(NBDClient *, bool))
2555 NBDClient *client;
2556 Coroutine *co;
2558 client = g_new0(NBDClient, 1);
2559 client->refcount = 1;
2560 client->tlscreds = tlscreds;
2561 if (tlscreds) {
2562 object_ref(OBJECT(client->tlscreds));
2564 client->tlsauthz = g_strdup(tlsauthz);
2565 client->sioc = sioc;
2566 object_ref(OBJECT(client->sioc));
2567 client->ioc = QIO_CHANNEL(sioc);
2568 object_ref(OBJECT(client->ioc));
2569 client->close_fn = close_fn;
2571 co = qemu_coroutine_create(nbd_co_client_start, client);
2572 qemu_coroutine_enter(co);