hw/arm/musicpal: Don't connect two qemu_irqs directly to the same input
[qemu/kevin.git] / nbd / server.c
blobd145e1a690834dae403fbb43c912627f90db1164
1 /*
2 * Copyright (C) 2016-2020 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"
22 #include "block/export.h"
23 #include "qapi/error.h"
24 #include "qemu/queue.h"
25 #include "trace.h"
26 #include "nbd-internal.h"
27 #include "qemu/units.h"
29 #define NBD_META_ID_BASE_ALLOCATION 0
30 #define NBD_META_ID_ALLOCATION_DEPTH 1
31 /* Dirty bitmaps use 'NBD_META_ID_DIRTY_BITMAP + i', so keep this id last. */
32 #define NBD_META_ID_DIRTY_BITMAP 2
35 * NBD_MAX_BLOCK_STATUS_EXTENTS: 1 MiB of extents data. An empirical
36 * constant. If an increase is needed, note that the NBD protocol
37 * recommends no larger than 32 mb, so that the client won't consider
38 * the reply as a denial of service attack.
40 #define NBD_MAX_BLOCK_STATUS_EXTENTS (1 * MiB / 8)
42 static int system_errno_to_nbd_errno(int err)
44 switch (err) {
45 case 0:
46 return NBD_SUCCESS;
47 case EPERM:
48 case EROFS:
49 return NBD_EPERM;
50 case EIO:
51 return NBD_EIO;
52 case ENOMEM:
53 return NBD_ENOMEM;
54 #ifdef EDQUOT
55 case EDQUOT:
56 #endif
57 case EFBIG:
58 case ENOSPC:
59 return NBD_ENOSPC;
60 case EOVERFLOW:
61 return NBD_EOVERFLOW;
62 case ENOTSUP:
63 #if ENOTSUP != EOPNOTSUPP
64 case EOPNOTSUPP:
65 #endif
66 return NBD_ENOTSUP;
67 case ESHUTDOWN:
68 return NBD_ESHUTDOWN;
69 case EINVAL:
70 default:
71 return NBD_EINVAL;
75 /* Definitions for opaque data types */
77 typedef struct NBDRequestData NBDRequestData;
79 struct NBDRequestData {
80 QSIMPLEQ_ENTRY(NBDRequestData) entry;
81 NBDClient *client;
82 uint8_t *data;
83 bool complete;
86 struct NBDExport {
87 BlockExport common;
89 char *name;
90 char *description;
91 uint64_t size;
92 uint16_t nbdflags;
93 QTAILQ_HEAD(, NBDClient) clients;
94 QTAILQ_ENTRY(NBDExport) next;
96 BlockBackend *eject_notifier_blk;
97 Notifier eject_notifier;
99 bool allocation_depth;
100 BdrvDirtyBitmap **export_bitmaps;
101 size_t nr_export_bitmaps;
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 size_t count; /* number of negotiated contexts */
112 bool base_allocation; /* export base:allocation context (block status) */
113 bool allocation_depth; /* export qemu:allocation-depth */
114 bool *bitmaps; /*
115 * export qemu:dirty-bitmap:<export bitmap name>,
116 * sized by exp->nr_export_bitmaps
118 } NBDExportMetaContexts;
120 struct NBDClient {
121 int refcount;
122 void (*close_fn)(NBDClient *client, bool negotiated);
124 NBDExport *exp;
125 QCryptoTLSCreds *tlscreds;
126 char *tlsauthz;
127 QIOChannelSocket *sioc; /* The underlying data channel */
128 QIOChannel *ioc; /* The current I/O channel which may differ (eg TLS) */
130 Coroutine *recv_coroutine;
132 CoMutex send_lock;
133 Coroutine *send_coroutine;
135 QTAILQ_ENTRY(NBDClient) next;
136 int nb_requests;
137 bool closing;
139 uint32_t check_align; /* If non-zero, check for aligned client requests */
141 bool structured_reply;
142 NBDExportMetaContexts export_meta;
144 uint32_t opt; /* Current option being negotiated */
145 uint32_t optlen; /* remaining length of data in ioc for the option being
146 negotiated now */
149 static void nbd_client_receive_next_request(NBDClient *client);
151 /* Basic flow for negotiation
153 Server Client
154 Negotiate
158 Server Client
159 Negotiate #1
160 Option
161 Negotiate #2
163 ----
165 followed by
167 Server Client
168 Request
169 Response
170 Request
171 Response
174 Request (type == 2)
178 static inline void set_be_option_rep(NBDOptionReply *rep, uint32_t option,
179 uint32_t type, uint32_t length)
181 stq_be_p(&rep->magic, NBD_REP_MAGIC);
182 stl_be_p(&rep->option, option);
183 stl_be_p(&rep->type, type);
184 stl_be_p(&rep->length, length);
187 /* Send a reply header, including length, but no payload.
188 * Return -errno on error, 0 on success. */
189 static int nbd_negotiate_send_rep_len(NBDClient *client, uint32_t type,
190 uint32_t len, Error **errp)
192 NBDOptionReply rep;
194 trace_nbd_negotiate_send_rep_len(client->opt, nbd_opt_lookup(client->opt),
195 type, nbd_rep_lookup(type), len);
197 assert(len < NBD_MAX_BUFFER_SIZE);
199 set_be_option_rep(&rep, client->opt, type, len);
200 return nbd_write(client->ioc, &rep, sizeof(rep), errp);
203 /* Send a reply header with default 0 length.
204 * Return -errno on error, 0 on success. */
205 static int nbd_negotiate_send_rep(NBDClient *client, uint32_t type,
206 Error **errp)
208 return nbd_negotiate_send_rep_len(client, type, 0, errp);
211 /* Send an error reply.
212 * Return -errno on error, 0 on success. */
213 static int GCC_FMT_ATTR(4, 0)
214 nbd_negotiate_send_rep_verr(NBDClient *client, uint32_t type,
215 Error **errp, const char *fmt, va_list va)
217 ERRP_GUARD();
218 g_autofree char *msg = NULL;
219 int ret;
220 size_t len;
222 msg = g_strdup_vprintf(fmt, va);
223 len = strlen(msg);
224 assert(len < NBD_MAX_STRING_SIZE);
225 trace_nbd_negotiate_send_rep_err(msg);
226 ret = nbd_negotiate_send_rep_len(client, type, len, errp);
227 if (ret < 0) {
228 return ret;
230 if (nbd_write(client->ioc, msg, len, errp) < 0) {
231 error_prepend(errp, "write failed (error message): ");
232 return -EIO;
235 return 0;
239 * Return a malloc'd copy of @name suitable for use in an error reply.
241 static char *
242 nbd_sanitize_name(const char *name)
244 if (strnlen(name, 80) < 80) {
245 return g_strdup(name);
247 /* XXX Should we also try to sanitize any control characters? */
248 return g_strdup_printf("%.80s...", name);
251 /* Send an error reply.
252 * Return -errno on error, 0 on success. */
253 static int GCC_FMT_ATTR(4, 5)
254 nbd_negotiate_send_rep_err(NBDClient *client, uint32_t type,
255 Error **errp, const char *fmt, ...)
257 va_list va;
258 int ret;
260 va_start(va, fmt);
261 ret = nbd_negotiate_send_rep_verr(client, type, errp, fmt, va);
262 va_end(va);
263 return ret;
266 /* Drop remainder of the current option, and send a reply with the
267 * given error type and message. Return -errno on read or write
268 * failure; or 0 if connection is still live. */
269 static int GCC_FMT_ATTR(4, 0)
270 nbd_opt_vdrop(NBDClient *client, uint32_t type, Error **errp,
271 const char *fmt, va_list va)
273 int ret = nbd_drop(client->ioc, client->optlen, errp);
275 client->optlen = 0;
276 if (!ret) {
277 ret = nbd_negotiate_send_rep_verr(client, type, errp, fmt, va);
279 return ret;
282 static int GCC_FMT_ATTR(4, 5)
283 nbd_opt_drop(NBDClient *client, uint32_t type, Error **errp,
284 const char *fmt, ...)
286 int ret;
287 va_list va;
289 va_start(va, fmt);
290 ret = nbd_opt_vdrop(client, type, errp, fmt, va);
291 va_end(va);
293 return ret;
296 static int GCC_FMT_ATTR(3, 4)
297 nbd_opt_invalid(NBDClient *client, Error **errp, const char *fmt, ...)
299 int ret;
300 va_list va;
302 va_start(va, fmt);
303 ret = nbd_opt_vdrop(client, NBD_REP_ERR_INVALID, errp, fmt, va);
304 va_end(va);
306 return ret;
309 /* Read size bytes from the unparsed payload of the current option.
310 * If @check_nul, require that no NUL bytes appear in buffer.
311 * Return -errno on I/O error, 0 if option was completely handled by
312 * sending a reply about inconsistent lengths, or 1 on success. */
313 static int nbd_opt_read(NBDClient *client, void *buffer, size_t size,
314 bool check_nul, Error **errp)
316 if (size > client->optlen) {
317 return nbd_opt_invalid(client, errp,
318 "Inconsistent lengths in option %s",
319 nbd_opt_lookup(client->opt));
321 client->optlen -= size;
322 if (qio_channel_read_all(client->ioc, buffer, size, errp) < 0) {
323 return -EIO;
326 if (check_nul && strnlen(buffer, size) != size) {
327 return nbd_opt_invalid(client, errp,
328 "Unexpected embedded NUL in option %s",
329 nbd_opt_lookup(client->opt));
331 return 1;
334 /* Drop size bytes from the unparsed payload of the current option.
335 * Return -errno on I/O error, 0 if option was completely handled by
336 * sending a reply about inconsistent lengths, or 1 on success. */
337 static int nbd_opt_skip(NBDClient *client, size_t size, Error **errp)
339 if (size > client->optlen) {
340 return nbd_opt_invalid(client, errp,
341 "Inconsistent lengths in option %s",
342 nbd_opt_lookup(client->opt));
344 client->optlen -= size;
345 return nbd_drop(client->ioc, size, errp) < 0 ? -EIO : 1;
348 /* nbd_opt_read_name
350 * Read a string with the format:
351 * uint32_t len (<= NBD_MAX_STRING_SIZE)
352 * len bytes string (not 0-terminated)
354 * On success, @name will be allocated.
355 * If @length is non-null, it will be set to the actual string length.
357 * Return -errno on I/O error, 0 if option was completely handled by
358 * sending a reply about inconsistent lengths, or 1 on success.
360 static int nbd_opt_read_name(NBDClient *client, char **name, uint32_t *length,
361 Error **errp)
363 int ret;
364 uint32_t len;
365 g_autofree char *local_name = NULL;
367 *name = NULL;
368 ret = nbd_opt_read(client, &len, sizeof(len), false, errp);
369 if (ret <= 0) {
370 return ret;
372 len = cpu_to_be32(len);
374 if (len > NBD_MAX_STRING_SIZE) {
375 return nbd_opt_invalid(client, errp,
376 "Invalid name length: %" PRIu32, len);
379 local_name = g_malloc(len + 1);
380 ret = nbd_opt_read(client, local_name, len, true, errp);
381 if (ret <= 0) {
382 return ret;
384 local_name[len] = '\0';
386 if (length) {
387 *length = len;
389 *name = g_steal_pointer(&local_name);
391 return 1;
394 /* Send a single NBD_REP_SERVER reply to NBD_OPT_LIST, including payload.
395 * Return -errno on error, 0 on success. */
396 static int nbd_negotiate_send_rep_list(NBDClient *client, NBDExport *exp,
397 Error **errp)
399 ERRP_GUARD();
400 size_t name_len, desc_len;
401 uint32_t len;
402 const char *name = exp->name ? exp->name : "";
403 const char *desc = exp->description ? exp->description : "";
404 QIOChannel *ioc = client->ioc;
405 int ret;
407 trace_nbd_negotiate_send_rep_list(name, desc);
408 name_len = strlen(name);
409 desc_len = strlen(desc);
410 assert(name_len <= NBD_MAX_STRING_SIZE && desc_len <= NBD_MAX_STRING_SIZE);
411 len = name_len + desc_len + sizeof(len);
412 ret = nbd_negotiate_send_rep_len(client, NBD_REP_SERVER, len, errp);
413 if (ret < 0) {
414 return ret;
417 len = cpu_to_be32(name_len);
418 if (nbd_write(ioc, &len, sizeof(len), errp) < 0) {
419 error_prepend(errp, "write failed (name length): ");
420 return -EINVAL;
423 if (nbd_write(ioc, name, name_len, errp) < 0) {
424 error_prepend(errp, "write failed (name buffer): ");
425 return -EINVAL;
428 if (nbd_write(ioc, desc, desc_len, errp) < 0) {
429 error_prepend(errp, "write failed (description buffer): ");
430 return -EINVAL;
433 return 0;
436 /* Process the NBD_OPT_LIST command, with a potential series of replies.
437 * Return -errno on error, 0 on success. */
438 static int nbd_negotiate_handle_list(NBDClient *client, Error **errp)
440 NBDExport *exp;
441 assert(client->opt == NBD_OPT_LIST);
443 /* For each export, send a NBD_REP_SERVER reply. */
444 QTAILQ_FOREACH(exp, &exports, next) {
445 if (nbd_negotiate_send_rep_list(client, exp, errp)) {
446 return -EINVAL;
449 /* Finish with a NBD_REP_ACK. */
450 return nbd_negotiate_send_rep(client, NBD_REP_ACK, errp);
453 static void nbd_check_meta_export(NBDClient *client)
455 if (client->exp != client->export_meta.exp) {
456 client->export_meta.count = 0;
460 /* Send a reply to NBD_OPT_EXPORT_NAME.
461 * Return -errno on error, 0 on success. */
462 static int nbd_negotiate_handle_export_name(NBDClient *client, bool no_zeroes,
463 Error **errp)
465 ERRP_GUARD();
466 g_autofree char *name = NULL;
467 char buf[NBD_REPLY_EXPORT_NAME_SIZE] = "";
468 size_t len;
469 int ret;
470 uint16_t myflags;
472 /* Client sends:
473 [20 .. xx] export name (length bytes)
474 Server replies:
475 [ 0 .. 7] size
476 [ 8 .. 9] export flags
477 [10 .. 133] reserved (0) [unless no_zeroes]
479 trace_nbd_negotiate_handle_export_name();
480 if (client->optlen > NBD_MAX_STRING_SIZE) {
481 error_setg(errp, "Bad length received");
482 return -EINVAL;
484 name = g_malloc(client->optlen + 1);
485 if (nbd_read(client->ioc, name, client->optlen, "export name", errp) < 0) {
486 return -EIO;
488 name[client->optlen] = '\0';
489 client->optlen = 0;
491 trace_nbd_negotiate_handle_export_name_request(name);
493 client->exp = nbd_export_find(name);
494 if (!client->exp) {
495 error_setg(errp, "export not found");
496 return -EINVAL;
499 myflags = client->exp->nbdflags;
500 if (client->structured_reply) {
501 myflags |= NBD_FLAG_SEND_DF;
503 trace_nbd_negotiate_new_style_size_flags(client->exp->size, myflags);
504 stq_be_p(buf, client->exp->size);
505 stw_be_p(buf + 8, myflags);
506 len = no_zeroes ? 10 : sizeof(buf);
507 ret = nbd_write(client->ioc, buf, len, errp);
508 if (ret < 0) {
509 error_prepend(errp, "write failed: ");
510 return ret;
513 QTAILQ_INSERT_TAIL(&client->exp->clients, client, next);
514 blk_exp_ref(&client->exp->common);
515 nbd_check_meta_export(client);
517 return 0;
520 /* Send a single NBD_REP_INFO, with a buffer @buf of @length bytes.
521 * The buffer does NOT include the info type prefix.
522 * Return -errno on error, 0 if ready to send more. */
523 static int nbd_negotiate_send_info(NBDClient *client,
524 uint16_t info, uint32_t length, void *buf,
525 Error **errp)
527 int rc;
529 trace_nbd_negotiate_send_info(info, nbd_info_lookup(info), length);
530 rc = nbd_negotiate_send_rep_len(client, NBD_REP_INFO,
531 sizeof(info) + length, errp);
532 if (rc < 0) {
533 return rc;
535 info = cpu_to_be16(info);
536 if (nbd_write(client->ioc, &info, sizeof(info), errp) < 0) {
537 return -EIO;
539 if (nbd_write(client->ioc, buf, length, errp) < 0) {
540 return -EIO;
542 return 0;
545 /* nbd_reject_length: Handle any unexpected payload.
546 * @fatal requests that we quit talking to the client, even if we are able
547 * to successfully send an error reply.
548 * Return:
549 * -errno transmission error occurred or @fatal was requested, errp is set
550 * 0 error message successfully sent to client, errp is not set
552 static int nbd_reject_length(NBDClient *client, bool fatal, Error **errp)
554 int ret;
556 assert(client->optlen);
557 ret = nbd_opt_invalid(client, errp, "option '%s' has unexpected length",
558 nbd_opt_lookup(client->opt));
559 if (fatal && !ret) {
560 error_setg(errp, "option '%s' has unexpected length",
561 nbd_opt_lookup(client->opt));
562 return -EINVAL;
564 return ret;
567 /* Handle NBD_OPT_INFO and NBD_OPT_GO.
568 * Return -errno on error, 0 if ready for next option, and 1 to move
569 * into transmission phase. */
570 static int nbd_negotiate_handle_info(NBDClient *client, Error **errp)
572 int rc;
573 g_autofree char *name = NULL;
574 NBDExport *exp;
575 uint16_t requests;
576 uint16_t request;
577 uint32_t namelen = 0;
578 bool sendname = false;
579 bool blocksize = false;
580 uint32_t sizes[3];
581 char buf[sizeof(uint64_t) + sizeof(uint16_t)];
582 uint32_t check_align = 0;
583 uint16_t myflags;
585 /* Client sends:
586 4 bytes: L, name length (can be 0)
587 L bytes: export name
588 2 bytes: N, number of requests (can be 0)
589 N * 2 bytes: N requests
591 rc = nbd_opt_read_name(client, &name, &namelen, errp);
592 if (rc <= 0) {
593 return rc;
595 trace_nbd_negotiate_handle_export_name_request(name);
597 rc = nbd_opt_read(client, &requests, sizeof(requests), false, errp);
598 if (rc <= 0) {
599 return rc;
601 requests = be16_to_cpu(requests);
602 trace_nbd_negotiate_handle_info_requests(requests);
603 while (requests--) {
604 rc = nbd_opt_read(client, &request, sizeof(request), false, errp);
605 if (rc <= 0) {
606 return rc;
608 request = be16_to_cpu(request);
609 trace_nbd_negotiate_handle_info_request(request,
610 nbd_info_lookup(request));
611 /* We care about NBD_INFO_NAME and NBD_INFO_BLOCK_SIZE;
612 * everything else is either a request we don't know or
613 * something we send regardless of request */
614 switch (request) {
615 case NBD_INFO_NAME:
616 sendname = true;
617 break;
618 case NBD_INFO_BLOCK_SIZE:
619 blocksize = true;
620 break;
623 if (client->optlen) {
624 return nbd_reject_length(client, false, errp);
627 exp = nbd_export_find(name);
628 if (!exp) {
629 g_autofree char *sane_name = nbd_sanitize_name(name);
631 return nbd_negotiate_send_rep_err(client, NBD_REP_ERR_UNKNOWN,
632 errp, "export '%s' not present",
633 sane_name);
636 /* Don't bother sending NBD_INFO_NAME unless client requested it */
637 if (sendname) {
638 rc = nbd_negotiate_send_info(client, NBD_INFO_NAME, namelen, name,
639 errp);
640 if (rc < 0) {
641 return rc;
645 /* Send NBD_INFO_DESCRIPTION only if available, regardless of
646 * client request */
647 if (exp->description) {
648 size_t len = strlen(exp->description);
650 assert(len <= NBD_MAX_STRING_SIZE);
651 rc = nbd_negotiate_send_info(client, NBD_INFO_DESCRIPTION,
652 len, exp->description, errp);
653 if (rc < 0) {
654 return rc;
658 /* Send NBD_INFO_BLOCK_SIZE always, but tweak the minimum size
659 * according to whether the client requested it, and according to
660 * whether this is OPT_INFO or OPT_GO. */
661 /* minimum - 1 for back-compat, or actual if client will obey it. */
662 if (client->opt == NBD_OPT_INFO || blocksize) {
663 check_align = sizes[0] = blk_get_request_alignment(exp->common.blk);
664 } else {
665 sizes[0] = 1;
667 assert(sizes[0] <= NBD_MAX_BUFFER_SIZE);
668 /* preferred - Hard-code to 4096 for now.
669 * TODO: is blk_bs(blk)->bl.opt_transfer appropriate? */
670 sizes[1] = MAX(4096, sizes[0]);
671 /* maximum - At most 32M, but smaller as appropriate. */
672 sizes[2] = MIN(blk_get_max_transfer(exp->common.blk), NBD_MAX_BUFFER_SIZE);
673 trace_nbd_negotiate_handle_info_block_size(sizes[0], sizes[1], sizes[2]);
674 sizes[0] = cpu_to_be32(sizes[0]);
675 sizes[1] = cpu_to_be32(sizes[1]);
676 sizes[2] = cpu_to_be32(sizes[2]);
677 rc = nbd_negotiate_send_info(client, NBD_INFO_BLOCK_SIZE,
678 sizeof(sizes), sizes, errp);
679 if (rc < 0) {
680 return rc;
683 /* Send NBD_INFO_EXPORT always */
684 myflags = exp->nbdflags;
685 if (client->structured_reply) {
686 myflags |= NBD_FLAG_SEND_DF;
688 trace_nbd_negotiate_new_style_size_flags(exp->size, myflags);
689 stq_be_p(buf, exp->size);
690 stw_be_p(buf + 8, myflags);
691 rc = nbd_negotiate_send_info(client, NBD_INFO_EXPORT,
692 sizeof(buf), buf, errp);
693 if (rc < 0) {
694 return rc;
698 * If the client is just asking for NBD_OPT_INFO, but forgot to
699 * request block sizes in a situation that would impact
700 * performance, then return an error. But for NBD_OPT_GO, we
701 * tolerate all clients, regardless of alignments.
703 if (client->opt == NBD_OPT_INFO && !blocksize &&
704 blk_get_request_alignment(exp->common.blk) > 1) {
705 return nbd_negotiate_send_rep_err(client,
706 NBD_REP_ERR_BLOCK_SIZE_REQD,
707 errp,
708 "request NBD_INFO_BLOCK_SIZE to "
709 "use this export");
712 /* Final reply */
713 rc = nbd_negotiate_send_rep(client, NBD_REP_ACK, errp);
714 if (rc < 0) {
715 return rc;
718 if (client->opt == NBD_OPT_GO) {
719 client->exp = exp;
720 client->check_align = check_align;
721 QTAILQ_INSERT_TAIL(&client->exp->clients, client, next);
722 blk_exp_ref(&client->exp->common);
723 nbd_check_meta_export(client);
724 rc = 1;
726 return rc;
730 /* Handle NBD_OPT_STARTTLS. Return NULL to drop connection, or else the
731 * new channel for all further (now-encrypted) communication. */
732 static QIOChannel *nbd_negotiate_handle_starttls(NBDClient *client,
733 Error **errp)
735 QIOChannel *ioc;
736 QIOChannelTLS *tioc;
737 struct NBDTLSHandshakeData data = { 0 };
739 assert(client->opt == NBD_OPT_STARTTLS);
741 trace_nbd_negotiate_handle_starttls();
742 ioc = client->ioc;
744 if (nbd_negotiate_send_rep(client, NBD_REP_ACK, errp) < 0) {
745 return NULL;
748 tioc = qio_channel_tls_new_server(ioc,
749 client->tlscreds,
750 client->tlsauthz,
751 errp);
752 if (!tioc) {
753 return NULL;
756 qio_channel_set_name(QIO_CHANNEL(tioc), "nbd-server-tls");
757 trace_nbd_negotiate_handle_starttls_handshake();
758 data.loop = g_main_loop_new(g_main_context_default(), FALSE);
759 qio_channel_tls_handshake(tioc,
760 nbd_tls_handshake,
761 &data,
762 NULL,
763 NULL);
765 if (!data.complete) {
766 g_main_loop_run(data.loop);
768 g_main_loop_unref(data.loop);
769 if (data.error) {
770 object_unref(OBJECT(tioc));
771 error_propagate(errp, data.error);
772 return NULL;
775 return QIO_CHANNEL(tioc);
778 /* nbd_negotiate_send_meta_context
780 * Send one chunk of reply to NBD_OPT_{LIST,SET}_META_CONTEXT
782 * For NBD_OPT_LIST_META_CONTEXT @context_id is ignored, 0 is used instead.
784 static int nbd_negotiate_send_meta_context(NBDClient *client,
785 const char *context,
786 uint32_t context_id,
787 Error **errp)
789 NBDOptionReplyMetaContext opt;
790 struct iovec iov[] = {
791 {.iov_base = &opt, .iov_len = sizeof(opt)},
792 {.iov_base = (void *)context, .iov_len = strlen(context)}
795 assert(iov[1].iov_len <= NBD_MAX_STRING_SIZE);
796 if (client->opt == NBD_OPT_LIST_META_CONTEXT) {
797 context_id = 0;
800 trace_nbd_negotiate_meta_query_reply(context, context_id);
801 set_be_option_rep(&opt.h, client->opt, NBD_REP_META_CONTEXT,
802 sizeof(opt) - sizeof(opt.h) + iov[1].iov_len);
803 stl_be_p(&opt.context_id, context_id);
805 return qio_channel_writev_all(client->ioc, iov, 2, errp) < 0 ? -EIO : 0;
809 * Return true if @query matches @pattern, or if @query is empty when
810 * the @client is performing _LIST_.
812 static bool nbd_meta_empty_or_pattern(NBDClient *client, const char *pattern,
813 const char *query)
815 if (!*query) {
816 trace_nbd_negotiate_meta_query_parse("empty");
817 return client->opt == NBD_OPT_LIST_META_CONTEXT;
819 if (strcmp(query, pattern) == 0) {
820 trace_nbd_negotiate_meta_query_parse(pattern);
821 return true;
823 trace_nbd_negotiate_meta_query_skip("pattern not matched");
824 return false;
828 * Return true and adjust @str in place if it begins with @prefix.
830 static bool nbd_strshift(const char **str, const char *prefix)
832 size_t len = strlen(prefix);
834 if (strncmp(*str, prefix, len) == 0) {
835 *str += len;
836 return true;
838 return false;
841 /* nbd_meta_base_query
843 * Handle queries to 'base' namespace. For now, only the base:allocation
844 * context is available. Return true if @query has been handled.
846 static bool nbd_meta_base_query(NBDClient *client, NBDExportMetaContexts *meta,
847 const char *query)
849 if (!nbd_strshift(&query, "base:")) {
850 return false;
852 trace_nbd_negotiate_meta_query_parse("base:");
854 if (nbd_meta_empty_or_pattern(client, "allocation", query)) {
855 meta->base_allocation = true;
857 return true;
860 /* nbd_meta_qemu_query
862 * Handle queries to 'qemu' namespace. For now, only the qemu:dirty-bitmap:
863 * and qemu:allocation-depth contexts are available. Return true if @query
864 * has been handled.
866 static bool nbd_meta_qemu_query(NBDClient *client, NBDExportMetaContexts *meta,
867 const char *query)
869 size_t i;
871 if (!nbd_strshift(&query, "qemu:")) {
872 return false;
874 trace_nbd_negotiate_meta_query_parse("qemu:");
876 if (!*query) {
877 if (client->opt == NBD_OPT_LIST_META_CONTEXT) {
878 meta->allocation_depth = meta->exp->allocation_depth;
879 memset(meta->bitmaps, 1, meta->exp->nr_export_bitmaps);
881 trace_nbd_negotiate_meta_query_parse("empty");
882 return true;
885 if (strcmp(query, "allocation-depth") == 0) {
886 trace_nbd_negotiate_meta_query_parse("allocation-depth");
887 meta->allocation_depth = meta->exp->allocation_depth;
888 return true;
891 if (nbd_strshift(&query, "dirty-bitmap:")) {
892 trace_nbd_negotiate_meta_query_parse("dirty-bitmap:");
893 if (!*query) {
894 if (client->opt == NBD_OPT_LIST_META_CONTEXT) {
895 memset(meta->bitmaps, 1, meta->exp->nr_export_bitmaps);
897 trace_nbd_negotiate_meta_query_parse("empty");
898 return true;
901 for (i = 0; i < meta->exp->nr_export_bitmaps; i++) {
902 const char *bm_name;
904 bm_name = bdrv_dirty_bitmap_name(meta->exp->export_bitmaps[i]);
905 if (strcmp(bm_name, query) == 0) {
906 meta->bitmaps[i] = true;
907 trace_nbd_negotiate_meta_query_parse(query);
908 return true;
911 trace_nbd_negotiate_meta_query_skip("no dirty-bitmap match");
912 return true;
915 trace_nbd_negotiate_meta_query_skip("unknown qemu context");
916 return true;
919 /* nbd_negotiate_meta_query
921 * Parse namespace name and call corresponding function to parse body of the
922 * query.
924 * The only supported namespaces are 'base' and 'qemu'.
926 * Return -errno on I/O error, 0 if option was completely handled by
927 * sending a reply about inconsistent lengths, or 1 on success. */
928 static int nbd_negotiate_meta_query(NBDClient *client,
929 NBDExportMetaContexts *meta, Error **errp)
931 int ret;
932 g_autofree char *query = NULL;
933 uint32_t len;
935 ret = nbd_opt_read(client, &len, sizeof(len), false, errp);
936 if (ret <= 0) {
937 return ret;
939 len = cpu_to_be32(len);
941 if (len > NBD_MAX_STRING_SIZE) {
942 trace_nbd_negotiate_meta_query_skip("length too long");
943 return nbd_opt_skip(client, len, errp);
946 query = g_malloc(len + 1);
947 ret = nbd_opt_read(client, query, len, true, errp);
948 if (ret <= 0) {
949 return ret;
951 query[len] = '\0';
953 if (nbd_meta_base_query(client, meta, query)) {
954 return 1;
956 if (nbd_meta_qemu_query(client, meta, query)) {
957 return 1;
960 trace_nbd_negotiate_meta_query_skip("unknown namespace");
961 return 1;
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 g_autofree bool *bitmaps = NULL;
974 NBDExportMetaContexts local_meta = {0};
975 uint32_t nb_queries;
976 size_t i;
977 size_t count = 0;
979 if (!client->structured_reply) {
980 return nbd_opt_invalid(client, errp,
981 "request option '%s' when structured reply "
982 "is not negotiated",
983 nbd_opt_lookup(client->opt));
986 if (client->opt == NBD_OPT_LIST_META_CONTEXT) {
987 /* Only change the caller's meta on SET. */
988 meta = &local_meta;
991 g_free(meta->bitmaps);
992 memset(meta, 0, sizeof(*meta));
994 ret = nbd_opt_read_name(client, &export_name, NULL, errp);
995 if (ret <= 0) {
996 return ret;
999 meta->exp = nbd_export_find(export_name);
1000 if (meta->exp == NULL) {
1001 g_autofree char *sane_name = nbd_sanitize_name(export_name);
1003 return nbd_opt_drop(client, NBD_REP_ERR_UNKNOWN, errp,
1004 "export '%s' not present", sane_name);
1006 meta->bitmaps = g_new0(bool, meta->exp->nr_export_bitmaps);
1007 if (client->opt == NBD_OPT_LIST_META_CONTEXT) {
1008 bitmaps = meta->bitmaps;
1011 ret = nbd_opt_read(client, &nb_queries, sizeof(nb_queries), false, errp);
1012 if (ret <= 0) {
1013 return ret;
1015 nb_queries = cpu_to_be32(nb_queries);
1016 trace_nbd_negotiate_meta_context(nbd_opt_lookup(client->opt),
1017 export_name, nb_queries);
1019 if (client->opt == NBD_OPT_LIST_META_CONTEXT && !nb_queries) {
1020 /* enable all known contexts */
1021 meta->base_allocation = true;
1022 meta->allocation_depth = meta->exp->allocation_depth;
1023 memset(meta->bitmaps, 1, meta->exp->nr_export_bitmaps);
1024 } else {
1025 for (i = 0; i < nb_queries; ++i) {
1026 ret = nbd_negotiate_meta_query(client, meta, errp);
1027 if (ret <= 0) {
1028 return ret;
1033 if (meta->base_allocation) {
1034 ret = nbd_negotiate_send_meta_context(client, "base:allocation",
1035 NBD_META_ID_BASE_ALLOCATION,
1036 errp);
1037 if (ret < 0) {
1038 return ret;
1040 count++;
1043 if (meta->allocation_depth) {
1044 ret = nbd_negotiate_send_meta_context(client, "qemu:allocation-depth",
1045 NBD_META_ID_ALLOCATION_DEPTH,
1046 errp);
1047 if (ret < 0) {
1048 return ret;
1050 count++;
1053 for (i = 0; i < meta->exp->nr_export_bitmaps; i++) {
1054 const char *bm_name;
1055 g_autofree char *context = NULL;
1057 if (!meta->bitmaps[i]) {
1058 continue;
1061 bm_name = bdrv_dirty_bitmap_name(meta->exp->export_bitmaps[i]);
1062 context = g_strdup_printf("qemu:dirty-bitmap:%s", bm_name);
1064 ret = nbd_negotiate_send_meta_context(client, context,
1065 NBD_META_ID_DIRTY_BITMAP + i,
1066 errp);
1067 if (ret < 0) {
1068 return ret;
1070 count++;
1073 ret = nbd_negotiate_send_rep(client, NBD_REP_ACK, errp);
1074 if (ret == 0) {
1075 meta->count = count;
1078 return ret;
1081 /* nbd_negotiate_options
1082 * Process all NBD_OPT_* client option commands, during fixed newstyle
1083 * negotiation.
1084 * Return:
1085 * -errno on error, errp is set
1086 * 0 on successful negotiation, errp is not set
1087 * 1 if client sent NBD_OPT_ABORT, i.e. on valid disconnect,
1088 * errp is not set
1090 static int nbd_negotiate_options(NBDClient *client, Error **errp)
1092 uint32_t flags;
1093 bool fixedNewstyle = false;
1094 bool no_zeroes = false;
1096 /* Client sends:
1097 [ 0 .. 3] client flags
1099 Then we loop until NBD_OPT_EXPORT_NAME or NBD_OPT_GO:
1100 [ 0 .. 7] NBD_OPTS_MAGIC
1101 [ 8 .. 11] NBD option
1102 [12 .. 15] Data length
1103 ... Rest of request
1105 [ 0 .. 7] NBD_OPTS_MAGIC
1106 [ 8 .. 11] Second NBD option
1107 [12 .. 15] Data length
1108 ... Rest of request
1111 if (nbd_read32(client->ioc, &flags, "flags", errp) < 0) {
1112 return -EIO;
1114 trace_nbd_negotiate_options_flags(flags);
1115 if (flags & NBD_FLAG_C_FIXED_NEWSTYLE) {
1116 fixedNewstyle = true;
1117 flags &= ~NBD_FLAG_C_FIXED_NEWSTYLE;
1119 if (flags & NBD_FLAG_C_NO_ZEROES) {
1120 no_zeroes = true;
1121 flags &= ~NBD_FLAG_C_NO_ZEROES;
1123 if (flags != 0) {
1124 error_setg(errp, "Unknown client flags 0x%" PRIx32 " received", flags);
1125 return -EINVAL;
1128 while (1) {
1129 int ret;
1130 uint32_t option, length;
1131 uint64_t magic;
1133 if (nbd_read64(client->ioc, &magic, "opts magic", errp) < 0) {
1134 return -EINVAL;
1136 trace_nbd_negotiate_options_check_magic(magic);
1137 if (magic != NBD_OPTS_MAGIC) {
1138 error_setg(errp, "Bad magic received");
1139 return -EINVAL;
1142 if (nbd_read32(client->ioc, &option, "option", errp) < 0) {
1143 return -EINVAL;
1145 client->opt = option;
1147 if (nbd_read32(client->ioc, &length, "option length", errp) < 0) {
1148 return -EINVAL;
1150 assert(!client->optlen);
1151 client->optlen = length;
1153 if (length > NBD_MAX_BUFFER_SIZE) {
1154 error_setg(errp, "len (%" PRIu32" ) is larger than max len (%u)",
1155 length, NBD_MAX_BUFFER_SIZE);
1156 return -EINVAL;
1159 trace_nbd_negotiate_options_check_option(option,
1160 nbd_opt_lookup(option));
1161 if (client->tlscreds &&
1162 client->ioc == (QIOChannel *)client->sioc) {
1163 QIOChannel *tioc;
1164 if (!fixedNewstyle) {
1165 error_setg(errp, "Unsupported option 0x%" PRIx32, option);
1166 return -EINVAL;
1168 switch (option) {
1169 case NBD_OPT_STARTTLS:
1170 if (length) {
1171 /* Unconditionally drop the connection if the client
1172 * can't start a TLS negotiation correctly */
1173 return nbd_reject_length(client, true, errp);
1175 tioc = nbd_negotiate_handle_starttls(client, errp);
1176 if (!tioc) {
1177 return -EIO;
1179 ret = 0;
1180 object_unref(OBJECT(client->ioc));
1181 client->ioc = QIO_CHANNEL(tioc);
1182 break;
1184 case NBD_OPT_EXPORT_NAME:
1185 /* No way to return an error to client, so drop connection */
1186 error_setg(errp, "Option 0x%x not permitted before TLS",
1187 option);
1188 return -EINVAL;
1190 default:
1191 /* Let the client keep trying, unless they asked to
1192 * quit. Always try to give an error back to the
1193 * client; but when replying to OPT_ABORT, be aware
1194 * that the client may hang up before receiving the
1195 * error, in which case we are fine ignoring the
1196 * resulting EPIPE. */
1197 ret = nbd_opt_drop(client, NBD_REP_ERR_TLS_REQD,
1198 option == NBD_OPT_ABORT ? NULL : errp,
1199 "Option 0x%" PRIx32
1200 " not permitted before TLS", option);
1201 if (option == NBD_OPT_ABORT) {
1202 return 1;
1204 break;
1206 } else if (fixedNewstyle) {
1207 switch (option) {
1208 case NBD_OPT_LIST:
1209 if (length) {
1210 ret = nbd_reject_length(client, false, errp);
1211 } else {
1212 ret = nbd_negotiate_handle_list(client, errp);
1214 break;
1216 case NBD_OPT_ABORT:
1217 /* NBD spec says we must try to reply before
1218 * disconnecting, but that we must also tolerate
1219 * guests that don't wait for our reply. */
1220 nbd_negotiate_send_rep(client, NBD_REP_ACK, NULL);
1221 return 1;
1223 case NBD_OPT_EXPORT_NAME:
1224 return nbd_negotiate_handle_export_name(client, no_zeroes,
1225 errp);
1227 case NBD_OPT_INFO:
1228 case NBD_OPT_GO:
1229 ret = nbd_negotiate_handle_info(client, errp);
1230 if (ret == 1) {
1231 assert(option == NBD_OPT_GO);
1232 return 0;
1234 break;
1236 case NBD_OPT_STARTTLS:
1237 if (length) {
1238 ret = nbd_reject_length(client, false, errp);
1239 } else if (client->tlscreds) {
1240 ret = nbd_negotiate_send_rep_err(client,
1241 NBD_REP_ERR_INVALID, errp,
1242 "TLS already enabled");
1243 } else {
1244 ret = nbd_negotiate_send_rep_err(client,
1245 NBD_REP_ERR_POLICY, errp,
1246 "TLS not configured");
1248 break;
1250 case NBD_OPT_STRUCTURED_REPLY:
1251 if (length) {
1252 ret = nbd_reject_length(client, false, errp);
1253 } else if (client->structured_reply) {
1254 ret = nbd_negotiate_send_rep_err(
1255 client, NBD_REP_ERR_INVALID, errp,
1256 "structured reply already negotiated");
1257 } else {
1258 ret = nbd_negotiate_send_rep(client, NBD_REP_ACK, errp);
1259 client->structured_reply = true;
1261 break;
1263 case NBD_OPT_LIST_META_CONTEXT:
1264 case NBD_OPT_SET_META_CONTEXT:
1265 ret = nbd_negotiate_meta_queries(client, &client->export_meta,
1266 errp);
1267 break;
1269 default:
1270 ret = nbd_opt_drop(client, NBD_REP_ERR_UNSUP, errp,
1271 "Unsupported option %" PRIu32 " (%s)",
1272 option, nbd_opt_lookup(option));
1273 break;
1275 } else {
1277 * If broken new-style we should drop the connection
1278 * for anything except NBD_OPT_EXPORT_NAME
1280 switch (option) {
1281 case NBD_OPT_EXPORT_NAME:
1282 return nbd_negotiate_handle_export_name(client, no_zeroes,
1283 errp);
1285 default:
1286 error_setg(errp, "Unsupported option %" PRIu32 " (%s)",
1287 option, nbd_opt_lookup(option));
1288 return -EINVAL;
1291 if (ret < 0) {
1292 return ret;
1297 /* nbd_negotiate
1298 * Return:
1299 * -errno on error, errp is set
1300 * 0 on successful negotiation, errp is not set
1301 * 1 if client sent NBD_OPT_ABORT, i.e. on valid disconnect,
1302 * errp is not set
1304 static coroutine_fn int nbd_negotiate(NBDClient *client, Error **errp)
1306 ERRP_GUARD();
1307 char buf[NBD_OLDSTYLE_NEGOTIATE_SIZE] = "";
1308 int ret;
1310 /* Old style negotiation header, no room for options
1311 [ 0 .. 7] passwd ("NBDMAGIC")
1312 [ 8 .. 15] magic (NBD_CLIENT_MAGIC)
1313 [16 .. 23] size
1314 [24 .. 27] export flags (zero-extended)
1315 [28 .. 151] reserved (0)
1317 New style negotiation header, client can send options
1318 [ 0 .. 7] passwd ("NBDMAGIC")
1319 [ 8 .. 15] magic (NBD_OPTS_MAGIC)
1320 [16 .. 17] server flags (0)
1321 ....options sent, ending in NBD_OPT_EXPORT_NAME or NBD_OPT_GO....
1324 qio_channel_set_blocking(client->ioc, false, NULL);
1326 trace_nbd_negotiate_begin();
1327 memcpy(buf, "NBDMAGIC", 8);
1329 stq_be_p(buf + 8, NBD_OPTS_MAGIC);
1330 stw_be_p(buf + 16, NBD_FLAG_FIXED_NEWSTYLE | NBD_FLAG_NO_ZEROES);
1332 if (nbd_write(client->ioc, buf, 18, errp) < 0) {
1333 error_prepend(errp, "write failed: ");
1334 return -EINVAL;
1336 ret = nbd_negotiate_options(client, errp);
1337 if (ret != 0) {
1338 if (ret < 0) {
1339 error_prepend(errp, "option negotiation failed: ");
1341 return ret;
1344 /* Attach the channel to the same AioContext as the export */
1345 if (client->exp && client->exp->common.ctx) {
1346 qio_channel_attach_aio_context(client->ioc, client->exp->common.ctx);
1349 assert(!client->optlen);
1350 trace_nbd_negotiate_success();
1352 return 0;
1355 static int nbd_receive_request(QIOChannel *ioc, NBDRequest *request,
1356 Error **errp)
1358 uint8_t buf[NBD_REQUEST_SIZE];
1359 uint32_t magic;
1360 int ret;
1362 ret = nbd_read(ioc, buf, sizeof(buf), "request", errp);
1363 if (ret < 0) {
1364 return ret;
1367 /* Request
1368 [ 0 .. 3] magic (NBD_REQUEST_MAGIC)
1369 [ 4 .. 5] flags (NBD_CMD_FLAG_FUA, ...)
1370 [ 6 .. 7] type (NBD_CMD_READ, ...)
1371 [ 8 .. 15] handle
1372 [16 .. 23] from
1373 [24 .. 27] len
1376 magic = ldl_be_p(buf);
1377 request->flags = lduw_be_p(buf + 4);
1378 request->type = lduw_be_p(buf + 6);
1379 request->handle = ldq_be_p(buf + 8);
1380 request->from = ldq_be_p(buf + 16);
1381 request->len = ldl_be_p(buf + 24);
1383 trace_nbd_receive_request(magic, request->flags, request->type,
1384 request->from, request->len);
1386 if (magic != NBD_REQUEST_MAGIC) {
1387 error_setg(errp, "invalid magic (got 0x%" PRIx32 ")", magic);
1388 return -EINVAL;
1390 return 0;
1393 #define MAX_NBD_REQUESTS 16
1395 void nbd_client_get(NBDClient *client)
1397 client->refcount++;
1400 void nbd_client_put(NBDClient *client)
1402 if (--client->refcount == 0) {
1403 /* The last reference should be dropped by client->close,
1404 * which is called by client_close.
1406 assert(client->closing);
1408 qio_channel_detach_aio_context(client->ioc);
1409 object_unref(OBJECT(client->sioc));
1410 object_unref(OBJECT(client->ioc));
1411 if (client->tlscreds) {
1412 object_unref(OBJECT(client->tlscreds));
1414 g_free(client->tlsauthz);
1415 if (client->exp) {
1416 QTAILQ_REMOVE(&client->exp->clients, client, next);
1417 blk_exp_unref(&client->exp->common);
1419 g_free(client->export_meta.bitmaps);
1420 g_free(client);
1424 static void client_close(NBDClient *client, bool negotiated)
1426 if (client->closing) {
1427 return;
1430 client->closing = true;
1432 /* Force requests to finish. They will drop their own references,
1433 * then we'll close the socket and free the NBDClient.
1435 qio_channel_shutdown(client->ioc, QIO_CHANNEL_SHUTDOWN_BOTH,
1436 NULL);
1438 /* Also tell the client, so that they release their reference. */
1439 if (client->close_fn) {
1440 client->close_fn(client, negotiated);
1444 static NBDRequestData *nbd_request_get(NBDClient *client)
1446 NBDRequestData *req;
1448 assert(client->nb_requests <= MAX_NBD_REQUESTS - 1);
1449 client->nb_requests++;
1451 req = g_new0(NBDRequestData, 1);
1452 nbd_client_get(client);
1453 req->client = client;
1454 return req;
1457 static void nbd_request_put(NBDRequestData *req)
1459 NBDClient *client = req->client;
1461 if (req->data) {
1462 qemu_vfree(req->data);
1464 g_free(req);
1466 client->nb_requests--;
1467 nbd_client_receive_next_request(client);
1469 nbd_client_put(client);
1472 static void blk_aio_attached(AioContext *ctx, void *opaque)
1474 NBDExport *exp = opaque;
1475 NBDClient *client;
1477 trace_nbd_blk_aio_attached(exp->name, ctx);
1479 exp->common.ctx = ctx;
1481 QTAILQ_FOREACH(client, &exp->clients, next) {
1482 qio_channel_attach_aio_context(client->ioc, ctx);
1483 if (client->recv_coroutine) {
1484 aio_co_schedule(ctx, client->recv_coroutine);
1486 if (client->send_coroutine) {
1487 aio_co_schedule(ctx, client->send_coroutine);
1492 static void blk_aio_detach(void *opaque)
1494 NBDExport *exp = opaque;
1495 NBDClient *client;
1497 trace_nbd_blk_aio_detach(exp->name, exp->common.ctx);
1499 QTAILQ_FOREACH(client, &exp->clients, next) {
1500 qio_channel_detach_aio_context(client->ioc);
1503 exp->common.ctx = NULL;
1506 static void nbd_eject_notifier(Notifier *n, void *data)
1508 NBDExport *exp = container_of(n, NBDExport, eject_notifier);
1510 blk_exp_request_shutdown(&exp->common);
1513 void nbd_export_set_on_eject_blk(BlockExport *exp, BlockBackend *blk)
1515 NBDExport *nbd_exp = container_of(exp, NBDExport, common);
1516 assert(exp->drv == &blk_exp_nbd);
1517 assert(nbd_exp->eject_notifier_blk == NULL);
1519 blk_ref(blk);
1520 nbd_exp->eject_notifier_blk = blk;
1521 nbd_exp->eject_notifier.notify = nbd_eject_notifier;
1522 blk_add_remove_bs_notifier(blk, &nbd_exp->eject_notifier);
1525 static int nbd_export_create(BlockExport *blk_exp, BlockExportOptions *exp_args,
1526 Error **errp)
1528 NBDExport *exp = container_of(blk_exp, NBDExport, common);
1529 BlockExportOptionsNbd *arg = &exp_args->u.nbd;
1530 BlockBackend *blk = blk_exp->blk;
1531 int64_t size;
1532 uint64_t perm, shared_perm;
1533 bool readonly = !exp_args->writable;
1534 bool shared = !exp_args->writable;
1535 strList *bitmaps;
1536 size_t i;
1537 int ret;
1539 assert(exp_args->type == BLOCK_EXPORT_TYPE_NBD);
1541 if (!nbd_server_is_running()) {
1542 error_setg(errp, "NBD server not running");
1543 return -EINVAL;
1546 if (!arg->has_name) {
1547 arg->name = exp_args->node_name;
1550 if (strlen(arg->name) > NBD_MAX_STRING_SIZE) {
1551 error_setg(errp, "export name '%s' too long", arg->name);
1552 return -EINVAL;
1555 if (arg->description && strlen(arg->description) > NBD_MAX_STRING_SIZE) {
1556 error_setg(errp, "description '%s' too long", arg->description);
1557 return -EINVAL;
1560 if (nbd_export_find(arg->name)) {
1561 error_setg(errp, "NBD server already has export named '%s'", arg->name);
1562 return -EEXIST;
1565 size = blk_getlength(blk);
1566 if (size < 0) {
1567 error_setg_errno(errp, -size,
1568 "Failed to determine the NBD export's length");
1569 return size;
1572 /* Don't allow resize while the NBD server is running, otherwise we don't
1573 * care what happens with the node. */
1574 blk_get_perm(blk, &perm, &shared_perm);
1575 ret = blk_set_perm(blk, perm, shared_perm & ~BLK_PERM_RESIZE, errp);
1576 if (ret < 0) {
1577 return ret;
1580 QTAILQ_INIT(&exp->clients);
1581 exp->name = g_strdup(arg->name);
1582 exp->description = g_strdup(arg->description);
1583 exp->nbdflags = (NBD_FLAG_HAS_FLAGS | NBD_FLAG_SEND_FLUSH |
1584 NBD_FLAG_SEND_FUA | NBD_FLAG_SEND_CACHE);
1585 if (readonly) {
1586 exp->nbdflags |= NBD_FLAG_READ_ONLY;
1587 if (shared) {
1588 exp->nbdflags |= NBD_FLAG_CAN_MULTI_CONN;
1590 } else {
1591 exp->nbdflags |= (NBD_FLAG_SEND_TRIM | NBD_FLAG_SEND_WRITE_ZEROES |
1592 NBD_FLAG_SEND_FAST_ZERO);
1594 exp->size = QEMU_ALIGN_DOWN(size, BDRV_SECTOR_SIZE);
1596 for (bitmaps = arg->bitmaps; bitmaps; bitmaps = bitmaps->next) {
1597 exp->nr_export_bitmaps++;
1599 exp->export_bitmaps = g_new0(BdrvDirtyBitmap *, exp->nr_export_bitmaps);
1600 for (i = 0, bitmaps = arg->bitmaps; bitmaps;
1601 i++, bitmaps = bitmaps->next) {
1602 const char *bitmap = bitmaps->value;
1603 BlockDriverState *bs = blk_bs(blk);
1604 BdrvDirtyBitmap *bm = NULL;
1606 while (bs) {
1607 bm = bdrv_find_dirty_bitmap(bs, bitmap);
1608 if (bm != NULL) {
1609 break;
1612 bs = bdrv_filter_or_cow_bs(bs);
1615 if (bm == NULL) {
1616 ret = -ENOENT;
1617 error_setg(errp, "Bitmap '%s' is not found", bitmap);
1618 goto fail;
1621 if (bdrv_dirty_bitmap_check(bm, BDRV_BITMAP_ALLOW_RO, errp)) {
1622 ret = -EINVAL;
1623 goto fail;
1626 if (readonly && bdrv_is_writable(bs) &&
1627 bdrv_dirty_bitmap_enabled(bm)) {
1628 ret = -EINVAL;
1629 error_setg(errp,
1630 "Enabled bitmap '%s' incompatible with readonly export",
1631 bitmap);
1632 goto fail;
1635 exp->export_bitmaps[i] = bm;
1636 assert(strlen(bitmap) <= BDRV_BITMAP_MAX_NAME_SIZE);
1639 /* Mark bitmaps busy in a separate loop, to simplify roll-back concerns. */
1640 for (i = 0; i < exp->nr_export_bitmaps; i++) {
1641 bdrv_dirty_bitmap_set_busy(exp->export_bitmaps[i], true);
1644 exp->allocation_depth = arg->allocation_depth;
1646 blk_add_aio_context_notifier(blk, blk_aio_attached, blk_aio_detach, exp);
1648 QTAILQ_INSERT_TAIL(&exports, exp, next);
1650 return 0;
1652 fail:
1653 g_free(exp->export_bitmaps);
1654 g_free(exp->name);
1655 g_free(exp->description);
1656 return ret;
1659 NBDExport *nbd_export_find(const char *name)
1661 NBDExport *exp;
1662 QTAILQ_FOREACH(exp, &exports, next) {
1663 if (strcmp(name, exp->name) == 0) {
1664 return exp;
1668 return NULL;
1671 AioContext *
1672 nbd_export_aio_context(NBDExport *exp)
1674 return exp->common.ctx;
1677 static void nbd_export_request_shutdown(BlockExport *blk_exp)
1679 NBDExport *exp = container_of(blk_exp, NBDExport, common);
1680 NBDClient *client, *next;
1682 blk_exp_ref(&exp->common);
1684 * TODO: Should we expand QMP NbdServerRemoveNode enum to allow a
1685 * close mode that stops advertising the export to new clients but
1686 * still permits existing clients to run to completion? Because of
1687 * that possibility, nbd_export_close() can be called more than
1688 * once on an export.
1690 QTAILQ_FOREACH_SAFE(client, &exp->clients, next, next) {
1691 client_close(client, true);
1693 if (exp->name) {
1694 g_free(exp->name);
1695 exp->name = NULL;
1696 QTAILQ_REMOVE(&exports, exp, next);
1698 blk_exp_unref(&exp->common);
1701 static void nbd_export_delete(BlockExport *blk_exp)
1703 size_t i;
1704 NBDExport *exp = container_of(blk_exp, NBDExport, common);
1706 assert(exp->name == NULL);
1707 assert(QTAILQ_EMPTY(&exp->clients));
1709 g_free(exp->description);
1710 exp->description = NULL;
1712 if (exp->common.blk) {
1713 if (exp->eject_notifier_blk) {
1714 notifier_remove(&exp->eject_notifier);
1715 blk_unref(exp->eject_notifier_blk);
1717 blk_remove_aio_context_notifier(exp->common.blk, blk_aio_attached,
1718 blk_aio_detach, exp);
1721 for (i = 0; i < exp->nr_export_bitmaps; i++) {
1722 bdrv_dirty_bitmap_set_busy(exp->export_bitmaps[i], false);
1726 const BlockExportDriver blk_exp_nbd = {
1727 .type = BLOCK_EXPORT_TYPE_NBD,
1728 .instance_size = sizeof(NBDExport),
1729 .create = nbd_export_create,
1730 .delete = nbd_export_delete,
1731 .request_shutdown = nbd_export_request_shutdown,
1734 static int coroutine_fn nbd_co_send_iov(NBDClient *client, struct iovec *iov,
1735 unsigned niov, Error **errp)
1737 int ret;
1739 g_assert(qemu_in_coroutine());
1740 qemu_co_mutex_lock(&client->send_lock);
1741 client->send_coroutine = qemu_coroutine_self();
1743 ret = qio_channel_writev_all(client->ioc, iov, niov, errp) < 0 ? -EIO : 0;
1745 client->send_coroutine = NULL;
1746 qemu_co_mutex_unlock(&client->send_lock);
1748 return ret;
1751 static inline void set_be_simple_reply(NBDSimpleReply *reply, uint64_t error,
1752 uint64_t handle)
1754 stl_be_p(&reply->magic, NBD_SIMPLE_REPLY_MAGIC);
1755 stl_be_p(&reply->error, error);
1756 stq_be_p(&reply->handle, handle);
1759 static int nbd_co_send_simple_reply(NBDClient *client,
1760 uint64_t handle,
1761 uint32_t error,
1762 void *data,
1763 size_t len,
1764 Error **errp)
1766 NBDSimpleReply reply;
1767 int nbd_err = system_errno_to_nbd_errno(error);
1768 struct iovec iov[] = {
1769 {.iov_base = &reply, .iov_len = sizeof(reply)},
1770 {.iov_base = data, .iov_len = len}
1773 trace_nbd_co_send_simple_reply(handle, nbd_err, nbd_err_lookup(nbd_err),
1774 len);
1775 set_be_simple_reply(&reply, nbd_err, handle);
1777 return nbd_co_send_iov(client, iov, len ? 2 : 1, errp);
1780 static inline void set_be_chunk(NBDStructuredReplyChunk *chunk, uint16_t flags,
1781 uint16_t type, uint64_t handle, uint32_t length)
1783 stl_be_p(&chunk->magic, NBD_STRUCTURED_REPLY_MAGIC);
1784 stw_be_p(&chunk->flags, flags);
1785 stw_be_p(&chunk->type, type);
1786 stq_be_p(&chunk->handle, handle);
1787 stl_be_p(&chunk->length, length);
1790 static int coroutine_fn nbd_co_send_structured_done(NBDClient *client,
1791 uint64_t handle,
1792 Error **errp)
1794 NBDStructuredReplyChunk chunk;
1795 struct iovec iov[] = {
1796 {.iov_base = &chunk, .iov_len = sizeof(chunk)},
1799 trace_nbd_co_send_structured_done(handle);
1800 set_be_chunk(&chunk, NBD_REPLY_FLAG_DONE, NBD_REPLY_TYPE_NONE, handle, 0);
1802 return nbd_co_send_iov(client, iov, 1, errp);
1805 static int coroutine_fn nbd_co_send_structured_read(NBDClient *client,
1806 uint64_t handle,
1807 uint64_t offset,
1808 void *data,
1809 size_t size,
1810 bool final,
1811 Error **errp)
1813 NBDStructuredReadData chunk;
1814 struct iovec iov[] = {
1815 {.iov_base = &chunk, .iov_len = sizeof(chunk)},
1816 {.iov_base = data, .iov_len = size}
1819 assert(size);
1820 trace_nbd_co_send_structured_read(handle, offset, data, size);
1821 set_be_chunk(&chunk.h, final ? NBD_REPLY_FLAG_DONE : 0,
1822 NBD_REPLY_TYPE_OFFSET_DATA, handle,
1823 sizeof(chunk) - sizeof(chunk.h) + size);
1824 stq_be_p(&chunk.offset, offset);
1826 return nbd_co_send_iov(client, iov, 2, errp);
1829 static int coroutine_fn nbd_co_send_structured_error(NBDClient *client,
1830 uint64_t handle,
1831 uint32_t error,
1832 const char *msg,
1833 Error **errp)
1835 NBDStructuredError chunk;
1836 int nbd_err = system_errno_to_nbd_errno(error);
1837 struct iovec iov[] = {
1838 {.iov_base = &chunk, .iov_len = sizeof(chunk)},
1839 {.iov_base = (char *)msg, .iov_len = msg ? strlen(msg) : 0},
1842 assert(nbd_err);
1843 trace_nbd_co_send_structured_error(handle, nbd_err,
1844 nbd_err_lookup(nbd_err), msg ? msg : "");
1845 set_be_chunk(&chunk.h, NBD_REPLY_FLAG_DONE, NBD_REPLY_TYPE_ERROR, handle,
1846 sizeof(chunk) - sizeof(chunk.h) + iov[1].iov_len);
1847 stl_be_p(&chunk.error, nbd_err);
1848 stw_be_p(&chunk.message_length, iov[1].iov_len);
1850 return nbd_co_send_iov(client, iov, 1 + !!iov[1].iov_len, errp);
1853 /* Do a sparse read and send the structured reply to the client.
1854 * Returns -errno if sending fails. bdrv_block_status_above() failure is
1855 * reported to the client, at which point this function succeeds.
1857 static int coroutine_fn nbd_co_send_sparse_read(NBDClient *client,
1858 uint64_t handle,
1859 uint64_t offset,
1860 uint8_t *data,
1861 size_t size,
1862 Error **errp)
1864 int ret = 0;
1865 NBDExport *exp = client->exp;
1866 size_t progress = 0;
1868 while (progress < size) {
1869 int64_t pnum;
1870 int status = bdrv_block_status_above(blk_bs(exp->common.blk), NULL,
1871 offset + progress,
1872 size - progress, &pnum, NULL,
1873 NULL);
1874 bool final;
1876 if (status < 0) {
1877 char *msg = g_strdup_printf("unable to check for holes: %s",
1878 strerror(-status));
1880 ret = nbd_co_send_structured_error(client, handle, -status, msg,
1881 errp);
1882 g_free(msg);
1883 return ret;
1885 assert(pnum && pnum <= size - progress);
1886 final = progress + pnum == size;
1887 if (status & BDRV_BLOCK_ZERO) {
1888 NBDStructuredReadHole chunk;
1889 struct iovec iov[] = {
1890 {.iov_base = &chunk, .iov_len = sizeof(chunk)},
1893 trace_nbd_co_send_structured_read_hole(handle, offset + progress,
1894 pnum);
1895 set_be_chunk(&chunk.h, final ? NBD_REPLY_FLAG_DONE : 0,
1896 NBD_REPLY_TYPE_OFFSET_HOLE,
1897 handle, sizeof(chunk) - sizeof(chunk.h));
1898 stq_be_p(&chunk.offset, offset + progress);
1899 stl_be_p(&chunk.length, pnum);
1900 ret = nbd_co_send_iov(client, iov, 1, errp);
1901 } else {
1902 ret = blk_pread(exp->common.blk, offset + progress,
1903 data + progress, pnum);
1904 if (ret < 0) {
1905 error_setg_errno(errp, -ret, "reading from file failed");
1906 break;
1908 ret = nbd_co_send_structured_read(client, handle, offset + progress,
1909 data + progress, pnum, final,
1910 errp);
1913 if (ret < 0) {
1914 break;
1916 progress += pnum;
1918 return ret;
1921 typedef struct NBDExtentArray {
1922 NBDExtent *extents;
1923 unsigned int nb_alloc;
1924 unsigned int count;
1925 uint64_t total_length;
1926 bool can_add;
1927 bool converted_to_be;
1928 } NBDExtentArray;
1930 static NBDExtentArray *nbd_extent_array_new(unsigned int nb_alloc)
1932 NBDExtentArray *ea = g_new0(NBDExtentArray, 1);
1934 ea->nb_alloc = nb_alloc;
1935 ea->extents = g_new(NBDExtent, nb_alloc);
1936 ea->can_add = true;
1938 return ea;
1941 static void nbd_extent_array_free(NBDExtentArray *ea)
1943 g_free(ea->extents);
1944 g_free(ea);
1946 G_DEFINE_AUTOPTR_CLEANUP_FUNC(NBDExtentArray, nbd_extent_array_free);
1948 /* Further modifications of the array after conversion are abandoned */
1949 static void nbd_extent_array_convert_to_be(NBDExtentArray *ea)
1951 int i;
1953 assert(!ea->converted_to_be);
1954 ea->can_add = false;
1955 ea->converted_to_be = true;
1957 for (i = 0; i < ea->count; i++) {
1958 ea->extents[i].flags = cpu_to_be32(ea->extents[i].flags);
1959 ea->extents[i].length = cpu_to_be32(ea->extents[i].length);
1964 * Add extent to NBDExtentArray. If extent can't be added (no available space),
1965 * return -1.
1966 * For safety, when returning -1 for the first time, .can_add is set to false,
1967 * further call to nbd_extent_array_add() will crash.
1968 * (to avoid the situation, when after failing to add an extent (returned -1),
1969 * user miss this failure and add another extent, which is successfully added
1970 * (array is full, but new extent may be squashed into the last one), then we
1971 * have invalid array with skipped extent)
1973 static int nbd_extent_array_add(NBDExtentArray *ea,
1974 uint32_t length, uint32_t flags)
1976 assert(ea->can_add);
1978 if (!length) {
1979 return 0;
1982 /* Extend previous extent if flags are the same */
1983 if (ea->count > 0 && flags == ea->extents[ea->count - 1].flags) {
1984 uint64_t sum = (uint64_t)length + ea->extents[ea->count - 1].length;
1986 if (sum <= UINT32_MAX) {
1987 ea->extents[ea->count - 1].length = sum;
1988 ea->total_length += length;
1989 return 0;
1993 if (ea->count >= ea->nb_alloc) {
1994 ea->can_add = false;
1995 return -1;
1998 ea->total_length += length;
1999 ea->extents[ea->count] = (NBDExtent) {.length = length, .flags = flags};
2000 ea->count++;
2002 return 0;
2005 static int blockstatus_to_extents(BlockDriverState *bs, uint64_t offset,
2006 uint64_t bytes, NBDExtentArray *ea)
2008 while (bytes) {
2009 uint32_t flags;
2010 int64_t num;
2011 int ret = bdrv_block_status_above(bs, NULL, offset, bytes, &num,
2012 NULL, NULL);
2014 if (ret < 0) {
2015 return ret;
2018 flags = (ret & BDRV_BLOCK_ALLOCATED ? 0 : NBD_STATE_HOLE) |
2019 (ret & BDRV_BLOCK_ZERO ? NBD_STATE_ZERO : 0);
2021 if (nbd_extent_array_add(ea, num, flags) < 0) {
2022 return 0;
2025 offset += num;
2026 bytes -= num;
2029 return 0;
2032 static int blockalloc_to_extents(BlockDriverState *bs, uint64_t offset,
2033 uint64_t bytes, NBDExtentArray *ea)
2035 while (bytes) {
2036 int64_t num;
2037 int ret = bdrv_is_allocated_above(bs, NULL, false, offset, bytes,
2038 &num);
2040 if (ret < 0) {
2041 return ret;
2044 if (nbd_extent_array_add(ea, num, ret) < 0) {
2045 return 0;
2048 offset += num;
2049 bytes -= num;
2052 return 0;
2056 * nbd_co_send_extents
2058 * @ea is converted to BE by the function
2059 * @last controls whether NBD_REPLY_FLAG_DONE is sent.
2061 static int nbd_co_send_extents(NBDClient *client, uint64_t handle,
2062 NBDExtentArray *ea,
2063 bool last, uint32_t context_id, Error **errp)
2065 NBDStructuredMeta chunk;
2066 struct iovec iov[] = {
2067 {.iov_base = &chunk, .iov_len = sizeof(chunk)},
2068 {.iov_base = ea->extents, .iov_len = ea->count * sizeof(ea->extents[0])}
2071 nbd_extent_array_convert_to_be(ea);
2073 trace_nbd_co_send_extents(handle, ea->count, context_id, ea->total_length,
2074 last);
2075 set_be_chunk(&chunk.h, last ? NBD_REPLY_FLAG_DONE : 0,
2076 NBD_REPLY_TYPE_BLOCK_STATUS,
2077 handle, sizeof(chunk) - sizeof(chunk.h) + iov[1].iov_len);
2078 stl_be_p(&chunk.context_id, context_id);
2080 return nbd_co_send_iov(client, iov, 2, errp);
2083 /* Get block status from the exported device and send it to the client */
2084 static int nbd_co_send_block_status(NBDClient *client, uint64_t handle,
2085 BlockDriverState *bs, uint64_t offset,
2086 uint32_t length, bool dont_fragment,
2087 bool last, uint32_t context_id,
2088 Error **errp)
2090 int ret;
2091 unsigned int nb_extents = dont_fragment ? 1 : NBD_MAX_BLOCK_STATUS_EXTENTS;
2092 g_autoptr(NBDExtentArray) ea = nbd_extent_array_new(nb_extents);
2094 if (context_id == NBD_META_ID_BASE_ALLOCATION) {
2095 ret = blockstatus_to_extents(bs, offset, length, ea);
2096 } else {
2097 ret = blockalloc_to_extents(bs, offset, length, ea);
2099 if (ret < 0) {
2100 return nbd_co_send_structured_error(
2101 client, handle, -ret, "can't get block status", errp);
2104 return nbd_co_send_extents(client, handle, ea, last, context_id, errp);
2107 /* Populate @ea from a dirty bitmap. */
2108 static void bitmap_to_extents(BdrvDirtyBitmap *bitmap,
2109 uint64_t offset, uint64_t length,
2110 NBDExtentArray *es)
2112 int64_t start, dirty_start, dirty_count;
2113 int64_t end = offset + length;
2114 bool full = false;
2116 bdrv_dirty_bitmap_lock(bitmap);
2118 for (start = offset;
2119 bdrv_dirty_bitmap_next_dirty_area(bitmap, start, end, INT32_MAX,
2120 &dirty_start, &dirty_count);
2121 start = dirty_start + dirty_count)
2123 if ((nbd_extent_array_add(es, dirty_start - start, 0) < 0) ||
2124 (nbd_extent_array_add(es, dirty_count, NBD_STATE_DIRTY) < 0))
2126 full = true;
2127 break;
2131 if (!full) {
2132 /* last non dirty extent */
2133 nbd_extent_array_add(es, end - start, 0);
2136 bdrv_dirty_bitmap_unlock(bitmap);
2139 static int nbd_co_send_bitmap(NBDClient *client, uint64_t handle,
2140 BdrvDirtyBitmap *bitmap, uint64_t offset,
2141 uint32_t length, bool dont_fragment, bool last,
2142 uint32_t context_id, Error **errp)
2144 unsigned int nb_extents = dont_fragment ? 1 : NBD_MAX_BLOCK_STATUS_EXTENTS;
2145 g_autoptr(NBDExtentArray) ea = nbd_extent_array_new(nb_extents);
2147 bitmap_to_extents(bitmap, offset, length, ea);
2149 return nbd_co_send_extents(client, handle, ea, last, context_id, errp);
2152 /* nbd_co_receive_request
2153 * Collect a client request. Return 0 if request looks valid, -EIO to drop
2154 * connection right away, and any other negative value to report an error to
2155 * the client (although the caller may still need to disconnect after reporting
2156 * the error).
2158 static int nbd_co_receive_request(NBDRequestData *req, NBDRequest *request,
2159 Error **errp)
2161 NBDClient *client = req->client;
2162 int valid_flags;
2164 g_assert(qemu_in_coroutine());
2165 assert(client->recv_coroutine == qemu_coroutine_self());
2166 if (nbd_receive_request(client->ioc, request, errp) < 0) {
2167 return -EIO;
2170 trace_nbd_co_receive_request_decode_type(request->handle, request->type,
2171 nbd_cmd_lookup(request->type));
2173 if (request->type != NBD_CMD_WRITE) {
2174 /* No payload, we are ready to read the next request. */
2175 req->complete = true;
2178 if (request->type == NBD_CMD_DISC) {
2179 /* Special case: we're going to disconnect without a reply,
2180 * whether or not flags, from, or len are bogus */
2181 return -EIO;
2184 if (request->type == NBD_CMD_READ || request->type == NBD_CMD_WRITE ||
2185 request->type == NBD_CMD_CACHE)
2187 if (request->len > NBD_MAX_BUFFER_SIZE) {
2188 error_setg(errp, "len (%" PRIu32" ) is larger than max len (%u)",
2189 request->len, NBD_MAX_BUFFER_SIZE);
2190 return -EINVAL;
2193 if (request->type != NBD_CMD_CACHE) {
2194 req->data = blk_try_blockalign(client->exp->common.blk,
2195 request->len);
2196 if (req->data == NULL) {
2197 error_setg(errp, "No memory");
2198 return -ENOMEM;
2203 if (request->type == NBD_CMD_WRITE) {
2204 if (nbd_read(client->ioc, req->data, request->len, "CMD_WRITE data",
2205 errp) < 0)
2207 return -EIO;
2209 req->complete = true;
2211 trace_nbd_co_receive_request_payload_received(request->handle,
2212 request->len);
2215 /* Sanity checks. */
2216 if (client->exp->nbdflags & NBD_FLAG_READ_ONLY &&
2217 (request->type == NBD_CMD_WRITE ||
2218 request->type == NBD_CMD_WRITE_ZEROES ||
2219 request->type == NBD_CMD_TRIM)) {
2220 error_setg(errp, "Export is read-only");
2221 return -EROFS;
2223 if (request->from > client->exp->size ||
2224 request->len > client->exp->size - request->from) {
2225 error_setg(errp, "operation past EOF; From: %" PRIu64 ", Len: %" PRIu32
2226 ", Size: %" PRIu64, request->from, request->len,
2227 client->exp->size);
2228 return (request->type == NBD_CMD_WRITE ||
2229 request->type == NBD_CMD_WRITE_ZEROES) ? -ENOSPC : -EINVAL;
2231 if (client->check_align && !QEMU_IS_ALIGNED(request->from | request->len,
2232 client->check_align)) {
2234 * The block layer gracefully handles unaligned requests, but
2235 * it's still worth tracing client non-compliance
2237 trace_nbd_co_receive_align_compliance(nbd_cmd_lookup(request->type),
2238 request->from,
2239 request->len,
2240 client->check_align);
2242 valid_flags = NBD_CMD_FLAG_FUA;
2243 if (request->type == NBD_CMD_READ && client->structured_reply) {
2244 valid_flags |= NBD_CMD_FLAG_DF;
2245 } else if (request->type == NBD_CMD_WRITE_ZEROES) {
2246 valid_flags |= NBD_CMD_FLAG_NO_HOLE | NBD_CMD_FLAG_FAST_ZERO;
2247 } else if (request->type == NBD_CMD_BLOCK_STATUS) {
2248 valid_flags |= NBD_CMD_FLAG_REQ_ONE;
2250 if (request->flags & ~valid_flags) {
2251 error_setg(errp, "unsupported flags for command %s (got 0x%x)",
2252 nbd_cmd_lookup(request->type), request->flags);
2253 return -EINVAL;
2256 return 0;
2259 /* Send simple reply without a payload, or a structured error
2260 * @error_msg is ignored if @ret >= 0
2261 * Returns 0 if connection is still live, -errno on failure to talk to client
2263 static coroutine_fn int nbd_send_generic_reply(NBDClient *client,
2264 uint64_t handle,
2265 int ret,
2266 const char *error_msg,
2267 Error **errp)
2269 if (client->structured_reply && ret < 0) {
2270 return nbd_co_send_structured_error(client, handle, -ret, error_msg,
2271 errp);
2272 } else {
2273 return nbd_co_send_simple_reply(client, handle, ret < 0 ? -ret : 0,
2274 NULL, 0, errp);
2278 /* Handle NBD_CMD_READ request.
2279 * Return -errno if sending fails. Other errors are reported directly to the
2280 * client as an error reply. */
2281 static coroutine_fn int nbd_do_cmd_read(NBDClient *client, NBDRequest *request,
2282 uint8_t *data, Error **errp)
2284 int ret;
2285 NBDExport *exp = client->exp;
2287 assert(request->type == NBD_CMD_READ);
2289 /* XXX: NBD Protocol only documents use of FUA with WRITE */
2290 if (request->flags & NBD_CMD_FLAG_FUA) {
2291 ret = blk_co_flush(exp->common.blk);
2292 if (ret < 0) {
2293 return nbd_send_generic_reply(client, request->handle, ret,
2294 "flush failed", errp);
2298 if (client->structured_reply && !(request->flags & NBD_CMD_FLAG_DF) &&
2299 request->len)
2301 return nbd_co_send_sparse_read(client, request->handle, request->from,
2302 data, request->len, errp);
2305 ret = blk_pread(exp->common.blk, request->from, data, request->len);
2306 if (ret < 0) {
2307 return nbd_send_generic_reply(client, request->handle, ret,
2308 "reading from file failed", errp);
2311 if (client->structured_reply) {
2312 if (request->len) {
2313 return nbd_co_send_structured_read(client, request->handle,
2314 request->from, data,
2315 request->len, true, errp);
2316 } else {
2317 return nbd_co_send_structured_done(client, request->handle, errp);
2319 } else {
2320 return nbd_co_send_simple_reply(client, request->handle, 0,
2321 data, request->len, errp);
2326 * nbd_do_cmd_cache
2328 * Handle NBD_CMD_CACHE request.
2329 * Return -errno if sending fails. Other errors are reported directly to the
2330 * client as an error reply.
2332 static coroutine_fn int nbd_do_cmd_cache(NBDClient *client, NBDRequest *request,
2333 Error **errp)
2335 int ret;
2336 NBDExport *exp = client->exp;
2338 assert(request->type == NBD_CMD_CACHE);
2340 ret = blk_co_preadv(exp->common.blk, request->from, request->len,
2341 NULL, BDRV_REQ_COPY_ON_READ | BDRV_REQ_PREFETCH);
2343 return nbd_send_generic_reply(client, request->handle, ret,
2344 "caching data failed", errp);
2347 /* Handle NBD request.
2348 * Return -errno if sending fails. Other errors are reported directly to the
2349 * client as an error reply. */
2350 static coroutine_fn int nbd_handle_request(NBDClient *client,
2351 NBDRequest *request,
2352 uint8_t *data, Error **errp)
2354 int ret;
2355 int flags;
2356 NBDExport *exp = client->exp;
2357 char *msg;
2358 size_t i;
2360 switch (request->type) {
2361 case NBD_CMD_CACHE:
2362 return nbd_do_cmd_cache(client, request, errp);
2364 case NBD_CMD_READ:
2365 return nbd_do_cmd_read(client, request, data, errp);
2367 case NBD_CMD_WRITE:
2368 flags = 0;
2369 if (request->flags & NBD_CMD_FLAG_FUA) {
2370 flags |= BDRV_REQ_FUA;
2372 ret = blk_pwrite(exp->common.blk, request->from, data, request->len,
2373 flags);
2374 return nbd_send_generic_reply(client, request->handle, ret,
2375 "writing to file failed", errp);
2377 case NBD_CMD_WRITE_ZEROES:
2378 flags = 0;
2379 if (request->flags & NBD_CMD_FLAG_FUA) {
2380 flags |= BDRV_REQ_FUA;
2382 if (!(request->flags & NBD_CMD_FLAG_NO_HOLE)) {
2383 flags |= BDRV_REQ_MAY_UNMAP;
2385 if (request->flags & NBD_CMD_FLAG_FAST_ZERO) {
2386 flags |= BDRV_REQ_NO_FALLBACK;
2388 ret = 0;
2389 /* FIXME simplify this when blk_pwrite_zeroes switches to 64-bit */
2390 while (ret >= 0 && request->len) {
2391 int align = client->check_align ?: 1;
2392 int len = MIN(request->len, QEMU_ALIGN_DOWN(BDRV_REQUEST_MAX_BYTES,
2393 align));
2394 ret = blk_pwrite_zeroes(exp->common.blk, request->from, len, flags);
2395 request->len -= len;
2396 request->from += len;
2398 return nbd_send_generic_reply(client, request->handle, ret,
2399 "writing to file failed", errp);
2401 case NBD_CMD_DISC:
2402 /* unreachable, thanks to special case in nbd_co_receive_request() */
2403 abort();
2405 case NBD_CMD_FLUSH:
2406 ret = blk_co_flush(exp->common.blk);
2407 return nbd_send_generic_reply(client, request->handle, ret,
2408 "flush failed", errp);
2410 case NBD_CMD_TRIM:
2411 ret = 0;
2412 /* FIXME simplify this when blk_co_pdiscard switches to 64-bit */
2413 while (ret >= 0 && request->len) {
2414 int align = client->check_align ?: 1;
2415 int len = MIN(request->len, QEMU_ALIGN_DOWN(BDRV_REQUEST_MAX_BYTES,
2416 align));
2417 ret = blk_co_pdiscard(exp->common.blk, request->from, len);
2418 request->len -= len;
2419 request->from += len;
2421 if (ret >= 0 && request->flags & NBD_CMD_FLAG_FUA) {
2422 ret = blk_co_flush(exp->common.blk);
2424 return nbd_send_generic_reply(client, request->handle, ret,
2425 "discard failed", errp);
2427 case NBD_CMD_BLOCK_STATUS:
2428 if (!request->len) {
2429 return nbd_send_generic_reply(client, request->handle, -EINVAL,
2430 "need non-zero length", errp);
2432 if (client->export_meta.count) {
2433 bool dont_fragment = request->flags & NBD_CMD_FLAG_REQ_ONE;
2434 int contexts_remaining = client->export_meta.count;
2436 if (client->export_meta.base_allocation) {
2437 ret = nbd_co_send_block_status(client, request->handle,
2438 blk_bs(exp->common.blk),
2439 request->from,
2440 request->len, dont_fragment,
2441 !--contexts_remaining,
2442 NBD_META_ID_BASE_ALLOCATION,
2443 errp);
2444 if (ret < 0) {
2445 return ret;
2449 if (client->export_meta.allocation_depth) {
2450 ret = nbd_co_send_block_status(client, request->handle,
2451 blk_bs(exp->common.blk),
2452 request->from, request->len,
2453 dont_fragment,
2454 !--contexts_remaining,
2455 NBD_META_ID_ALLOCATION_DEPTH,
2456 errp);
2457 if (ret < 0) {
2458 return ret;
2462 for (i = 0; i < client->exp->nr_export_bitmaps; i++) {
2463 if (!client->export_meta.bitmaps[i]) {
2464 continue;
2466 ret = nbd_co_send_bitmap(client, request->handle,
2467 client->exp->export_bitmaps[i],
2468 request->from, request->len,
2469 dont_fragment, !--contexts_remaining,
2470 NBD_META_ID_DIRTY_BITMAP + i, errp);
2471 if (ret < 0) {
2472 return ret;
2476 assert(!contexts_remaining);
2478 return 0;
2479 } else {
2480 return nbd_send_generic_reply(client, request->handle, -EINVAL,
2481 "CMD_BLOCK_STATUS not negotiated",
2482 errp);
2485 default:
2486 msg = g_strdup_printf("invalid request type (%" PRIu32 ") received",
2487 request->type);
2488 ret = nbd_send_generic_reply(client, request->handle, -EINVAL, msg,
2489 errp);
2490 g_free(msg);
2491 return ret;
2495 /* Owns a reference to the NBDClient passed as opaque. */
2496 static coroutine_fn void nbd_trip(void *opaque)
2498 NBDClient *client = opaque;
2499 NBDRequestData *req;
2500 NBDRequest request = { 0 }; /* GCC thinks it can be used uninitialized */
2501 int ret;
2502 Error *local_err = NULL;
2504 trace_nbd_trip();
2505 if (client->closing) {
2506 nbd_client_put(client);
2507 return;
2510 req = nbd_request_get(client);
2511 ret = nbd_co_receive_request(req, &request, &local_err);
2512 client->recv_coroutine = NULL;
2514 if (client->closing) {
2516 * The client may be closed when we are blocked in
2517 * nbd_co_receive_request()
2519 goto done;
2522 nbd_client_receive_next_request(client);
2523 if (ret == -EIO) {
2524 goto disconnect;
2527 if (ret < 0) {
2528 /* It wans't -EIO, so, according to nbd_co_receive_request()
2529 * semantics, we should return the error to the client. */
2530 Error *export_err = local_err;
2532 local_err = NULL;
2533 ret = nbd_send_generic_reply(client, request.handle, -EINVAL,
2534 error_get_pretty(export_err), &local_err);
2535 error_free(export_err);
2536 } else {
2537 ret = nbd_handle_request(client, &request, req->data, &local_err);
2539 if (ret < 0) {
2540 error_prepend(&local_err, "Failed to send reply: ");
2541 goto disconnect;
2544 /* We must disconnect after NBD_CMD_WRITE if we did not
2545 * read the payload.
2547 if (!req->complete) {
2548 error_setg(&local_err, "Request handling failed in intermediate state");
2549 goto disconnect;
2552 done:
2553 nbd_request_put(req);
2554 nbd_client_put(client);
2555 return;
2557 disconnect:
2558 if (local_err) {
2559 error_reportf_err(local_err, "Disconnect client, due to: ");
2561 nbd_request_put(req);
2562 client_close(client, true);
2563 nbd_client_put(client);
2566 static void nbd_client_receive_next_request(NBDClient *client)
2568 if (!client->recv_coroutine && client->nb_requests < MAX_NBD_REQUESTS) {
2569 nbd_client_get(client);
2570 client->recv_coroutine = qemu_coroutine_create(nbd_trip, client);
2571 aio_co_schedule(client->exp->common.ctx, client->recv_coroutine);
2575 static coroutine_fn void nbd_co_client_start(void *opaque)
2577 NBDClient *client = opaque;
2578 Error *local_err = NULL;
2580 qemu_co_mutex_init(&client->send_lock);
2582 if (nbd_negotiate(client, &local_err)) {
2583 if (local_err) {
2584 error_report_err(local_err);
2586 client_close(client, false);
2587 return;
2590 nbd_client_receive_next_request(client);
2594 * Create a new client listener using the given channel @sioc.
2595 * Begin servicing it in a coroutine. When the connection closes, call
2596 * @close_fn with an indication of whether the client completed negotiation.
2598 void nbd_client_new(QIOChannelSocket *sioc,
2599 QCryptoTLSCreds *tlscreds,
2600 const char *tlsauthz,
2601 void (*close_fn)(NBDClient *, bool))
2603 NBDClient *client;
2604 Coroutine *co;
2606 client = g_new0(NBDClient, 1);
2607 client->refcount = 1;
2608 client->tlscreds = tlscreds;
2609 if (tlscreds) {
2610 object_ref(OBJECT(client->tlscreds));
2612 client->tlsauthz = g_strdup(tlsauthz);
2613 client->sioc = sioc;
2614 object_ref(OBJECT(client->sioc));
2615 client->ioc = QIO_CHANNEL(sioc);
2616 object_ref(OBJECT(client->ioc));
2617 client->close_fn = close_fn;
2619 co = qemu_coroutine_create(nbd_co_client_start, client);
2620 qemu_coroutine_enter(co);