mips/mips_jazz: add max ram size check
[qemu.git] / nbd / server.c
blob87fcd2e7bfac12e98b21c036356e1d20b1386e1f
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 g_autofree char *msg = NULL;
215 int ret;
216 size_t len;
218 msg = g_strdup_vprintf(fmt, va);
219 len = strlen(msg);
220 assert(len < 4096);
221 trace_nbd_negotiate_send_rep_err(msg);
222 ret = nbd_negotiate_send_rep_len(client, type, len, errp);
223 if (ret < 0) {
224 return ret;
226 if (nbd_write(client->ioc, msg, len, errp) < 0) {
227 error_prepend(errp, "write failed (error message): ");
228 return -EIO;
231 return 0;
234 /* Send an error reply.
235 * Return -errno on error, 0 on success. */
236 static int GCC_FMT_ATTR(4, 5)
237 nbd_negotiate_send_rep_err(NBDClient *client, uint32_t type,
238 Error **errp, const char *fmt, ...)
240 va_list va;
241 int ret;
243 va_start(va, fmt);
244 ret = nbd_negotiate_send_rep_verr(client, type, errp, fmt, va);
245 va_end(va);
246 return ret;
249 /* Drop remainder of the current option, and send a reply with the
250 * given error type and message. Return -errno on read or write
251 * failure; or 0 if connection is still live. */
252 static int GCC_FMT_ATTR(4, 0)
253 nbd_opt_vdrop(NBDClient *client, uint32_t type, Error **errp,
254 const char *fmt, va_list va)
256 int ret = nbd_drop(client->ioc, client->optlen, errp);
258 client->optlen = 0;
259 if (!ret) {
260 ret = nbd_negotiate_send_rep_verr(client, type, errp, fmt, va);
262 return ret;
265 static int GCC_FMT_ATTR(4, 5)
266 nbd_opt_drop(NBDClient *client, uint32_t type, Error **errp,
267 const char *fmt, ...)
269 int ret;
270 va_list va;
272 va_start(va, fmt);
273 ret = nbd_opt_vdrop(client, type, errp, fmt, va);
274 va_end(va);
276 return ret;
279 static int GCC_FMT_ATTR(3, 4)
280 nbd_opt_invalid(NBDClient *client, Error **errp, const char *fmt, ...)
282 int ret;
283 va_list va;
285 va_start(va, fmt);
286 ret = nbd_opt_vdrop(client, NBD_REP_ERR_INVALID, errp, fmt, va);
287 va_end(va);
289 return ret;
292 /* Read size bytes from the unparsed payload of the current option.
293 * Return -errno on I/O error, 0 if option was completely handled by
294 * sending a reply about inconsistent lengths, or 1 on success. */
295 static int nbd_opt_read(NBDClient *client, void *buffer, size_t size,
296 Error **errp)
298 if (size > client->optlen) {
299 return nbd_opt_invalid(client, errp,
300 "Inconsistent lengths in option %s",
301 nbd_opt_lookup(client->opt));
303 client->optlen -= size;
304 return qio_channel_read_all(client->ioc, buffer, size, errp) < 0 ? -EIO : 1;
307 /* Drop size bytes from the unparsed payload of the current option.
308 * Return -errno on I/O error, 0 if option was completely handled by
309 * sending a reply about inconsistent lengths, or 1 on success. */
310 static int nbd_opt_skip(NBDClient *client, size_t size, 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 nbd_drop(client->ioc, size, errp) < 0 ? -EIO : 1;
321 /* nbd_opt_read_name
323 * Read a string with the format:
324 * uint32_t len (<= NBD_MAX_STRING_SIZE)
325 * len bytes string (not 0-terminated)
327 * On success, @name will be allocated.
328 * If @length is non-null, it will be set to the actual string length.
330 * Return -errno on I/O error, 0 if option was completely handled by
331 * sending a reply about inconsistent lengths, or 1 on success.
333 static int nbd_opt_read_name(NBDClient *client, char **name, uint32_t *length,
334 Error **errp)
336 int ret;
337 uint32_t len;
338 g_autofree char *local_name = NULL;
340 *name = NULL;
341 ret = nbd_opt_read(client, &len, sizeof(len), errp);
342 if (ret <= 0) {
343 return ret;
345 len = cpu_to_be32(len);
347 if (len > NBD_MAX_STRING_SIZE) {
348 return nbd_opt_invalid(client, errp,
349 "Invalid name length: %" PRIu32, len);
352 local_name = g_malloc(len + 1);
353 ret = nbd_opt_read(client, local_name, len, errp);
354 if (ret <= 0) {
355 return ret;
357 local_name[len] = '\0';
359 if (length) {
360 *length = len;
362 *name = g_steal_pointer(&local_name);
364 return 1;
367 /* Send a single NBD_REP_SERVER reply to NBD_OPT_LIST, including payload.
368 * Return -errno on error, 0 on success. */
369 static int nbd_negotiate_send_rep_list(NBDClient *client, NBDExport *exp,
370 Error **errp)
372 size_t name_len, desc_len;
373 uint32_t len;
374 const char *name = exp->name ? exp->name : "";
375 const char *desc = exp->description ? exp->description : "";
376 QIOChannel *ioc = client->ioc;
377 int ret;
379 trace_nbd_negotiate_send_rep_list(name, desc);
380 name_len = strlen(name);
381 desc_len = strlen(desc);
382 assert(name_len <= NBD_MAX_STRING_SIZE && desc_len <= NBD_MAX_STRING_SIZE);
383 len = name_len + desc_len + sizeof(len);
384 ret = nbd_negotiate_send_rep_len(client, NBD_REP_SERVER, len, errp);
385 if (ret < 0) {
386 return ret;
389 len = cpu_to_be32(name_len);
390 if (nbd_write(ioc, &len, sizeof(len), errp) < 0) {
391 error_prepend(errp, "write failed (name length): ");
392 return -EINVAL;
395 if (nbd_write(ioc, name, name_len, errp) < 0) {
396 error_prepend(errp, "write failed (name buffer): ");
397 return -EINVAL;
400 if (nbd_write(ioc, desc, desc_len, errp) < 0) {
401 error_prepend(errp, "write failed (description buffer): ");
402 return -EINVAL;
405 return 0;
408 /* Process the NBD_OPT_LIST command, with a potential series of replies.
409 * Return -errno on error, 0 on success. */
410 static int nbd_negotiate_handle_list(NBDClient *client, Error **errp)
412 NBDExport *exp;
413 assert(client->opt == NBD_OPT_LIST);
415 /* For each export, send a NBD_REP_SERVER reply. */
416 QTAILQ_FOREACH(exp, &exports, next) {
417 if (nbd_negotiate_send_rep_list(client, exp, errp)) {
418 return -EINVAL;
421 /* Finish with a NBD_REP_ACK. */
422 return nbd_negotiate_send_rep(client, NBD_REP_ACK, errp);
425 static void nbd_check_meta_export(NBDClient *client)
427 client->export_meta.valid &= client->exp == client->export_meta.exp;
430 /* Send a reply to NBD_OPT_EXPORT_NAME.
431 * Return -errno on error, 0 on success. */
432 static int nbd_negotiate_handle_export_name(NBDClient *client, bool no_zeroes,
433 Error **errp)
435 g_autofree char *name = NULL;
436 char buf[NBD_REPLY_EXPORT_NAME_SIZE] = "";
437 size_t len;
438 int ret;
439 uint16_t myflags;
441 /* Client sends:
442 [20 .. xx] export name (length bytes)
443 Server replies:
444 [ 0 .. 7] size
445 [ 8 .. 9] export flags
446 [10 .. 133] reserved (0) [unless no_zeroes]
448 trace_nbd_negotiate_handle_export_name();
449 if (client->optlen > NBD_MAX_STRING_SIZE) {
450 error_setg(errp, "Bad length received");
451 return -EINVAL;
453 name = g_malloc(client->optlen + 1);
454 if (nbd_read(client->ioc, name, client->optlen, "export name", errp) < 0) {
455 return -EIO;
457 name[client->optlen] = '\0';
458 client->optlen = 0;
460 trace_nbd_negotiate_handle_export_name_request(name);
462 client->exp = nbd_export_find(name);
463 if (!client->exp) {
464 error_setg(errp, "export not found");
465 return -EINVAL;
468 myflags = client->exp->nbdflags;
469 if (client->structured_reply) {
470 myflags |= NBD_FLAG_SEND_DF;
472 trace_nbd_negotiate_new_style_size_flags(client->exp->size, myflags);
473 stq_be_p(buf, client->exp->size);
474 stw_be_p(buf + 8, myflags);
475 len = no_zeroes ? 10 : sizeof(buf);
476 ret = nbd_write(client->ioc, buf, len, errp);
477 if (ret < 0) {
478 error_prepend(errp, "write failed: ");
479 return ret;
482 QTAILQ_INSERT_TAIL(&client->exp->clients, client, next);
483 nbd_export_get(client->exp);
484 nbd_check_meta_export(client);
486 return 0;
489 /* Send a single NBD_REP_INFO, with a buffer @buf of @length bytes.
490 * The buffer does NOT include the info type prefix.
491 * Return -errno on error, 0 if ready to send more. */
492 static int nbd_negotiate_send_info(NBDClient *client,
493 uint16_t info, uint32_t length, void *buf,
494 Error **errp)
496 int rc;
498 trace_nbd_negotiate_send_info(info, nbd_info_lookup(info), length);
499 rc = nbd_negotiate_send_rep_len(client, NBD_REP_INFO,
500 sizeof(info) + length, errp);
501 if (rc < 0) {
502 return rc;
504 info = cpu_to_be16(info);
505 if (nbd_write(client->ioc, &info, sizeof(info), errp) < 0) {
506 return -EIO;
508 if (nbd_write(client->ioc, buf, length, errp) < 0) {
509 return -EIO;
511 return 0;
514 /* nbd_reject_length: Handle any unexpected payload.
515 * @fatal requests that we quit talking to the client, even if we are able
516 * to successfully send an error reply.
517 * Return:
518 * -errno transmission error occurred or @fatal was requested, errp is set
519 * 0 error message successfully sent to client, errp is not set
521 static int nbd_reject_length(NBDClient *client, bool fatal, Error **errp)
523 int ret;
525 assert(client->optlen);
526 ret = nbd_opt_invalid(client, errp, "option '%s' has unexpected length",
527 nbd_opt_lookup(client->opt));
528 if (fatal && !ret) {
529 error_setg(errp, "option '%s' has unexpected length",
530 nbd_opt_lookup(client->opt));
531 return -EINVAL;
533 return ret;
536 /* Handle NBD_OPT_INFO and NBD_OPT_GO.
537 * Return -errno on error, 0 if ready for next option, and 1 to move
538 * into transmission phase. */
539 static int nbd_negotiate_handle_info(NBDClient *client, Error **errp)
541 int rc;
542 g_autofree char *name = NULL;
543 NBDExport *exp;
544 uint16_t requests;
545 uint16_t request;
546 uint32_t namelen;
547 bool sendname = false;
548 bool blocksize = false;
549 uint32_t sizes[3];
550 char buf[sizeof(uint64_t) + sizeof(uint16_t)];
551 uint32_t check_align = 0;
552 uint16_t myflags;
554 /* Client sends:
555 4 bytes: L, name length (can be 0)
556 L bytes: export name
557 2 bytes: N, number of requests (can be 0)
558 N * 2 bytes: N requests
560 rc = nbd_opt_read_name(client, &name, &namelen, errp);
561 if (rc <= 0) {
562 return rc;
564 trace_nbd_negotiate_handle_export_name_request(name);
566 rc = nbd_opt_read(client, &requests, sizeof(requests), errp);
567 if (rc <= 0) {
568 return rc;
570 requests = be16_to_cpu(requests);
571 trace_nbd_negotiate_handle_info_requests(requests);
572 while (requests--) {
573 rc = nbd_opt_read(client, &request, sizeof(request), errp);
574 if (rc <= 0) {
575 return rc;
577 request = be16_to_cpu(request);
578 trace_nbd_negotiate_handle_info_request(request,
579 nbd_info_lookup(request));
580 /* We care about NBD_INFO_NAME and NBD_INFO_BLOCK_SIZE;
581 * everything else is either a request we don't know or
582 * something we send regardless of request */
583 switch (request) {
584 case NBD_INFO_NAME:
585 sendname = true;
586 break;
587 case NBD_INFO_BLOCK_SIZE:
588 blocksize = true;
589 break;
592 if (client->optlen) {
593 return nbd_reject_length(client, false, errp);
596 exp = nbd_export_find(name);
597 if (!exp) {
598 return nbd_negotiate_send_rep_err(client, NBD_REP_ERR_UNKNOWN,
599 errp, "export '%s' not present",
600 name);
603 /* Don't bother sending NBD_INFO_NAME unless client requested it */
604 if (sendname) {
605 rc = nbd_negotiate_send_info(client, NBD_INFO_NAME, namelen, name,
606 errp);
607 if (rc < 0) {
608 return rc;
612 /* Send NBD_INFO_DESCRIPTION only if available, regardless of
613 * client request */
614 if (exp->description) {
615 size_t len = strlen(exp->description);
617 assert(len <= NBD_MAX_STRING_SIZE);
618 rc = nbd_negotiate_send_info(client, NBD_INFO_DESCRIPTION,
619 len, exp->description, errp);
620 if (rc < 0) {
621 return rc;
625 /* Send NBD_INFO_BLOCK_SIZE always, but tweak the minimum size
626 * according to whether the client requested it, and according to
627 * whether this is OPT_INFO or OPT_GO. */
628 /* minimum - 1 for back-compat, or actual if client will obey it. */
629 if (client->opt == NBD_OPT_INFO || blocksize) {
630 check_align = sizes[0] = blk_get_request_alignment(exp->blk);
631 } else {
632 sizes[0] = 1;
634 assert(sizes[0] <= NBD_MAX_BUFFER_SIZE);
635 /* preferred - Hard-code to 4096 for now.
636 * TODO: is blk_bs(blk)->bl.opt_transfer appropriate? */
637 sizes[1] = MAX(4096, sizes[0]);
638 /* maximum - At most 32M, but smaller as appropriate. */
639 sizes[2] = MIN(blk_get_max_transfer(exp->blk), NBD_MAX_BUFFER_SIZE);
640 trace_nbd_negotiate_handle_info_block_size(sizes[0], sizes[1], sizes[2]);
641 sizes[0] = cpu_to_be32(sizes[0]);
642 sizes[1] = cpu_to_be32(sizes[1]);
643 sizes[2] = cpu_to_be32(sizes[2]);
644 rc = nbd_negotiate_send_info(client, NBD_INFO_BLOCK_SIZE,
645 sizeof(sizes), sizes, errp);
646 if (rc < 0) {
647 return rc;
650 /* Send NBD_INFO_EXPORT always */
651 myflags = exp->nbdflags;
652 if (client->structured_reply) {
653 myflags |= NBD_FLAG_SEND_DF;
655 trace_nbd_negotiate_new_style_size_flags(exp->size, myflags);
656 stq_be_p(buf, exp->size);
657 stw_be_p(buf + 8, myflags);
658 rc = nbd_negotiate_send_info(client, NBD_INFO_EXPORT,
659 sizeof(buf), buf, errp);
660 if (rc < 0) {
661 return rc;
665 * If the client is just asking for NBD_OPT_INFO, but forgot to
666 * request block sizes in a situation that would impact
667 * performance, then return an error. But for NBD_OPT_GO, we
668 * tolerate all clients, regardless of alignments.
670 if (client->opt == NBD_OPT_INFO && !blocksize &&
671 blk_get_request_alignment(exp->blk) > 1) {
672 return nbd_negotiate_send_rep_err(client,
673 NBD_REP_ERR_BLOCK_SIZE_REQD,
674 errp,
675 "request NBD_INFO_BLOCK_SIZE to "
676 "use this export");
679 /* Final reply */
680 rc = nbd_negotiate_send_rep(client, NBD_REP_ACK, errp);
681 if (rc < 0) {
682 return rc;
685 if (client->opt == NBD_OPT_GO) {
686 client->exp = exp;
687 client->check_align = check_align;
688 QTAILQ_INSERT_TAIL(&client->exp->clients, client, next);
689 nbd_export_get(client->exp);
690 nbd_check_meta_export(client);
691 rc = 1;
693 return rc;
697 /* Handle NBD_OPT_STARTTLS. Return NULL to drop connection, or else the
698 * new channel for all further (now-encrypted) communication. */
699 static QIOChannel *nbd_negotiate_handle_starttls(NBDClient *client,
700 Error **errp)
702 QIOChannel *ioc;
703 QIOChannelTLS *tioc;
704 struct NBDTLSHandshakeData data = { 0 };
706 assert(client->opt == NBD_OPT_STARTTLS);
708 trace_nbd_negotiate_handle_starttls();
709 ioc = client->ioc;
711 if (nbd_negotiate_send_rep(client, NBD_REP_ACK, errp) < 0) {
712 return NULL;
715 tioc = qio_channel_tls_new_server(ioc,
716 client->tlscreds,
717 client->tlsauthz,
718 errp);
719 if (!tioc) {
720 return NULL;
723 qio_channel_set_name(QIO_CHANNEL(tioc), "nbd-server-tls");
724 trace_nbd_negotiate_handle_starttls_handshake();
725 data.loop = g_main_loop_new(g_main_context_default(), FALSE);
726 qio_channel_tls_handshake(tioc,
727 nbd_tls_handshake,
728 &data,
729 NULL,
730 NULL);
732 if (!data.complete) {
733 g_main_loop_run(data.loop);
735 g_main_loop_unref(data.loop);
736 if (data.error) {
737 object_unref(OBJECT(tioc));
738 error_propagate(errp, data.error);
739 return NULL;
742 return QIO_CHANNEL(tioc);
745 /* nbd_negotiate_send_meta_context
747 * Send one chunk of reply to NBD_OPT_{LIST,SET}_META_CONTEXT
749 * For NBD_OPT_LIST_META_CONTEXT @context_id is ignored, 0 is used instead.
751 static int nbd_negotiate_send_meta_context(NBDClient *client,
752 const char *context,
753 uint32_t context_id,
754 Error **errp)
756 NBDOptionReplyMetaContext opt;
757 struct iovec iov[] = {
758 {.iov_base = &opt, .iov_len = sizeof(opt)},
759 {.iov_base = (void *)context, .iov_len = strlen(context)}
762 assert(iov[1].iov_len <= NBD_MAX_STRING_SIZE);
763 if (client->opt == NBD_OPT_LIST_META_CONTEXT) {
764 context_id = 0;
767 trace_nbd_negotiate_meta_query_reply(context, context_id);
768 set_be_option_rep(&opt.h, client->opt, NBD_REP_META_CONTEXT,
769 sizeof(opt) - sizeof(opt.h) + iov[1].iov_len);
770 stl_be_p(&opt.context_id, context_id);
772 return qio_channel_writev_all(client->ioc, iov, 2, errp) < 0 ? -EIO : 0;
775 /* Read strlen(@pattern) bytes, and set @match to true if they match @pattern.
776 * @match is never set to false.
778 * Return -errno on I/O error, 0 if option was completely handled by
779 * sending a reply about inconsistent lengths, or 1 on success.
781 * Note: return code = 1 doesn't mean that we've read exactly @pattern.
782 * It only means that there are no errors.
784 static int nbd_meta_pattern(NBDClient *client, const char *pattern, bool *match,
785 Error **errp)
787 int ret;
788 char *query;
789 size_t len = strlen(pattern);
791 assert(len);
793 query = g_malloc(len);
794 ret = nbd_opt_read(client, query, len, errp);
795 if (ret <= 0) {
796 g_free(query);
797 return ret;
800 if (strncmp(query, pattern, len) == 0) {
801 trace_nbd_negotiate_meta_query_parse(pattern);
802 *match = true;
803 } else {
804 trace_nbd_negotiate_meta_query_skip("pattern not matched");
806 g_free(query);
808 return 1;
812 * Read @len bytes, and set @match to true if they match @pattern, or if @len
813 * is 0 and the client is performing _LIST_. @match is never set to false.
815 * Return -errno on I/O error, 0 if option was completely handled by
816 * sending a reply about inconsistent lengths, or 1 on success.
818 * Note: return code = 1 doesn't mean that we've read exactly @pattern.
819 * It only means that there are no errors.
821 static int nbd_meta_empty_or_pattern(NBDClient *client, const char *pattern,
822 uint32_t len, bool *match, Error **errp)
824 if (len == 0) {
825 if (client->opt == NBD_OPT_LIST_META_CONTEXT) {
826 *match = true;
828 trace_nbd_negotiate_meta_query_parse("empty");
829 return 1;
832 if (len != strlen(pattern)) {
833 trace_nbd_negotiate_meta_query_skip("different lengths");
834 return nbd_opt_skip(client, len, errp);
837 return nbd_meta_pattern(client, pattern, match, errp);
840 /* nbd_meta_base_query
842 * Handle queries to 'base' namespace. For now, only the base:allocation
843 * context is available. 'len' is the amount of text remaining to be read from
844 * the current name, after the 'base:' portion has been stripped.
846 * Return -errno on I/O error, 0 if option was completely handled by
847 * sending a reply about inconsistent lengths, or 1 on success.
849 static int nbd_meta_base_query(NBDClient *client, NBDExportMetaContexts *meta,
850 uint32_t len, Error **errp)
852 return nbd_meta_empty_or_pattern(client, "allocation", len,
853 &meta->base_allocation, errp);
856 /* nbd_meta_bitmap_query
858 * Handle query to 'qemu:' namespace.
859 * @len is the amount of text remaining to be read from the current name, after
860 * the 'qemu:' portion has been stripped.
862 * Return -errno on I/O error, 0 if option was completely handled by
863 * sending a reply about inconsistent lengths, or 1 on success. */
864 static int nbd_meta_qemu_query(NBDClient *client, NBDExportMetaContexts *meta,
865 uint32_t len, Error **errp)
867 bool dirty_bitmap = false;
868 size_t dirty_bitmap_len = strlen("dirty-bitmap:");
869 int ret;
871 if (!meta->exp->export_bitmap) {
872 trace_nbd_negotiate_meta_query_skip("no dirty-bitmap exported");
873 return nbd_opt_skip(client, len, errp);
876 if (len == 0) {
877 if (client->opt == NBD_OPT_LIST_META_CONTEXT) {
878 meta->bitmap = true;
880 trace_nbd_negotiate_meta_query_parse("empty");
881 return 1;
884 if (len < dirty_bitmap_len) {
885 trace_nbd_negotiate_meta_query_skip("not dirty-bitmap:");
886 return nbd_opt_skip(client, len, errp);
889 len -= dirty_bitmap_len;
890 ret = nbd_meta_pattern(client, "dirty-bitmap:", &dirty_bitmap, errp);
891 if (ret <= 0) {
892 return ret;
894 if (!dirty_bitmap) {
895 trace_nbd_negotiate_meta_query_skip("not dirty-bitmap:");
896 return nbd_opt_skip(client, len, errp);
899 trace_nbd_negotiate_meta_query_parse("dirty-bitmap:");
901 return nbd_meta_empty_or_pattern(
902 client, meta->exp->export_bitmap_context +
903 strlen("qemu:dirty_bitmap:"), len, &meta->bitmap, errp);
906 /* nbd_negotiate_meta_query
908 * Parse namespace name and call corresponding function to parse body of the
909 * query.
911 * The only supported namespaces are 'base' and 'qemu'.
913 * The function aims not wasting time and memory to read long unknown namespace
914 * names.
916 * Return -errno on I/O error, 0 if option was completely handled by
917 * sending a reply about inconsistent lengths, or 1 on success. */
918 static int nbd_negotiate_meta_query(NBDClient *client,
919 NBDExportMetaContexts *meta, Error **errp)
922 * Both 'qemu' and 'base' namespaces have length = 5 including a
923 * colon. If another length namespace is later introduced, this
924 * should certainly be refactored.
926 int ret;
927 size_t ns_len = 5;
928 char ns[5];
929 uint32_t len;
931 ret = nbd_opt_read(client, &len, sizeof(len), errp);
932 if (ret <= 0) {
933 return ret;
935 len = cpu_to_be32(len);
937 if (len > NBD_MAX_STRING_SIZE) {
938 trace_nbd_negotiate_meta_query_skip("length too long");
939 return nbd_opt_skip(client, len, errp);
941 if (len < ns_len) {
942 trace_nbd_negotiate_meta_query_skip("length too short");
943 return nbd_opt_skip(client, len, errp);
946 len -= ns_len;
947 ret = nbd_opt_read(client, ns, ns_len, errp);
948 if (ret <= 0) {
949 return ret;
952 if (!strncmp(ns, "base:", ns_len)) {
953 trace_nbd_negotiate_meta_query_parse("base:");
954 return nbd_meta_base_query(client, meta, len, errp);
955 } else if (!strncmp(ns, "qemu:", ns_len)) {
956 trace_nbd_negotiate_meta_query_parse("qemu:");
957 return nbd_meta_qemu_query(client, meta, len, errp);
960 trace_nbd_negotiate_meta_query_skip("unknown namespace");
961 return nbd_opt_skip(client, len, errp);
964 /* nbd_negotiate_meta_queries
965 * Handle NBD_OPT_LIST_META_CONTEXT and NBD_OPT_SET_META_CONTEXT
967 * Return -errno on I/O error, or 0 if option was completely handled. */
968 static int nbd_negotiate_meta_queries(NBDClient *client,
969 NBDExportMetaContexts *meta, Error **errp)
971 int ret;
972 g_autofree char *export_name = NULL;
973 NBDExportMetaContexts local_meta;
974 uint32_t nb_queries;
975 int i;
977 if (!client->structured_reply) {
978 return nbd_opt_invalid(client, errp,
979 "request option '%s' when structured reply "
980 "is not negotiated",
981 nbd_opt_lookup(client->opt));
984 if (client->opt == NBD_OPT_LIST_META_CONTEXT) {
985 /* Only change the caller's meta on SET. */
986 meta = &local_meta;
989 memset(meta, 0, sizeof(*meta));
991 ret = nbd_opt_read_name(client, &export_name, NULL, errp);
992 if (ret <= 0) {
993 return ret;
996 meta->exp = nbd_export_find(export_name);
997 if (meta->exp == NULL) {
998 return nbd_opt_drop(client, NBD_REP_ERR_UNKNOWN, errp,
999 "export '%s' not present", export_name);
1002 ret = nbd_opt_read(client, &nb_queries, sizeof(nb_queries), errp);
1003 if (ret <= 0) {
1004 return ret;
1006 nb_queries = cpu_to_be32(nb_queries);
1007 trace_nbd_negotiate_meta_context(nbd_opt_lookup(client->opt),
1008 export_name, nb_queries);
1010 if (client->opt == NBD_OPT_LIST_META_CONTEXT && !nb_queries) {
1011 /* enable all known contexts */
1012 meta->base_allocation = true;
1013 meta->bitmap = !!meta->exp->export_bitmap;
1014 } else {
1015 for (i = 0; i < nb_queries; ++i) {
1016 ret = nbd_negotiate_meta_query(client, meta, errp);
1017 if (ret <= 0) {
1018 return ret;
1023 if (meta->base_allocation) {
1024 ret = nbd_negotiate_send_meta_context(client, "base:allocation",
1025 NBD_META_ID_BASE_ALLOCATION,
1026 errp);
1027 if (ret < 0) {
1028 return ret;
1032 if (meta->bitmap) {
1033 ret = nbd_negotiate_send_meta_context(client,
1034 meta->exp->export_bitmap_context,
1035 NBD_META_ID_DIRTY_BITMAP,
1036 errp);
1037 if (ret < 0) {
1038 return ret;
1042 ret = nbd_negotiate_send_rep(client, NBD_REP_ACK, errp);
1043 if (ret == 0) {
1044 meta->valid = true;
1047 return ret;
1050 /* nbd_negotiate_options
1051 * Process all NBD_OPT_* client option commands, during fixed newstyle
1052 * negotiation.
1053 * Return:
1054 * -errno on error, errp is set
1055 * 0 on successful negotiation, errp is not set
1056 * 1 if client sent NBD_OPT_ABORT, i.e. on valid disconnect,
1057 * errp is not set
1059 static int nbd_negotiate_options(NBDClient *client, Error **errp)
1061 uint32_t flags;
1062 bool fixedNewstyle = false;
1063 bool no_zeroes = false;
1065 /* Client sends:
1066 [ 0 .. 3] client flags
1068 Then we loop until NBD_OPT_EXPORT_NAME or NBD_OPT_GO:
1069 [ 0 .. 7] NBD_OPTS_MAGIC
1070 [ 8 .. 11] NBD option
1071 [12 .. 15] Data length
1072 ... Rest of request
1074 [ 0 .. 7] NBD_OPTS_MAGIC
1075 [ 8 .. 11] Second NBD option
1076 [12 .. 15] Data length
1077 ... Rest of request
1080 if (nbd_read32(client->ioc, &flags, "flags", errp) < 0) {
1081 return -EIO;
1083 trace_nbd_negotiate_options_flags(flags);
1084 if (flags & NBD_FLAG_C_FIXED_NEWSTYLE) {
1085 fixedNewstyle = true;
1086 flags &= ~NBD_FLAG_C_FIXED_NEWSTYLE;
1088 if (flags & NBD_FLAG_C_NO_ZEROES) {
1089 no_zeroes = true;
1090 flags &= ~NBD_FLAG_C_NO_ZEROES;
1092 if (flags != 0) {
1093 error_setg(errp, "Unknown client flags 0x%" PRIx32 " received", flags);
1094 return -EINVAL;
1097 while (1) {
1098 int ret;
1099 uint32_t option, length;
1100 uint64_t magic;
1102 if (nbd_read64(client->ioc, &magic, "opts magic", errp) < 0) {
1103 return -EINVAL;
1105 trace_nbd_negotiate_options_check_magic(magic);
1106 if (magic != NBD_OPTS_MAGIC) {
1107 error_setg(errp, "Bad magic received");
1108 return -EINVAL;
1111 if (nbd_read32(client->ioc, &option, "option", errp) < 0) {
1112 return -EINVAL;
1114 client->opt = option;
1116 if (nbd_read32(client->ioc, &length, "option length", errp) < 0) {
1117 return -EINVAL;
1119 assert(!client->optlen);
1120 client->optlen = length;
1122 if (length > NBD_MAX_BUFFER_SIZE) {
1123 error_setg(errp, "len (%" PRIu32" ) is larger than max len (%u)",
1124 length, NBD_MAX_BUFFER_SIZE);
1125 return -EINVAL;
1128 trace_nbd_negotiate_options_check_option(option,
1129 nbd_opt_lookup(option));
1130 if (client->tlscreds &&
1131 client->ioc == (QIOChannel *)client->sioc) {
1132 QIOChannel *tioc;
1133 if (!fixedNewstyle) {
1134 error_setg(errp, "Unsupported option 0x%" PRIx32, option);
1135 return -EINVAL;
1137 switch (option) {
1138 case NBD_OPT_STARTTLS:
1139 if (length) {
1140 /* Unconditionally drop the connection if the client
1141 * can't start a TLS negotiation correctly */
1142 return nbd_reject_length(client, true, errp);
1144 tioc = nbd_negotiate_handle_starttls(client, errp);
1145 if (!tioc) {
1146 return -EIO;
1148 ret = 0;
1149 object_unref(OBJECT(client->ioc));
1150 client->ioc = QIO_CHANNEL(tioc);
1151 break;
1153 case NBD_OPT_EXPORT_NAME:
1154 /* No way to return an error to client, so drop connection */
1155 error_setg(errp, "Option 0x%x not permitted before TLS",
1156 option);
1157 return -EINVAL;
1159 default:
1160 /* Let the client keep trying, unless they asked to
1161 * quit. Always try to give an error back to the
1162 * client; but when replying to OPT_ABORT, be aware
1163 * that the client may hang up before receiving the
1164 * error, in which case we are fine ignoring the
1165 * resulting EPIPE. */
1166 ret = nbd_opt_drop(client, NBD_REP_ERR_TLS_REQD,
1167 option == NBD_OPT_ABORT ? NULL : errp,
1168 "Option 0x%" PRIx32
1169 " not permitted before TLS", option);
1170 if (option == NBD_OPT_ABORT) {
1171 return 1;
1173 break;
1175 } else if (fixedNewstyle) {
1176 switch (option) {
1177 case NBD_OPT_LIST:
1178 if (length) {
1179 ret = nbd_reject_length(client, false, errp);
1180 } else {
1181 ret = nbd_negotiate_handle_list(client, errp);
1183 break;
1185 case NBD_OPT_ABORT:
1186 /* NBD spec says we must try to reply before
1187 * disconnecting, but that we must also tolerate
1188 * guests that don't wait for our reply. */
1189 nbd_negotiate_send_rep(client, NBD_REP_ACK, NULL);
1190 return 1;
1192 case NBD_OPT_EXPORT_NAME:
1193 return nbd_negotiate_handle_export_name(client, no_zeroes,
1194 errp);
1196 case NBD_OPT_INFO:
1197 case NBD_OPT_GO:
1198 ret = nbd_negotiate_handle_info(client, errp);
1199 if (ret == 1) {
1200 assert(option == NBD_OPT_GO);
1201 return 0;
1203 break;
1205 case NBD_OPT_STARTTLS:
1206 if (length) {
1207 ret = nbd_reject_length(client, false, errp);
1208 } else if (client->tlscreds) {
1209 ret = nbd_negotiate_send_rep_err(client,
1210 NBD_REP_ERR_INVALID, errp,
1211 "TLS already enabled");
1212 } else {
1213 ret = nbd_negotiate_send_rep_err(client,
1214 NBD_REP_ERR_POLICY, errp,
1215 "TLS not configured");
1217 break;
1219 case NBD_OPT_STRUCTURED_REPLY:
1220 if (length) {
1221 ret = nbd_reject_length(client, false, errp);
1222 } else if (client->structured_reply) {
1223 ret = nbd_negotiate_send_rep_err(
1224 client, NBD_REP_ERR_INVALID, errp,
1225 "structured reply already negotiated");
1226 } else {
1227 ret = nbd_negotiate_send_rep(client, NBD_REP_ACK, errp);
1228 client->structured_reply = true;
1230 break;
1232 case NBD_OPT_LIST_META_CONTEXT:
1233 case NBD_OPT_SET_META_CONTEXT:
1234 ret = nbd_negotiate_meta_queries(client, &client->export_meta,
1235 errp);
1236 break;
1238 default:
1239 ret = nbd_opt_drop(client, NBD_REP_ERR_UNSUP, errp,
1240 "Unsupported option %" PRIu32 " (%s)",
1241 option, nbd_opt_lookup(option));
1242 break;
1244 } else {
1246 * If broken new-style we should drop the connection
1247 * for anything except NBD_OPT_EXPORT_NAME
1249 switch (option) {
1250 case NBD_OPT_EXPORT_NAME:
1251 return nbd_negotiate_handle_export_name(client, no_zeroes,
1252 errp);
1254 default:
1255 error_setg(errp, "Unsupported option %" PRIu32 " (%s)",
1256 option, nbd_opt_lookup(option));
1257 return -EINVAL;
1260 if (ret < 0) {
1261 return ret;
1266 /* nbd_negotiate
1267 * Return:
1268 * -errno on error, errp is set
1269 * 0 on successful negotiation, errp is not set
1270 * 1 if client sent NBD_OPT_ABORT, i.e. on valid disconnect,
1271 * errp is not set
1273 static coroutine_fn int nbd_negotiate(NBDClient *client, Error **errp)
1275 char buf[NBD_OLDSTYLE_NEGOTIATE_SIZE] = "";
1276 int ret;
1278 /* Old style negotiation header, no room for options
1279 [ 0 .. 7] passwd ("NBDMAGIC")
1280 [ 8 .. 15] magic (NBD_CLIENT_MAGIC)
1281 [16 .. 23] size
1282 [24 .. 27] export flags (zero-extended)
1283 [28 .. 151] reserved (0)
1285 New style negotiation header, client can send options
1286 [ 0 .. 7] passwd ("NBDMAGIC")
1287 [ 8 .. 15] magic (NBD_OPTS_MAGIC)
1288 [16 .. 17] server flags (0)
1289 ....options sent, ending in NBD_OPT_EXPORT_NAME or NBD_OPT_GO....
1292 qio_channel_set_blocking(client->ioc, false, NULL);
1294 trace_nbd_negotiate_begin();
1295 memcpy(buf, "NBDMAGIC", 8);
1297 stq_be_p(buf + 8, NBD_OPTS_MAGIC);
1298 stw_be_p(buf + 16, NBD_FLAG_FIXED_NEWSTYLE | NBD_FLAG_NO_ZEROES);
1300 if (nbd_write(client->ioc, buf, 18, errp) < 0) {
1301 error_prepend(errp, "write failed: ");
1302 return -EINVAL;
1304 ret = nbd_negotiate_options(client, errp);
1305 if (ret != 0) {
1306 if (ret < 0) {
1307 error_prepend(errp, "option negotiation failed: ");
1309 return ret;
1312 /* Attach the channel to the same AioContext as the export */
1313 if (client->exp && client->exp->ctx) {
1314 qio_channel_attach_aio_context(client->ioc, client->exp->ctx);
1317 assert(!client->optlen);
1318 trace_nbd_negotiate_success();
1320 return 0;
1323 static int nbd_receive_request(QIOChannel *ioc, NBDRequest *request,
1324 Error **errp)
1326 uint8_t buf[NBD_REQUEST_SIZE];
1327 uint32_t magic;
1328 int ret;
1330 ret = nbd_read(ioc, buf, sizeof(buf), "request", errp);
1331 if (ret < 0) {
1332 return ret;
1335 /* Request
1336 [ 0 .. 3] magic (NBD_REQUEST_MAGIC)
1337 [ 4 .. 5] flags (NBD_CMD_FLAG_FUA, ...)
1338 [ 6 .. 7] type (NBD_CMD_READ, ...)
1339 [ 8 .. 15] handle
1340 [16 .. 23] from
1341 [24 .. 27] len
1344 magic = ldl_be_p(buf);
1345 request->flags = lduw_be_p(buf + 4);
1346 request->type = lduw_be_p(buf + 6);
1347 request->handle = ldq_be_p(buf + 8);
1348 request->from = ldq_be_p(buf + 16);
1349 request->len = ldl_be_p(buf + 24);
1351 trace_nbd_receive_request(magic, request->flags, request->type,
1352 request->from, request->len);
1354 if (magic != NBD_REQUEST_MAGIC) {
1355 error_setg(errp, "invalid magic (got 0x%" PRIx32 ")", magic);
1356 return -EINVAL;
1358 return 0;
1361 #define MAX_NBD_REQUESTS 16
1363 void nbd_client_get(NBDClient *client)
1365 client->refcount++;
1368 void nbd_client_put(NBDClient *client)
1370 if (--client->refcount == 0) {
1371 /* The last reference should be dropped by client->close,
1372 * which is called by client_close.
1374 assert(client->closing);
1376 qio_channel_detach_aio_context(client->ioc);
1377 object_unref(OBJECT(client->sioc));
1378 object_unref(OBJECT(client->ioc));
1379 if (client->tlscreds) {
1380 object_unref(OBJECT(client->tlscreds));
1382 g_free(client->tlsauthz);
1383 if (client->exp) {
1384 QTAILQ_REMOVE(&client->exp->clients, client, next);
1385 nbd_export_put(client->exp);
1387 g_free(client);
1391 static void client_close(NBDClient *client, bool negotiated)
1393 if (client->closing) {
1394 return;
1397 client->closing = true;
1399 /* Force requests to finish. They will drop their own references,
1400 * then we'll close the socket and free the NBDClient.
1402 qio_channel_shutdown(client->ioc, QIO_CHANNEL_SHUTDOWN_BOTH,
1403 NULL);
1405 /* Also tell the client, so that they release their reference. */
1406 if (client->close_fn) {
1407 client->close_fn(client, negotiated);
1411 static NBDRequestData *nbd_request_get(NBDClient *client)
1413 NBDRequestData *req;
1415 assert(client->nb_requests <= MAX_NBD_REQUESTS - 1);
1416 client->nb_requests++;
1418 req = g_new0(NBDRequestData, 1);
1419 nbd_client_get(client);
1420 req->client = client;
1421 return req;
1424 static void nbd_request_put(NBDRequestData *req)
1426 NBDClient *client = req->client;
1428 if (req->data) {
1429 qemu_vfree(req->data);
1431 g_free(req);
1433 client->nb_requests--;
1434 nbd_client_receive_next_request(client);
1436 nbd_client_put(client);
1439 static void blk_aio_attached(AioContext *ctx, void *opaque)
1441 NBDExport *exp = opaque;
1442 NBDClient *client;
1444 trace_nbd_blk_aio_attached(exp->name, ctx);
1446 exp->ctx = ctx;
1448 QTAILQ_FOREACH(client, &exp->clients, next) {
1449 qio_channel_attach_aio_context(client->ioc, ctx);
1450 if (client->recv_coroutine) {
1451 aio_co_schedule(ctx, client->recv_coroutine);
1453 if (client->send_coroutine) {
1454 aio_co_schedule(ctx, client->send_coroutine);
1459 static void blk_aio_detach(void *opaque)
1461 NBDExport *exp = opaque;
1462 NBDClient *client;
1464 trace_nbd_blk_aio_detach(exp->name, exp->ctx);
1466 QTAILQ_FOREACH(client, &exp->clients, next) {
1467 qio_channel_detach_aio_context(client->ioc);
1470 exp->ctx = NULL;
1473 static void nbd_eject_notifier(Notifier *n, void *data)
1475 NBDExport *exp = container_of(n, NBDExport, eject_notifier);
1476 AioContext *aio_context;
1478 aio_context = exp->ctx;
1479 aio_context_acquire(aio_context);
1480 nbd_export_close(exp);
1481 aio_context_release(aio_context);
1484 NBDExport *nbd_export_new(BlockDriverState *bs, uint64_t dev_offset,
1485 uint64_t size, const char *name, const char *desc,
1486 const char *bitmap, bool readonly, bool shared,
1487 void (*close)(NBDExport *), bool writethrough,
1488 BlockBackend *on_eject_blk, Error **errp)
1490 AioContext *ctx;
1491 BlockBackend *blk;
1492 NBDExport *exp = g_new0(NBDExport, 1);
1493 uint64_t perm;
1494 int ret;
1497 * NBD exports are used for non-shared storage migration. Make sure
1498 * that BDRV_O_INACTIVE is cleared and the image is ready for write
1499 * access since the export could be available before migration handover.
1500 * ctx was acquired in the caller.
1502 assert(name && strlen(name) <= NBD_MAX_STRING_SIZE);
1503 ctx = bdrv_get_aio_context(bs);
1504 bdrv_invalidate_cache(bs, NULL);
1506 /* Don't allow resize while the NBD server is running, otherwise we don't
1507 * care what happens with the node. */
1508 perm = BLK_PERM_CONSISTENT_READ;
1509 if (!readonly) {
1510 perm |= BLK_PERM_WRITE;
1512 blk = blk_new(ctx, perm,
1513 BLK_PERM_CONSISTENT_READ | BLK_PERM_WRITE_UNCHANGED |
1514 BLK_PERM_WRITE | BLK_PERM_GRAPH_MOD);
1515 ret = blk_insert_bs(blk, bs, errp);
1516 if (ret < 0) {
1517 goto fail;
1519 blk_set_enable_write_cache(blk, !writethrough);
1520 blk_set_allow_aio_context_change(blk, true);
1522 exp->refcount = 1;
1523 QTAILQ_INIT(&exp->clients);
1524 exp->blk = blk;
1525 assert(dev_offset <= INT64_MAX);
1526 exp->dev_offset = dev_offset;
1527 exp->name = g_strdup(name);
1528 assert(!desc || strlen(desc) <= NBD_MAX_STRING_SIZE);
1529 exp->description = g_strdup(desc);
1530 exp->nbdflags = (NBD_FLAG_HAS_FLAGS | NBD_FLAG_SEND_FLUSH |
1531 NBD_FLAG_SEND_FUA | NBD_FLAG_SEND_CACHE);
1532 if (readonly) {
1533 exp->nbdflags |= NBD_FLAG_READ_ONLY;
1534 if (shared) {
1535 exp->nbdflags |= NBD_FLAG_CAN_MULTI_CONN;
1537 } else {
1538 exp->nbdflags |= (NBD_FLAG_SEND_TRIM | NBD_FLAG_SEND_WRITE_ZEROES |
1539 NBD_FLAG_SEND_FAST_ZERO);
1541 assert(size <= INT64_MAX - dev_offset);
1542 exp->size = QEMU_ALIGN_DOWN(size, BDRV_SECTOR_SIZE);
1544 if (bitmap) {
1545 BdrvDirtyBitmap *bm = NULL;
1547 while (true) {
1548 bm = bdrv_find_dirty_bitmap(bs, bitmap);
1549 if (bm != NULL || bs->backing == NULL) {
1550 break;
1553 bs = bs->backing->bs;
1556 if (bm == NULL) {
1557 error_setg(errp, "Bitmap '%s' is not found", bitmap);
1558 goto fail;
1561 if (bdrv_dirty_bitmap_check(bm, BDRV_BITMAP_ALLOW_RO, errp)) {
1562 goto fail;
1565 if (readonly && bdrv_is_writable(bs) &&
1566 bdrv_dirty_bitmap_enabled(bm)) {
1567 error_setg(errp,
1568 "Enabled bitmap '%s' incompatible with readonly export",
1569 bitmap);
1570 goto fail;
1573 bdrv_dirty_bitmap_set_busy(bm, true);
1574 exp->export_bitmap = bm;
1575 assert(strlen(bitmap) <= BDRV_BITMAP_MAX_NAME_SIZE);
1576 exp->export_bitmap_context = g_strdup_printf("qemu:dirty-bitmap:%s",
1577 bitmap);
1578 assert(strlen(exp->export_bitmap_context) < NBD_MAX_STRING_SIZE);
1581 exp->close = close;
1582 exp->ctx = ctx;
1583 blk_add_aio_context_notifier(blk, blk_aio_attached, blk_aio_detach, exp);
1585 if (on_eject_blk) {
1586 blk_ref(on_eject_blk);
1587 exp->eject_notifier_blk = on_eject_blk;
1588 exp->eject_notifier.notify = nbd_eject_notifier;
1589 blk_add_remove_bs_notifier(on_eject_blk, &exp->eject_notifier);
1591 QTAILQ_INSERT_TAIL(&exports, exp, next);
1592 nbd_export_get(exp);
1593 return exp;
1595 fail:
1596 blk_unref(blk);
1597 g_free(exp->name);
1598 g_free(exp->description);
1599 g_free(exp);
1600 return NULL;
1603 NBDExport *nbd_export_find(const char *name)
1605 NBDExport *exp;
1606 QTAILQ_FOREACH(exp, &exports, next) {
1607 if (strcmp(name, exp->name) == 0) {
1608 return exp;
1612 return NULL;
1615 AioContext *
1616 nbd_export_aio_context(NBDExport *exp)
1618 return exp->ctx;
1621 void nbd_export_close(NBDExport *exp)
1623 NBDClient *client, *next;
1625 nbd_export_get(exp);
1627 * TODO: Should we expand QMP NbdServerRemoveNode enum to allow a
1628 * close mode that stops advertising the export to new clients but
1629 * still permits existing clients to run to completion? Because of
1630 * that possibility, nbd_export_close() can be called more than
1631 * once on an export.
1633 QTAILQ_FOREACH_SAFE(client, &exp->clients, next, next) {
1634 client_close(client, true);
1636 if (exp->name) {
1637 nbd_export_put(exp);
1638 g_free(exp->name);
1639 exp->name = NULL;
1640 QTAILQ_REMOVE(&exports, exp, next);
1642 g_free(exp->description);
1643 exp->description = NULL;
1644 nbd_export_put(exp);
1647 void nbd_export_remove(NBDExport *exp, NbdServerRemoveMode mode, Error **errp)
1649 if (mode == NBD_SERVER_REMOVE_MODE_HARD || QTAILQ_EMPTY(&exp->clients)) {
1650 nbd_export_close(exp);
1651 return;
1654 assert(mode == NBD_SERVER_REMOVE_MODE_SAFE);
1656 error_setg(errp, "export '%s' still in use", exp->name);
1657 error_append_hint(errp, "Use mode='hard' to force client disconnect\n");
1660 void nbd_export_get(NBDExport *exp)
1662 assert(exp->refcount > 0);
1663 exp->refcount++;
1666 void nbd_export_put(NBDExport *exp)
1668 assert(exp->refcount > 0);
1669 if (exp->refcount == 1) {
1670 nbd_export_close(exp);
1673 /* nbd_export_close() may theoretically reduce refcount to 0. It may happen
1674 * if someone calls nbd_export_put() on named export not through
1675 * nbd_export_set_name() when refcount is 1. So, let's assert that
1676 * it is > 0.
1678 assert(exp->refcount > 0);
1679 if (--exp->refcount == 0) {
1680 assert(exp->name == NULL);
1681 assert(exp->description == NULL);
1683 if (exp->close) {
1684 exp->close(exp);
1687 if (exp->blk) {
1688 if (exp->eject_notifier_blk) {
1689 notifier_remove(&exp->eject_notifier);
1690 blk_unref(exp->eject_notifier_blk);
1692 blk_remove_aio_context_notifier(exp->blk, blk_aio_attached,
1693 blk_aio_detach, exp);
1694 blk_unref(exp->blk);
1695 exp->blk = NULL;
1698 if (exp->export_bitmap) {
1699 bdrv_dirty_bitmap_set_busy(exp->export_bitmap, false);
1700 g_free(exp->export_bitmap_context);
1703 g_free(exp);
1707 BlockBackend *nbd_export_get_blockdev(NBDExport *exp)
1709 return exp->blk;
1712 void nbd_export_close_all(void)
1714 NBDExport *exp, *next;
1715 AioContext *aio_context;
1717 QTAILQ_FOREACH_SAFE(exp, &exports, next, next) {
1718 aio_context = exp->ctx;
1719 aio_context_acquire(aio_context);
1720 nbd_export_close(exp);
1721 aio_context_release(aio_context);
1725 static int coroutine_fn nbd_co_send_iov(NBDClient *client, struct iovec *iov,
1726 unsigned niov, Error **errp)
1728 int ret;
1730 g_assert(qemu_in_coroutine());
1731 qemu_co_mutex_lock(&client->send_lock);
1732 client->send_coroutine = qemu_coroutine_self();
1734 ret = qio_channel_writev_all(client->ioc, iov, niov, errp) < 0 ? -EIO : 0;
1736 client->send_coroutine = NULL;
1737 qemu_co_mutex_unlock(&client->send_lock);
1739 return ret;
1742 static inline void set_be_simple_reply(NBDSimpleReply *reply, uint64_t error,
1743 uint64_t handle)
1745 stl_be_p(&reply->magic, NBD_SIMPLE_REPLY_MAGIC);
1746 stl_be_p(&reply->error, error);
1747 stq_be_p(&reply->handle, handle);
1750 static int nbd_co_send_simple_reply(NBDClient *client,
1751 uint64_t handle,
1752 uint32_t error,
1753 void *data,
1754 size_t len,
1755 Error **errp)
1757 NBDSimpleReply reply;
1758 int nbd_err = system_errno_to_nbd_errno(error);
1759 struct iovec iov[] = {
1760 {.iov_base = &reply, .iov_len = sizeof(reply)},
1761 {.iov_base = data, .iov_len = len}
1764 trace_nbd_co_send_simple_reply(handle, nbd_err, nbd_err_lookup(nbd_err),
1765 len);
1766 set_be_simple_reply(&reply, nbd_err, handle);
1768 return nbd_co_send_iov(client, iov, len ? 2 : 1, errp);
1771 static inline void set_be_chunk(NBDStructuredReplyChunk *chunk, uint16_t flags,
1772 uint16_t type, uint64_t handle, uint32_t length)
1774 stl_be_p(&chunk->magic, NBD_STRUCTURED_REPLY_MAGIC);
1775 stw_be_p(&chunk->flags, flags);
1776 stw_be_p(&chunk->type, type);
1777 stq_be_p(&chunk->handle, handle);
1778 stl_be_p(&chunk->length, length);
1781 static int coroutine_fn nbd_co_send_structured_done(NBDClient *client,
1782 uint64_t handle,
1783 Error **errp)
1785 NBDStructuredReplyChunk chunk;
1786 struct iovec iov[] = {
1787 {.iov_base = &chunk, .iov_len = sizeof(chunk)},
1790 trace_nbd_co_send_structured_done(handle);
1791 set_be_chunk(&chunk, NBD_REPLY_FLAG_DONE, NBD_REPLY_TYPE_NONE, handle, 0);
1793 return nbd_co_send_iov(client, iov, 1, errp);
1796 static int coroutine_fn nbd_co_send_structured_read(NBDClient *client,
1797 uint64_t handle,
1798 uint64_t offset,
1799 void *data,
1800 size_t size,
1801 bool final,
1802 Error **errp)
1804 NBDStructuredReadData chunk;
1805 struct iovec iov[] = {
1806 {.iov_base = &chunk, .iov_len = sizeof(chunk)},
1807 {.iov_base = data, .iov_len = size}
1810 assert(size);
1811 trace_nbd_co_send_structured_read(handle, offset, data, size);
1812 set_be_chunk(&chunk.h, final ? NBD_REPLY_FLAG_DONE : 0,
1813 NBD_REPLY_TYPE_OFFSET_DATA, handle,
1814 sizeof(chunk) - sizeof(chunk.h) + size);
1815 stq_be_p(&chunk.offset, offset);
1817 return nbd_co_send_iov(client, iov, 2, errp);
1820 static int coroutine_fn nbd_co_send_structured_error(NBDClient *client,
1821 uint64_t handle,
1822 uint32_t error,
1823 const char *msg,
1824 Error **errp)
1826 NBDStructuredError chunk;
1827 int nbd_err = system_errno_to_nbd_errno(error);
1828 struct iovec iov[] = {
1829 {.iov_base = &chunk, .iov_len = sizeof(chunk)},
1830 {.iov_base = (char *)msg, .iov_len = msg ? strlen(msg) : 0},
1833 assert(nbd_err);
1834 trace_nbd_co_send_structured_error(handle, nbd_err,
1835 nbd_err_lookup(nbd_err), msg ? msg : "");
1836 set_be_chunk(&chunk.h, NBD_REPLY_FLAG_DONE, NBD_REPLY_TYPE_ERROR, handle,
1837 sizeof(chunk) - sizeof(chunk.h) + iov[1].iov_len);
1838 stl_be_p(&chunk.error, nbd_err);
1839 stw_be_p(&chunk.message_length, iov[1].iov_len);
1841 return nbd_co_send_iov(client, iov, 1 + !!iov[1].iov_len, errp);
1844 /* Do a sparse read and send the structured reply to the client.
1845 * Returns -errno if sending fails. bdrv_block_status_above() failure is
1846 * reported to the client, at which point this function succeeds.
1848 static int coroutine_fn nbd_co_send_sparse_read(NBDClient *client,
1849 uint64_t handle,
1850 uint64_t offset,
1851 uint8_t *data,
1852 size_t size,
1853 Error **errp)
1855 int ret = 0;
1856 NBDExport *exp = client->exp;
1857 size_t progress = 0;
1859 while (progress < size) {
1860 int64_t pnum;
1861 int status = bdrv_block_status_above(blk_bs(exp->blk), NULL,
1862 offset + progress,
1863 size - progress, &pnum, NULL,
1864 NULL);
1865 bool final;
1867 if (status < 0) {
1868 char *msg = g_strdup_printf("unable to check for holes: %s",
1869 strerror(-status));
1871 ret = nbd_co_send_structured_error(client, handle, -status, msg,
1872 errp);
1873 g_free(msg);
1874 return ret;
1876 assert(pnum && pnum <= size - progress);
1877 final = progress + pnum == size;
1878 if (status & BDRV_BLOCK_ZERO) {
1879 NBDStructuredReadHole chunk;
1880 struct iovec iov[] = {
1881 {.iov_base = &chunk, .iov_len = sizeof(chunk)},
1884 trace_nbd_co_send_structured_read_hole(handle, offset + progress,
1885 pnum);
1886 set_be_chunk(&chunk.h, final ? NBD_REPLY_FLAG_DONE : 0,
1887 NBD_REPLY_TYPE_OFFSET_HOLE,
1888 handle, sizeof(chunk) - sizeof(chunk.h));
1889 stq_be_p(&chunk.offset, offset + progress);
1890 stl_be_p(&chunk.length, pnum);
1891 ret = nbd_co_send_iov(client, iov, 1, errp);
1892 } else {
1893 ret = blk_pread(exp->blk, offset + progress + exp->dev_offset,
1894 data + progress, pnum);
1895 if (ret < 0) {
1896 error_setg_errno(errp, -ret, "reading from file failed");
1897 break;
1899 ret = nbd_co_send_structured_read(client, handle, offset + progress,
1900 data + progress, pnum, final,
1901 errp);
1904 if (ret < 0) {
1905 break;
1907 progress += pnum;
1909 return ret;
1913 * Populate @extents from block status. Update @bytes to be the actual
1914 * length encoded (which may be smaller than the original), and update
1915 * @nb_extents to the number of extents used.
1917 * Returns zero on success and -errno on bdrv_block_status_above failure.
1919 static int blockstatus_to_extents(BlockDriverState *bs, uint64_t offset,
1920 uint64_t *bytes, NBDExtent *extents,
1921 unsigned int *nb_extents)
1923 uint64_t remaining_bytes = *bytes;
1924 NBDExtent *extent = extents, *extents_end = extents + *nb_extents;
1925 bool first_extent = true;
1927 assert(*nb_extents);
1928 while (remaining_bytes) {
1929 uint32_t flags;
1930 int64_t num;
1931 int ret = bdrv_block_status_above(bs, NULL, offset, remaining_bytes,
1932 &num, NULL, NULL);
1934 if (ret < 0) {
1935 return ret;
1938 flags = (ret & BDRV_BLOCK_ALLOCATED ? 0 : NBD_STATE_HOLE) |
1939 (ret & BDRV_BLOCK_ZERO ? NBD_STATE_ZERO : 0);
1941 if (first_extent) {
1942 extent->flags = flags;
1943 extent->length = num;
1944 first_extent = false;
1945 } else if (flags == extent->flags) {
1946 /* extend current extent */
1947 extent->length += num;
1948 } else {
1949 if (extent + 1 == extents_end) {
1950 break;
1953 /* start new extent */
1954 extent++;
1955 extent->flags = flags;
1956 extent->length = num;
1958 offset += num;
1959 remaining_bytes -= num;
1962 extents_end = extent + 1;
1964 for (extent = extents; extent < extents_end; extent++) {
1965 extent->flags = cpu_to_be32(extent->flags);
1966 extent->length = cpu_to_be32(extent->length);
1969 *bytes -= remaining_bytes;
1970 *nb_extents = extents_end - extents;
1972 return 0;
1975 /* nbd_co_send_extents
1977 * @length is only for tracing purposes (and may be smaller or larger
1978 * than the client's original request). @last controls whether
1979 * NBD_REPLY_FLAG_DONE is sent. @extents should already be in
1980 * big-endian format.
1982 static int nbd_co_send_extents(NBDClient *client, uint64_t handle,
1983 NBDExtent *extents, unsigned int nb_extents,
1984 uint64_t length, bool last,
1985 uint32_t context_id, Error **errp)
1987 NBDStructuredMeta chunk;
1989 struct iovec iov[] = {
1990 {.iov_base = &chunk, .iov_len = sizeof(chunk)},
1991 {.iov_base = extents, .iov_len = nb_extents * sizeof(extents[0])}
1994 trace_nbd_co_send_extents(handle, nb_extents, context_id, length, last);
1995 set_be_chunk(&chunk.h, last ? NBD_REPLY_FLAG_DONE : 0,
1996 NBD_REPLY_TYPE_BLOCK_STATUS,
1997 handle, sizeof(chunk) - sizeof(chunk.h) + iov[1].iov_len);
1998 stl_be_p(&chunk.context_id, context_id);
2000 return nbd_co_send_iov(client, iov, 2, errp);
2003 /* Get block status from the exported device and send it to the client */
2004 static int nbd_co_send_block_status(NBDClient *client, uint64_t handle,
2005 BlockDriverState *bs, uint64_t offset,
2006 uint32_t length, bool dont_fragment,
2007 bool last, uint32_t context_id,
2008 Error **errp)
2010 int ret;
2011 unsigned int nb_extents = dont_fragment ? 1 : NBD_MAX_BLOCK_STATUS_EXTENTS;
2012 NBDExtent *extents = g_new(NBDExtent, nb_extents);
2013 uint64_t final_length = length;
2015 ret = blockstatus_to_extents(bs, offset, &final_length, extents,
2016 &nb_extents);
2017 if (ret < 0) {
2018 g_free(extents);
2019 return nbd_co_send_structured_error(
2020 client, handle, -ret, "can't get block status", errp);
2023 ret = nbd_co_send_extents(client, handle, extents, nb_extents,
2024 final_length, last, context_id, errp);
2026 g_free(extents);
2028 return ret;
2032 * Populate @extents from a dirty bitmap. Unless @dont_fragment, the
2033 * final extent may exceed the original @length. Store in @length the
2034 * byte length encoded (which may be smaller or larger than the
2035 * original), and return the number of extents used.
2037 static unsigned int bitmap_to_extents(BdrvDirtyBitmap *bitmap, uint64_t offset,
2038 uint64_t *length, NBDExtent *extents,
2039 unsigned int nb_extents,
2040 bool dont_fragment)
2042 uint64_t begin = offset, end = offset;
2043 uint64_t overall_end = offset + *length;
2044 unsigned int i = 0;
2045 BdrvDirtyBitmapIter *it;
2046 bool dirty;
2048 bdrv_dirty_bitmap_lock(bitmap);
2050 it = bdrv_dirty_iter_new(bitmap);
2051 dirty = bdrv_dirty_bitmap_get_locked(bitmap, offset);
2053 assert(begin < overall_end && nb_extents);
2054 while (begin < overall_end && i < nb_extents) {
2055 bool next_dirty = !dirty;
2057 if (dirty) {
2058 end = bdrv_dirty_bitmap_next_zero(bitmap, begin, UINT64_MAX);
2059 } else {
2060 bdrv_set_dirty_iter(it, begin);
2061 end = bdrv_dirty_iter_next(it);
2063 if (end == -1 || end - begin > UINT32_MAX) {
2064 /* Cap to an aligned value < 4G beyond begin. */
2065 end = MIN(bdrv_dirty_bitmap_size(bitmap),
2066 begin + UINT32_MAX + 1 -
2067 bdrv_dirty_bitmap_granularity(bitmap));
2068 next_dirty = dirty;
2070 if (dont_fragment && end > overall_end) {
2071 end = overall_end;
2074 extents[i].length = cpu_to_be32(end - begin);
2075 extents[i].flags = cpu_to_be32(dirty ? NBD_STATE_DIRTY : 0);
2076 i++;
2077 begin = end;
2078 dirty = next_dirty;
2081 bdrv_dirty_iter_free(it);
2083 bdrv_dirty_bitmap_unlock(bitmap);
2085 assert(offset < end);
2086 *length = end - offset;
2087 return i;
2090 static int nbd_co_send_bitmap(NBDClient *client, uint64_t handle,
2091 BdrvDirtyBitmap *bitmap, uint64_t offset,
2092 uint32_t length, bool dont_fragment, bool last,
2093 uint32_t context_id, Error **errp)
2095 int ret;
2096 unsigned int nb_extents = dont_fragment ? 1 : NBD_MAX_BLOCK_STATUS_EXTENTS;
2097 NBDExtent *extents = g_new(NBDExtent, nb_extents);
2098 uint64_t final_length = length;
2100 nb_extents = bitmap_to_extents(bitmap, offset, &final_length, extents,
2101 nb_extents, dont_fragment);
2103 ret = nbd_co_send_extents(client, handle, extents, nb_extents,
2104 final_length, last, context_id, errp);
2106 g_free(extents);
2108 return ret;
2111 /* nbd_co_receive_request
2112 * Collect a client request. Return 0 if request looks valid, -EIO to drop
2113 * connection right away, and any other negative value to report an error to
2114 * the client (although the caller may still need to disconnect after reporting
2115 * the error).
2117 static int nbd_co_receive_request(NBDRequestData *req, NBDRequest *request,
2118 Error **errp)
2120 NBDClient *client = req->client;
2121 int valid_flags;
2123 g_assert(qemu_in_coroutine());
2124 assert(client->recv_coroutine == qemu_coroutine_self());
2125 if (nbd_receive_request(client->ioc, request, errp) < 0) {
2126 return -EIO;
2129 trace_nbd_co_receive_request_decode_type(request->handle, request->type,
2130 nbd_cmd_lookup(request->type));
2132 if (request->type != NBD_CMD_WRITE) {
2133 /* No payload, we are ready to read the next request. */
2134 req->complete = true;
2137 if (request->type == NBD_CMD_DISC) {
2138 /* Special case: we're going to disconnect without a reply,
2139 * whether or not flags, from, or len are bogus */
2140 return -EIO;
2143 if (request->type == NBD_CMD_READ || request->type == NBD_CMD_WRITE ||
2144 request->type == NBD_CMD_CACHE)
2146 if (request->len > NBD_MAX_BUFFER_SIZE) {
2147 error_setg(errp, "len (%" PRIu32" ) is larger than max len (%u)",
2148 request->len, NBD_MAX_BUFFER_SIZE);
2149 return -EINVAL;
2152 if (request->type != NBD_CMD_CACHE) {
2153 req->data = blk_try_blockalign(client->exp->blk, request->len);
2154 if (req->data == NULL) {
2155 error_setg(errp, "No memory");
2156 return -ENOMEM;
2161 if (request->type == NBD_CMD_WRITE) {
2162 if (nbd_read(client->ioc, req->data, request->len, "CMD_WRITE data",
2163 errp) < 0)
2165 return -EIO;
2167 req->complete = true;
2169 trace_nbd_co_receive_request_payload_received(request->handle,
2170 request->len);
2173 /* Sanity checks. */
2174 if (client->exp->nbdflags & NBD_FLAG_READ_ONLY &&
2175 (request->type == NBD_CMD_WRITE ||
2176 request->type == NBD_CMD_WRITE_ZEROES ||
2177 request->type == NBD_CMD_TRIM)) {
2178 error_setg(errp, "Export is read-only");
2179 return -EROFS;
2181 if (request->from > client->exp->size ||
2182 request->len > client->exp->size - request->from) {
2183 error_setg(errp, "operation past EOF; From: %" PRIu64 ", Len: %" PRIu32
2184 ", Size: %" PRIu64, request->from, request->len,
2185 client->exp->size);
2186 return (request->type == NBD_CMD_WRITE ||
2187 request->type == NBD_CMD_WRITE_ZEROES) ? -ENOSPC : -EINVAL;
2189 if (client->check_align && !QEMU_IS_ALIGNED(request->from | request->len,
2190 client->check_align)) {
2192 * The block layer gracefully handles unaligned requests, but
2193 * it's still worth tracing client non-compliance
2195 trace_nbd_co_receive_align_compliance(nbd_cmd_lookup(request->type),
2196 request->from,
2197 request->len,
2198 client->check_align);
2200 valid_flags = NBD_CMD_FLAG_FUA;
2201 if (request->type == NBD_CMD_READ && client->structured_reply) {
2202 valid_flags |= NBD_CMD_FLAG_DF;
2203 } else if (request->type == NBD_CMD_WRITE_ZEROES) {
2204 valid_flags |= NBD_CMD_FLAG_NO_HOLE | NBD_CMD_FLAG_FAST_ZERO;
2205 } else if (request->type == NBD_CMD_BLOCK_STATUS) {
2206 valid_flags |= NBD_CMD_FLAG_REQ_ONE;
2208 if (request->flags & ~valid_flags) {
2209 error_setg(errp, "unsupported flags for command %s (got 0x%x)",
2210 nbd_cmd_lookup(request->type), request->flags);
2211 return -EINVAL;
2214 return 0;
2217 /* Send simple reply without a payload, or a structured error
2218 * @error_msg is ignored if @ret >= 0
2219 * Returns 0 if connection is still live, -errno on failure to talk to client
2221 static coroutine_fn int nbd_send_generic_reply(NBDClient *client,
2222 uint64_t handle,
2223 int ret,
2224 const char *error_msg,
2225 Error **errp)
2227 if (client->structured_reply && ret < 0) {
2228 return nbd_co_send_structured_error(client, handle, -ret, error_msg,
2229 errp);
2230 } else {
2231 return nbd_co_send_simple_reply(client, handle, ret < 0 ? -ret : 0,
2232 NULL, 0, errp);
2236 /* Handle NBD_CMD_READ request.
2237 * Return -errno if sending fails. Other errors are reported directly to the
2238 * client as an error reply. */
2239 static coroutine_fn int nbd_do_cmd_read(NBDClient *client, NBDRequest *request,
2240 uint8_t *data, Error **errp)
2242 int ret;
2243 NBDExport *exp = client->exp;
2245 assert(request->type == NBD_CMD_READ);
2247 /* XXX: NBD Protocol only documents use of FUA with WRITE */
2248 if (request->flags & NBD_CMD_FLAG_FUA) {
2249 ret = blk_co_flush(exp->blk);
2250 if (ret < 0) {
2251 return nbd_send_generic_reply(client, request->handle, ret,
2252 "flush failed", errp);
2256 if (client->structured_reply && !(request->flags & NBD_CMD_FLAG_DF) &&
2257 request->len)
2259 return nbd_co_send_sparse_read(client, request->handle, request->from,
2260 data, request->len, errp);
2263 ret = blk_pread(exp->blk, request->from + exp->dev_offset, data,
2264 request->len);
2265 if (ret < 0) {
2266 return nbd_send_generic_reply(client, request->handle, ret,
2267 "reading from file failed", errp);
2270 if (client->structured_reply) {
2271 if (request->len) {
2272 return nbd_co_send_structured_read(client, request->handle,
2273 request->from, data,
2274 request->len, true, errp);
2275 } else {
2276 return nbd_co_send_structured_done(client, request->handle, errp);
2278 } else {
2279 return nbd_co_send_simple_reply(client, request->handle, 0,
2280 data, request->len, errp);
2285 * nbd_do_cmd_cache
2287 * Handle NBD_CMD_CACHE request.
2288 * Return -errno if sending fails. Other errors are reported directly to the
2289 * client as an error reply.
2291 static coroutine_fn int nbd_do_cmd_cache(NBDClient *client, NBDRequest *request,
2292 Error **errp)
2294 int ret;
2295 NBDExport *exp = client->exp;
2297 assert(request->type == NBD_CMD_CACHE);
2299 ret = blk_co_preadv(exp->blk, request->from + exp->dev_offset, request->len,
2300 NULL, BDRV_REQ_COPY_ON_READ | BDRV_REQ_PREFETCH);
2302 return nbd_send_generic_reply(client, request->handle, ret,
2303 "caching data failed", errp);
2306 /* Handle NBD request.
2307 * Return -errno if sending fails. Other errors are reported directly to the
2308 * client as an error reply. */
2309 static coroutine_fn int nbd_handle_request(NBDClient *client,
2310 NBDRequest *request,
2311 uint8_t *data, Error **errp)
2313 int ret;
2314 int flags;
2315 NBDExport *exp = client->exp;
2316 char *msg;
2318 switch (request->type) {
2319 case NBD_CMD_CACHE:
2320 return nbd_do_cmd_cache(client, request, errp);
2322 case NBD_CMD_READ:
2323 return nbd_do_cmd_read(client, request, data, errp);
2325 case NBD_CMD_WRITE:
2326 flags = 0;
2327 if (request->flags & NBD_CMD_FLAG_FUA) {
2328 flags |= BDRV_REQ_FUA;
2330 ret = blk_pwrite(exp->blk, request->from + exp->dev_offset,
2331 data, request->len, flags);
2332 return nbd_send_generic_reply(client, request->handle, ret,
2333 "writing to file failed", errp);
2335 case NBD_CMD_WRITE_ZEROES:
2336 flags = 0;
2337 if (request->flags & NBD_CMD_FLAG_FUA) {
2338 flags |= BDRV_REQ_FUA;
2340 if (!(request->flags & NBD_CMD_FLAG_NO_HOLE)) {
2341 flags |= BDRV_REQ_MAY_UNMAP;
2343 if (request->flags & NBD_CMD_FLAG_FAST_ZERO) {
2344 flags |= BDRV_REQ_NO_FALLBACK;
2346 ret = blk_pwrite_zeroes(exp->blk, request->from + exp->dev_offset,
2347 request->len, flags);
2348 return nbd_send_generic_reply(client, request->handle, ret,
2349 "writing to file failed", errp);
2351 case NBD_CMD_DISC:
2352 /* unreachable, thanks to special case in nbd_co_receive_request() */
2353 abort();
2355 case NBD_CMD_FLUSH:
2356 ret = blk_co_flush(exp->blk);
2357 return nbd_send_generic_reply(client, request->handle, ret,
2358 "flush failed", errp);
2360 case NBD_CMD_TRIM:
2361 ret = blk_co_pdiscard(exp->blk, request->from + exp->dev_offset,
2362 request->len);
2363 if (ret == 0 && request->flags & NBD_CMD_FLAG_FUA) {
2364 ret = blk_co_flush(exp->blk);
2366 return nbd_send_generic_reply(client, request->handle, ret,
2367 "discard failed", errp);
2369 case NBD_CMD_BLOCK_STATUS:
2370 if (!request->len) {
2371 return nbd_send_generic_reply(client, request->handle, -EINVAL,
2372 "need non-zero length", errp);
2374 if (client->export_meta.valid &&
2375 (client->export_meta.base_allocation ||
2376 client->export_meta.bitmap))
2378 bool dont_fragment = request->flags & NBD_CMD_FLAG_REQ_ONE;
2380 if (client->export_meta.base_allocation) {
2381 ret = nbd_co_send_block_status(client, request->handle,
2382 blk_bs(exp->blk), request->from,
2383 request->len, dont_fragment,
2384 !client->export_meta.bitmap,
2385 NBD_META_ID_BASE_ALLOCATION,
2386 errp);
2387 } else { /* client->export_meta.bitmap */
2388 ret = nbd_co_send_bitmap(client, request->handle,
2389 client->exp->export_bitmap,
2390 request->from, request->len,
2391 dont_fragment,
2392 true, NBD_META_ID_DIRTY_BITMAP, errp);
2395 return ret;
2396 } else {
2397 return nbd_send_generic_reply(client, request->handle, -EINVAL,
2398 "CMD_BLOCK_STATUS not negotiated",
2399 errp);
2402 default:
2403 msg = g_strdup_printf("invalid request type (%" PRIu32 ") received",
2404 request->type);
2405 ret = nbd_send_generic_reply(client, request->handle, -EINVAL, msg,
2406 errp);
2407 g_free(msg);
2408 return ret;
2412 /* Owns a reference to the NBDClient passed as opaque. */
2413 static coroutine_fn void nbd_trip(void *opaque)
2415 NBDClient *client = opaque;
2416 NBDRequestData *req;
2417 NBDRequest request = { 0 }; /* GCC thinks it can be used uninitialized */
2418 int ret;
2419 Error *local_err = NULL;
2421 trace_nbd_trip();
2422 if (client->closing) {
2423 nbd_client_put(client);
2424 return;
2427 req = nbd_request_get(client);
2428 ret = nbd_co_receive_request(req, &request, &local_err);
2429 client->recv_coroutine = NULL;
2431 if (client->closing) {
2433 * The client may be closed when we are blocked in
2434 * nbd_co_receive_request()
2436 goto done;
2439 nbd_client_receive_next_request(client);
2440 if (ret == -EIO) {
2441 goto disconnect;
2444 if (ret < 0) {
2445 /* It wans't -EIO, so, according to nbd_co_receive_request()
2446 * semantics, we should return the error to the client. */
2447 Error *export_err = local_err;
2449 local_err = NULL;
2450 ret = nbd_send_generic_reply(client, request.handle, -EINVAL,
2451 error_get_pretty(export_err), &local_err);
2452 error_free(export_err);
2453 } else {
2454 ret = nbd_handle_request(client, &request, req->data, &local_err);
2456 if (ret < 0) {
2457 error_prepend(&local_err, "Failed to send reply: ");
2458 goto disconnect;
2461 /* We must disconnect after NBD_CMD_WRITE if we did not
2462 * read the payload.
2464 if (!req->complete) {
2465 error_setg(&local_err, "Request handling failed in intermediate state");
2466 goto disconnect;
2469 done:
2470 nbd_request_put(req);
2471 nbd_client_put(client);
2472 return;
2474 disconnect:
2475 if (local_err) {
2476 error_reportf_err(local_err, "Disconnect client, due to: ");
2478 nbd_request_put(req);
2479 client_close(client, true);
2480 nbd_client_put(client);
2483 static void nbd_client_receive_next_request(NBDClient *client)
2485 if (!client->recv_coroutine && client->nb_requests < MAX_NBD_REQUESTS) {
2486 nbd_client_get(client);
2487 client->recv_coroutine = qemu_coroutine_create(nbd_trip, client);
2488 aio_co_schedule(client->exp->ctx, client->recv_coroutine);
2492 static coroutine_fn void nbd_co_client_start(void *opaque)
2494 NBDClient *client = opaque;
2495 Error *local_err = NULL;
2497 qemu_co_mutex_init(&client->send_lock);
2499 if (nbd_negotiate(client, &local_err)) {
2500 if (local_err) {
2501 error_report_err(local_err);
2503 client_close(client, false);
2504 return;
2507 nbd_client_receive_next_request(client);
2511 * Create a new client listener using the given channel @sioc.
2512 * Begin servicing it in a coroutine. When the connection closes, call
2513 * @close_fn with an indication of whether the client completed negotiation.
2515 void nbd_client_new(QIOChannelSocket *sioc,
2516 QCryptoTLSCreds *tlscreds,
2517 const char *tlsauthz,
2518 void (*close_fn)(NBDClient *, bool))
2520 NBDClient *client;
2521 Coroutine *co;
2523 client = g_new0(NBDClient, 1);
2524 client->refcount = 1;
2525 client->tlscreds = tlscreds;
2526 if (tlscreds) {
2527 object_ref(OBJECT(client->tlscreds));
2529 client->tlsauthz = g_strdup(tlsauthz);
2530 client->sioc = sioc;
2531 object_ref(OBJECT(client->sioc));
2532 client->ioc = QIO_CHANNEL(sioc);
2533 object_ref(OBJECT(client->ioc));
2534 client->close_fn = close_fn;
2536 co = qemu_coroutine_create(nbd_co_client_start, client);
2537 qemu_coroutine_enter(co);