target/arm: Create ARMVAParameters and helpers
[qemu/ar7.git] / nbd / server.c
blob6b136019f829a6c8c668d46f7a2e0fedf7d74e56
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 off_t dev_offset;
81 off_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, errp) < 0) {
442 error_prepend(errp, "read failed: ");
443 return -EIO;
445 name[client->optlen] = '\0';
446 client->optlen = 0;
448 trace_nbd_negotiate_handle_export_name_request(name);
450 client->exp = nbd_export_find(name);
451 if (!client->exp) {
452 error_setg(errp, "export not found");
453 return -EINVAL;
456 trace_nbd_negotiate_new_style_size_flags(client->exp->size,
457 client->exp->nbdflags | myflags);
458 stq_be_p(buf, client->exp->size);
459 stw_be_p(buf + 8, client->exp->nbdflags | myflags);
460 len = no_zeroes ? 10 : sizeof(buf);
461 ret = nbd_write(client->ioc, buf, len, errp);
462 if (ret < 0) {
463 error_prepend(errp, "write failed: ");
464 return ret;
467 QTAILQ_INSERT_TAIL(&client->exp->clients, client, next);
468 nbd_export_get(client->exp);
469 nbd_check_meta_export(client);
471 return 0;
474 /* Send a single NBD_REP_INFO, with a buffer @buf of @length bytes.
475 * The buffer does NOT include the info type prefix.
476 * Return -errno on error, 0 if ready to send more. */
477 static int nbd_negotiate_send_info(NBDClient *client,
478 uint16_t info, uint32_t length, void *buf,
479 Error **errp)
481 int rc;
483 trace_nbd_negotiate_send_info(info, nbd_info_lookup(info), length);
484 rc = nbd_negotiate_send_rep_len(client, NBD_REP_INFO,
485 sizeof(info) + length, errp);
486 if (rc < 0) {
487 return rc;
489 info = cpu_to_be16(info);
490 if (nbd_write(client->ioc, &info, sizeof(info), errp) < 0) {
491 return -EIO;
493 if (nbd_write(client->ioc, buf, length, errp) < 0) {
494 return -EIO;
496 return 0;
499 /* nbd_reject_length: Handle any unexpected payload.
500 * @fatal requests that we quit talking to the client, even if we are able
501 * to successfully send an error reply.
502 * Return:
503 * -errno transmission error occurred or @fatal was requested, errp is set
504 * 0 error message successfully sent to client, errp is not set
506 static int nbd_reject_length(NBDClient *client, bool fatal, Error **errp)
508 int ret;
510 assert(client->optlen);
511 ret = nbd_opt_invalid(client, errp, "option '%s' has unexpected length",
512 nbd_opt_lookup(client->opt));
513 if (fatal && !ret) {
514 error_setg(errp, "option '%s' has unexpected length",
515 nbd_opt_lookup(client->opt));
516 return -EINVAL;
518 return ret;
521 /* Handle NBD_OPT_INFO and NBD_OPT_GO.
522 * Return -errno on error, 0 if ready for next option, and 1 to move
523 * into transmission phase. */
524 static int nbd_negotiate_handle_info(NBDClient *client, uint16_t myflags,
525 Error **errp)
527 int rc;
528 char name[NBD_MAX_NAME_SIZE + 1];
529 NBDExport *exp;
530 uint16_t requests;
531 uint16_t request;
532 uint32_t namelen;
533 bool sendname = false;
534 bool blocksize = false;
535 uint32_t sizes[3];
536 char buf[sizeof(uint64_t) + sizeof(uint16_t)];
538 /* Client sends:
539 4 bytes: L, name length (can be 0)
540 L bytes: export name
541 2 bytes: N, number of requests (can be 0)
542 N * 2 bytes: N requests
544 rc = nbd_opt_read_name(client, name, &namelen, errp);
545 if (rc <= 0) {
546 return rc;
548 trace_nbd_negotiate_handle_export_name_request(name);
550 rc = nbd_opt_read(client, &requests, sizeof(requests), errp);
551 if (rc <= 0) {
552 return rc;
554 requests = be16_to_cpu(requests);
555 trace_nbd_negotiate_handle_info_requests(requests);
556 while (requests--) {
557 rc = nbd_opt_read(client, &request, sizeof(request), errp);
558 if (rc <= 0) {
559 return rc;
561 request = be16_to_cpu(request);
562 trace_nbd_negotiate_handle_info_request(request,
563 nbd_info_lookup(request));
564 /* We care about NBD_INFO_NAME and NBD_INFO_BLOCK_SIZE;
565 * everything else is either a request we don't know or
566 * something we send regardless of request */
567 switch (request) {
568 case NBD_INFO_NAME:
569 sendname = true;
570 break;
571 case NBD_INFO_BLOCK_SIZE:
572 blocksize = true;
573 break;
576 if (client->optlen) {
577 return nbd_reject_length(client, false, errp);
580 exp = nbd_export_find(name);
581 if (!exp) {
582 return nbd_negotiate_send_rep_err(client, NBD_REP_ERR_UNKNOWN,
583 errp, "export '%s' not present",
584 name);
587 /* Don't bother sending NBD_INFO_NAME unless client requested it */
588 if (sendname) {
589 rc = nbd_negotiate_send_info(client, NBD_INFO_NAME, namelen, name,
590 errp);
591 if (rc < 0) {
592 return rc;
596 /* Send NBD_INFO_DESCRIPTION only if available, regardless of
597 * client request */
598 if (exp->description) {
599 size_t len = strlen(exp->description);
601 rc = nbd_negotiate_send_info(client, NBD_INFO_DESCRIPTION,
602 len, exp->description, errp);
603 if (rc < 0) {
604 return rc;
608 /* Send NBD_INFO_BLOCK_SIZE always, but tweak the minimum size
609 * according to whether the client requested it, and according to
610 * whether this is OPT_INFO or OPT_GO. */
611 /* minimum - 1 for back-compat, or 512 if client is new enough.
612 * TODO: consult blk_bs(blk)->bl.request_alignment? */
613 sizes[0] =
614 (client->opt == NBD_OPT_INFO || blocksize) ? BDRV_SECTOR_SIZE : 1;
615 /* preferred - Hard-code to 4096 for now.
616 * TODO: is blk_bs(blk)->bl.opt_transfer appropriate? */
617 sizes[1] = 4096;
618 /* maximum - At most 32M, but smaller as appropriate. */
619 sizes[2] = MIN(blk_get_max_transfer(exp->blk), NBD_MAX_BUFFER_SIZE);
620 trace_nbd_negotiate_handle_info_block_size(sizes[0], sizes[1], sizes[2]);
621 sizes[0] = cpu_to_be32(sizes[0]);
622 sizes[1] = cpu_to_be32(sizes[1]);
623 sizes[2] = cpu_to_be32(sizes[2]);
624 rc = nbd_negotiate_send_info(client, NBD_INFO_BLOCK_SIZE,
625 sizeof(sizes), sizes, errp);
626 if (rc < 0) {
627 return rc;
630 /* Send NBD_INFO_EXPORT always */
631 trace_nbd_negotiate_new_style_size_flags(exp->size,
632 exp->nbdflags | myflags);
633 stq_be_p(buf, exp->size);
634 stw_be_p(buf + 8, exp->nbdflags | myflags);
635 rc = nbd_negotiate_send_info(client, NBD_INFO_EXPORT,
636 sizeof(buf), buf, errp);
637 if (rc < 0) {
638 return rc;
641 /* If the client is just asking for NBD_OPT_INFO, but forgot to
642 * request block sizes, return an error.
643 * TODO: consult blk_bs(blk)->request_align, and only error if it
644 * is not 1? */
645 if (client->opt == NBD_OPT_INFO && !blocksize) {
646 return nbd_negotiate_send_rep_err(client,
647 NBD_REP_ERR_BLOCK_SIZE_REQD,
648 errp,
649 "request NBD_INFO_BLOCK_SIZE to "
650 "use this export");
653 /* Final reply */
654 rc = nbd_negotiate_send_rep(client, NBD_REP_ACK, errp);
655 if (rc < 0) {
656 return rc;
659 if (client->opt == NBD_OPT_GO) {
660 client->exp = exp;
661 QTAILQ_INSERT_TAIL(&client->exp->clients, client, next);
662 nbd_export_get(client->exp);
663 nbd_check_meta_export(client);
664 rc = 1;
666 return rc;
670 /* Handle NBD_OPT_STARTTLS. Return NULL to drop connection, or else the
671 * new channel for all further (now-encrypted) communication. */
672 static QIOChannel *nbd_negotiate_handle_starttls(NBDClient *client,
673 Error **errp)
675 QIOChannel *ioc;
676 QIOChannelTLS *tioc;
677 struct NBDTLSHandshakeData data = { 0 };
679 assert(client->opt == NBD_OPT_STARTTLS);
681 trace_nbd_negotiate_handle_starttls();
682 ioc = client->ioc;
684 if (nbd_negotiate_send_rep(client, NBD_REP_ACK, errp) < 0) {
685 return NULL;
688 tioc = qio_channel_tls_new_server(ioc,
689 client->tlscreds,
690 client->tlsaclname,
691 errp);
692 if (!tioc) {
693 return NULL;
696 qio_channel_set_name(QIO_CHANNEL(tioc), "nbd-server-tls");
697 trace_nbd_negotiate_handle_starttls_handshake();
698 data.loop = g_main_loop_new(g_main_context_default(), FALSE);
699 qio_channel_tls_handshake(tioc,
700 nbd_tls_handshake,
701 &data,
702 NULL,
703 NULL);
705 if (!data.complete) {
706 g_main_loop_run(data.loop);
708 g_main_loop_unref(data.loop);
709 if (data.error) {
710 object_unref(OBJECT(tioc));
711 error_propagate(errp, data.error);
712 return NULL;
715 return QIO_CHANNEL(tioc);
718 /* nbd_negotiate_send_meta_context
720 * Send one chunk of reply to NBD_OPT_{LIST,SET}_META_CONTEXT
722 * For NBD_OPT_LIST_META_CONTEXT @context_id is ignored, 0 is used instead.
724 static int nbd_negotiate_send_meta_context(NBDClient *client,
725 const char *context,
726 uint32_t context_id,
727 Error **errp)
729 NBDOptionReplyMetaContext opt;
730 struct iovec iov[] = {
731 {.iov_base = &opt, .iov_len = sizeof(opt)},
732 {.iov_base = (void *)context, .iov_len = strlen(context)}
735 if (client->opt == NBD_OPT_LIST_META_CONTEXT) {
736 context_id = 0;
739 trace_nbd_negotiate_meta_query_reply(context, context_id);
740 set_be_option_rep(&opt.h, client->opt, NBD_REP_META_CONTEXT,
741 sizeof(opt) - sizeof(opt.h) + iov[1].iov_len);
742 stl_be_p(&opt.context_id, context_id);
744 return qio_channel_writev_all(client->ioc, iov, 2, errp) < 0 ? -EIO : 0;
747 /* Read strlen(@pattern) bytes, and set @match to true if they match @pattern.
748 * @match is never set to false.
750 * Return -errno on I/O error, 0 if option was completely handled by
751 * sending a reply about inconsistent lengths, or 1 on success.
753 * Note: return code = 1 doesn't mean that we've read exactly @pattern.
754 * It only means that there are no errors.
756 static int nbd_meta_pattern(NBDClient *client, const char *pattern, bool *match,
757 Error **errp)
759 int ret;
760 char *query;
761 size_t len = strlen(pattern);
763 assert(len);
765 query = g_malloc(len);
766 ret = nbd_opt_read(client, query, len, errp);
767 if (ret <= 0) {
768 g_free(query);
769 return ret;
772 if (strncmp(query, pattern, len) == 0) {
773 trace_nbd_negotiate_meta_query_parse(pattern);
774 *match = true;
775 } else {
776 trace_nbd_negotiate_meta_query_skip("pattern not matched");
778 g_free(query);
780 return 1;
784 * Read @len bytes, and set @match to true if they match @pattern, or if @len
785 * is 0 and the client is performing _LIST_. @match is never set to false.
787 * Return -errno on I/O error, 0 if option was completely handled by
788 * sending a reply about inconsistent lengths, or 1 on success.
790 * Note: return code = 1 doesn't mean that we've read exactly @pattern.
791 * It only means that there are no errors.
793 static int nbd_meta_empty_or_pattern(NBDClient *client, const char *pattern,
794 uint32_t len, bool *match, Error **errp)
796 if (len == 0) {
797 if (client->opt == NBD_OPT_LIST_META_CONTEXT) {
798 *match = true;
800 trace_nbd_negotiate_meta_query_parse("empty");
801 return 1;
804 if (len != strlen(pattern)) {
805 trace_nbd_negotiate_meta_query_skip("different lengths");
806 return nbd_opt_skip(client, len, errp);
809 return nbd_meta_pattern(client, pattern, match, errp);
812 /* nbd_meta_base_query
814 * Handle queries to 'base' namespace. For now, only the base:allocation
815 * context is available. 'len' is the amount of text remaining to be read from
816 * the current name, after the 'base:' portion has been stripped.
818 * Return -errno on I/O error, 0 if option was completely handled by
819 * sending a reply about inconsistent lengths, or 1 on success.
821 static int nbd_meta_base_query(NBDClient *client, NBDExportMetaContexts *meta,
822 uint32_t len, Error **errp)
824 return nbd_meta_empty_or_pattern(client, "allocation", len,
825 &meta->base_allocation, errp);
828 /* nbd_meta_bitmap_query
830 * Handle query to 'qemu:' namespace.
831 * @len is the amount of text remaining to be read from the current name, after
832 * the 'qemu:' portion has been stripped.
834 * Return -errno on I/O error, 0 if option was completely handled by
835 * sending a reply about inconsistent lengths, or 1 on success. */
836 static int nbd_meta_qemu_query(NBDClient *client, NBDExportMetaContexts *meta,
837 uint32_t len, Error **errp)
839 bool dirty_bitmap = false;
840 size_t dirty_bitmap_len = strlen("dirty-bitmap:");
841 int ret;
843 if (!meta->exp->export_bitmap) {
844 trace_nbd_negotiate_meta_query_skip("no dirty-bitmap exported");
845 return nbd_opt_skip(client, len, errp);
848 if (len == 0) {
849 if (client->opt == NBD_OPT_LIST_META_CONTEXT) {
850 meta->bitmap = true;
852 trace_nbd_negotiate_meta_query_parse("empty");
853 return 1;
856 if (len < dirty_bitmap_len) {
857 trace_nbd_negotiate_meta_query_skip("not dirty-bitmap:");
858 return nbd_opt_skip(client, len, errp);
861 len -= dirty_bitmap_len;
862 ret = nbd_meta_pattern(client, "dirty-bitmap:", &dirty_bitmap, errp);
863 if (ret <= 0) {
864 return ret;
866 if (!dirty_bitmap) {
867 trace_nbd_negotiate_meta_query_skip("not dirty-bitmap:");
868 return nbd_opt_skip(client, len, errp);
871 trace_nbd_negotiate_meta_query_parse("dirty-bitmap:");
873 return nbd_meta_empty_or_pattern(
874 client, meta->exp->export_bitmap_context +
875 strlen("qemu:dirty_bitmap:"), len, &meta->bitmap, errp);
878 /* nbd_negotiate_meta_query
880 * Parse namespace name and call corresponding function to parse body of the
881 * query.
883 * The only supported namespace now is 'base'.
885 * The function aims not wasting time and memory to read long unknown namespace
886 * names.
888 * Return -errno on I/O error, 0 if option was completely handled by
889 * sending a reply about inconsistent lengths, or 1 on success. */
890 static int nbd_negotiate_meta_query(NBDClient *client,
891 NBDExportMetaContexts *meta, Error **errp)
894 * Both 'qemu' and 'base' namespaces have length = 5 including a
895 * colon. If another length namespace is later introduced, this
896 * should certainly be refactored.
898 int ret;
899 size_t ns_len = 5;
900 char ns[5];
901 uint32_t len;
903 ret = nbd_opt_read(client, &len, sizeof(len), errp);
904 if (ret <= 0) {
905 return ret;
907 len = cpu_to_be32(len);
909 if (len < ns_len) {
910 trace_nbd_negotiate_meta_query_skip("length too short");
911 return nbd_opt_skip(client, len, errp);
914 len -= ns_len;
915 ret = nbd_opt_read(client, ns, ns_len, errp);
916 if (ret <= 0) {
917 return ret;
920 if (!strncmp(ns, "base:", ns_len)) {
921 trace_nbd_negotiate_meta_query_parse("base:");
922 return nbd_meta_base_query(client, meta, len, errp);
923 } else if (!strncmp(ns, "qemu:", ns_len)) {
924 trace_nbd_negotiate_meta_query_parse("qemu:");
925 return nbd_meta_qemu_query(client, meta, len, errp);
928 trace_nbd_negotiate_meta_query_skip("unknown namespace");
929 return nbd_opt_skip(client, len, errp);
932 /* nbd_negotiate_meta_queries
933 * Handle NBD_OPT_LIST_META_CONTEXT and NBD_OPT_SET_META_CONTEXT
935 * Return -errno on I/O error, or 0 if option was completely handled. */
936 static int nbd_negotiate_meta_queries(NBDClient *client,
937 NBDExportMetaContexts *meta, Error **errp)
939 int ret;
940 char export_name[NBD_MAX_NAME_SIZE + 1];
941 NBDExportMetaContexts local_meta;
942 uint32_t nb_queries;
943 int i;
945 if (!client->structured_reply) {
946 return nbd_opt_invalid(client, errp,
947 "request option '%s' when structured reply "
948 "is not negotiated",
949 nbd_opt_lookup(client->opt));
952 if (client->opt == NBD_OPT_LIST_META_CONTEXT) {
953 /* Only change the caller's meta on SET. */
954 meta = &local_meta;
957 memset(meta, 0, sizeof(*meta));
959 ret = nbd_opt_read_name(client, export_name, NULL, errp);
960 if (ret <= 0) {
961 return ret;
964 meta->exp = nbd_export_find(export_name);
965 if (meta->exp == NULL) {
966 return nbd_opt_drop(client, NBD_REP_ERR_UNKNOWN, errp,
967 "export '%s' not present", export_name);
970 ret = nbd_opt_read(client, &nb_queries, sizeof(nb_queries), errp);
971 if (ret <= 0) {
972 return ret;
974 nb_queries = cpu_to_be32(nb_queries);
975 trace_nbd_negotiate_meta_context(nbd_opt_lookup(client->opt),
976 export_name, nb_queries);
978 if (client->opt == NBD_OPT_LIST_META_CONTEXT && !nb_queries) {
979 /* enable all known contexts */
980 meta->base_allocation = true;
981 meta->bitmap = !!meta->exp->export_bitmap;
982 } else {
983 for (i = 0; i < nb_queries; ++i) {
984 ret = nbd_negotiate_meta_query(client, meta, errp);
985 if (ret <= 0) {
986 return ret;
991 if (meta->base_allocation) {
992 ret = nbd_negotiate_send_meta_context(client, "base:allocation",
993 NBD_META_ID_BASE_ALLOCATION,
994 errp);
995 if (ret < 0) {
996 return ret;
1000 if (meta->bitmap) {
1001 ret = nbd_negotiate_send_meta_context(client,
1002 meta->exp->export_bitmap_context,
1003 NBD_META_ID_DIRTY_BITMAP,
1004 errp);
1005 if (ret < 0) {
1006 return ret;
1010 ret = nbd_negotiate_send_rep(client, NBD_REP_ACK, errp);
1011 if (ret == 0) {
1012 meta->valid = true;
1015 return ret;
1018 /* nbd_negotiate_options
1019 * Process all NBD_OPT_* client option commands, during fixed newstyle
1020 * negotiation.
1021 * Return:
1022 * -errno on error, errp is set
1023 * 0 on successful negotiation, errp is not set
1024 * 1 if client sent NBD_OPT_ABORT, i.e. on valid disconnect,
1025 * errp is not set
1027 static int nbd_negotiate_options(NBDClient *client, uint16_t myflags,
1028 Error **errp)
1030 uint32_t flags;
1031 bool fixedNewstyle = false;
1032 bool no_zeroes = false;
1034 /* Client sends:
1035 [ 0 .. 3] client flags
1037 Then we loop until NBD_OPT_EXPORT_NAME or NBD_OPT_GO:
1038 [ 0 .. 7] NBD_OPTS_MAGIC
1039 [ 8 .. 11] NBD option
1040 [12 .. 15] Data length
1041 ... Rest of request
1043 [ 0 .. 7] NBD_OPTS_MAGIC
1044 [ 8 .. 11] Second NBD option
1045 [12 .. 15] Data length
1046 ... Rest of request
1049 if (nbd_read(client->ioc, &flags, sizeof(flags), errp) < 0) {
1050 error_prepend(errp, "read failed: ");
1051 return -EIO;
1053 flags = be32_to_cpu(flags);
1054 trace_nbd_negotiate_options_flags(flags);
1055 if (flags & NBD_FLAG_C_FIXED_NEWSTYLE) {
1056 fixedNewstyle = true;
1057 flags &= ~NBD_FLAG_C_FIXED_NEWSTYLE;
1059 if (flags & NBD_FLAG_C_NO_ZEROES) {
1060 no_zeroes = true;
1061 flags &= ~NBD_FLAG_C_NO_ZEROES;
1063 if (flags != 0) {
1064 error_setg(errp, "Unknown client flags 0x%" PRIx32 " received", flags);
1065 return -EINVAL;
1068 while (1) {
1069 int ret;
1070 uint32_t option, length;
1071 uint64_t magic;
1073 if (nbd_read(client->ioc, &magic, sizeof(magic), errp) < 0) {
1074 error_prepend(errp, "read failed: ");
1075 return -EINVAL;
1077 magic = be64_to_cpu(magic);
1078 trace_nbd_negotiate_options_check_magic(magic);
1079 if (magic != NBD_OPTS_MAGIC) {
1080 error_setg(errp, "Bad magic received");
1081 return -EINVAL;
1084 if (nbd_read(client->ioc, &option,
1085 sizeof(option), errp) < 0) {
1086 error_prepend(errp, "read failed: ");
1087 return -EINVAL;
1089 option = be32_to_cpu(option);
1090 client->opt = option;
1092 if (nbd_read(client->ioc, &length, sizeof(length), errp) < 0) {
1093 error_prepend(errp, "read failed: ");
1094 return -EINVAL;
1096 length = be32_to_cpu(length);
1097 assert(!client->optlen);
1098 client->optlen = length;
1100 if (length > NBD_MAX_BUFFER_SIZE) {
1101 error_setg(errp, "len (%" PRIu32" ) is larger than max len (%u)",
1102 length, NBD_MAX_BUFFER_SIZE);
1103 return -EINVAL;
1106 trace_nbd_negotiate_options_check_option(option,
1107 nbd_opt_lookup(option));
1108 if (client->tlscreds &&
1109 client->ioc == (QIOChannel *)client->sioc) {
1110 QIOChannel *tioc;
1111 if (!fixedNewstyle) {
1112 error_setg(errp, "Unsupported option 0x%" PRIx32, option);
1113 return -EINVAL;
1115 switch (option) {
1116 case NBD_OPT_STARTTLS:
1117 if (length) {
1118 /* Unconditionally drop the connection if the client
1119 * can't start a TLS negotiation correctly */
1120 return nbd_reject_length(client, true, errp);
1122 tioc = nbd_negotiate_handle_starttls(client, errp);
1123 if (!tioc) {
1124 return -EIO;
1126 ret = 0;
1127 object_unref(OBJECT(client->ioc));
1128 client->ioc = QIO_CHANNEL(tioc);
1129 break;
1131 case NBD_OPT_EXPORT_NAME:
1132 /* No way to return an error to client, so drop connection */
1133 error_setg(errp, "Option 0x%x not permitted before TLS",
1134 option);
1135 return -EINVAL;
1137 default:
1138 /* Let the client keep trying, unless they asked to
1139 * quit. Always try to give an error back to the
1140 * client; but when replying to OPT_ABORT, be aware
1141 * that the client may hang up before receiving the
1142 * error, in which case we are fine ignoring the
1143 * resulting EPIPE. */
1144 ret = nbd_opt_drop(client, NBD_REP_ERR_TLS_REQD,
1145 option == NBD_OPT_ABORT ? NULL : errp,
1146 "Option 0x%" PRIx32
1147 " not permitted before TLS", option);
1148 if (option == NBD_OPT_ABORT) {
1149 return 1;
1151 break;
1153 } else if (fixedNewstyle) {
1154 switch (option) {
1155 case NBD_OPT_LIST:
1156 if (length) {
1157 ret = nbd_reject_length(client, false, errp);
1158 } else {
1159 ret = nbd_negotiate_handle_list(client, errp);
1161 break;
1163 case NBD_OPT_ABORT:
1164 /* NBD spec says we must try to reply before
1165 * disconnecting, but that we must also tolerate
1166 * guests that don't wait for our reply. */
1167 nbd_negotiate_send_rep(client, NBD_REP_ACK, NULL);
1168 return 1;
1170 case NBD_OPT_EXPORT_NAME:
1171 return nbd_negotiate_handle_export_name(client,
1172 myflags, no_zeroes,
1173 errp);
1175 case NBD_OPT_INFO:
1176 case NBD_OPT_GO:
1177 ret = nbd_negotiate_handle_info(client, myflags, errp);
1178 if (ret == 1) {
1179 assert(option == NBD_OPT_GO);
1180 return 0;
1182 break;
1184 case NBD_OPT_STARTTLS:
1185 if (length) {
1186 ret = nbd_reject_length(client, false, errp);
1187 } else if (client->tlscreds) {
1188 ret = nbd_negotiate_send_rep_err(client,
1189 NBD_REP_ERR_INVALID, errp,
1190 "TLS already enabled");
1191 } else {
1192 ret = nbd_negotiate_send_rep_err(client,
1193 NBD_REP_ERR_POLICY, errp,
1194 "TLS not configured");
1196 break;
1198 case NBD_OPT_STRUCTURED_REPLY:
1199 if (length) {
1200 ret = nbd_reject_length(client, false, errp);
1201 } else if (client->structured_reply) {
1202 ret = nbd_negotiate_send_rep_err(
1203 client, NBD_REP_ERR_INVALID, errp,
1204 "structured reply already negotiated");
1205 } else {
1206 ret = nbd_negotiate_send_rep(client, NBD_REP_ACK, errp);
1207 client->structured_reply = true;
1208 myflags |= NBD_FLAG_SEND_DF;
1210 break;
1212 case NBD_OPT_LIST_META_CONTEXT:
1213 case NBD_OPT_SET_META_CONTEXT:
1214 ret = nbd_negotiate_meta_queries(client, &client->export_meta,
1215 errp);
1216 break;
1218 default:
1219 ret = nbd_opt_drop(client, NBD_REP_ERR_UNSUP, errp,
1220 "Unsupported option %" PRIu32 " (%s)",
1221 option, nbd_opt_lookup(option));
1222 break;
1224 } else {
1226 * If broken new-style we should drop the connection
1227 * for anything except NBD_OPT_EXPORT_NAME
1229 switch (option) {
1230 case NBD_OPT_EXPORT_NAME:
1231 return nbd_negotiate_handle_export_name(client,
1232 myflags, no_zeroes,
1233 errp);
1235 default:
1236 error_setg(errp, "Unsupported option %" PRIu32 " (%s)",
1237 option, nbd_opt_lookup(option));
1238 return -EINVAL;
1241 if (ret < 0) {
1242 return ret;
1247 /* nbd_negotiate
1248 * Return:
1249 * -errno on error, errp is set
1250 * 0 on successful negotiation, errp is not set
1251 * 1 if client sent NBD_OPT_ABORT, i.e. on valid disconnect,
1252 * errp is not set
1254 static coroutine_fn int nbd_negotiate(NBDClient *client, Error **errp)
1256 char buf[NBD_OLDSTYLE_NEGOTIATE_SIZE] = "";
1257 int ret;
1258 const uint16_t myflags = (NBD_FLAG_HAS_FLAGS | NBD_FLAG_SEND_TRIM |
1259 NBD_FLAG_SEND_FLUSH | NBD_FLAG_SEND_FUA |
1260 NBD_FLAG_SEND_WRITE_ZEROES | NBD_FLAG_SEND_CACHE);
1262 /* Old style negotiation header, no room for options
1263 [ 0 .. 7] passwd ("NBDMAGIC")
1264 [ 8 .. 15] magic (NBD_CLIENT_MAGIC)
1265 [16 .. 23] size
1266 [24 .. 27] export flags (zero-extended)
1267 [28 .. 151] reserved (0)
1269 New style negotiation header, client can send options
1270 [ 0 .. 7] passwd ("NBDMAGIC")
1271 [ 8 .. 15] magic (NBD_OPTS_MAGIC)
1272 [16 .. 17] server flags (0)
1273 ....options sent, ending in NBD_OPT_EXPORT_NAME or NBD_OPT_GO....
1276 qio_channel_set_blocking(client->ioc, false, NULL);
1278 trace_nbd_negotiate_begin();
1279 memcpy(buf, "NBDMAGIC", 8);
1281 stq_be_p(buf + 8, NBD_OPTS_MAGIC);
1282 stw_be_p(buf + 16, NBD_FLAG_FIXED_NEWSTYLE | NBD_FLAG_NO_ZEROES);
1284 if (nbd_write(client->ioc, buf, 18, errp) < 0) {
1285 error_prepend(errp, "write failed: ");
1286 return -EINVAL;
1288 ret = nbd_negotiate_options(client, myflags, errp);
1289 if (ret != 0) {
1290 if (ret < 0) {
1291 error_prepend(errp, "option negotiation failed: ");
1293 return ret;
1296 assert(!client->optlen);
1297 trace_nbd_negotiate_success();
1299 return 0;
1302 static int nbd_receive_request(QIOChannel *ioc, NBDRequest *request,
1303 Error **errp)
1305 uint8_t buf[NBD_REQUEST_SIZE];
1306 uint32_t magic;
1307 int ret;
1309 ret = nbd_read(ioc, buf, sizeof(buf), errp);
1310 if (ret < 0) {
1311 return ret;
1314 /* Request
1315 [ 0 .. 3] magic (NBD_REQUEST_MAGIC)
1316 [ 4 .. 5] flags (NBD_CMD_FLAG_FUA, ...)
1317 [ 6 .. 7] type (NBD_CMD_READ, ...)
1318 [ 8 .. 15] handle
1319 [16 .. 23] from
1320 [24 .. 27] len
1323 magic = ldl_be_p(buf);
1324 request->flags = lduw_be_p(buf + 4);
1325 request->type = lduw_be_p(buf + 6);
1326 request->handle = ldq_be_p(buf + 8);
1327 request->from = ldq_be_p(buf + 16);
1328 request->len = ldl_be_p(buf + 24);
1330 trace_nbd_receive_request(magic, request->flags, request->type,
1331 request->from, request->len);
1333 if (magic != NBD_REQUEST_MAGIC) {
1334 error_setg(errp, "invalid magic (got 0x%" PRIx32 ")", magic);
1335 return -EINVAL;
1337 return 0;
1340 #define MAX_NBD_REQUESTS 16
1342 void nbd_client_get(NBDClient *client)
1344 client->refcount++;
1347 void nbd_client_put(NBDClient *client)
1349 if (--client->refcount == 0) {
1350 /* The last reference should be dropped by client->close,
1351 * which is called by client_close.
1353 assert(client->closing);
1355 qio_channel_detach_aio_context(client->ioc);
1356 object_unref(OBJECT(client->sioc));
1357 object_unref(OBJECT(client->ioc));
1358 if (client->tlscreds) {
1359 object_unref(OBJECT(client->tlscreds));
1361 g_free(client->tlsaclname);
1362 if (client->exp) {
1363 QTAILQ_REMOVE(&client->exp->clients, client, next);
1364 nbd_export_put(client->exp);
1366 g_free(client);
1370 static void client_close(NBDClient *client, bool negotiated)
1372 if (client->closing) {
1373 return;
1376 client->closing = true;
1378 /* Force requests to finish. They will drop their own references,
1379 * then we'll close the socket and free the NBDClient.
1381 qio_channel_shutdown(client->ioc, QIO_CHANNEL_SHUTDOWN_BOTH,
1382 NULL);
1384 /* Also tell the client, so that they release their reference. */
1385 if (client->close_fn) {
1386 client->close_fn(client, negotiated);
1390 static NBDRequestData *nbd_request_get(NBDClient *client)
1392 NBDRequestData *req;
1394 assert(client->nb_requests <= MAX_NBD_REQUESTS - 1);
1395 client->nb_requests++;
1397 req = g_new0(NBDRequestData, 1);
1398 nbd_client_get(client);
1399 req->client = client;
1400 return req;
1403 static void nbd_request_put(NBDRequestData *req)
1405 NBDClient *client = req->client;
1407 if (req->data) {
1408 qemu_vfree(req->data);
1410 g_free(req);
1412 client->nb_requests--;
1413 nbd_client_receive_next_request(client);
1415 nbd_client_put(client);
1418 static void blk_aio_attached(AioContext *ctx, void *opaque)
1420 NBDExport *exp = opaque;
1421 NBDClient *client;
1423 trace_nbd_blk_aio_attached(exp->name, ctx);
1425 exp->ctx = ctx;
1427 QTAILQ_FOREACH(client, &exp->clients, next) {
1428 qio_channel_attach_aio_context(client->ioc, ctx);
1429 if (client->recv_coroutine) {
1430 aio_co_schedule(ctx, client->recv_coroutine);
1432 if (client->send_coroutine) {
1433 aio_co_schedule(ctx, client->send_coroutine);
1438 static void blk_aio_detach(void *opaque)
1440 NBDExport *exp = opaque;
1441 NBDClient *client;
1443 trace_nbd_blk_aio_detach(exp->name, exp->ctx);
1445 QTAILQ_FOREACH(client, &exp->clients, next) {
1446 qio_channel_detach_aio_context(client->ioc);
1449 exp->ctx = NULL;
1452 static void nbd_eject_notifier(Notifier *n, void *data)
1454 NBDExport *exp = container_of(n, NBDExport, eject_notifier);
1455 nbd_export_close(exp);
1458 NBDExport *nbd_export_new(BlockDriverState *bs, off_t dev_offset, off_t size,
1459 const char *name, const char *description,
1460 const char *bitmap, uint16_t nbdflags,
1461 void (*close)(NBDExport *), bool writethrough,
1462 BlockBackend *on_eject_blk, Error **errp)
1464 AioContext *ctx;
1465 BlockBackend *blk;
1466 NBDExport *exp = g_new0(NBDExport, 1);
1467 uint64_t perm;
1468 int ret;
1471 * NBD exports are used for non-shared storage migration. Make sure
1472 * that BDRV_O_INACTIVE is cleared and the image is ready for write
1473 * access since the export could be available before migration handover.
1475 assert(name);
1476 ctx = bdrv_get_aio_context(bs);
1477 aio_context_acquire(ctx);
1478 bdrv_invalidate_cache(bs, NULL);
1479 aio_context_release(ctx);
1481 /* Don't allow resize while the NBD server is running, otherwise we don't
1482 * care what happens with the node. */
1483 perm = BLK_PERM_CONSISTENT_READ;
1484 if ((nbdflags & NBD_FLAG_READ_ONLY) == 0) {
1485 perm |= BLK_PERM_WRITE;
1487 blk = blk_new(perm, BLK_PERM_CONSISTENT_READ | BLK_PERM_WRITE_UNCHANGED |
1488 BLK_PERM_WRITE | BLK_PERM_GRAPH_MOD);
1489 ret = blk_insert_bs(blk, bs, errp);
1490 if (ret < 0) {
1491 goto fail;
1493 blk_set_enable_write_cache(blk, !writethrough);
1495 exp->refcount = 1;
1496 QTAILQ_INIT(&exp->clients);
1497 exp->blk = blk;
1498 exp->dev_offset = dev_offset;
1499 exp->name = g_strdup(name);
1500 exp->description = g_strdup(description);
1501 exp->nbdflags = nbdflags;
1502 exp->size = size < 0 ? blk_getlength(blk) : size;
1503 if (exp->size < 0) {
1504 error_setg_errno(errp, -exp->size,
1505 "Failed to determine the NBD export's length");
1506 goto fail;
1508 exp->size -= exp->size % BDRV_SECTOR_SIZE;
1510 if (bitmap) {
1511 BdrvDirtyBitmap *bm = NULL;
1512 BlockDriverState *bs = blk_bs(blk);
1514 while (true) {
1515 bm = bdrv_find_dirty_bitmap(bs, bitmap);
1516 if (bm != NULL || bs->backing == NULL) {
1517 break;
1520 bs = bs->backing->bs;
1523 if (bm == NULL) {
1524 error_setg(errp, "Bitmap '%s' is not found", bitmap);
1525 goto fail;
1528 if ((nbdflags & NBD_FLAG_READ_ONLY) && bdrv_is_writable(bs) &&
1529 bdrv_dirty_bitmap_enabled(bm)) {
1530 error_setg(errp,
1531 "Enabled bitmap '%s' incompatible with readonly export",
1532 bitmap);
1533 goto fail;
1536 if (bdrv_dirty_bitmap_user_locked(bm)) {
1537 error_setg(errp, "Bitmap '%s' is in use", bitmap);
1538 goto fail;
1541 bdrv_dirty_bitmap_set_qmp_locked(bm, true);
1542 exp->export_bitmap = bm;
1543 exp->export_bitmap_context = g_strdup_printf("qemu:dirty-bitmap:%s",
1544 bitmap);
1547 exp->close = close;
1548 exp->ctx = blk_get_aio_context(blk);
1549 blk_add_aio_context_notifier(blk, blk_aio_attached, blk_aio_detach, exp);
1551 if (on_eject_blk) {
1552 blk_ref(on_eject_blk);
1553 exp->eject_notifier_blk = on_eject_blk;
1554 exp->eject_notifier.notify = nbd_eject_notifier;
1555 blk_add_remove_bs_notifier(on_eject_blk, &exp->eject_notifier);
1557 QTAILQ_INSERT_TAIL(&exports, exp, next);
1558 nbd_export_get(exp);
1559 return exp;
1561 fail:
1562 blk_unref(blk);
1563 g_free(exp->name);
1564 g_free(exp->description);
1565 g_free(exp);
1566 return NULL;
1569 NBDExport *nbd_export_find(const char *name)
1571 NBDExport *exp;
1572 QTAILQ_FOREACH(exp, &exports, next) {
1573 if (strcmp(name, exp->name) == 0) {
1574 return exp;
1578 return NULL;
1581 void nbd_export_close(NBDExport *exp)
1583 NBDClient *client, *next;
1585 nbd_export_get(exp);
1587 * TODO: Should we expand QMP NbdServerRemoveNode enum to allow a
1588 * close mode that stops advertising the export to new clients but
1589 * still permits existing clients to run to completion? Because of
1590 * that possibility, nbd_export_close() can be called more than
1591 * once on an export.
1593 QTAILQ_FOREACH_SAFE(client, &exp->clients, next, next) {
1594 client_close(client, true);
1596 if (exp->name) {
1597 nbd_export_put(exp);
1598 g_free(exp->name);
1599 exp->name = NULL;
1600 QTAILQ_REMOVE(&exports, exp, next);
1602 g_free(exp->description);
1603 exp->description = NULL;
1604 nbd_export_put(exp);
1607 void nbd_export_remove(NBDExport *exp, NbdServerRemoveMode mode, Error **errp)
1609 if (mode == NBD_SERVER_REMOVE_MODE_HARD || QTAILQ_EMPTY(&exp->clients)) {
1610 nbd_export_close(exp);
1611 return;
1614 assert(mode == NBD_SERVER_REMOVE_MODE_SAFE);
1616 error_setg(errp, "export '%s' still in use", exp->name);
1617 error_append_hint(errp, "Use mode='hard' to force client disconnect\n");
1620 void nbd_export_get(NBDExport *exp)
1622 assert(exp->refcount > 0);
1623 exp->refcount++;
1626 void nbd_export_put(NBDExport *exp)
1628 assert(exp->refcount > 0);
1629 if (exp->refcount == 1) {
1630 nbd_export_close(exp);
1633 /* nbd_export_close() may theoretically reduce refcount to 0. It may happen
1634 * if someone calls nbd_export_put() on named export not through
1635 * nbd_export_set_name() when refcount is 1. So, let's assert that
1636 * it is > 0.
1638 assert(exp->refcount > 0);
1639 if (--exp->refcount == 0) {
1640 assert(exp->name == NULL);
1641 assert(exp->description == NULL);
1643 if (exp->close) {
1644 exp->close(exp);
1647 if (exp->blk) {
1648 if (exp->eject_notifier_blk) {
1649 notifier_remove(&exp->eject_notifier);
1650 blk_unref(exp->eject_notifier_blk);
1652 blk_remove_aio_context_notifier(exp->blk, blk_aio_attached,
1653 blk_aio_detach, exp);
1654 blk_unref(exp->blk);
1655 exp->blk = NULL;
1658 if (exp->export_bitmap) {
1659 bdrv_dirty_bitmap_set_qmp_locked(exp->export_bitmap, false);
1660 g_free(exp->export_bitmap_context);
1663 g_free(exp);
1667 BlockBackend *nbd_export_get_blockdev(NBDExport *exp)
1669 return exp->blk;
1672 void nbd_export_close_all(void)
1674 NBDExport *exp, *next;
1676 QTAILQ_FOREACH_SAFE(exp, &exports, next, next) {
1677 nbd_export_close(exp);
1681 static int coroutine_fn nbd_co_send_iov(NBDClient *client, struct iovec *iov,
1682 unsigned niov, Error **errp)
1684 int ret;
1686 g_assert(qemu_in_coroutine());
1687 qemu_co_mutex_lock(&client->send_lock);
1688 client->send_coroutine = qemu_coroutine_self();
1690 ret = qio_channel_writev_all(client->ioc, iov, niov, errp) < 0 ? -EIO : 0;
1692 client->send_coroutine = NULL;
1693 qemu_co_mutex_unlock(&client->send_lock);
1695 return ret;
1698 static inline void set_be_simple_reply(NBDSimpleReply *reply, uint64_t error,
1699 uint64_t handle)
1701 stl_be_p(&reply->magic, NBD_SIMPLE_REPLY_MAGIC);
1702 stl_be_p(&reply->error, error);
1703 stq_be_p(&reply->handle, handle);
1706 static int nbd_co_send_simple_reply(NBDClient *client,
1707 uint64_t handle,
1708 uint32_t error,
1709 void *data,
1710 size_t len,
1711 Error **errp)
1713 NBDSimpleReply reply;
1714 int nbd_err = system_errno_to_nbd_errno(error);
1715 struct iovec iov[] = {
1716 {.iov_base = &reply, .iov_len = sizeof(reply)},
1717 {.iov_base = data, .iov_len = len}
1720 trace_nbd_co_send_simple_reply(handle, nbd_err, nbd_err_lookup(nbd_err),
1721 len);
1722 set_be_simple_reply(&reply, nbd_err, handle);
1724 return nbd_co_send_iov(client, iov, len ? 2 : 1, errp);
1727 static inline void set_be_chunk(NBDStructuredReplyChunk *chunk, uint16_t flags,
1728 uint16_t type, uint64_t handle, uint32_t length)
1730 stl_be_p(&chunk->magic, NBD_STRUCTURED_REPLY_MAGIC);
1731 stw_be_p(&chunk->flags, flags);
1732 stw_be_p(&chunk->type, type);
1733 stq_be_p(&chunk->handle, handle);
1734 stl_be_p(&chunk->length, length);
1737 static int coroutine_fn nbd_co_send_structured_done(NBDClient *client,
1738 uint64_t handle,
1739 Error **errp)
1741 NBDStructuredReplyChunk chunk;
1742 struct iovec iov[] = {
1743 {.iov_base = &chunk, .iov_len = sizeof(chunk)},
1746 trace_nbd_co_send_structured_done(handle);
1747 set_be_chunk(&chunk, NBD_REPLY_FLAG_DONE, NBD_REPLY_TYPE_NONE, handle, 0);
1749 return nbd_co_send_iov(client, iov, 1, errp);
1752 static int coroutine_fn nbd_co_send_structured_read(NBDClient *client,
1753 uint64_t handle,
1754 uint64_t offset,
1755 void *data,
1756 size_t size,
1757 bool final,
1758 Error **errp)
1760 NBDStructuredReadData chunk;
1761 struct iovec iov[] = {
1762 {.iov_base = &chunk, .iov_len = sizeof(chunk)},
1763 {.iov_base = data, .iov_len = size}
1766 assert(size);
1767 trace_nbd_co_send_structured_read(handle, offset, data, size);
1768 set_be_chunk(&chunk.h, final ? NBD_REPLY_FLAG_DONE : 0,
1769 NBD_REPLY_TYPE_OFFSET_DATA, handle,
1770 sizeof(chunk) - sizeof(chunk.h) + size);
1771 stq_be_p(&chunk.offset, offset);
1773 return nbd_co_send_iov(client, iov, 2, errp);
1776 static int coroutine_fn nbd_co_send_structured_error(NBDClient *client,
1777 uint64_t handle,
1778 uint32_t error,
1779 const char *msg,
1780 Error **errp)
1782 NBDStructuredError chunk;
1783 int nbd_err = system_errno_to_nbd_errno(error);
1784 struct iovec iov[] = {
1785 {.iov_base = &chunk, .iov_len = sizeof(chunk)},
1786 {.iov_base = (char *)msg, .iov_len = msg ? strlen(msg) : 0},
1789 assert(nbd_err);
1790 trace_nbd_co_send_structured_error(handle, nbd_err,
1791 nbd_err_lookup(nbd_err), msg ? msg : "");
1792 set_be_chunk(&chunk.h, NBD_REPLY_FLAG_DONE, NBD_REPLY_TYPE_ERROR, handle,
1793 sizeof(chunk) - sizeof(chunk.h) + iov[1].iov_len);
1794 stl_be_p(&chunk.error, nbd_err);
1795 stw_be_p(&chunk.message_length, iov[1].iov_len);
1797 return nbd_co_send_iov(client, iov, 1 + !!iov[1].iov_len, errp);
1800 /* Do a sparse read and send the structured reply to the client.
1801 * Returns -errno if sending fails. bdrv_block_status_above() failure is
1802 * reported to the client, at which point this function succeeds.
1804 static int coroutine_fn nbd_co_send_sparse_read(NBDClient *client,
1805 uint64_t handle,
1806 uint64_t offset,
1807 uint8_t *data,
1808 size_t size,
1809 Error **errp)
1811 int ret = 0;
1812 NBDExport *exp = client->exp;
1813 size_t progress = 0;
1815 while (progress < size) {
1816 int64_t pnum;
1817 int status = bdrv_block_status_above(blk_bs(exp->blk), NULL,
1818 offset + progress,
1819 size - progress, &pnum, NULL,
1820 NULL);
1821 bool final;
1823 if (status < 0) {
1824 char *msg = g_strdup_printf("unable to check for holes: %s",
1825 strerror(-status));
1827 ret = nbd_co_send_structured_error(client, handle, -status, msg,
1828 errp);
1829 g_free(msg);
1830 return ret;
1832 assert(pnum && pnum <= size - progress);
1833 final = progress + pnum == size;
1834 if (status & BDRV_BLOCK_ZERO) {
1835 NBDStructuredReadHole chunk;
1836 struct iovec iov[] = {
1837 {.iov_base = &chunk, .iov_len = sizeof(chunk)},
1840 trace_nbd_co_send_structured_read_hole(handle, offset + progress,
1841 pnum);
1842 set_be_chunk(&chunk.h, final ? NBD_REPLY_FLAG_DONE : 0,
1843 NBD_REPLY_TYPE_OFFSET_HOLE,
1844 handle, sizeof(chunk) - sizeof(chunk.h));
1845 stq_be_p(&chunk.offset, offset + progress);
1846 stl_be_p(&chunk.length, pnum);
1847 ret = nbd_co_send_iov(client, iov, 1, errp);
1848 } else {
1849 ret = blk_pread(exp->blk, offset + progress + exp->dev_offset,
1850 data + progress, pnum);
1851 if (ret < 0) {
1852 error_setg_errno(errp, -ret, "reading from file failed");
1853 break;
1855 ret = nbd_co_send_structured_read(client, handle, offset + progress,
1856 data + progress, pnum, final,
1857 errp);
1860 if (ret < 0) {
1861 break;
1863 progress += pnum;
1865 return ret;
1869 * Populate @extents from block status. Update @bytes to be the actual
1870 * length encoded (which may be smaller than the original), and update
1871 * @nb_extents to the number of extents used.
1873 * Returns zero on success and -errno on bdrv_block_status_above failure.
1875 static int blockstatus_to_extents(BlockDriverState *bs, uint64_t offset,
1876 uint64_t *bytes, NBDExtent *extents,
1877 unsigned int *nb_extents)
1879 uint64_t remaining_bytes = *bytes;
1880 NBDExtent *extent = extents, *extents_end = extents + *nb_extents;
1881 bool first_extent = true;
1883 assert(*nb_extents);
1884 while (remaining_bytes) {
1885 uint32_t flags;
1886 int64_t num;
1887 int ret = bdrv_block_status_above(bs, NULL, offset, remaining_bytes,
1888 &num, NULL, NULL);
1890 if (ret < 0) {
1891 return ret;
1894 flags = (ret & BDRV_BLOCK_ALLOCATED ? 0 : NBD_STATE_HOLE) |
1895 (ret & BDRV_BLOCK_ZERO ? NBD_STATE_ZERO : 0);
1896 offset += num;
1897 remaining_bytes -= num;
1899 if (first_extent) {
1900 extent->flags = flags;
1901 extent->length = num;
1902 first_extent = false;
1903 continue;
1906 if (flags == extent->flags) {
1907 /* extend current extent */
1908 extent->length += num;
1909 } else {
1910 if (extent + 1 == extents_end) {
1911 break;
1914 /* start new extent */
1915 extent++;
1916 extent->flags = flags;
1917 extent->length = num;
1921 extents_end = extent + 1;
1923 for (extent = extents; extent < extents_end; extent++) {
1924 extent->flags = cpu_to_be32(extent->flags);
1925 extent->length = cpu_to_be32(extent->length);
1928 *bytes -= remaining_bytes;
1929 *nb_extents = extents_end - extents;
1931 return 0;
1934 /* nbd_co_send_extents
1936 * @length is only for tracing purposes (and may be smaller or larger
1937 * than the client's original request). @last controls whether
1938 * NBD_REPLY_FLAG_DONE is sent. @extents should already be in
1939 * big-endian format.
1941 static int nbd_co_send_extents(NBDClient *client, uint64_t handle,
1942 NBDExtent *extents, unsigned int nb_extents,
1943 uint64_t length, bool last,
1944 uint32_t context_id, Error **errp)
1946 NBDStructuredMeta chunk;
1948 struct iovec iov[] = {
1949 {.iov_base = &chunk, .iov_len = sizeof(chunk)},
1950 {.iov_base = extents, .iov_len = nb_extents * sizeof(extents[0])}
1953 trace_nbd_co_send_extents(handle, nb_extents, context_id, length, last);
1954 set_be_chunk(&chunk.h, last ? NBD_REPLY_FLAG_DONE : 0,
1955 NBD_REPLY_TYPE_BLOCK_STATUS,
1956 handle, sizeof(chunk) - sizeof(chunk.h) + iov[1].iov_len);
1957 stl_be_p(&chunk.context_id, context_id);
1959 return nbd_co_send_iov(client, iov, 2, errp);
1962 /* Get block status from the exported device and send it to the client */
1963 static int nbd_co_send_block_status(NBDClient *client, uint64_t handle,
1964 BlockDriverState *bs, uint64_t offset,
1965 uint32_t length, bool dont_fragment,
1966 bool last, uint32_t context_id,
1967 Error **errp)
1969 int ret;
1970 unsigned int nb_extents = dont_fragment ? 1 : NBD_MAX_BITMAP_EXTENTS;
1971 NBDExtent *extents = g_new(NBDExtent, nb_extents);
1972 uint64_t final_length = length;
1974 ret = blockstatus_to_extents(bs, offset, &final_length, extents,
1975 &nb_extents);
1976 if (ret < 0) {
1977 g_free(extents);
1978 return nbd_co_send_structured_error(
1979 client, handle, -ret, "can't get block status", errp);
1982 ret = nbd_co_send_extents(client, handle, extents, nb_extents,
1983 final_length, last, context_id, errp);
1985 g_free(extents);
1987 return ret;
1991 * Populate @extents from a dirty bitmap. Unless @dont_fragment, the
1992 * final extent may exceed the original @length. Store in @length the
1993 * byte length encoded (which may be smaller or larger than the
1994 * original), and return the number of extents used.
1996 static unsigned int bitmap_to_extents(BdrvDirtyBitmap *bitmap, uint64_t offset,
1997 uint64_t *length, NBDExtent *extents,
1998 unsigned int nb_extents,
1999 bool dont_fragment)
2001 uint64_t begin = offset, end = offset;
2002 uint64_t overall_end = offset + *length;
2003 unsigned int i = 0;
2004 BdrvDirtyBitmapIter *it;
2005 bool dirty;
2007 bdrv_dirty_bitmap_lock(bitmap);
2009 it = bdrv_dirty_iter_new(bitmap);
2010 dirty = bdrv_get_dirty_locked(NULL, bitmap, offset);
2012 assert(begin < overall_end && nb_extents);
2013 while (begin < overall_end && i < nb_extents) {
2014 bool next_dirty = !dirty;
2016 if (dirty) {
2017 end = bdrv_dirty_bitmap_next_zero(bitmap, begin, UINT64_MAX);
2018 } else {
2019 bdrv_set_dirty_iter(it, begin);
2020 end = bdrv_dirty_iter_next(it);
2022 if (end == -1 || end - begin > UINT32_MAX) {
2023 /* Cap to an aligned value < 4G beyond begin. */
2024 end = MIN(bdrv_dirty_bitmap_size(bitmap),
2025 begin + UINT32_MAX + 1 -
2026 bdrv_dirty_bitmap_granularity(bitmap));
2027 next_dirty = dirty;
2029 if (dont_fragment && end > overall_end) {
2030 end = overall_end;
2033 extents[i].length = cpu_to_be32(end - begin);
2034 extents[i].flags = cpu_to_be32(dirty ? NBD_STATE_DIRTY : 0);
2035 i++;
2036 begin = end;
2037 dirty = next_dirty;
2040 bdrv_dirty_iter_free(it);
2042 bdrv_dirty_bitmap_unlock(bitmap);
2044 assert(offset < end);
2045 *length = end - offset;
2046 return i;
2049 static int nbd_co_send_bitmap(NBDClient *client, uint64_t handle,
2050 BdrvDirtyBitmap *bitmap, uint64_t offset,
2051 uint32_t length, bool dont_fragment, bool last,
2052 uint32_t context_id, Error **errp)
2054 int ret;
2055 unsigned int nb_extents = dont_fragment ? 1 : NBD_MAX_BITMAP_EXTENTS;
2056 NBDExtent *extents = g_new(NBDExtent, nb_extents);
2057 uint64_t final_length = length;
2059 nb_extents = bitmap_to_extents(bitmap, offset, &final_length, extents,
2060 nb_extents, dont_fragment);
2062 ret = nbd_co_send_extents(client, handle, extents, nb_extents,
2063 final_length, last, context_id, errp);
2065 g_free(extents);
2067 return ret;
2070 /* nbd_co_receive_request
2071 * Collect a client request. Return 0 if request looks valid, -EIO to drop
2072 * connection right away, and any other negative value to report an error to
2073 * the client (although the caller may still need to disconnect after reporting
2074 * the error).
2076 static int nbd_co_receive_request(NBDRequestData *req, NBDRequest *request,
2077 Error **errp)
2079 NBDClient *client = req->client;
2080 int valid_flags;
2082 g_assert(qemu_in_coroutine());
2083 assert(client->recv_coroutine == qemu_coroutine_self());
2084 if (nbd_receive_request(client->ioc, request, errp) < 0) {
2085 return -EIO;
2088 trace_nbd_co_receive_request_decode_type(request->handle, request->type,
2089 nbd_cmd_lookup(request->type));
2091 if (request->type != NBD_CMD_WRITE) {
2092 /* No payload, we are ready to read the next request. */
2093 req->complete = true;
2096 if (request->type == NBD_CMD_DISC) {
2097 /* Special case: we're going to disconnect without a reply,
2098 * whether or not flags, from, or len are bogus */
2099 return -EIO;
2102 if (request->type == NBD_CMD_READ || request->type == NBD_CMD_WRITE ||
2103 request->type == NBD_CMD_CACHE)
2105 if (request->len > NBD_MAX_BUFFER_SIZE) {
2106 error_setg(errp, "len (%" PRIu32" ) is larger than max len (%u)",
2107 request->len, NBD_MAX_BUFFER_SIZE);
2108 return -EINVAL;
2111 req->data = blk_try_blockalign(client->exp->blk, request->len);
2112 if (req->data == NULL) {
2113 error_setg(errp, "No memory");
2114 return -ENOMEM;
2117 if (request->type == NBD_CMD_WRITE) {
2118 if (nbd_read(client->ioc, req->data, request->len, errp) < 0) {
2119 error_prepend(errp, "reading from socket failed: ");
2120 return -EIO;
2122 req->complete = true;
2124 trace_nbd_co_receive_request_payload_received(request->handle,
2125 request->len);
2128 /* Sanity checks. */
2129 if (client->exp->nbdflags & NBD_FLAG_READ_ONLY &&
2130 (request->type == NBD_CMD_WRITE ||
2131 request->type == NBD_CMD_WRITE_ZEROES ||
2132 request->type == NBD_CMD_TRIM)) {
2133 error_setg(errp, "Export is read-only");
2134 return -EROFS;
2136 if (request->from > client->exp->size ||
2137 request->from + request->len > client->exp->size) {
2138 error_setg(errp, "operation past EOF; From: %" PRIu64 ", Len: %" PRIu32
2139 ", Size: %" PRIu64, request->from, request->len,
2140 (uint64_t)client->exp->size);
2141 return (request->type == NBD_CMD_WRITE ||
2142 request->type == NBD_CMD_WRITE_ZEROES) ? -ENOSPC : -EINVAL;
2144 valid_flags = NBD_CMD_FLAG_FUA;
2145 if (request->type == NBD_CMD_READ && client->structured_reply) {
2146 valid_flags |= NBD_CMD_FLAG_DF;
2147 } else if (request->type == NBD_CMD_WRITE_ZEROES) {
2148 valid_flags |= NBD_CMD_FLAG_NO_HOLE;
2149 } else if (request->type == NBD_CMD_BLOCK_STATUS) {
2150 valid_flags |= NBD_CMD_FLAG_REQ_ONE;
2152 if (request->flags & ~valid_flags) {
2153 error_setg(errp, "unsupported flags for command %s (got 0x%x)",
2154 nbd_cmd_lookup(request->type), request->flags);
2155 return -EINVAL;
2158 return 0;
2161 /* Send simple reply without a payload, or a structured error
2162 * @error_msg is ignored if @ret >= 0
2163 * Returns 0 if connection is still live, -errno on failure to talk to client
2165 static coroutine_fn int nbd_send_generic_reply(NBDClient *client,
2166 uint64_t handle,
2167 int ret,
2168 const char *error_msg,
2169 Error **errp)
2171 if (client->structured_reply && ret < 0) {
2172 return nbd_co_send_structured_error(client, handle, -ret, error_msg,
2173 errp);
2174 } else {
2175 return nbd_co_send_simple_reply(client, handle, ret < 0 ? -ret : 0,
2176 NULL, 0, errp);
2180 /* Handle NBD_CMD_READ request.
2181 * Return -errno if sending fails. Other errors are reported directly to the
2182 * client as an error reply. */
2183 static coroutine_fn int nbd_do_cmd_read(NBDClient *client, NBDRequest *request,
2184 uint8_t *data, Error **errp)
2186 int ret;
2187 NBDExport *exp = client->exp;
2189 assert(request->type == NBD_CMD_READ || request->type == NBD_CMD_CACHE);
2191 /* XXX: NBD Protocol only documents use of FUA with WRITE */
2192 if (request->flags & NBD_CMD_FLAG_FUA) {
2193 ret = blk_co_flush(exp->blk);
2194 if (ret < 0) {
2195 return nbd_send_generic_reply(client, request->handle, ret,
2196 "flush failed", errp);
2200 if (client->structured_reply && !(request->flags & NBD_CMD_FLAG_DF) &&
2201 request->len && request->type != NBD_CMD_CACHE)
2203 return nbd_co_send_sparse_read(client, request->handle, request->from,
2204 data, request->len, errp);
2207 ret = blk_pread(exp->blk, request->from + exp->dev_offset, data,
2208 request->len);
2209 if (ret < 0 || request->type == NBD_CMD_CACHE) {
2210 return nbd_send_generic_reply(client, request->handle, ret,
2211 "reading from file failed", errp);
2214 if (client->structured_reply) {
2215 if (request->len) {
2216 return nbd_co_send_structured_read(client, request->handle,
2217 request->from, data,
2218 request->len, true, errp);
2219 } else {
2220 return nbd_co_send_structured_done(client, request->handle, errp);
2222 } else {
2223 return nbd_co_send_simple_reply(client, request->handle, 0,
2224 data, request->len, errp);
2228 /* Handle NBD request.
2229 * Return -errno if sending fails. Other errors are reported directly to the
2230 * client as an error reply. */
2231 static coroutine_fn int nbd_handle_request(NBDClient *client,
2232 NBDRequest *request,
2233 uint8_t *data, Error **errp)
2235 int ret;
2236 int flags;
2237 NBDExport *exp = client->exp;
2238 char *msg;
2240 switch (request->type) {
2241 case NBD_CMD_READ:
2242 case NBD_CMD_CACHE:
2243 return nbd_do_cmd_read(client, request, data, errp);
2245 case NBD_CMD_WRITE:
2246 flags = 0;
2247 if (request->flags & NBD_CMD_FLAG_FUA) {
2248 flags |= BDRV_REQ_FUA;
2250 ret = blk_pwrite(exp->blk, request->from + exp->dev_offset,
2251 data, request->len, flags);
2252 return nbd_send_generic_reply(client, request->handle, ret,
2253 "writing to file failed", errp);
2255 case NBD_CMD_WRITE_ZEROES:
2256 flags = 0;
2257 if (request->flags & NBD_CMD_FLAG_FUA) {
2258 flags |= BDRV_REQ_FUA;
2260 if (!(request->flags & NBD_CMD_FLAG_NO_HOLE)) {
2261 flags |= BDRV_REQ_MAY_UNMAP;
2263 ret = blk_pwrite_zeroes(exp->blk, request->from + exp->dev_offset,
2264 request->len, flags);
2265 return nbd_send_generic_reply(client, request->handle, ret,
2266 "writing to file failed", errp);
2268 case NBD_CMD_DISC:
2269 /* unreachable, thanks to special case in nbd_co_receive_request() */
2270 abort();
2272 case NBD_CMD_FLUSH:
2273 ret = blk_co_flush(exp->blk);
2274 return nbd_send_generic_reply(client, request->handle, ret,
2275 "flush failed", errp);
2277 case NBD_CMD_TRIM:
2278 ret = blk_co_pdiscard(exp->blk, request->from + exp->dev_offset,
2279 request->len);
2280 if (ret == 0 && request->flags & NBD_CMD_FLAG_FUA) {
2281 ret = blk_co_flush(exp->blk);
2283 return nbd_send_generic_reply(client, request->handle, ret,
2284 "discard failed", errp);
2286 case NBD_CMD_BLOCK_STATUS:
2287 if (!request->len) {
2288 return nbd_send_generic_reply(client, request->handle, -EINVAL,
2289 "need non-zero length", errp);
2291 if (client->export_meta.valid &&
2292 (client->export_meta.base_allocation ||
2293 client->export_meta.bitmap))
2295 bool dont_fragment = request->flags & NBD_CMD_FLAG_REQ_ONE;
2297 if (client->export_meta.base_allocation) {
2298 ret = nbd_co_send_block_status(client, request->handle,
2299 blk_bs(exp->blk), request->from,
2300 request->len, dont_fragment,
2301 !client->export_meta.bitmap,
2302 NBD_META_ID_BASE_ALLOCATION,
2303 errp);
2304 if (ret < 0) {
2305 return ret;
2309 if (client->export_meta.bitmap) {
2310 ret = nbd_co_send_bitmap(client, request->handle,
2311 client->exp->export_bitmap,
2312 request->from, request->len,
2313 dont_fragment,
2314 true, NBD_META_ID_DIRTY_BITMAP, errp);
2315 if (ret < 0) {
2316 return ret;
2320 return ret;
2321 } else {
2322 return nbd_send_generic_reply(client, request->handle, -EINVAL,
2323 "CMD_BLOCK_STATUS not negotiated",
2324 errp);
2327 default:
2328 msg = g_strdup_printf("invalid request type (%" PRIu32 ") received",
2329 request->type);
2330 ret = nbd_send_generic_reply(client, request->handle, -EINVAL, msg,
2331 errp);
2332 g_free(msg);
2333 return ret;
2337 /* Owns a reference to the NBDClient passed as opaque. */
2338 static coroutine_fn void nbd_trip(void *opaque)
2340 NBDClient *client = opaque;
2341 NBDRequestData *req;
2342 NBDRequest request = { 0 }; /* GCC thinks it can be used uninitialized */
2343 int ret;
2344 Error *local_err = NULL;
2346 trace_nbd_trip();
2347 if (client->closing) {
2348 nbd_client_put(client);
2349 return;
2352 req = nbd_request_get(client);
2353 ret = nbd_co_receive_request(req, &request, &local_err);
2354 client->recv_coroutine = NULL;
2356 if (client->closing) {
2358 * The client may be closed when we are blocked in
2359 * nbd_co_receive_request()
2361 goto done;
2364 nbd_client_receive_next_request(client);
2365 if (ret == -EIO) {
2366 goto disconnect;
2369 if (ret < 0) {
2370 /* It wans't -EIO, so, according to nbd_co_receive_request()
2371 * semantics, we should return the error to the client. */
2372 Error *export_err = local_err;
2374 local_err = NULL;
2375 ret = nbd_send_generic_reply(client, request.handle, -EINVAL,
2376 error_get_pretty(export_err), &local_err);
2377 error_free(export_err);
2378 } else {
2379 ret = nbd_handle_request(client, &request, req->data, &local_err);
2381 if (ret < 0) {
2382 error_prepend(&local_err, "Failed to send reply: ");
2383 goto disconnect;
2386 /* We must disconnect after NBD_CMD_WRITE if we did not
2387 * read the payload.
2389 if (!req->complete) {
2390 error_setg(&local_err, "Request handling failed in intermediate state");
2391 goto disconnect;
2394 done:
2395 nbd_request_put(req);
2396 nbd_client_put(client);
2397 return;
2399 disconnect:
2400 if (local_err) {
2401 error_reportf_err(local_err, "Disconnect client, due to: ");
2403 nbd_request_put(req);
2404 client_close(client, true);
2405 nbd_client_put(client);
2408 static void nbd_client_receive_next_request(NBDClient *client)
2410 if (!client->recv_coroutine && client->nb_requests < MAX_NBD_REQUESTS) {
2411 nbd_client_get(client);
2412 client->recv_coroutine = qemu_coroutine_create(nbd_trip, client);
2413 aio_co_schedule(client->exp->ctx, client->recv_coroutine);
2417 static coroutine_fn void nbd_co_client_start(void *opaque)
2419 NBDClient *client = opaque;
2420 Error *local_err = NULL;
2422 qemu_co_mutex_init(&client->send_lock);
2424 if (nbd_negotiate(client, &local_err)) {
2425 if (local_err) {
2426 error_report_err(local_err);
2428 client_close(client, false);
2429 return;
2432 nbd_client_receive_next_request(client);
2436 * Create a new client listener using the given channel @sioc.
2437 * Begin servicing it in a coroutine. When the connection closes, call
2438 * @close_fn with an indication of whether the client completed negotiation.
2440 void nbd_client_new(QIOChannelSocket *sioc,
2441 QCryptoTLSCreds *tlscreds,
2442 const char *tlsaclname,
2443 void (*close_fn)(NBDClient *, bool))
2445 NBDClient *client;
2446 Coroutine *co;
2448 client = g_new0(NBDClient, 1);
2449 client->refcount = 1;
2450 client->tlscreds = tlscreds;
2451 if (tlscreds) {
2452 object_ref(OBJECT(client->tlscreds));
2454 client->tlsaclname = g_strdup(tlsaclname);
2455 client->sioc = sioc;
2456 object_ref(OBJECT(client->sioc));
2457 client->ioc = QIO_CHANNEL(sioc);
2458 object_ref(OBJECT(client->ioc));
2459 client->close_fn = close_fn;
2461 co = qemu_coroutine_create(nbd_co_client_start, client);
2462 qemu_coroutine_enter(co);