tests/vm: move images to $HOME/.cache/qemu-vm/images
[qemu/ericb.git] / nbd / server.c
blob838c150d8ca3abb53ceee52f84b23817608d2859
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 "trace.h"
23 #include "nbd-internal.h"
25 #define NBD_META_ID_BASE_ALLOCATION 0
26 #define NBD_META_ID_DIRTY_BITMAP 1
28 /* NBD_MAX_BITMAP_EXTENTS: 1 mb of extents data. An empirical
29 * constant. If an increase is needed, note that the NBD protocol
30 * recommends no larger than 32 mb, so that the client won't consider
31 * the reply as a denial of service attack. */
32 #define NBD_MAX_BITMAP_EXTENTS (0x100000 / 8)
34 static int system_errno_to_nbd_errno(int err)
36 switch (err) {
37 case 0:
38 return NBD_SUCCESS;
39 case EPERM:
40 case EROFS:
41 return NBD_EPERM;
42 case EIO:
43 return NBD_EIO;
44 case ENOMEM:
45 return NBD_ENOMEM;
46 #ifdef EDQUOT
47 case EDQUOT:
48 #endif
49 case EFBIG:
50 case ENOSPC:
51 return NBD_ENOSPC;
52 case EOVERFLOW:
53 return NBD_EOVERFLOW;
54 case ESHUTDOWN:
55 return NBD_ESHUTDOWN;
56 case EINVAL:
57 default:
58 return NBD_EINVAL;
62 /* Definitions for opaque data types */
64 typedef struct NBDRequestData NBDRequestData;
66 struct NBDRequestData {
67 QSIMPLEQ_ENTRY(NBDRequestData) entry;
68 NBDClient *client;
69 uint8_t *data;
70 bool complete;
73 struct NBDExport {
74 int refcount;
75 void (*close)(NBDExport *exp);
77 BlockBackend *blk;
78 char *name;
79 char *description;
80 uint64_t dev_offset;
81 uint64_t size;
82 uint16_t nbdflags;
83 QTAILQ_HEAD(, NBDClient) clients;
84 QTAILQ_ENTRY(NBDExport) next;
86 AioContext *ctx;
88 BlockBackend *eject_notifier_blk;
89 Notifier eject_notifier;
91 BdrvDirtyBitmap *export_bitmap;
92 char *export_bitmap_context;
95 static QTAILQ_HEAD(, NBDExport) exports = QTAILQ_HEAD_INITIALIZER(exports);
97 /* NBDExportMetaContexts represents a list of contexts to be exported,
98 * as selected by NBD_OPT_SET_META_CONTEXT. Also used for
99 * NBD_OPT_LIST_META_CONTEXT. */
100 typedef struct NBDExportMetaContexts {
101 NBDExport *exp;
102 bool valid; /* means that negotiation of the option finished without
103 errors */
104 bool base_allocation; /* export base:allocation context (block status) */
105 bool bitmap; /* export qemu:dirty-bitmap:<export bitmap name> */
106 } NBDExportMetaContexts;
108 struct NBDClient {
109 int refcount;
110 void (*close_fn)(NBDClient *client, bool negotiated);
112 NBDExport *exp;
113 QCryptoTLSCreds *tlscreds;
114 char *tlsaclname;
115 QIOChannelSocket *sioc; /* The underlying data channel */
116 QIOChannel *ioc; /* The current I/O channel which may differ (eg TLS) */
118 Coroutine *recv_coroutine;
120 CoMutex send_lock;
121 Coroutine *send_coroutine;
123 QTAILQ_ENTRY(NBDClient) next;
124 int nb_requests;
125 bool closing;
127 bool structured_reply;
128 NBDExportMetaContexts export_meta;
130 uint32_t opt; /* Current option being negotiated */
131 uint32_t optlen; /* remaining length of data in ioc for the option being
132 negotiated now */
135 static void nbd_client_receive_next_request(NBDClient *client);
137 /* Basic flow for negotiation
139 Server Client
140 Negotiate
144 Server Client
145 Negotiate #1
146 Option
147 Negotiate #2
149 ----
151 followed by
153 Server Client
154 Request
155 Response
156 Request
157 Response
160 Request (type == 2)
164 static inline void set_be_option_rep(NBDOptionReply *rep, uint32_t option,
165 uint32_t type, uint32_t length)
167 stq_be_p(&rep->magic, NBD_REP_MAGIC);
168 stl_be_p(&rep->option, option);
169 stl_be_p(&rep->type, type);
170 stl_be_p(&rep->length, length);
173 /* Send a reply header, including length, but no payload.
174 * Return -errno on error, 0 on success. */
175 static int nbd_negotiate_send_rep_len(NBDClient *client, uint32_t type,
176 uint32_t len, Error **errp)
178 NBDOptionReply rep;
180 trace_nbd_negotiate_send_rep_len(client->opt, nbd_opt_lookup(client->opt),
181 type, nbd_rep_lookup(type), len);
183 assert(len < NBD_MAX_BUFFER_SIZE);
185 set_be_option_rep(&rep, client->opt, type, len);
186 return nbd_write(client->ioc, &rep, sizeof(rep), errp);
189 /* Send a reply header with default 0 length.
190 * Return -errno on error, 0 on success. */
191 static int nbd_negotiate_send_rep(NBDClient *client, uint32_t type,
192 Error **errp)
194 return nbd_negotiate_send_rep_len(client, type, 0, errp);
197 /* Send an error reply.
198 * Return -errno on error, 0 on success. */
199 static int GCC_FMT_ATTR(4, 0)
200 nbd_negotiate_send_rep_verr(NBDClient *client, uint32_t type,
201 Error **errp, const char *fmt, va_list va)
203 char *msg;
204 int ret;
205 size_t len;
207 msg = g_strdup_vprintf(fmt, va);
208 len = strlen(msg);
209 assert(len < 4096);
210 trace_nbd_negotiate_send_rep_err(msg);
211 ret = nbd_negotiate_send_rep_len(client, type, len, errp);
212 if (ret < 0) {
213 goto out;
215 if (nbd_write(client->ioc, msg, len, errp) < 0) {
216 error_prepend(errp, "write failed (error message): ");
217 ret = -EIO;
218 } else {
219 ret = 0;
222 out:
223 g_free(msg);
224 return ret;
227 /* Send an error reply.
228 * Return -errno on error, 0 on success. */
229 static int GCC_FMT_ATTR(4, 5)
230 nbd_negotiate_send_rep_err(NBDClient *client, uint32_t type,
231 Error **errp, const char *fmt, ...)
233 va_list va;
234 int ret;
236 va_start(va, fmt);
237 ret = nbd_negotiate_send_rep_verr(client, type, errp, fmt, va);
238 va_end(va);
239 return ret;
242 /* Drop remainder of the current option, and send a reply with the
243 * given error type and message. Return -errno on read or write
244 * failure; or 0 if connection is still live. */
245 static int GCC_FMT_ATTR(4, 0)
246 nbd_opt_vdrop(NBDClient *client, uint32_t type, Error **errp,
247 const char *fmt, va_list va)
249 int ret = nbd_drop(client->ioc, client->optlen, errp);
251 client->optlen = 0;
252 if (!ret) {
253 ret = nbd_negotiate_send_rep_verr(client, type, errp, fmt, va);
255 return ret;
258 static int GCC_FMT_ATTR(4, 5)
259 nbd_opt_drop(NBDClient *client, uint32_t type, Error **errp,
260 const char *fmt, ...)
262 int ret;
263 va_list va;
265 va_start(va, fmt);
266 ret = nbd_opt_vdrop(client, type, errp, fmt, va);
267 va_end(va);
269 return ret;
272 static int GCC_FMT_ATTR(3, 4)
273 nbd_opt_invalid(NBDClient *client, Error **errp, const char *fmt, ...)
275 int ret;
276 va_list va;
278 va_start(va, fmt);
279 ret = nbd_opt_vdrop(client, NBD_REP_ERR_INVALID, errp, fmt, va);
280 va_end(va);
282 return ret;
285 /* Read size bytes from the unparsed payload of the current option.
286 * Return -errno on I/O error, 0 if option was completely handled by
287 * sending a reply about inconsistent lengths, or 1 on success. */
288 static int nbd_opt_read(NBDClient *client, void *buffer, size_t size,
289 Error **errp)
291 if (size > client->optlen) {
292 return nbd_opt_invalid(client, errp,
293 "Inconsistent lengths in option %s",
294 nbd_opt_lookup(client->opt));
296 client->optlen -= size;
297 return qio_channel_read_all(client->ioc, buffer, size, errp) < 0 ? -EIO : 1;
300 /* Drop size bytes from the unparsed payload of the current option.
301 * Return -errno on I/O error, 0 if option was completely handled by
302 * sending a reply about inconsistent lengths, or 1 on success. */
303 static int nbd_opt_skip(NBDClient *client, size_t size, Error **errp)
305 if (size > client->optlen) {
306 return nbd_opt_invalid(client, errp,
307 "Inconsistent lengths in option %s",
308 nbd_opt_lookup(client->opt));
310 client->optlen -= size;
311 return nbd_drop(client->ioc, size, errp) < 0 ? -EIO : 1;
314 /* nbd_opt_read_name
316 * Read a string with the format:
317 * uint32_t len (<= NBD_MAX_NAME_SIZE)
318 * len bytes string (not 0-terminated)
320 * @name should be enough to store NBD_MAX_NAME_SIZE+1.
321 * If @length is non-null, it will be set to the actual string length.
323 * Return -errno on I/O error, 0 if option was completely handled by
324 * sending a reply about inconsistent lengths, or 1 on success.
326 static int nbd_opt_read_name(NBDClient *client, char *name, uint32_t *length,
327 Error **errp)
329 int ret;
330 uint32_t len;
332 ret = nbd_opt_read(client, &len, sizeof(len), errp);
333 if (ret <= 0) {
334 return ret;
336 len = cpu_to_be32(len);
338 if (len > NBD_MAX_NAME_SIZE) {
339 return nbd_opt_invalid(client, errp,
340 "Invalid name length: %" PRIu32, len);
343 ret = nbd_opt_read(client, name, len, errp);
344 if (ret <= 0) {
345 return ret;
347 name[len] = '\0';
349 if (length) {
350 *length = len;
353 return 1;
356 /* Send a single NBD_REP_SERVER reply to NBD_OPT_LIST, including payload.
357 * Return -errno on error, 0 on success. */
358 static int nbd_negotiate_send_rep_list(NBDClient *client, NBDExport *exp,
359 Error **errp)
361 size_t name_len, desc_len;
362 uint32_t len;
363 const char *name = exp->name ? exp->name : "";
364 const char *desc = exp->description ? exp->description : "";
365 QIOChannel *ioc = client->ioc;
366 int ret;
368 trace_nbd_negotiate_send_rep_list(name, desc);
369 name_len = strlen(name);
370 desc_len = strlen(desc);
371 len = name_len + desc_len + sizeof(len);
372 ret = nbd_negotiate_send_rep_len(client, NBD_REP_SERVER, len, errp);
373 if (ret < 0) {
374 return ret;
377 len = cpu_to_be32(name_len);
378 if (nbd_write(ioc, &len, sizeof(len), errp) < 0) {
379 error_prepend(errp, "write failed (name length): ");
380 return -EINVAL;
383 if (nbd_write(ioc, name, name_len, errp) < 0) {
384 error_prepend(errp, "write failed (name buffer): ");
385 return -EINVAL;
388 if (nbd_write(ioc, desc, desc_len, errp) < 0) {
389 error_prepend(errp, "write failed (description buffer): ");
390 return -EINVAL;
393 return 0;
396 /* Process the NBD_OPT_LIST command, with a potential series of replies.
397 * Return -errno on error, 0 on success. */
398 static int nbd_negotiate_handle_list(NBDClient *client, Error **errp)
400 NBDExport *exp;
401 assert(client->opt == NBD_OPT_LIST);
403 /* For each export, send a NBD_REP_SERVER reply. */
404 QTAILQ_FOREACH(exp, &exports, next) {
405 if (nbd_negotiate_send_rep_list(client, exp, errp)) {
406 return -EINVAL;
409 /* Finish with a NBD_REP_ACK. */
410 return nbd_negotiate_send_rep(client, NBD_REP_ACK, errp);
413 static void nbd_check_meta_export(NBDClient *client)
415 client->export_meta.valid &= client->exp == client->export_meta.exp;
418 /* Send a reply to NBD_OPT_EXPORT_NAME.
419 * Return -errno on error, 0 on success. */
420 static int nbd_negotiate_handle_export_name(NBDClient *client,
421 uint16_t myflags, bool no_zeroes,
422 Error **errp)
424 char name[NBD_MAX_NAME_SIZE + 1];
425 char buf[NBD_REPLY_EXPORT_NAME_SIZE] = "";
426 size_t len;
427 int ret;
429 /* Client sends:
430 [20 .. xx] export name (length bytes)
431 Server replies:
432 [ 0 .. 7] size
433 [ 8 .. 9] export flags
434 [10 .. 133] reserved (0) [unless no_zeroes]
436 trace_nbd_negotiate_handle_export_name();
437 if (client->optlen >= sizeof(name)) {
438 error_setg(errp, "Bad length received");
439 return -EINVAL;
441 if (nbd_read(client->ioc, name, client->optlen, "export name", errp) < 0) {
442 return -EIO;
444 name[client->optlen] = '\0';
445 client->optlen = 0;
447 trace_nbd_negotiate_handle_export_name_request(name);
449 client->exp = nbd_export_find(name);
450 if (!client->exp) {
451 error_setg(errp, "export not found");
452 return -EINVAL;
455 trace_nbd_negotiate_new_style_size_flags(client->exp->size,
456 client->exp->nbdflags | myflags);
457 stq_be_p(buf, client->exp->size);
458 stw_be_p(buf + 8, client->exp->nbdflags | myflags);
459 len = no_zeroes ? 10 : sizeof(buf);
460 ret = nbd_write(client->ioc, buf, len, errp);
461 if (ret < 0) {
462 error_prepend(errp, "write failed: ");
463 return ret;
466 QTAILQ_INSERT_TAIL(&client->exp->clients, client, next);
467 nbd_export_get(client->exp);
468 nbd_check_meta_export(client);
470 return 0;
473 /* Send a single NBD_REP_INFO, with a buffer @buf of @length bytes.
474 * The buffer does NOT include the info type prefix.
475 * Return -errno on error, 0 if ready to send more. */
476 static int nbd_negotiate_send_info(NBDClient *client,
477 uint16_t info, uint32_t length, void *buf,
478 Error **errp)
480 int rc;
482 trace_nbd_negotiate_send_info(info, nbd_info_lookup(info), length);
483 rc = nbd_negotiate_send_rep_len(client, NBD_REP_INFO,
484 sizeof(info) + length, errp);
485 if (rc < 0) {
486 return rc;
488 info = cpu_to_be16(info);
489 if (nbd_write(client->ioc, &info, sizeof(info), errp) < 0) {
490 return -EIO;
492 if (nbd_write(client->ioc, buf, length, errp) < 0) {
493 return -EIO;
495 return 0;
498 /* nbd_reject_length: Handle any unexpected payload.
499 * @fatal requests that we quit talking to the client, even if we are able
500 * to successfully send an error reply.
501 * Return:
502 * -errno transmission error occurred or @fatal was requested, errp is set
503 * 0 error message successfully sent to client, errp is not set
505 static int nbd_reject_length(NBDClient *client, bool fatal, Error **errp)
507 int ret;
509 assert(client->optlen);
510 ret = nbd_opt_invalid(client, errp, "option '%s' has unexpected length",
511 nbd_opt_lookup(client->opt));
512 if (fatal && !ret) {
513 error_setg(errp, "option '%s' has unexpected length",
514 nbd_opt_lookup(client->opt));
515 return -EINVAL;
517 return ret;
520 /* Handle NBD_OPT_INFO and NBD_OPT_GO.
521 * Return -errno on error, 0 if ready for next option, and 1 to move
522 * into transmission phase. */
523 static int nbd_negotiate_handle_info(NBDClient *client, uint16_t myflags,
524 Error **errp)
526 int rc;
527 char name[NBD_MAX_NAME_SIZE + 1];
528 NBDExport *exp;
529 uint16_t requests;
530 uint16_t request;
531 uint32_t namelen;
532 bool sendname = false;
533 bool blocksize = false;
534 uint32_t sizes[3];
535 char buf[sizeof(uint64_t) + sizeof(uint16_t)];
537 /* Client sends:
538 4 bytes: L, name length (can be 0)
539 L bytes: export name
540 2 bytes: N, number of requests (can be 0)
541 N * 2 bytes: N requests
543 rc = nbd_opt_read_name(client, name, &namelen, errp);
544 if (rc <= 0) {
545 return rc;
547 trace_nbd_negotiate_handle_export_name_request(name);
549 rc = nbd_opt_read(client, &requests, sizeof(requests), errp);
550 if (rc <= 0) {
551 return rc;
553 requests = be16_to_cpu(requests);
554 trace_nbd_negotiate_handle_info_requests(requests);
555 while (requests--) {
556 rc = nbd_opt_read(client, &request, sizeof(request), errp);
557 if (rc <= 0) {
558 return rc;
560 request = be16_to_cpu(request);
561 trace_nbd_negotiate_handle_info_request(request,
562 nbd_info_lookup(request));
563 /* We care about NBD_INFO_NAME and NBD_INFO_BLOCK_SIZE;
564 * everything else is either a request we don't know or
565 * something we send regardless of request */
566 switch (request) {
567 case NBD_INFO_NAME:
568 sendname = true;
569 break;
570 case NBD_INFO_BLOCK_SIZE:
571 blocksize = true;
572 break;
575 if (client->optlen) {
576 return nbd_reject_length(client, false, errp);
579 exp = nbd_export_find(name);
580 if (!exp) {
581 return nbd_negotiate_send_rep_err(client, NBD_REP_ERR_UNKNOWN,
582 errp, "export '%s' not present",
583 name);
586 /* Don't bother sending NBD_INFO_NAME unless client requested it */
587 if (sendname) {
588 rc = nbd_negotiate_send_info(client, NBD_INFO_NAME, namelen, name,
589 errp);
590 if (rc < 0) {
591 return rc;
595 /* Send NBD_INFO_DESCRIPTION only if available, regardless of
596 * client request */
597 if (exp->description) {
598 size_t len = strlen(exp->description);
600 rc = nbd_negotiate_send_info(client, NBD_INFO_DESCRIPTION,
601 len, exp->description, errp);
602 if (rc < 0) {
603 return rc;
607 /* Send NBD_INFO_BLOCK_SIZE always, but tweak the minimum size
608 * according to whether the client requested it, and according to
609 * whether this is OPT_INFO or OPT_GO. */
610 /* minimum - 1 for back-compat, or 512 if client is new enough.
611 * TODO: consult blk_bs(blk)->bl.request_alignment? */
612 sizes[0] =
613 (client->opt == NBD_OPT_INFO || blocksize) ? BDRV_SECTOR_SIZE : 1;
614 /* preferred - Hard-code to 4096 for now.
615 * TODO: is blk_bs(blk)->bl.opt_transfer appropriate? */
616 sizes[1] = 4096;
617 /* maximum - At most 32M, but smaller as appropriate. */
618 sizes[2] = MIN(blk_get_max_transfer(exp->blk), NBD_MAX_BUFFER_SIZE);
619 trace_nbd_negotiate_handle_info_block_size(sizes[0], sizes[1], sizes[2]);
620 sizes[0] = cpu_to_be32(sizes[0]);
621 sizes[1] = cpu_to_be32(sizes[1]);
622 sizes[2] = cpu_to_be32(sizes[2]);
623 rc = nbd_negotiate_send_info(client, NBD_INFO_BLOCK_SIZE,
624 sizeof(sizes), sizes, errp);
625 if (rc < 0) {
626 return rc;
629 /* Send NBD_INFO_EXPORT always */
630 trace_nbd_negotiate_new_style_size_flags(exp->size,
631 exp->nbdflags | myflags);
632 stq_be_p(buf, exp->size);
633 stw_be_p(buf + 8, exp->nbdflags | myflags);
634 rc = nbd_negotiate_send_info(client, NBD_INFO_EXPORT,
635 sizeof(buf), buf, errp);
636 if (rc < 0) {
637 return rc;
640 /* If the client is just asking for NBD_OPT_INFO, but forgot to
641 * request block sizes, return an error.
642 * TODO: consult blk_bs(blk)->request_align, and only error if it
643 * is not 1? */
644 if (client->opt == NBD_OPT_INFO && !blocksize) {
645 return nbd_negotiate_send_rep_err(client,
646 NBD_REP_ERR_BLOCK_SIZE_REQD,
647 errp,
648 "request NBD_INFO_BLOCK_SIZE to "
649 "use this export");
652 /* Final reply */
653 rc = nbd_negotiate_send_rep(client, NBD_REP_ACK, errp);
654 if (rc < 0) {
655 return rc;
658 if (client->opt == NBD_OPT_GO) {
659 client->exp = exp;
660 QTAILQ_INSERT_TAIL(&client->exp->clients, client, next);
661 nbd_export_get(client->exp);
662 nbd_check_meta_export(client);
663 rc = 1;
665 return rc;
669 /* Handle NBD_OPT_STARTTLS. Return NULL to drop connection, or else the
670 * new channel for all further (now-encrypted) communication. */
671 static QIOChannel *nbd_negotiate_handle_starttls(NBDClient *client,
672 Error **errp)
674 QIOChannel *ioc;
675 QIOChannelTLS *tioc;
676 struct NBDTLSHandshakeData data = { 0 };
678 assert(client->opt == NBD_OPT_STARTTLS);
680 trace_nbd_negotiate_handle_starttls();
681 ioc = client->ioc;
683 if (nbd_negotiate_send_rep(client, NBD_REP_ACK, errp) < 0) {
684 return NULL;
687 tioc = qio_channel_tls_new_server(ioc,
688 client->tlscreds,
689 client->tlsaclname,
690 errp);
691 if (!tioc) {
692 return NULL;
695 qio_channel_set_name(QIO_CHANNEL(tioc), "nbd-server-tls");
696 trace_nbd_negotiate_handle_starttls_handshake();
697 data.loop = g_main_loop_new(g_main_context_default(), FALSE);
698 qio_channel_tls_handshake(tioc,
699 nbd_tls_handshake,
700 &data,
701 NULL,
702 NULL);
704 if (!data.complete) {
705 g_main_loop_run(data.loop);
707 g_main_loop_unref(data.loop);
708 if (data.error) {
709 object_unref(OBJECT(tioc));
710 error_propagate(errp, data.error);
711 return NULL;
714 return QIO_CHANNEL(tioc);
717 /* nbd_negotiate_send_meta_context
719 * Send one chunk of reply to NBD_OPT_{LIST,SET}_META_CONTEXT
721 * For NBD_OPT_LIST_META_CONTEXT @context_id is ignored, 0 is used instead.
723 static int nbd_negotiate_send_meta_context(NBDClient *client,
724 const char *context,
725 uint32_t context_id,
726 Error **errp)
728 NBDOptionReplyMetaContext opt;
729 struct iovec iov[] = {
730 {.iov_base = &opt, .iov_len = sizeof(opt)},
731 {.iov_base = (void *)context, .iov_len = strlen(context)}
734 if (client->opt == NBD_OPT_LIST_META_CONTEXT) {
735 context_id = 0;
738 trace_nbd_negotiate_meta_query_reply(context, context_id);
739 set_be_option_rep(&opt.h, client->opt, NBD_REP_META_CONTEXT,
740 sizeof(opt) - sizeof(opt.h) + iov[1].iov_len);
741 stl_be_p(&opt.context_id, context_id);
743 return qio_channel_writev_all(client->ioc, iov, 2, errp) < 0 ? -EIO : 0;
746 /* Read strlen(@pattern) bytes, and set @match to true if they match @pattern.
747 * @match is never set to false.
749 * Return -errno on I/O error, 0 if option was completely handled by
750 * sending a reply about inconsistent lengths, or 1 on success.
752 * Note: return code = 1 doesn't mean that we've read exactly @pattern.
753 * It only means that there are no errors.
755 static int nbd_meta_pattern(NBDClient *client, const char *pattern, bool *match,
756 Error **errp)
758 int ret;
759 char *query;
760 size_t len = strlen(pattern);
762 assert(len);
764 query = g_malloc(len);
765 ret = nbd_opt_read(client, query, len, errp);
766 if (ret <= 0) {
767 g_free(query);
768 return ret;
771 if (strncmp(query, pattern, len) == 0) {
772 trace_nbd_negotiate_meta_query_parse(pattern);
773 *match = true;
774 } else {
775 trace_nbd_negotiate_meta_query_skip("pattern not matched");
777 g_free(query);
779 return 1;
783 * Read @len bytes, and set @match to true if they match @pattern, or if @len
784 * is 0 and the client is performing _LIST_. @match is never set to false.
786 * Return -errno on I/O error, 0 if option was completely handled by
787 * sending a reply about inconsistent lengths, or 1 on success.
789 * Note: return code = 1 doesn't mean that we've read exactly @pattern.
790 * It only means that there are no errors.
792 static int nbd_meta_empty_or_pattern(NBDClient *client, const char *pattern,
793 uint32_t len, bool *match, Error **errp)
795 if (len == 0) {
796 if (client->opt == NBD_OPT_LIST_META_CONTEXT) {
797 *match = true;
799 trace_nbd_negotiate_meta_query_parse("empty");
800 return 1;
803 if (len != strlen(pattern)) {
804 trace_nbd_negotiate_meta_query_skip("different lengths");
805 return nbd_opt_skip(client, len, errp);
808 return nbd_meta_pattern(client, pattern, match, errp);
811 /* nbd_meta_base_query
813 * Handle queries to 'base' namespace. For now, only the base:allocation
814 * context is available. 'len' is the amount of text remaining to be read from
815 * the current name, after the 'base:' portion has been stripped.
817 * Return -errno on I/O error, 0 if option was completely handled by
818 * sending a reply about inconsistent lengths, or 1 on success.
820 static int nbd_meta_base_query(NBDClient *client, NBDExportMetaContexts *meta,
821 uint32_t len, Error **errp)
823 return nbd_meta_empty_or_pattern(client, "allocation", len,
824 &meta->base_allocation, errp);
827 /* nbd_meta_bitmap_query
829 * Handle query to 'qemu:' namespace.
830 * @len is the amount of text remaining to be read from the current name, after
831 * the 'qemu:' portion has been stripped.
833 * Return -errno on I/O error, 0 if option was completely handled by
834 * sending a reply about inconsistent lengths, or 1 on success. */
835 static int nbd_meta_qemu_query(NBDClient *client, NBDExportMetaContexts *meta,
836 uint32_t len, Error **errp)
838 bool dirty_bitmap = false;
839 size_t dirty_bitmap_len = strlen("dirty-bitmap:");
840 int ret;
842 if (!meta->exp->export_bitmap) {
843 trace_nbd_negotiate_meta_query_skip("no dirty-bitmap exported");
844 return nbd_opt_skip(client, len, errp);
847 if (len == 0) {
848 if (client->opt == NBD_OPT_LIST_META_CONTEXT) {
849 meta->bitmap = true;
851 trace_nbd_negotiate_meta_query_parse("empty");
852 return 1;
855 if (len < dirty_bitmap_len) {
856 trace_nbd_negotiate_meta_query_skip("not dirty-bitmap:");
857 return nbd_opt_skip(client, len, errp);
860 len -= dirty_bitmap_len;
861 ret = nbd_meta_pattern(client, "dirty-bitmap:", &dirty_bitmap, errp);
862 if (ret <= 0) {
863 return ret;
865 if (!dirty_bitmap) {
866 trace_nbd_negotiate_meta_query_skip("not dirty-bitmap:");
867 return nbd_opt_skip(client, len, errp);
870 trace_nbd_negotiate_meta_query_parse("dirty-bitmap:");
872 return nbd_meta_empty_or_pattern(
873 client, meta->exp->export_bitmap_context +
874 strlen("qemu:dirty_bitmap:"), len, &meta->bitmap, errp);
877 /* nbd_negotiate_meta_query
879 * Parse namespace name and call corresponding function to parse body of the
880 * query.
882 * The only supported namespace now is 'base'.
884 * The function aims not wasting time and memory to read long unknown namespace
885 * names.
887 * Return -errno on I/O error, 0 if option was completely handled by
888 * sending a reply about inconsistent lengths, or 1 on success. */
889 static int nbd_negotiate_meta_query(NBDClient *client,
890 NBDExportMetaContexts *meta, Error **errp)
893 * Both 'qemu' and 'base' namespaces have length = 5 including a
894 * colon. If another length namespace is later introduced, this
895 * should certainly be refactored.
897 int ret;
898 size_t ns_len = 5;
899 char ns[5];
900 uint32_t len;
902 ret = nbd_opt_read(client, &len, sizeof(len), errp);
903 if (ret <= 0) {
904 return ret;
906 len = cpu_to_be32(len);
908 if (len < ns_len) {
909 trace_nbd_negotiate_meta_query_skip("length too short");
910 return nbd_opt_skip(client, len, errp);
913 len -= ns_len;
914 ret = nbd_opt_read(client, ns, ns_len, errp);
915 if (ret <= 0) {
916 return ret;
919 if (!strncmp(ns, "base:", ns_len)) {
920 trace_nbd_negotiate_meta_query_parse("base:");
921 return nbd_meta_base_query(client, meta, len, errp);
922 } else if (!strncmp(ns, "qemu:", ns_len)) {
923 trace_nbd_negotiate_meta_query_parse("qemu:");
924 return nbd_meta_qemu_query(client, meta, len, errp);
927 trace_nbd_negotiate_meta_query_skip("unknown namespace");
928 return nbd_opt_skip(client, len, errp);
931 /* nbd_negotiate_meta_queries
932 * Handle NBD_OPT_LIST_META_CONTEXT and NBD_OPT_SET_META_CONTEXT
934 * Return -errno on I/O error, or 0 if option was completely handled. */
935 static int nbd_negotiate_meta_queries(NBDClient *client,
936 NBDExportMetaContexts *meta, Error **errp)
938 int ret;
939 char export_name[NBD_MAX_NAME_SIZE + 1];
940 NBDExportMetaContexts local_meta;
941 uint32_t nb_queries;
942 int i;
944 if (!client->structured_reply) {
945 return nbd_opt_invalid(client, errp,
946 "request option '%s' when structured reply "
947 "is not negotiated",
948 nbd_opt_lookup(client->opt));
951 if (client->opt == NBD_OPT_LIST_META_CONTEXT) {
952 /* Only change the caller's meta on SET. */
953 meta = &local_meta;
956 memset(meta, 0, sizeof(*meta));
958 ret = nbd_opt_read_name(client, export_name, NULL, errp);
959 if (ret <= 0) {
960 return ret;
963 meta->exp = nbd_export_find(export_name);
964 if (meta->exp == NULL) {
965 return nbd_opt_drop(client, NBD_REP_ERR_UNKNOWN, errp,
966 "export '%s' not present", export_name);
969 ret = nbd_opt_read(client, &nb_queries, sizeof(nb_queries), errp);
970 if (ret <= 0) {
971 return ret;
973 nb_queries = cpu_to_be32(nb_queries);
974 trace_nbd_negotiate_meta_context(nbd_opt_lookup(client->opt),
975 export_name, nb_queries);
977 if (client->opt == NBD_OPT_LIST_META_CONTEXT && !nb_queries) {
978 /* enable all known contexts */
979 meta->base_allocation = true;
980 meta->bitmap = !!meta->exp->export_bitmap;
981 } else {
982 for (i = 0; i < nb_queries; ++i) {
983 ret = nbd_negotiate_meta_query(client, meta, errp);
984 if (ret <= 0) {
985 return ret;
990 if (meta->base_allocation) {
991 ret = nbd_negotiate_send_meta_context(client, "base:allocation",
992 NBD_META_ID_BASE_ALLOCATION,
993 errp);
994 if (ret < 0) {
995 return ret;
999 if (meta->bitmap) {
1000 ret = nbd_negotiate_send_meta_context(client,
1001 meta->exp->export_bitmap_context,
1002 NBD_META_ID_DIRTY_BITMAP,
1003 errp);
1004 if (ret < 0) {
1005 return ret;
1009 ret = nbd_negotiate_send_rep(client, NBD_REP_ACK, errp);
1010 if (ret == 0) {
1011 meta->valid = true;
1014 return ret;
1017 /* nbd_negotiate_options
1018 * Process all NBD_OPT_* client option commands, during fixed newstyle
1019 * negotiation.
1020 * Return:
1021 * -errno on error, errp is set
1022 * 0 on successful negotiation, errp is not set
1023 * 1 if client sent NBD_OPT_ABORT, i.e. on valid disconnect,
1024 * errp is not set
1026 static int nbd_negotiate_options(NBDClient *client, uint16_t myflags,
1027 Error **errp)
1029 uint32_t flags;
1030 bool fixedNewstyle = false;
1031 bool no_zeroes = false;
1033 /* Client sends:
1034 [ 0 .. 3] client flags
1036 Then we loop until NBD_OPT_EXPORT_NAME or NBD_OPT_GO:
1037 [ 0 .. 7] NBD_OPTS_MAGIC
1038 [ 8 .. 11] NBD option
1039 [12 .. 15] Data length
1040 ... Rest of request
1042 [ 0 .. 7] NBD_OPTS_MAGIC
1043 [ 8 .. 11] Second NBD option
1044 [12 .. 15] Data length
1045 ... Rest of request
1048 if (nbd_read32(client->ioc, &flags, "flags", errp) < 0) {
1049 return -EIO;
1051 trace_nbd_negotiate_options_flags(flags);
1052 if (flags & NBD_FLAG_C_FIXED_NEWSTYLE) {
1053 fixedNewstyle = true;
1054 flags &= ~NBD_FLAG_C_FIXED_NEWSTYLE;
1056 if (flags & NBD_FLAG_C_NO_ZEROES) {
1057 no_zeroes = true;
1058 flags &= ~NBD_FLAG_C_NO_ZEROES;
1060 if (flags != 0) {
1061 error_setg(errp, "Unknown client flags 0x%" PRIx32 " received", flags);
1062 return -EINVAL;
1065 while (1) {
1066 int ret;
1067 uint32_t option, length;
1068 uint64_t magic;
1070 if (nbd_read64(client->ioc, &magic, "opts magic", errp) < 0) {
1071 return -EINVAL;
1073 trace_nbd_negotiate_options_check_magic(magic);
1074 if (magic != NBD_OPTS_MAGIC) {
1075 error_setg(errp, "Bad magic received");
1076 return -EINVAL;
1079 if (nbd_read32(client->ioc, &option, "option", errp) < 0) {
1080 return -EINVAL;
1082 client->opt = option;
1084 if (nbd_read32(client->ioc, &length, "option length", errp) < 0) {
1085 return -EINVAL;
1087 assert(!client->optlen);
1088 client->optlen = length;
1090 if (length > NBD_MAX_BUFFER_SIZE) {
1091 error_setg(errp, "len (%" PRIu32" ) is larger than max len (%u)",
1092 length, NBD_MAX_BUFFER_SIZE);
1093 return -EINVAL;
1096 trace_nbd_negotiate_options_check_option(option,
1097 nbd_opt_lookup(option));
1098 if (client->tlscreds &&
1099 client->ioc == (QIOChannel *)client->sioc) {
1100 QIOChannel *tioc;
1101 if (!fixedNewstyle) {
1102 error_setg(errp, "Unsupported option 0x%" PRIx32, option);
1103 return -EINVAL;
1105 switch (option) {
1106 case NBD_OPT_STARTTLS:
1107 if (length) {
1108 /* Unconditionally drop the connection if the client
1109 * can't start a TLS negotiation correctly */
1110 return nbd_reject_length(client, true, errp);
1112 tioc = nbd_negotiate_handle_starttls(client, errp);
1113 if (!tioc) {
1114 return -EIO;
1116 ret = 0;
1117 object_unref(OBJECT(client->ioc));
1118 client->ioc = QIO_CHANNEL(tioc);
1119 break;
1121 case NBD_OPT_EXPORT_NAME:
1122 /* No way to return an error to client, so drop connection */
1123 error_setg(errp, "Option 0x%x not permitted before TLS",
1124 option);
1125 return -EINVAL;
1127 default:
1128 /* Let the client keep trying, unless they asked to
1129 * quit. Always try to give an error back to the
1130 * client; but when replying to OPT_ABORT, be aware
1131 * that the client may hang up before receiving the
1132 * error, in which case we are fine ignoring the
1133 * resulting EPIPE. */
1134 ret = nbd_opt_drop(client, NBD_REP_ERR_TLS_REQD,
1135 option == NBD_OPT_ABORT ? NULL : errp,
1136 "Option 0x%" PRIx32
1137 " not permitted before TLS", option);
1138 if (option == NBD_OPT_ABORT) {
1139 return 1;
1141 break;
1143 } else if (fixedNewstyle) {
1144 switch (option) {
1145 case NBD_OPT_LIST:
1146 if (length) {
1147 ret = nbd_reject_length(client, false, errp);
1148 } else {
1149 ret = nbd_negotiate_handle_list(client, errp);
1151 break;
1153 case NBD_OPT_ABORT:
1154 /* NBD spec says we must try to reply before
1155 * disconnecting, but that we must also tolerate
1156 * guests that don't wait for our reply. */
1157 nbd_negotiate_send_rep(client, NBD_REP_ACK, NULL);
1158 return 1;
1160 case NBD_OPT_EXPORT_NAME:
1161 return nbd_negotiate_handle_export_name(client,
1162 myflags, no_zeroes,
1163 errp);
1165 case NBD_OPT_INFO:
1166 case NBD_OPT_GO:
1167 ret = nbd_negotiate_handle_info(client, myflags, errp);
1168 if (ret == 1) {
1169 assert(option == NBD_OPT_GO);
1170 return 0;
1172 break;
1174 case NBD_OPT_STARTTLS:
1175 if (length) {
1176 ret = nbd_reject_length(client, false, errp);
1177 } else if (client->tlscreds) {
1178 ret = nbd_negotiate_send_rep_err(client,
1179 NBD_REP_ERR_INVALID, errp,
1180 "TLS already enabled");
1181 } else {
1182 ret = nbd_negotiate_send_rep_err(client,
1183 NBD_REP_ERR_POLICY, errp,
1184 "TLS not configured");
1186 break;
1188 case NBD_OPT_STRUCTURED_REPLY:
1189 if (length) {
1190 ret = nbd_reject_length(client, false, errp);
1191 } else if (client->structured_reply) {
1192 ret = nbd_negotiate_send_rep_err(
1193 client, NBD_REP_ERR_INVALID, errp,
1194 "structured reply already negotiated");
1195 } else {
1196 ret = nbd_negotiate_send_rep(client, NBD_REP_ACK, errp);
1197 client->structured_reply = true;
1198 myflags |= NBD_FLAG_SEND_DF;
1200 break;
1202 case NBD_OPT_LIST_META_CONTEXT:
1203 case NBD_OPT_SET_META_CONTEXT:
1204 ret = nbd_negotiate_meta_queries(client, &client->export_meta,
1205 errp);
1206 break;
1208 default:
1209 ret = nbd_opt_drop(client, NBD_REP_ERR_UNSUP, errp,
1210 "Unsupported option %" PRIu32 " (%s)",
1211 option, nbd_opt_lookup(option));
1212 break;
1214 } else {
1216 * If broken new-style we should drop the connection
1217 * for anything except NBD_OPT_EXPORT_NAME
1219 switch (option) {
1220 case NBD_OPT_EXPORT_NAME:
1221 return nbd_negotiate_handle_export_name(client,
1222 myflags, no_zeroes,
1223 errp);
1225 default:
1226 error_setg(errp, "Unsupported option %" PRIu32 " (%s)",
1227 option, nbd_opt_lookup(option));
1228 return -EINVAL;
1231 if (ret < 0) {
1232 return ret;
1237 /* nbd_negotiate
1238 * Return:
1239 * -errno on error, errp is set
1240 * 0 on successful negotiation, errp is not set
1241 * 1 if client sent NBD_OPT_ABORT, i.e. on valid disconnect,
1242 * errp is not set
1244 static coroutine_fn int nbd_negotiate(NBDClient *client, Error **errp)
1246 char buf[NBD_OLDSTYLE_NEGOTIATE_SIZE] = "";
1247 int ret;
1248 const uint16_t myflags = (NBD_FLAG_HAS_FLAGS | NBD_FLAG_SEND_TRIM |
1249 NBD_FLAG_SEND_FLUSH | NBD_FLAG_SEND_FUA |
1250 NBD_FLAG_SEND_WRITE_ZEROES | NBD_FLAG_SEND_CACHE);
1252 /* Old style negotiation header, no room for options
1253 [ 0 .. 7] passwd ("NBDMAGIC")
1254 [ 8 .. 15] magic (NBD_CLIENT_MAGIC)
1255 [16 .. 23] size
1256 [24 .. 27] export flags (zero-extended)
1257 [28 .. 151] reserved (0)
1259 New style negotiation header, client can send options
1260 [ 0 .. 7] passwd ("NBDMAGIC")
1261 [ 8 .. 15] magic (NBD_OPTS_MAGIC)
1262 [16 .. 17] server flags (0)
1263 ....options sent, ending in NBD_OPT_EXPORT_NAME or NBD_OPT_GO....
1266 qio_channel_set_blocking(client->ioc, false, NULL);
1268 trace_nbd_negotiate_begin();
1269 memcpy(buf, "NBDMAGIC", 8);
1271 stq_be_p(buf + 8, NBD_OPTS_MAGIC);
1272 stw_be_p(buf + 16, NBD_FLAG_FIXED_NEWSTYLE | NBD_FLAG_NO_ZEROES);
1274 if (nbd_write(client->ioc, buf, 18, errp) < 0) {
1275 error_prepend(errp, "write failed: ");
1276 return -EINVAL;
1278 ret = nbd_negotiate_options(client, myflags, errp);
1279 if (ret != 0) {
1280 if (ret < 0) {
1281 error_prepend(errp, "option negotiation failed: ");
1283 return ret;
1286 assert(!client->optlen);
1287 trace_nbd_negotiate_success();
1289 return 0;
1292 static int nbd_receive_request(QIOChannel *ioc, NBDRequest *request,
1293 Error **errp)
1295 uint8_t buf[NBD_REQUEST_SIZE];
1296 uint32_t magic;
1297 int ret;
1299 ret = nbd_read(ioc, buf, sizeof(buf), "request", errp);
1300 if (ret < 0) {
1301 return ret;
1304 /* Request
1305 [ 0 .. 3] magic (NBD_REQUEST_MAGIC)
1306 [ 4 .. 5] flags (NBD_CMD_FLAG_FUA, ...)
1307 [ 6 .. 7] type (NBD_CMD_READ, ...)
1308 [ 8 .. 15] handle
1309 [16 .. 23] from
1310 [24 .. 27] len
1313 magic = ldl_be_p(buf);
1314 request->flags = lduw_be_p(buf + 4);
1315 request->type = lduw_be_p(buf + 6);
1316 request->handle = ldq_be_p(buf + 8);
1317 request->from = ldq_be_p(buf + 16);
1318 request->len = ldl_be_p(buf + 24);
1320 trace_nbd_receive_request(magic, request->flags, request->type,
1321 request->from, request->len);
1323 if (magic != NBD_REQUEST_MAGIC) {
1324 error_setg(errp, "invalid magic (got 0x%" PRIx32 ")", magic);
1325 return -EINVAL;
1327 return 0;
1330 #define MAX_NBD_REQUESTS 16
1332 void nbd_client_get(NBDClient *client)
1334 client->refcount++;
1337 void nbd_client_put(NBDClient *client)
1339 if (--client->refcount == 0) {
1340 /* The last reference should be dropped by client->close,
1341 * which is called by client_close.
1343 assert(client->closing);
1345 qio_channel_detach_aio_context(client->ioc);
1346 object_unref(OBJECT(client->sioc));
1347 object_unref(OBJECT(client->ioc));
1348 if (client->tlscreds) {
1349 object_unref(OBJECT(client->tlscreds));
1351 g_free(client->tlsaclname);
1352 if (client->exp) {
1353 QTAILQ_REMOVE(&client->exp->clients, client, next);
1354 nbd_export_put(client->exp);
1356 g_free(client);
1360 static void client_close(NBDClient *client, bool negotiated)
1362 if (client->closing) {
1363 return;
1366 client->closing = true;
1368 /* Force requests to finish. They will drop their own references,
1369 * then we'll close the socket and free the NBDClient.
1371 qio_channel_shutdown(client->ioc, QIO_CHANNEL_SHUTDOWN_BOTH,
1372 NULL);
1374 /* Also tell the client, so that they release their reference. */
1375 if (client->close_fn) {
1376 client->close_fn(client, negotiated);
1380 static NBDRequestData *nbd_request_get(NBDClient *client)
1382 NBDRequestData *req;
1384 assert(client->nb_requests <= MAX_NBD_REQUESTS - 1);
1385 client->nb_requests++;
1387 req = g_new0(NBDRequestData, 1);
1388 nbd_client_get(client);
1389 req->client = client;
1390 return req;
1393 static void nbd_request_put(NBDRequestData *req)
1395 NBDClient *client = req->client;
1397 if (req->data) {
1398 qemu_vfree(req->data);
1400 g_free(req);
1402 client->nb_requests--;
1403 nbd_client_receive_next_request(client);
1405 nbd_client_put(client);
1408 static void blk_aio_attached(AioContext *ctx, void *opaque)
1410 NBDExport *exp = opaque;
1411 NBDClient *client;
1413 trace_nbd_blk_aio_attached(exp->name, ctx);
1415 exp->ctx = ctx;
1417 QTAILQ_FOREACH(client, &exp->clients, next) {
1418 qio_channel_attach_aio_context(client->ioc, ctx);
1419 if (client->recv_coroutine) {
1420 aio_co_schedule(ctx, client->recv_coroutine);
1422 if (client->send_coroutine) {
1423 aio_co_schedule(ctx, client->send_coroutine);
1428 static void blk_aio_detach(void *opaque)
1430 NBDExport *exp = opaque;
1431 NBDClient *client;
1433 trace_nbd_blk_aio_detach(exp->name, exp->ctx);
1435 QTAILQ_FOREACH(client, &exp->clients, next) {
1436 qio_channel_detach_aio_context(client->ioc);
1439 exp->ctx = NULL;
1442 static void nbd_eject_notifier(Notifier *n, void *data)
1444 NBDExport *exp = container_of(n, NBDExport, eject_notifier);
1445 nbd_export_close(exp);
1448 NBDExport *nbd_export_new(BlockDriverState *bs, uint64_t dev_offset,
1449 uint64_t size, const char *name, const char *desc,
1450 const char *bitmap, uint16_t nbdflags,
1451 void (*close)(NBDExport *), bool writethrough,
1452 BlockBackend *on_eject_blk, Error **errp)
1454 AioContext *ctx;
1455 BlockBackend *blk;
1456 NBDExport *exp = g_new0(NBDExport, 1);
1457 uint64_t perm;
1458 int ret;
1461 * NBD exports are used for non-shared storage migration. Make sure
1462 * that BDRV_O_INACTIVE is cleared and the image is ready for write
1463 * access since the export could be available before migration handover.
1465 assert(name);
1466 ctx = bdrv_get_aio_context(bs);
1467 aio_context_acquire(ctx);
1468 bdrv_invalidate_cache(bs, NULL);
1469 aio_context_release(ctx);
1471 /* Don't allow resize while the NBD server is running, otherwise we don't
1472 * care what happens with the node. */
1473 perm = BLK_PERM_CONSISTENT_READ;
1474 if ((nbdflags & NBD_FLAG_READ_ONLY) == 0) {
1475 perm |= BLK_PERM_WRITE;
1477 blk = blk_new(perm, BLK_PERM_CONSISTENT_READ | BLK_PERM_WRITE_UNCHANGED |
1478 BLK_PERM_WRITE | BLK_PERM_GRAPH_MOD);
1479 ret = blk_insert_bs(blk, bs, errp);
1480 if (ret < 0) {
1481 goto fail;
1483 blk_set_enable_write_cache(blk, !writethrough);
1485 exp->refcount = 1;
1486 QTAILQ_INIT(&exp->clients);
1487 exp->blk = blk;
1488 assert(dev_offset <= INT64_MAX);
1489 exp->dev_offset = dev_offset;
1490 exp->name = g_strdup(name);
1491 exp->description = g_strdup(desc);
1492 exp->nbdflags = nbdflags;
1493 assert(size <= INT64_MAX - dev_offset);
1494 exp->size = QEMU_ALIGN_DOWN(size, BDRV_SECTOR_SIZE);
1496 if (bitmap) {
1497 BdrvDirtyBitmap *bm = NULL;
1498 BlockDriverState *bs = blk_bs(blk);
1500 while (true) {
1501 bm = bdrv_find_dirty_bitmap(bs, bitmap);
1502 if (bm != NULL || bs->backing == NULL) {
1503 break;
1506 bs = bs->backing->bs;
1509 if (bm == NULL) {
1510 error_setg(errp, "Bitmap '%s' is not found", bitmap);
1511 goto fail;
1514 if ((nbdflags & NBD_FLAG_READ_ONLY) && bdrv_is_writable(bs) &&
1515 bdrv_dirty_bitmap_enabled(bm)) {
1516 error_setg(errp,
1517 "Enabled bitmap '%s' incompatible with readonly export",
1518 bitmap);
1519 goto fail;
1522 if (bdrv_dirty_bitmap_user_locked(bm)) {
1523 error_setg(errp, "Bitmap '%s' is in use", bitmap);
1524 goto fail;
1527 bdrv_dirty_bitmap_set_qmp_locked(bm, true);
1528 exp->export_bitmap = bm;
1529 exp->export_bitmap_context = g_strdup_printf("qemu:dirty-bitmap:%s",
1530 bitmap);
1533 exp->close = close;
1534 exp->ctx = blk_get_aio_context(blk);
1535 blk_add_aio_context_notifier(blk, blk_aio_attached, blk_aio_detach, exp);
1537 if (on_eject_blk) {
1538 blk_ref(on_eject_blk);
1539 exp->eject_notifier_blk = on_eject_blk;
1540 exp->eject_notifier.notify = nbd_eject_notifier;
1541 blk_add_remove_bs_notifier(on_eject_blk, &exp->eject_notifier);
1543 QTAILQ_INSERT_TAIL(&exports, exp, next);
1544 nbd_export_get(exp);
1545 return exp;
1547 fail:
1548 blk_unref(blk);
1549 g_free(exp->name);
1550 g_free(exp->description);
1551 g_free(exp);
1552 return NULL;
1555 NBDExport *nbd_export_find(const char *name)
1557 NBDExport *exp;
1558 QTAILQ_FOREACH(exp, &exports, next) {
1559 if (strcmp(name, exp->name) == 0) {
1560 return exp;
1564 return NULL;
1567 void nbd_export_close(NBDExport *exp)
1569 NBDClient *client, *next;
1571 nbd_export_get(exp);
1573 * TODO: Should we expand QMP NbdServerRemoveNode enum to allow a
1574 * close mode that stops advertising the export to new clients but
1575 * still permits existing clients to run to completion? Because of
1576 * that possibility, nbd_export_close() can be called more than
1577 * once on an export.
1579 QTAILQ_FOREACH_SAFE(client, &exp->clients, next, next) {
1580 client_close(client, true);
1582 if (exp->name) {
1583 nbd_export_put(exp);
1584 g_free(exp->name);
1585 exp->name = NULL;
1586 QTAILQ_REMOVE(&exports, exp, next);
1588 g_free(exp->description);
1589 exp->description = NULL;
1590 nbd_export_put(exp);
1593 void nbd_export_remove(NBDExport *exp, NbdServerRemoveMode mode, Error **errp)
1595 if (mode == NBD_SERVER_REMOVE_MODE_HARD || QTAILQ_EMPTY(&exp->clients)) {
1596 nbd_export_close(exp);
1597 return;
1600 assert(mode == NBD_SERVER_REMOVE_MODE_SAFE);
1602 error_setg(errp, "export '%s' still in use", exp->name);
1603 error_append_hint(errp, "Use mode='hard' to force client disconnect\n");
1606 void nbd_export_get(NBDExport *exp)
1608 assert(exp->refcount > 0);
1609 exp->refcount++;
1612 void nbd_export_put(NBDExport *exp)
1614 assert(exp->refcount > 0);
1615 if (exp->refcount == 1) {
1616 nbd_export_close(exp);
1619 /* nbd_export_close() may theoretically reduce refcount to 0. It may happen
1620 * if someone calls nbd_export_put() on named export not through
1621 * nbd_export_set_name() when refcount is 1. So, let's assert that
1622 * it is > 0.
1624 assert(exp->refcount > 0);
1625 if (--exp->refcount == 0) {
1626 assert(exp->name == NULL);
1627 assert(exp->description == NULL);
1629 if (exp->close) {
1630 exp->close(exp);
1633 if (exp->blk) {
1634 if (exp->eject_notifier_blk) {
1635 notifier_remove(&exp->eject_notifier);
1636 blk_unref(exp->eject_notifier_blk);
1638 blk_remove_aio_context_notifier(exp->blk, blk_aio_attached,
1639 blk_aio_detach, exp);
1640 blk_unref(exp->blk);
1641 exp->blk = NULL;
1644 if (exp->export_bitmap) {
1645 bdrv_dirty_bitmap_set_qmp_locked(exp->export_bitmap, false);
1646 g_free(exp->export_bitmap_context);
1649 g_free(exp);
1653 BlockBackend *nbd_export_get_blockdev(NBDExport *exp)
1655 return exp->blk;
1658 void nbd_export_close_all(void)
1660 NBDExport *exp, *next;
1662 QTAILQ_FOREACH_SAFE(exp, &exports, next, next) {
1663 nbd_export_close(exp);
1667 static int coroutine_fn nbd_co_send_iov(NBDClient *client, struct iovec *iov,
1668 unsigned niov, Error **errp)
1670 int ret;
1672 g_assert(qemu_in_coroutine());
1673 qemu_co_mutex_lock(&client->send_lock);
1674 client->send_coroutine = qemu_coroutine_self();
1676 ret = qio_channel_writev_all(client->ioc, iov, niov, errp) < 0 ? -EIO : 0;
1678 client->send_coroutine = NULL;
1679 qemu_co_mutex_unlock(&client->send_lock);
1681 return ret;
1684 static inline void set_be_simple_reply(NBDSimpleReply *reply, uint64_t error,
1685 uint64_t handle)
1687 stl_be_p(&reply->magic, NBD_SIMPLE_REPLY_MAGIC);
1688 stl_be_p(&reply->error, error);
1689 stq_be_p(&reply->handle, handle);
1692 static int nbd_co_send_simple_reply(NBDClient *client,
1693 uint64_t handle,
1694 uint32_t error,
1695 void *data,
1696 size_t len,
1697 Error **errp)
1699 NBDSimpleReply reply;
1700 int nbd_err = system_errno_to_nbd_errno(error);
1701 struct iovec iov[] = {
1702 {.iov_base = &reply, .iov_len = sizeof(reply)},
1703 {.iov_base = data, .iov_len = len}
1706 trace_nbd_co_send_simple_reply(handle, nbd_err, nbd_err_lookup(nbd_err),
1707 len);
1708 set_be_simple_reply(&reply, nbd_err, handle);
1710 return nbd_co_send_iov(client, iov, len ? 2 : 1, errp);
1713 static inline void set_be_chunk(NBDStructuredReplyChunk *chunk, uint16_t flags,
1714 uint16_t type, uint64_t handle, uint32_t length)
1716 stl_be_p(&chunk->magic, NBD_STRUCTURED_REPLY_MAGIC);
1717 stw_be_p(&chunk->flags, flags);
1718 stw_be_p(&chunk->type, type);
1719 stq_be_p(&chunk->handle, handle);
1720 stl_be_p(&chunk->length, length);
1723 static int coroutine_fn nbd_co_send_structured_done(NBDClient *client,
1724 uint64_t handle,
1725 Error **errp)
1727 NBDStructuredReplyChunk chunk;
1728 struct iovec iov[] = {
1729 {.iov_base = &chunk, .iov_len = sizeof(chunk)},
1732 trace_nbd_co_send_structured_done(handle);
1733 set_be_chunk(&chunk, NBD_REPLY_FLAG_DONE, NBD_REPLY_TYPE_NONE, handle, 0);
1735 return nbd_co_send_iov(client, iov, 1, errp);
1738 static int coroutine_fn nbd_co_send_structured_read(NBDClient *client,
1739 uint64_t handle,
1740 uint64_t offset,
1741 void *data,
1742 size_t size,
1743 bool final,
1744 Error **errp)
1746 NBDStructuredReadData chunk;
1747 struct iovec iov[] = {
1748 {.iov_base = &chunk, .iov_len = sizeof(chunk)},
1749 {.iov_base = data, .iov_len = size}
1752 assert(size);
1753 trace_nbd_co_send_structured_read(handle, offset, data, size);
1754 set_be_chunk(&chunk.h, final ? NBD_REPLY_FLAG_DONE : 0,
1755 NBD_REPLY_TYPE_OFFSET_DATA, handle,
1756 sizeof(chunk) - sizeof(chunk.h) + size);
1757 stq_be_p(&chunk.offset, offset);
1759 return nbd_co_send_iov(client, iov, 2, errp);
1762 static int coroutine_fn nbd_co_send_structured_error(NBDClient *client,
1763 uint64_t handle,
1764 uint32_t error,
1765 const char *msg,
1766 Error **errp)
1768 NBDStructuredError chunk;
1769 int nbd_err = system_errno_to_nbd_errno(error);
1770 struct iovec iov[] = {
1771 {.iov_base = &chunk, .iov_len = sizeof(chunk)},
1772 {.iov_base = (char *)msg, .iov_len = msg ? strlen(msg) : 0},
1775 assert(nbd_err);
1776 trace_nbd_co_send_structured_error(handle, nbd_err,
1777 nbd_err_lookup(nbd_err), msg ? msg : "");
1778 set_be_chunk(&chunk.h, NBD_REPLY_FLAG_DONE, NBD_REPLY_TYPE_ERROR, handle,
1779 sizeof(chunk) - sizeof(chunk.h) + iov[1].iov_len);
1780 stl_be_p(&chunk.error, nbd_err);
1781 stw_be_p(&chunk.message_length, iov[1].iov_len);
1783 return nbd_co_send_iov(client, iov, 1 + !!iov[1].iov_len, errp);
1786 /* Do a sparse read and send the structured reply to the client.
1787 * Returns -errno if sending fails. bdrv_block_status_above() failure is
1788 * reported to the client, at which point this function succeeds.
1790 static int coroutine_fn nbd_co_send_sparse_read(NBDClient *client,
1791 uint64_t handle,
1792 uint64_t offset,
1793 uint8_t *data,
1794 size_t size,
1795 Error **errp)
1797 int ret = 0;
1798 NBDExport *exp = client->exp;
1799 size_t progress = 0;
1801 while (progress < size) {
1802 int64_t pnum;
1803 int status = bdrv_block_status_above(blk_bs(exp->blk), NULL,
1804 offset + progress,
1805 size - progress, &pnum, NULL,
1806 NULL);
1807 bool final;
1809 if (status < 0) {
1810 char *msg = g_strdup_printf("unable to check for holes: %s",
1811 strerror(-status));
1813 ret = nbd_co_send_structured_error(client, handle, -status, msg,
1814 errp);
1815 g_free(msg);
1816 return ret;
1818 assert(pnum && pnum <= size - progress);
1819 final = progress + pnum == size;
1820 if (status & BDRV_BLOCK_ZERO) {
1821 NBDStructuredReadHole chunk;
1822 struct iovec iov[] = {
1823 {.iov_base = &chunk, .iov_len = sizeof(chunk)},
1826 trace_nbd_co_send_structured_read_hole(handle, offset + progress,
1827 pnum);
1828 set_be_chunk(&chunk.h, final ? NBD_REPLY_FLAG_DONE : 0,
1829 NBD_REPLY_TYPE_OFFSET_HOLE,
1830 handle, sizeof(chunk) - sizeof(chunk.h));
1831 stq_be_p(&chunk.offset, offset + progress);
1832 stl_be_p(&chunk.length, pnum);
1833 ret = nbd_co_send_iov(client, iov, 1, errp);
1834 } else {
1835 ret = blk_pread(exp->blk, offset + progress + exp->dev_offset,
1836 data + progress, pnum);
1837 if (ret < 0) {
1838 error_setg_errno(errp, -ret, "reading from file failed");
1839 break;
1841 ret = nbd_co_send_structured_read(client, handle, offset + progress,
1842 data + progress, pnum, final,
1843 errp);
1846 if (ret < 0) {
1847 break;
1849 progress += pnum;
1851 return ret;
1855 * Populate @extents from block status. Update @bytes to be the actual
1856 * length encoded (which may be smaller than the original), and update
1857 * @nb_extents to the number of extents used.
1859 * Returns zero on success and -errno on bdrv_block_status_above failure.
1861 static int blockstatus_to_extents(BlockDriverState *bs, uint64_t offset,
1862 uint64_t *bytes, NBDExtent *extents,
1863 unsigned int *nb_extents)
1865 uint64_t remaining_bytes = *bytes;
1866 NBDExtent *extent = extents, *extents_end = extents + *nb_extents;
1867 bool first_extent = true;
1869 assert(*nb_extents);
1870 while (remaining_bytes) {
1871 uint32_t flags;
1872 int64_t num;
1873 int ret = bdrv_block_status_above(bs, NULL, offset, remaining_bytes,
1874 &num, NULL, NULL);
1876 if (ret < 0) {
1877 return ret;
1880 flags = (ret & BDRV_BLOCK_ALLOCATED ? 0 : NBD_STATE_HOLE) |
1881 (ret & BDRV_BLOCK_ZERO ? NBD_STATE_ZERO : 0);
1882 offset += num;
1883 remaining_bytes -= num;
1885 if (first_extent) {
1886 extent->flags = flags;
1887 extent->length = num;
1888 first_extent = false;
1889 continue;
1892 if (flags == extent->flags) {
1893 /* extend current extent */
1894 extent->length += num;
1895 } else {
1896 if (extent + 1 == extents_end) {
1897 break;
1900 /* start new extent */
1901 extent++;
1902 extent->flags = flags;
1903 extent->length = num;
1907 extents_end = extent + 1;
1909 for (extent = extents; extent < extents_end; extent++) {
1910 extent->flags = cpu_to_be32(extent->flags);
1911 extent->length = cpu_to_be32(extent->length);
1914 *bytes -= remaining_bytes;
1915 *nb_extents = extents_end - extents;
1917 return 0;
1920 /* nbd_co_send_extents
1922 * @length is only for tracing purposes (and may be smaller or larger
1923 * than the client's original request). @last controls whether
1924 * NBD_REPLY_FLAG_DONE is sent. @extents should already be in
1925 * big-endian format.
1927 static int nbd_co_send_extents(NBDClient *client, uint64_t handle,
1928 NBDExtent *extents, unsigned int nb_extents,
1929 uint64_t length, bool last,
1930 uint32_t context_id, Error **errp)
1932 NBDStructuredMeta chunk;
1934 struct iovec iov[] = {
1935 {.iov_base = &chunk, .iov_len = sizeof(chunk)},
1936 {.iov_base = extents, .iov_len = nb_extents * sizeof(extents[0])}
1939 trace_nbd_co_send_extents(handle, nb_extents, context_id, length, last);
1940 set_be_chunk(&chunk.h, last ? NBD_REPLY_FLAG_DONE : 0,
1941 NBD_REPLY_TYPE_BLOCK_STATUS,
1942 handle, sizeof(chunk) - sizeof(chunk.h) + iov[1].iov_len);
1943 stl_be_p(&chunk.context_id, context_id);
1945 return nbd_co_send_iov(client, iov, 2, errp);
1948 /* Get block status from the exported device and send it to the client */
1949 static int nbd_co_send_block_status(NBDClient *client, uint64_t handle,
1950 BlockDriverState *bs, uint64_t offset,
1951 uint32_t length, bool dont_fragment,
1952 bool last, uint32_t context_id,
1953 Error **errp)
1955 int ret;
1956 unsigned int nb_extents = dont_fragment ? 1 : NBD_MAX_BITMAP_EXTENTS;
1957 NBDExtent *extents = g_new(NBDExtent, nb_extents);
1958 uint64_t final_length = length;
1960 ret = blockstatus_to_extents(bs, offset, &final_length, extents,
1961 &nb_extents);
1962 if (ret < 0) {
1963 g_free(extents);
1964 return nbd_co_send_structured_error(
1965 client, handle, -ret, "can't get block status", errp);
1968 ret = nbd_co_send_extents(client, handle, extents, nb_extents,
1969 final_length, last, context_id, errp);
1971 g_free(extents);
1973 return ret;
1977 * Populate @extents from a dirty bitmap. Unless @dont_fragment, the
1978 * final extent may exceed the original @length. Store in @length the
1979 * byte length encoded (which may be smaller or larger than the
1980 * original), and return the number of extents used.
1982 static unsigned int bitmap_to_extents(BdrvDirtyBitmap *bitmap, uint64_t offset,
1983 uint64_t *length, NBDExtent *extents,
1984 unsigned int nb_extents,
1985 bool dont_fragment)
1987 uint64_t begin = offset, end = offset;
1988 uint64_t overall_end = offset + *length;
1989 unsigned int i = 0;
1990 BdrvDirtyBitmapIter *it;
1991 bool dirty;
1993 bdrv_dirty_bitmap_lock(bitmap);
1995 it = bdrv_dirty_iter_new(bitmap);
1996 dirty = bdrv_get_dirty_locked(NULL, bitmap, offset);
1998 assert(begin < overall_end && nb_extents);
1999 while (begin < overall_end && i < nb_extents) {
2000 bool next_dirty = !dirty;
2002 if (dirty) {
2003 end = bdrv_dirty_bitmap_next_zero(bitmap, begin, UINT64_MAX);
2004 } else {
2005 bdrv_set_dirty_iter(it, begin);
2006 end = bdrv_dirty_iter_next(it);
2008 if (end == -1 || end - begin > UINT32_MAX) {
2009 /* Cap to an aligned value < 4G beyond begin. */
2010 end = MIN(bdrv_dirty_bitmap_size(bitmap),
2011 begin + UINT32_MAX + 1 -
2012 bdrv_dirty_bitmap_granularity(bitmap));
2013 next_dirty = dirty;
2015 if (dont_fragment && end > overall_end) {
2016 end = overall_end;
2019 extents[i].length = cpu_to_be32(end - begin);
2020 extents[i].flags = cpu_to_be32(dirty ? NBD_STATE_DIRTY : 0);
2021 i++;
2022 begin = end;
2023 dirty = next_dirty;
2026 bdrv_dirty_iter_free(it);
2028 bdrv_dirty_bitmap_unlock(bitmap);
2030 assert(offset < end);
2031 *length = end - offset;
2032 return i;
2035 static int nbd_co_send_bitmap(NBDClient *client, uint64_t handle,
2036 BdrvDirtyBitmap *bitmap, uint64_t offset,
2037 uint32_t length, bool dont_fragment, bool last,
2038 uint32_t context_id, Error **errp)
2040 int ret;
2041 unsigned int nb_extents = dont_fragment ? 1 : NBD_MAX_BITMAP_EXTENTS;
2042 NBDExtent *extents = g_new(NBDExtent, nb_extents);
2043 uint64_t final_length = length;
2045 nb_extents = bitmap_to_extents(bitmap, offset, &final_length, extents,
2046 nb_extents, dont_fragment);
2048 ret = nbd_co_send_extents(client, handle, extents, nb_extents,
2049 final_length, last, context_id, errp);
2051 g_free(extents);
2053 return ret;
2056 /* nbd_co_receive_request
2057 * Collect a client request. Return 0 if request looks valid, -EIO to drop
2058 * connection right away, and any other negative value to report an error to
2059 * the client (although the caller may still need to disconnect after reporting
2060 * the error).
2062 static int nbd_co_receive_request(NBDRequestData *req, NBDRequest *request,
2063 Error **errp)
2065 NBDClient *client = req->client;
2066 int valid_flags;
2068 g_assert(qemu_in_coroutine());
2069 assert(client->recv_coroutine == qemu_coroutine_self());
2070 if (nbd_receive_request(client->ioc, request, errp) < 0) {
2071 return -EIO;
2074 trace_nbd_co_receive_request_decode_type(request->handle, request->type,
2075 nbd_cmd_lookup(request->type));
2077 if (request->type != NBD_CMD_WRITE) {
2078 /* No payload, we are ready to read the next request. */
2079 req->complete = true;
2082 if (request->type == NBD_CMD_DISC) {
2083 /* Special case: we're going to disconnect without a reply,
2084 * whether or not flags, from, or len are bogus */
2085 return -EIO;
2088 if (request->type == NBD_CMD_READ || request->type == NBD_CMD_WRITE ||
2089 request->type == NBD_CMD_CACHE)
2091 if (request->len > NBD_MAX_BUFFER_SIZE) {
2092 error_setg(errp, "len (%" PRIu32" ) is larger than max len (%u)",
2093 request->len, NBD_MAX_BUFFER_SIZE);
2094 return -EINVAL;
2097 req->data = blk_try_blockalign(client->exp->blk, request->len);
2098 if (req->data == NULL) {
2099 error_setg(errp, "No memory");
2100 return -ENOMEM;
2103 if (request->type == NBD_CMD_WRITE) {
2104 if (nbd_read(client->ioc, req->data, request->len, "CMD_WRITE data",
2105 errp) < 0)
2107 return -EIO;
2109 req->complete = true;
2111 trace_nbd_co_receive_request_payload_received(request->handle,
2112 request->len);
2115 /* Sanity checks. */
2116 if (client->exp->nbdflags & NBD_FLAG_READ_ONLY &&
2117 (request->type == NBD_CMD_WRITE ||
2118 request->type == NBD_CMD_WRITE_ZEROES ||
2119 request->type == NBD_CMD_TRIM)) {
2120 error_setg(errp, "Export is read-only");
2121 return -EROFS;
2123 if (request->from > client->exp->size ||
2124 request->len > client->exp->size - request->from) {
2125 error_setg(errp, "operation past EOF; From: %" PRIu64 ", Len: %" PRIu32
2126 ", Size: %" PRIu64, request->from, request->len,
2127 client->exp->size);
2128 return (request->type == NBD_CMD_WRITE ||
2129 request->type == NBD_CMD_WRITE_ZEROES) ? -ENOSPC : -EINVAL;
2131 valid_flags = NBD_CMD_FLAG_FUA;
2132 if (request->type == NBD_CMD_READ && client->structured_reply) {
2133 valid_flags |= NBD_CMD_FLAG_DF;
2134 } else if (request->type == NBD_CMD_WRITE_ZEROES) {
2135 valid_flags |= NBD_CMD_FLAG_NO_HOLE;
2136 } else if (request->type == NBD_CMD_BLOCK_STATUS) {
2137 valid_flags |= NBD_CMD_FLAG_REQ_ONE;
2139 if (request->flags & ~valid_flags) {
2140 error_setg(errp, "unsupported flags for command %s (got 0x%x)",
2141 nbd_cmd_lookup(request->type), request->flags);
2142 return -EINVAL;
2145 return 0;
2148 /* Send simple reply without a payload, or a structured error
2149 * @error_msg is ignored if @ret >= 0
2150 * Returns 0 if connection is still live, -errno on failure to talk to client
2152 static coroutine_fn int nbd_send_generic_reply(NBDClient *client,
2153 uint64_t handle,
2154 int ret,
2155 const char *error_msg,
2156 Error **errp)
2158 if (client->structured_reply && ret < 0) {
2159 return nbd_co_send_structured_error(client, handle, -ret, error_msg,
2160 errp);
2161 } else {
2162 return nbd_co_send_simple_reply(client, handle, ret < 0 ? -ret : 0,
2163 NULL, 0, errp);
2167 /* Handle NBD_CMD_READ request.
2168 * Return -errno if sending fails. Other errors are reported directly to the
2169 * client as an error reply. */
2170 static coroutine_fn int nbd_do_cmd_read(NBDClient *client, NBDRequest *request,
2171 uint8_t *data, Error **errp)
2173 int ret;
2174 NBDExport *exp = client->exp;
2176 assert(request->type == NBD_CMD_READ || request->type == NBD_CMD_CACHE);
2178 /* XXX: NBD Protocol only documents use of FUA with WRITE */
2179 if (request->flags & NBD_CMD_FLAG_FUA) {
2180 ret = blk_co_flush(exp->blk);
2181 if (ret < 0) {
2182 return nbd_send_generic_reply(client, request->handle, ret,
2183 "flush failed", errp);
2187 if (client->structured_reply && !(request->flags & NBD_CMD_FLAG_DF) &&
2188 request->len && request->type != NBD_CMD_CACHE)
2190 return nbd_co_send_sparse_read(client, request->handle, request->from,
2191 data, request->len, errp);
2194 ret = blk_pread(exp->blk, request->from + exp->dev_offset, data,
2195 request->len);
2196 if (ret < 0 || request->type == NBD_CMD_CACHE) {
2197 return nbd_send_generic_reply(client, request->handle, ret,
2198 "reading from file failed", errp);
2201 if (client->structured_reply) {
2202 if (request->len) {
2203 return nbd_co_send_structured_read(client, request->handle,
2204 request->from, data,
2205 request->len, true, errp);
2206 } else {
2207 return nbd_co_send_structured_done(client, request->handle, errp);
2209 } else {
2210 return nbd_co_send_simple_reply(client, request->handle, 0,
2211 data, request->len, errp);
2215 /* Handle NBD request.
2216 * Return -errno if sending fails. Other errors are reported directly to the
2217 * client as an error reply. */
2218 static coroutine_fn int nbd_handle_request(NBDClient *client,
2219 NBDRequest *request,
2220 uint8_t *data, Error **errp)
2222 int ret;
2223 int flags;
2224 NBDExport *exp = client->exp;
2225 char *msg;
2227 switch (request->type) {
2228 case NBD_CMD_READ:
2229 case NBD_CMD_CACHE:
2230 return nbd_do_cmd_read(client, request, data, errp);
2232 case NBD_CMD_WRITE:
2233 flags = 0;
2234 if (request->flags & NBD_CMD_FLAG_FUA) {
2235 flags |= BDRV_REQ_FUA;
2237 ret = blk_pwrite(exp->blk, request->from + exp->dev_offset,
2238 data, request->len, flags);
2239 return nbd_send_generic_reply(client, request->handle, ret,
2240 "writing to file failed", errp);
2242 case NBD_CMD_WRITE_ZEROES:
2243 flags = 0;
2244 if (request->flags & NBD_CMD_FLAG_FUA) {
2245 flags |= BDRV_REQ_FUA;
2247 if (!(request->flags & NBD_CMD_FLAG_NO_HOLE)) {
2248 flags |= BDRV_REQ_MAY_UNMAP;
2250 ret = blk_pwrite_zeroes(exp->blk, request->from + exp->dev_offset,
2251 request->len, flags);
2252 return nbd_send_generic_reply(client, request->handle, ret,
2253 "writing to file failed", errp);
2255 case NBD_CMD_DISC:
2256 /* unreachable, thanks to special case in nbd_co_receive_request() */
2257 abort();
2259 case NBD_CMD_FLUSH:
2260 ret = blk_co_flush(exp->blk);
2261 return nbd_send_generic_reply(client, request->handle, ret,
2262 "flush failed", errp);
2264 case NBD_CMD_TRIM:
2265 ret = blk_co_pdiscard(exp->blk, request->from + exp->dev_offset,
2266 request->len);
2267 if (ret == 0 && request->flags & NBD_CMD_FLAG_FUA) {
2268 ret = blk_co_flush(exp->blk);
2270 return nbd_send_generic_reply(client, request->handle, ret,
2271 "discard failed", errp);
2273 case NBD_CMD_BLOCK_STATUS:
2274 if (!request->len) {
2275 return nbd_send_generic_reply(client, request->handle, -EINVAL,
2276 "need non-zero length", errp);
2278 if (client->export_meta.valid &&
2279 (client->export_meta.base_allocation ||
2280 client->export_meta.bitmap))
2282 bool dont_fragment = request->flags & NBD_CMD_FLAG_REQ_ONE;
2284 if (client->export_meta.base_allocation) {
2285 ret = nbd_co_send_block_status(client, request->handle,
2286 blk_bs(exp->blk), request->from,
2287 request->len, dont_fragment,
2288 !client->export_meta.bitmap,
2289 NBD_META_ID_BASE_ALLOCATION,
2290 errp);
2291 if (ret < 0) {
2292 return ret;
2296 if (client->export_meta.bitmap) {
2297 ret = nbd_co_send_bitmap(client, request->handle,
2298 client->exp->export_bitmap,
2299 request->from, request->len,
2300 dont_fragment,
2301 true, NBD_META_ID_DIRTY_BITMAP, errp);
2302 if (ret < 0) {
2303 return ret;
2307 return ret;
2308 } else {
2309 return nbd_send_generic_reply(client, request->handle, -EINVAL,
2310 "CMD_BLOCK_STATUS not negotiated",
2311 errp);
2314 default:
2315 msg = g_strdup_printf("invalid request type (%" PRIu32 ") received",
2316 request->type);
2317 ret = nbd_send_generic_reply(client, request->handle, -EINVAL, msg,
2318 errp);
2319 g_free(msg);
2320 return ret;
2324 /* Owns a reference to the NBDClient passed as opaque. */
2325 static coroutine_fn void nbd_trip(void *opaque)
2327 NBDClient *client = opaque;
2328 NBDRequestData *req;
2329 NBDRequest request = { 0 }; /* GCC thinks it can be used uninitialized */
2330 int ret;
2331 Error *local_err = NULL;
2333 trace_nbd_trip();
2334 if (client->closing) {
2335 nbd_client_put(client);
2336 return;
2339 req = nbd_request_get(client);
2340 ret = nbd_co_receive_request(req, &request, &local_err);
2341 client->recv_coroutine = NULL;
2343 if (client->closing) {
2345 * The client may be closed when we are blocked in
2346 * nbd_co_receive_request()
2348 goto done;
2351 nbd_client_receive_next_request(client);
2352 if (ret == -EIO) {
2353 goto disconnect;
2356 if (ret < 0) {
2357 /* It wans't -EIO, so, according to nbd_co_receive_request()
2358 * semantics, we should return the error to the client. */
2359 Error *export_err = local_err;
2361 local_err = NULL;
2362 ret = nbd_send_generic_reply(client, request.handle, -EINVAL,
2363 error_get_pretty(export_err), &local_err);
2364 error_free(export_err);
2365 } else {
2366 ret = nbd_handle_request(client, &request, req->data, &local_err);
2368 if (ret < 0) {
2369 error_prepend(&local_err, "Failed to send reply: ");
2370 goto disconnect;
2373 /* We must disconnect after NBD_CMD_WRITE if we did not
2374 * read the payload.
2376 if (!req->complete) {
2377 error_setg(&local_err, "Request handling failed in intermediate state");
2378 goto disconnect;
2381 done:
2382 nbd_request_put(req);
2383 nbd_client_put(client);
2384 return;
2386 disconnect:
2387 if (local_err) {
2388 error_reportf_err(local_err, "Disconnect client, due to: ");
2390 nbd_request_put(req);
2391 client_close(client, true);
2392 nbd_client_put(client);
2395 static void nbd_client_receive_next_request(NBDClient *client)
2397 if (!client->recv_coroutine && client->nb_requests < MAX_NBD_REQUESTS) {
2398 nbd_client_get(client);
2399 client->recv_coroutine = qemu_coroutine_create(nbd_trip, client);
2400 aio_co_schedule(client->exp->ctx, client->recv_coroutine);
2404 static coroutine_fn void nbd_co_client_start(void *opaque)
2406 NBDClient *client = opaque;
2407 Error *local_err = NULL;
2409 qemu_co_mutex_init(&client->send_lock);
2411 if (nbd_negotiate(client, &local_err)) {
2412 if (local_err) {
2413 error_report_err(local_err);
2415 client_close(client, false);
2416 return;
2419 nbd_client_receive_next_request(client);
2423 * Create a new client listener using the given channel @sioc.
2424 * Begin servicing it in a coroutine. When the connection closes, call
2425 * @close_fn with an indication of whether the client completed negotiation.
2427 void nbd_client_new(QIOChannelSocket *sioc,
2428 QCryptoTLSCreds *tlscreds,
2429 const char *tlsaclname,
2430 void (*close_fn)(NBDClient *, bool))
2432 NBDClient *client;
2433 Coroutine *co;
2435 client = g_new0(NBDClient, 1);
2436 client->refcount = 1;
2437 client->tlscreds = tlscreds;
2438 if (tlscreds) {
2439 object_ref(OBJECT(client->tlscreds));
2441 client->tlsaclname = g_strdup(tlsaclname);
2442 client->sioc = sioc;
2443 object_ref(OBJECT(client->sioc));
2444 client->ioc = QIO_CHANNEL(sioc);
2445 object_ref(OBJECT(client->ioc));
2446 client->close_fn = close_fn;
2448 co = qemu_coroutine_create(nbd_co_client_start, client);
2449 qemu_coroutine_enter(co);