2 * Copyright (C) 2016-2017 Red Hat, Inc.
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"
23 #include "nbd-internal.h"
25 static int system_errno_to_nbd_errno(int err)
53 /* Definitions for opaque data types */
55 typedef struct NBDRequestData NBDRequestData;
57 struct NBDRequestData {
58 QSIMPLEQ_ENTRY(NBDRequestData) entry;
66 void (*close)(NBDExport *exp);
74 QTAILQ_HEAD(, NBDClient) clients;
75 QTAILQ_ENTRY(NBDExport) next;
79 BlockBackend *eject_notifier_blk;
80 Notifier eject_notifier;
83 static QTAILQ_HEAD(, NBDExport) exports = QTAILQ_HEAD_INITIALIZER(exports);
87 void (*close_fn)(NBDClient *client, bool negotiated);
90 QCryptoTLSCreds *tlscreds;
92 QIOChannelSocket *sioc; /* The underlying data channel */
93 QIOChannel *ioc; /* The current I/O channel which may differ (eg TLS) */
95 Coroutine *recv_coroutine;
98 Coroutine *send_coroutine;
100 QTAILQ_ENTRY(NBDClient) next;
104 bool structured_reply;
107 /* That's all folks */
109 static void nbd_client_receive_next_request(NBDClient *client);
111 /* Basic flow for negotiation
138 /* Send a reply header, including length, but no payload.
139 * Return -errno on error, 0 on success. */
140 static int nbd_negotiate_send_rep_len(QIOChannel *ioc, uint32_t type,
141 uint32_t opt, uint32_t len, Error **errp)
145 trace_nbd_negotiate_send_rep_len(opt, nbd_opt_lookup(opt),
146 type, nbd_rep_lookup(type), len);
148 assert(len < NBD_MAX_BUFFER_SIZE);
149 magic = cpu_to_be64(NBD_REP_MAGIC);
150 if (nbd_write(ioc, &magic, sizeof(magic), errp) < 0) {
151 error_prepend(errp, "write failed (rep magic): ");
155 opt = cpu_to_be32(opt);
156 if (nbd_write(ioc, &opt, sizeof(opt), errp) < 0) {
157 error_prepend(errp, "write failed (rep opt): ");
161 type = cpu_to_be32(type);
162 if (nbd_write(ioc, &type, sizeof(type), errp) < 0) {
163 error_prepend(errp, "write failed (rep type): ");
167 len = cpu_to_be32(len);
168 if (nbd_write(ioc, &len, sizeof(len), errp) < 0) {
169 error_prepend(errp, "write failed (rep data length): ");
175 /* Send a reply header with default 0 length.
176 * Return -errno on error, 0 on success. */
177 static int nbd_negotiate_send_rep(QIOChannel *ioc, uint32_t type, uint32_t opt,
180 return nbd_negotiate_send_rep_len(ioc, type, opt, 0, errp);
183 /* Send an error reply.
184 * Return -errno on error, 0 on success. */
185 static int GCC_FMT_ATTR(5, 6)
186 nbd_negotiate_send_rep_err(QIOChannel *ioc, uint32_t type,
187 uint32_t opt, Error **errp, const char *fmt, ...)
195 msg = g_strdup_vprintf(fmt, va);
199 trace_nbd_negotiate_send_rep_err(msg);
200 ret = nbd_negotiate_send_rep_len(ioc, type, opt, len, errp);
204 if (nbd_write(ioc, msg, len, errp) < 0) {
205 error_prepend(errp, "write failed (error message): ");
216 /* Send a single NBD_REP_SERVER reply to NBD_OPT_LIST, including payload.
217 * Return -errno on error, 0 on success. */
218 static int nbd_negotiate_send_rep_list(QIOChannel *ioc, NBDExport *exp,
221 size_t name_len, desc_len;
223 const char *name = exp->name ? exp->name : "";
224 const char *desc = exp->description ? exp->description : "";
227 trace_nbd_negotiate_send_rep_list(name, desc);
228 name_len = strlen(name);
229 desc_len = strlen(desc);
230 len = name_len + desc_len + sizeof(len);
231 ret = nbd_negotiate_send_rep_len(ioc, NBD_REP_SERVER, NBD_OPT_LIST, len,
237 len = cpu_to_be32(name_len);
238 if (nbd_write(ioc, &len, sizeof(len), errp) < 0) {
239 error_prepend(errp, "write failed (name length): ");
243 if (nbd_write(ioc, name, name_len, errp) < 0) {
244 error_prepend(errp, "write failed (name buffer): ");
248 if (nbd_write(ioc, desc, desc_len, errp) < 0) {
249 error_prepend(errp, "write failed (description buffer): ");
256 /* Process the NBD_OPT_LIST command, with a potential series of replies.
257 * Return -errno on error, 0 on success. */
258 static int nbd_negotiate_handle_list(NBDClient *client, Error **errp)
262 /* For each export, send a NBD_REP_SERVER reply. */
263 QTAILQ_FOREACH(exp, &exports, next) {
264 if (nbd_negotiate_send_rep_list(client->ioc, exp, errp)) {
268 /* Finish with a NBD_REP_ACK. */
269 return nbd_negotiate_send_rep(client->ioc, NBD_REP_ACK, NBD_OPT_LIST, errp);
272 /* Send a reply to NBD_OPT_EXPORT_NAME.
273 * Return -errno on error, 0 on success. */
274 static int nbd_negotiate_handle_export_name(NBDClient *client, uint32_t length,
275 uint16_t myflags, bool no_zeroes,
278 char name[NBD_MAX_NAME_SIZE + 1];
279 char buf[NBD_REPLY_EXPORT_NAME_SIZE] = "";
284 [20 .. xx] export name (length bytes)
287 [ 8 .. 9] export flags
288 [10 .. 133] reserved (0) [unless no_zeroes]
290 trace_nbd_negotiate_handle_export_name();
291 if (length >= sizeof(name)) {
292 error_setg(errp, "Bad length received");
295 if (nbd_read(client->ioc, name, length, errp) < 0) {
296 error_prepend(errp, "read failed: ");
301 trace_nbd_negotiate_handle_export_name_request(name);
303 client->exp = nbd_export_find(name);
305 error_setg(errp, "export not found");
309 trace_nbd_negotiate_new_style_size_flags(client->exp->size,
310 client->exp->nbdflags | myflags);
311 stq_be_p(buf, client->exp->size);
312 stw_be_p(buf + 8, client->exp->nbdflags | myflags);
313 len = no_zeroes ? 10 : sizeof(buf);
314 ret = nbd_write(client->ioc, buf, len, errp);
316 error_prepend(errp, "write failed: ");
320 QTAILQ_INSERT_TAIL(&client->exp->clients, client, next);
321 nbd_export_get(client->exp);
326 /* Send a single NBD_REP_INFO, with a buffer @buf of @length bytes.
327 * The buffer does NOT include the info type prefix.
328 * Return -errno on error, 0 if ready to send more. */
329 static int nbd_negotiate_send_info(NBDClient *client, uint32_t opt,
330 uint16_t info, uint32_t length, void *buf,
335 trace_nbd_negotiate_send_info(info, nbd_info_lookup(info), length);
336 rc = nbd_negotiate_send_rep_len(client->ioc, NBD_REP_INFO, opt,
337 sizeof(info) + length, errp);
342 if (nbd_write(client->ioc, &info, sizeof(info), errp) < 0) {
345 if (nbd_write(client->ioc, buf, length, errp) < 0) {
351 /* Handle NBD_OPT_INFO and NBD_OPT_GO.
352 * Return -errno on error, 0 if ready for next option, and 1 to move
353 * into transmission phase. */
354 static int nbd_negotiate_handle_info(NBDClient *client, uint32_t length,
355 uint32_t opt, uint16_t myflags,
359 char name[NBD_MAX_NAME_SIZE + 1];
364 bool sendname = false;
365 bool blocksize = false;
367 char buf[sizeof(uint64_t) + sizeof(uint16_t)];
371 4 bytes: L, name length (can be 0)
373 2 bytes: N, number of requests (can be 0)
374 N * 2 bytes: N requests
376 if (length < sizeof(namelen) + sizeof(requests)) {
377 msg = "overall request too short";
380 if (nbd_read(client->ioc, &namelen, sizeof(namelen), errp) < 0) {
383 be32_to_cpus(&namelen);
384 length -= sizeof(namelen);
385 if (namelen > length - sizeof(requests) || (length - namelen) % 2) {
386 msg = "name length is incorrect";
389 if (nbd_read(client->ioc, name, namelen, errp) < 0) {
392 name[namelen] = '\0';
394 trace_nbd_negotiate_handle_export_name_request(name);
396 if (nbd_read(client->ioc, &requests, sizeof(requests), errp) < 0) {
399 be16_to_cpus(&requests);
400 length -= sizeof(requests);
401 trace_nbd_negotiate_handle_info_requests(requests);
402 if (requests != length / sizeof(request)) {
403 msg = "incorrect number of requests for overall length";
407 if (nbd_read(client->ioc, &request, sizeof(request), errp) < 0) {
410 be16_to_cpus(&request);
411 length -= sizeof(request);
412 trace_nbd_negotiate_handle_info_request(request,
413 nbd_info_lookup(request));
414 /* We care about NBD_INFO_NAME and NBD_INFO_BLOCK_SIZE;
415 * everything else is either a request we don't know or
416 * something we send regardless of request */
421 case NBD_INFO_BLOCK_SIZE:
428 exp = nbd_export_find(name);
430 return nbd_negotiate_send_rep_err(client->ioc, NBD_REP_ERR_UNKNOWN,
431 opt, errp, "export '%s' not present",
435 /* Don't bother sending NBD_INFO_NAME unless client requested it */
437 rc = nbd_negotiate_send_info(client, opt, NBD_INFO_NAME, namelen, name,
444 /* Send NBD_INFO_DESCRIPTION only if available, regardless of
446 if (exp->description) {
447 size_t len = strlen(exp->description);
449 rc = nbd_negotiate_send_info(client, opt, NBD_INFO_DESCRIPTION,
450 len, exp->description, errp);
456 /* Send NBD_INFO_BLOCK_SIZE always, but tweak the minimum size
457 * according to whether the client requested it, and according to
458 * whether this is OPT_INFO or OPT_GO. */
459 /* minimum - 1 for back-compat, or 512 if client is new enough.
460 * TODO: consult blk_bs(blk)->bl.request_alignment? */
461 sizes[0] = (opt == NBD_OPT_INFO || blocksize) ? BDRV_SECTOR_SIZE : 1;
462 /* preferred - Hard-code to 4096 for now.
463 * TODO: is blk_bs(blk)->bl.opt_transfer appropriate? */
465 /* maximum - At most 32M, but smaller as appropriate. */
466 sizes[2] = MIN(blk_get_max_transfer(exp->blk), NBD_MAX_BUFFER_SIZE);
467 trace_nbd_negotiate_handle_info_block_size(sizes[0], sizes[1], sizes[2]);
468 cpu_to_be32s(&sizes[0]);
469 cpu_to_be32s(&sizes[1]);
470 cpu_to_be32s(&sizes[2]);
471 rc = nbd_negotiate_send_info(client, opt, NBD_INFO_BLOCK_SIZE,
472 sizeof(sizes), sizes, errp);
477 /* Send NBD_INFO_EXPORT always */
478 trace_nbd_negotiate_new_style_size_flags(exp->size,
479 exp->nbdflags | myflags);
480 stq_be_p(buf, exp->size);
481 stw_be_p(buf + 8, exp->nbdflags | myflags);
482 rc = nbd_negotiate_send_info(client, opt, NBD_INFO_EXPORT,
483 sizeof(buf), buf, errp);
488 /* If the client is just asking for NBD_OPT_INFO, but forgot to
489 * request block sizes, return an error.
490 * TODO: consult blk_bs(blk)->request_align, and only error if it
492 if (opt == NBD_OPT_INFO && !blocksize) {
493 return nbd_negotiate_send_rep_err(client->ioc,
494 NBD_REP_ERR_BLOCK_SIZE_REQD, opt,
496 "request NBD_INFO_BLOCK_SIZE to "
501 rc = nbd_negotiate_send_rep(client->ioc, NBD_REP_ACK, opt, errp);
506 if (opt == NBD_OPT_GO) {
508 QTAILQ_INSERT_TAIL(&client->exp->clients, client, next);
509 nbd_export_get(client->exp);
515 if (nbd_drop(client->ioc, length, errp) < 0) {
518 return nbd_negotiate_send_rep_err(client->ioc, NBD_REP_ERR_INVALID, opt,
523 /* Handle NBD_OPT_STARTTLS. Return NULL to drop connection, or else the
524 * new channel for all further (now-encrypted) communication. */
525 static QIOChannel *nbd_negotiate_handle_starttls(NBDClient *client,
530 struct NBDTLSHandshakeData data = { 0 };
532 trace_nbd_negotiate_handle_starttls();
535 if (nbd_negotiate_send_rep(client->ioc, NBD_REP_ACK,
536 NBD_OPT_STARTTLS, errp) < 0) {
540 tioc = qio_channel_tls_new_server(ioc,
548 qio_channel_set_name(QIO_CHANNEL(tioc), "nbd-server-tls");
549 trace_nbd_negotiate_handle_starttls_handshake();
550 data.loop = g_main_loop_new(g_main_context_default(), FALSE);
551 qio_channel_tls_handshake(tioc,
556 if (!data.complete) {
557 g_main_loop_run(data.loop);
559 g_main_loop_unref(data.loop);
561 object_unref(OBJECT(tioc));
562 error_propagate(errp, data.error);
566 return QIO_CHANNEL(tioc);
569 /* nbd_reject_length: Handle any unexpected payload.
570 * @fatal requests that we quit talking to the client, even if we are able
571 * to successfully send an error to the guest.
573 * -errno transmission error occurred or @fatal was requested, errp is set
574 * 0 error message successfully sent to client, errp is not set
576 static int nbd_reject_length(NBDClient *client, uint32_t length,
577 uint32_t option, bool fatal, Error **errp)
582 if (nbd_drop(client->ioc, length, errp) < 0) {
585 ret = nbd_negotiate_send_rep_err(client->ioc, NBD_REP_ERR_INVALID,
587 "option '%s' should have zero length",
588 nbd_opt_lookup(option));
590 error_setg(errp, "option '%s' should have zero length",
591 nbd_opt_lookup(option));
597 /* nbd_negotiate_options
598 * Process all NBD_OPT_* client option commands, during fixed newstyle
601 * -errno on error, errp is set
602 * 0 on successful negotiation, errp is not set
603 * 1 if client sent NBD_OPT_ABORT, i.e. on valid disconnect,
606 static int nbd_negotiate_options(NBDClient *client, uint16_t myflags,
610 bool fixedNewstyle = false;
611 bool no_zeroes = false;
614 [ 0 .. 3] client flags
616 Then we loop until NBD_OPT_EXPORT_NAME or NBD_OPT_GO:
617 [ 0 .. 7] NBD_OPTS_MAGIC
618 [ 8 .. 11] NBD option
619 [12 .. 15] Data length
622 [ 0 .. 7] NBD_OPTS_MAGIC
623 [ 8 .. 11] Second NBD option
624 [12 .. 15] Data length
628 if (nbd_read(client->ioc, &flags, sizeof(flags), errp) < 0) {
629 error_prepend(errp, "read failed: ");
632 be32_to_cpus(&flags);
633 trace_nbd_negotiate_options_flags(flags);
634 if (flags & NBD_FLAG_C_FIXED_NEWSTYLE) {
635 fixedNewstyle = true;
636 flags &= ~NBD_FLAG_C_FIXED_NEWSTYLE;
638 if (flags & NBD_FLAG_C_NO_ZEROES) {
640 flags &= ~NBD_FLAG_C_NO_ZEROES;
643 error_setg(errp, "Unknown client flags 0x%" PRIx32 " received", flags);
649 uint32_t option, length;
652 if (nbd_read(client->ioc, &magic, sizeof(magic), errp) < 0) {
653 error_prepend(errp, "read failed: ");
656 magic = be64_to_cpu(magic);
657 trace_nbd_negotiate_options_check_magic(magic);
658 if (magic != NBD_OPTS_MAGIC) {
659 error_setg(errp, "Bad magic received");
663 if (nbd_read(client->ioc, &option,
664 sizeof(option), errp) < 0) {
665 error_prepend(errp, "read failed: ");
668 option = be32_to_cpu(option);
670 if (nbd_read(client->ioc, &length, sizeof(length), errp) < 0) {
671 error_prepend(errp, "read failed: ");
674 length = be32_to_cpu(length);
676 trace_nbd_negotiate_options_check_option(option,
677 nbd_opt_lookup(option));
678 if (client->tlscreds &&
679 client->ioc == (QIOChannel *)client->sioc) {
681 if (!fixedNewstyle) {
682 error_setg(errp, "Unsupported option 0x%" PRIx32, option);
686 case NBD_OPT_STARTTLS:
688 /* Unconditionally drop the connection if the client
689 * can't start a TLS negotiation correctly */
690 return nbd_reject_length(client, length, option, true,
693 tioc = nbd_negotiate_handle_starttls(client, errp);
698 object_unref(OBJECT(client->ioc));
699 client->ioc = QIO_CHANNEL(tioc);
702 case NBD_OPT_EXPORT_NAME:
703 /* No way to return an error to client, so drop connection */
704 error_setg(errp, "Option 0x%x not permitted before TLS",
709 if (nbd_drop(client->ioc, length, errp) < 0) {
712 ret = nbd_negotiate_send_rep_err(client->ioc,
713 NBD_REP_ERR_TLS_REQD,
716 "not permitted before TLS",
718 /* Let the client keep trying, unless they asked to
719 * quit. In this mode, we've already sent an error, so
720 * we can't ack the abort. */
721 if (option == NBD_OPT_ABORT) {
726 } else if (fixedNewstyle) {
730 ret = nbd_reject_length(client, length, option, false,
733 ret = nbd_negotiate_handle_list(client, errp);
738 /* NBD spec says we must try to reply before
739 * disconnecting, but that we must also tolerate
740 * guests that don't wait for our reply. */
741 nbd_negotiate_send_rep(client->ioc, NBD_REP_ACK, option, NULL);
744 case NBD_OPT_EXPORT_NAME:
745 return nbd_negotiate_handle_export_name(client, length,
751 ret = nbd_negotiate_handle_info(client, length, option,
754 assert(option == NBD_OPT_GO);
759 case NBD_OPT_STARTTLS:
761 ret = nbd_reject_length(client, length, option, false,
763 } else if (client->tlscreds) {
764 ret = nbd_negotiate_send_rep_err(client->ioc,
767 "TLS already enabled");
769 ret = nbd_negotiate_send_rep_err(client->ioc,
772 "TLS not configured");
776 case NBD_OPT_STRUCTURED_REPLY:
778 ret = nbd_reject_length(client, length, option, false,
780 } else if (client->structured_reply) {
781 ret = nbd_negotiate_send_rep_err(
782 client->ioc, NBD_REP_ERR_INVALID, option, errp,
783 "structured reply already negotiated");
785 ret = nbd_negotiate_send_rep(client->ioc, NBD_REP_ACK,
787 client->structured_reply = true;
788 myflags |= NBD_FLAG_SEND_DF;
793 if (nbd_drop(client->ioc, length, errp) < 0) {
796 ret = nbd_negotiate_send_rep_err(client->ioc,
799 "Unsupported option 0x%"
800 PRIx32 " (%s)", option,
801 nbd_opt_lookup(option));
806 * If broken new-style we should drop the connection
807 * for anything except NBD_OPT_EXPORT_NAME
810 case NBD_OPT_EXPORT_NAME:
811 return nbd_negotiate_handle_export_name(client, length,
816 error_setg(errp, "Unsupported option 0x%" PRIx32 " (%s)",
817 option, nbd_opt_lookup(option));
829 * -errno on error, errp is set
830 * 0 on successful negotiation, errp is not set
831 * 1 if client sent NBD_OPT_ABORT, i.e. on valid disconnect,
834 static coroutine_fn int nbd_negotiate(NBDClient *client, Error **errp)
836 char buf[NBD_OLDSTYLE_NEGOTIATE_SIZE] = "";
838 const uint16_t myflags = (NBD_FLAG_HAS_FLAGS | NBD_FLAG_SEND_TRIM |
839 NBD_FLAG_SEND_FLUSH | NBD_FLAG_SEND_FUA |
840 NBD_FLAG_SEND_WRITE_ZEROES);
843 /* Old style negotiation header, no room for options
844 [ 0 .. 7] passwd ("NBDMAGIC")
845 [ 8 .. 15] magic (NBD_CLIENT_MAGIC)
847 [24 .. 27] export flags (zero-extended)
848 [28 .. 151] reserved (0)
850 New style negotiation header, client can send options
851 [ 0 .. 7] passwd ("NBDMAGIC")
852 [ 8 .. 15] magic (NBD_OPTS_MAGIC)
853 [16 .. 17] server flags (0)
854 ....options sent, ending in NBD_OPT_EXPORT_NAME or NBD_OPT_GO....
857 qio_channel_set_blocking(client->ioc, false, NULL);
859 trace_nbd_negotiate_begin();
860 memcpy(buf, "NBDMAGIC", 8);
862 oldStyle = client->exp != NULL && !client->tlscreds;
864 trace_nbd_negotiate_old_style(client->exp->size,
865 client->exp->nbdflags | myflags);
866 stq_be_p(buf + 8, NBD_CLIENT_MAGIC);
867 stq_be_p(buf + 16, client->exp->size);
868 stl_be_p(buf + 24, client->exp->nbdflags | myflags);
870 if (nbd_write(client->ioc, buf, sizeof(buf), errp) < 0) {
871 error_prepend(errp, "write failed: ");
875 stq_be_p(buf + 8, NBD_OPTS_MAGIC);
876 stw_be_p(buf + 16, NBD_FLAG_FIXED_NEWSTYLE | NBD_FLAG_NO_ZEROES);
878 if (nbd_write(client->ioc, buf, 18, errp) < 0) {
879 error_prepend(errp, "write failed: ");
882 ret = nbd_negotiate_options(client, myflags, errp);
885 error_prepend(errp, "option negotiation failed: ");
891 trace_nbd_negotiate_success();
896 static int nbd_receive_request(QIOChannel *ioc, NBDRequest *request,
899 uint8_t buf[NBD_REQUEST_SIZE];
903 ret = nbd_read(ioc, buf, sizeof(buf), errp);
909 [ 0 .. 3] magic (NBD_REQUEST_MAGIC)
910 [ 4 .. 5] flags (NBD_CMD_FLAG_FUA, ...)
911 [ 6 .. 7] type (NBD_CMD_READ, ...)
917 magic = ldl_be_p(buf);
918 request->flags = lduw_be_p(buf + 4);
919 request->type = lduw_be_p(buf + 6);
920 request->handle = ldq_be_p(buf + 8);
921 request->from = ldq_be_p(buf + 16);
922 request->len = ldl_be_p(buf + 24);
924 trace_nbd_receive_request(magic, request->flags, request->type,
925 request->from, request->len);
927 if (magic != NBD_REQUEST_MAGIC) {
928 error_setg(errp, "invalid magic (got 0x%" PRIx32 ")", magic);
934 #define MAX_NBD_REQUESTS 16
936 void nbd_client_get(NBDClient *client)
941 void nbd_client_put(NBDClient *client)
943 if (--client->refcount == 0) {
944 /* The last reference should be dropped by client->close,
945 * which is called by client_close.
947 assert(client->closing);
949 qio_channel_detach_aio_context(client->ioc);
950 object_unref(OBJECT(client->sioc));
951 object_unref(OBJECT(client->ioc));
952 if (client->tlscreds) {
953 object_unref(OBJECT(client->tlscreds));
955 g_free(client->tlsaclname);
957 QTAILQ_REMOVE(&client->exp->clients, client, next);
958 nbd_export_put(client->exp);
964 static void client_close(NBDClient *client, bool negotiated)
966 if (client->closing) {
970 client->closing = true;
972 /* Force requests to finish. They will drop their own references,
973 * then we'll close the socket and free the NBDClient.
975 qio_channel_shutdown(client->ioc, QIO_CHANNEL_SHUTDOWN_BOTH,
978 /* Also tell the client, so that they release their reference. */
979 if (client->close_fn) {
980 client->close_fn(client, negotiated);
984 static NBDRequestData *nbd_request_get(NBDClient *client)
988 assert(client->nb_requests <= MAX_NBD_REQUESTS - 1);
989 client->nb_requests++;
991 req = g_new0(NBDRequestData, 1);
992 nbd_client_get(client);
993 req->client = client;
997 static void nbd_request_put(NBDRequestData *req)
999 NBDClient *client = req->client;
1002 qemu_vfree(req->data);
1006 client->nb_requests--;
1007 nbd_client_receive_next_request(client);
1009 nbd_client_put(client);
1012 static void blk_aio_attached(AioContext *ctx, void *opaque)
1014 NBDExport *exp = opaque;
1017 trace_nbd_blk_aio_attached(exp->name, ctx);
1021 QTAILQ_FOREACH(client, &exp->clients, next) {
1022 qio_channel_attach_aio_context(client->ioc, ctx);
1023 if (client->recv_coroutine) {
1024 aio_co_schedule(ctx, client->recv_coroutine);
1026 if (client->send_coroutine) {
1027 aio_co_schedule(ctx, client->send_coroutine);
1032 static void blk_aio_detach(void *opaque)
1034 NBDExport *exp = opaque;
1037 trace_nbd_blk_aio_detach(exp->name, exp->ctx);
1039 QTAILQ_FOREACH(client, &exp->clients, next) {
1040 qio_channel_detach_aio_context(client->ioc);
1046 static void nbd_eject_notifier(Notifier *n, void *data)
1048 NBDExport *exp = container_of(n, NBDExport, eject_notifier);
1049 nbd_export_close(exp);
1052 NBDExport *nbd_export_new(BlockDriverState *bs, off_t dev_offset, off_t size,
1053 uint16_t nbdflags, void (*close)(NBDExport *),
1054 bool writethrough, BlockBackend *on_eject_blk,
1059 NBDExport *exp = g_new0(NBDExport, 1);
1064 * NBD exports are used for non-shared storage migration. Make sure
1065 * that BDRV_O_INACTIVE is cleared and the image is ready for write
1066 * access since the export could be available before migration handover.
1068 ctx = bdrv_get_aio_context(bs);
1069 aio_context_acquire(ctx);
1070 bdrv_invalidate_cache(bs, NULL);
1071 aio_context_release(ctx);
1073 /* Don't allow resize while the NBD server is running, otherwise we don't
1074 * care what happens with the node. */
1075 perm = BLK_PERM_CONSISTENT_READ;
1076 if ((nbdflags & NBD_FLAG_READ_ONLY) == 0) {
1077 perm |= BLK_PERM_WRITE;
1079 blk = blk_new(perm, BLK_PERM_CONSISTENT_READ | BLK_PERM_WRITE_UNCHANGED |
1080 BLK_PERM_WRITE | BLK_PERM_GRAPH_MOD);
1081 ret = blk_insert_bs(blk, bs, errp);
1085 blk_set_enable_write_cache(blk, !writethrough);
1088 QTAILQ_INIT(&exp->clients);
1090 exp->dev_offset = dev_offset;
1091 exp->nbdflags = nbdflags;
1092 exp->size = size < 0 ? blk_getlength(blk) : size;
1093 if (exp->size < 0) {
1094 error_setg_errno(errp, -exp->size,
1095 "Failed to determine the NBD export's length");
1098 exp->size -= exp->size % BDRV_SECTOR_SIZE;
1101 exp->ctx = blk_get_aio_context(blk);
1102 blk_add_aio_context_notifier(blk, blk_aio_attached, blk_aio_detach, exp);
1105 blk_ref(on_eject_blk);
1106 exp->eject_notifier_blk = on_eject_blk;
1107 exp->eject_notifier.notify = nbd_eject_notifier;
1108 blk_add_remove_bs_notifier(on_eject_blk, &exp->eject_notifier);
1118 NBDExport *nbd_export_find(const char *name)
1121 QTAILQ_FOREACH(exp, &exports, next) {
1122 if (strcmp(name, exp->name) == 0) {
1130 void nbd_export_set_name(NBDExport *exp, const char *name)
1132 if (exp->name == name) {
1136 nbd_export_get(exp);
1137 if (exp->name != NULL) {
1140 QTAILQ_REMOVE(&exports, exp, next);
1141 nbd_export_put(exp);
1144 nbd_export_get(exp);
1145 exp->name = g_strdup(name);
1146 QTAILQ_INSERT_TAIL(&exports, exp, next);
1148 nbd_export_put(exp);
1151 void nbd_export_set_description(NBDExport *exp, const char *description)
1153 g_free(exp->description);
1154 exp->description = g_strdup(description);
1157 void nbd_export_close(NBDExport *exp)
1159 NBDClient *client, *next;
1161 nbd_export_get(exp);
1162 QTAILQ_FOREACH_SAFE(client, &exp->clients, next, next) {
1163 client_close(client, true);
1165 nbd_export_set_name(exp, NULL);
1166 nbd_export_set_description(exp, NULL);
1167 nbd_export_put(exp);
1170 void nbd_export_get(NBDExport *exp)
1172 assert(exp->refcount > 0);
1176 void nbd_export_put(NBDExport *exp)
1178 assert(exp->refcount > 0);
1179 if (exp->refcount == 1) {
1180 nbd_export_close(exp);
1183 if (--exp->refcount == 0) {
1184 assert(exp->name == NULL);
1185 assert(exp->description == NULL);
1192 if (exp->eject_notifier_blk) {
1193 notifier_remove(&exp->eject_notifier);
1194 blk_unref(exp->eject_notifier_blk);
1196 blk_remove_aio_context_notifier(exp->blk, blk_aio_attached,
1197 blk_aio_detach, exp);
1198 blk_unref(exp->blk);
1206 BlockBackend *nbd_export_get_blockdev(NBDExport *exp)
1211 void nbd_export_close_all(void)
1213 NBDExport *exp, *next;
1215 QTAILQ_FOREACH_SAFE(exp, &exports, next, next) {
1216 nbd_export_close(exp);
1220 static int coroutine_fn nbd_co_send_iov(NBDClient *client, struct iovec *iov,
1221 unsigned niov, Error **errp)
1225 g_assert(qemu_in_coroutine());
1226 qemu_co_mutex_lock(&client->send_lock);
1227 client->send_coroutine = qemu_coroutine_self();
1229 ret = qio_channel_writev_all(client->ioc, iov, niov, errp) < 0 ? -EIO : 0;
1231 client->send_coroutine = NULL;
1232 qemu_co_mutex_unlock(&client->send_lock);
1237 static inline void set_be_simple_reply(NBDSimpleReply *reply, uint64_t error,
1240 stl_be_p(&reply->magic, NBD_SIMPLE_REPLY_MAGIC);
1241 stl_be_p(&reply->error, error);
1242 stq_be_p(&reply->handle, handle);
1245 static int nbd_co_send_simple_reply(NBDClient *client,
1252 NBDSimpleReply reply;
1253 int nbd_err = system_errno_to_nbd_errno(error);
1254 struct iovec iov[] = {
1255 {.iov_base = &reply, .iov_len = sizeof(reply)},
1256 {.iov_base = data, .iov_len = len}
1259 trace_nbd_co_send_simple_reply(handle, nbd_err, nbd_err_lookup(nbd_err),
1261 set_be_simple_reply(&reply, nbd_err, handle);
1263 return nbd_co_send_iov(client, iov, len ? 2 : 1, errp);
1266 static inline void set_be_chunk(NBDStructuredReplyChunk *chunk, uint16_t flags,
1267 uint16_t type, uint64_t handle, uint32_t length)
1269 stl_be_p(&chunk->magic, NBD_STRUCTURED_REPLY_MAGIC);
1270 stw_be_p(&chunk->flags, flags);
1271 stw_be_p(&chunk->type, type);
1272 stq_be_p(&chunk->handle, handle);
1273 stl_be_p(&chunk->length, length);
1276 static int coroutine_fn nbd_co_send_structured_done(NBDClient *client,
1280 NBDStructuredReplyChunk chunk;
1281 struct iovec iov[] = {
1282 {.iov_base = &chunk, .iov_len = sizeof(chunk)},
1285 trace_nbd_co_send_structured_done(handle);
1286 set_be_chunk(&chunk, NBD_REPLY_FLAG_DONE, NBD_REPLY_TYPE_NONE, handle, 0);
1288 return nbd_co_send_iov(client, iov, 1, errp);
1291 static int coroutine_fn nbd_co_send_structured_read(NBDClient *client,
1298 NBDStructuredReadData chunk;
1299 struct iovec iov[] = {
1300 {.iov_base = &chunk, .iov_len = sizeof(chunk)},
1301 {.iov_base = data, .iov_len = size}
1305 trace_nbd_co_send_structured_read(handle, offset, data, size);
1306 set_be_chunk(&chunk.h, NBD_REPLY_FLAG_DONE, NBD_REPLY_TYPE_OFFSET_DATA,
1307 handle, sizeof(chunk) - sizeof(chunk.h) + size);
1308 stq_be_p(&chunk.offset, offset);
1310 return nbd_co_send_iov(client, iov, 2, errp);
1313 static int coroutine_fn nbd_co_send_structured_error(NBDClient *client,
1319 NBDStructuredError chunk;
1320 int nbd_err = system_errno_to_nbd_errno(error);
1321 struct iovec iov[] = {
1322 {.iov_base = &chunk, .iov_len = sizeof(chunk)},
1323 {.iov_base = (char *)msg, .iov_len = msg ? strlen(msg) : 0},
1327 trace_nbd_co_send_structured_error(handle, nbd_err,
1328 nbd_err_lookup(nbd_err), msg ? msg : "");
1329 set_be_chunk(&chunk.h, NBD_REPLY_FLAG_DONE, NBD_REPLY_TYPE_ERROR, handle,
1330 sizeof(chunk) - sizeof(chunk.h) + iov[1].iov_len);
1331 stl_be_p(&chunk.error, nbd_err);
1332 stw_be_p(&chunk.message_length, iov[1].iov_len);
1334 return nbd_co_send_iov(client, iov, 1 + !!iov[1].iov_len, errp);
1337 /* nbd_co_receive_request
1338 * Collect a client request. Return 0 if request looks valid, -EIO to drop
1339 * connection right away, and any other negative value to report an error to
1340 * the client (although the caller may still need to disconnect after reporting
1343 static int nbd_co_receive_request(NBDRequestData *req, NBDRequest *request,
1346 NBDClient *client = req->client;
1349 g_assert(qemu_in_coroutine());
1350 assert(client->recv_coroutine == qemu_coroutine_self());
1351 if (nbd_receive_request(client->ioc, request, errp) < 0) {
1355 trace_nbd_co_receive_request_decode_type(request->handle, request->type,
1356 nbd_cmd_lookup(request->type));
1358 if (request->type != NBD_CMD_WRITE) {
1359 /* No payload, we are ready to read the next request. */
1360 req->complete = true;
1363 if (request->type == NBD_CMD_DISC) {
1364 /* Special case: we're going to disconnect without a reply,
1365 * whether or not flags, from, or len are bogus */
1369 if (request->type == NBD_CMD_READ || request->type == NBD_CMD_WRITE) {
1370 if (request->len > NBD_MAX_BUFFER_SIZE) {
1371 error_setg(errp, "len (%" PRIu32" ) is larger than max len (%u)",
1372 request->len, NBD_MAX_BUFFER_SIZE);
1376 req->data = blk_try_blockalign(client->exp->blk, request->len);
1377 if (req->data == NULL) {
1378 error_setg(errp, "No memory");
1382 if (request->type == NBD_CMD_WRITE) {
1383 if (nbd_read(client->ioc, req->data, request->len, errp) < 0) {
1384 error_prepend(errp, "reading from socket failed: ");
1387 req->complete = true;
1389 trace_nbd_co_receive_request_payload_received(request->handle,
1393 /* Sanity checks. */
1394 if (client->exp->nbdflags & NBD_FLAG_READ_ONLY &&
1395 (request->type == NBD_CMD_WRITE ||
1396 request->type == NBD_CMD_WRITE_ZEROES ||
1397 request->type == NBD_CMD_TRIM)) {
1398 error_setg(errp, "Export is read-only");
1401 if (request->from > client->exp->size ||
1402 request->from + request->len > client->exp->size) {
1403 error_setg(errp, "operation past EOF; From: %" PRIu64 ", Len: %" PRIu32
1404 ", Size: %" PRIu64, request->from, request->len,
1405 (uint64_t)client->exp->size);
1406 return (request->type == NBD_CMD_WRITE ||
1407 request->type == NBD_CMD_WRITE_ZEROES) ? -ENOSPC : -EINVAL;
1409 valid_flags = NBD_CMD_FLAG_FUA;
1410 if (request->type == NBD_CMD_READ && client->structured_reply) {
1411 valid_flags |= NBD_CMD_FLAG_DF;
1412 } else if (request->type == NBD_CMD_WRITE_ZEROES) {
1413 valid_flags |= NBD_CMD_FLAG_NO_HOLE;
1415 if (request->flags & ~valid_flags) {
1416 error_setg(errp, "unsupported flags for command %s (got 0x%x)",
1417 nbd_cmd_lookup(request->type), request->flags);
1424 /* Owns a reference to the NBDClient passed as opaque. */
1425 static coroutine_fn void nbd_trip(void *opaque)
1427 NBDClient *client = opaque;
1428 NBDExport *exp = client->exp;
1429 NBDRequestData *req;
1430 NBDRequest request = { 0 }; /* GCC thinks it can be used uninitialized */
1433 int reply_data_len = 0;
1434 Error *local_err = NULL;
1438 if (client->closing) {
1439 nbd_client_put(client);
1443 req = nbd_request_get(client);
1444 ret = nbd_co_receive_request(req, &request, &local_err);
1445 client->recv_coroutine = NULL;
1446 nbd_client_receive_next_request(client);
1455 if (client->closing) {
1457 * The client may be closed when we are blocked in
1458 * nbd_co_receive_request()
1463 switch (request.type) {
1465 /* XXX: NBD Protocol only documents use of FUA with WRITE */
1466 if (request.flags & NBD_CMD_FLAG_FUA) {
1467 ret = blk_co_flush(exp->blk);
1469 error_setg_errno(&local_err, -ret, "flush failed");
1474 ret = blk_pread(exp->blk, request.from + exp->dev_offset,
1475 req->data, request.len);
1477 error_setg_errno(&local_err, -ret, "reading from file failed");
1481 reply_data_len = request.len;
1486 if (request.flags & NBD_CMD_FLAG_FUA) {
1487 flags |= BDRV_REQ_FUA;
1489 ret = blk_pwrite(exp->blk, request.from + exp->dev_offset,
1490 req->data, request.len, flags);
1492 error_setg_errno(&local_err, -ret, "writing to file failed");
1496 case NBD_CMD_WRITE_ZEROES:
1498 if (request.flags & NBD_CMD_FLAG_FUA) {
1499 flags |= BDRV_REQ_FUA;
1501 if (!(request.flags & NBD_CMD_FLAG_NO_HOLE)) {
1502 flags |= BDRV_REQ_MAY_UNMAP;
1504 ret = blk_pwrite_zeroes(exp->blk, request.from + exp->dev_offset,
1505 request.len, flags);
1507 error_setg_errno(&local_err, -ret, "writing to file failed");
1512 /* unreachable, thanks to special case in nbd_co_receive_request() */
1516 ret = blk_co_flush(exp->blk);
1518 error_setg_errno(&local_err, -ret, "flush failed");
1523 ret = blk_co_pdiscard(exp->blk, request.from + exp->dev_offset,
1526 error_setg_errno(&local_err, -ret, "discard failed");
1531 error_setg(&local_err, "invalid request type (%" PRIu32 ") received",
1538 /* If we get here, local_err was not a fatal error, and should be sent
1541 msg = g_strdup(error_get_pretty(local_err));
1542 error_report_err(local_err);
1546 if (client->structured_reply &&
1547 (ret < 0 || request.type == NBD_CMD_READ)) {
1549 ret = nbd_co_send_structured_error(req->client, request.handle,
1550 -ret, msg, &local_err);
1551 } else if (reply_data_len) {
1552 ret = nbd_co_send_structured_read(req->client, request.handle,
1553 request.from, req->data,
1554 reply_data_len, &local_err);
1556 ret = nbd_co_send_structured_done(req->client, request.handle,
1560 ret = nbd_co_send_simple_reply(req->client, request.handle,
1562 req->data, reply_data_len, &local_err);
1566 error_prepend(&local_err, "Failed to send reply: ");
1570 /* We must disconnect after NBD_CMD_WRITE if we did not
1573 if (!req->complete) {
1574 error_setg(&local_err, "Request handling failed in intermediate state");
1579 nbd_request_put(req);
1580 nbd_client_put(client);
1585 error_reportf_err(local_err, "Disconnect client, due to: ");
1587 nbd_request_put(req);
1588 client_close(client, true);
1589 nbd_client_put(client);
1592 static void nbd_client_receive_next_request(NBDClient *client)
1594 if (!client->recv_coroutine && client->nb_requests < MAX_NBD_REQUESTS) {
1595 nbd_client_get(client);
1596 client->recv_coroutine = qemu_coroutine_create(nbd_trip, client);
1597 aio_co_schedule(client->exp->ctx, client->recv_coroutine);
1601 static coroutine_fn void nbd_co_client_start(void *opaque)
1603 NBDClient *client = opaque;
1604 NBDExport *exp = client->exp;
1605 Error *local_err = NULL;
1608 nbd_export_get(exp);
1609 QTAILQ_INSERT_TAIL(&exp->clients, client, next);
1611 qemu_co_mutex_init(&client->send_lock);
1613 if (nbd_negotiate(client, &local_err)) {
1615 error_report_err(local_err);
1617 client_close(client, false);
1621 nbd_client_receive_next_request(client);
1625 * Create a new client listener on the given export @exp, using the
1626 * given channel @sioc. Begin servicing it in a coroutine. When the
1627 * connection closes, call @close_fn with an indication of whether the
1628 * client completed negotiation.
1630 void nbd_client_new(NBDExport *exp,
1631 QIOChannelSocket *sioc,
1632 QCryptoTLSCreds *tlscreds,
1633 const char *tlsaclname,
1634 void (*close_fn)(NBDClient *, bool))
1639 client = g_new0(NBDClient, 1);
1640 client->refcount = 1;
1642 client->tlscreds = tlscreds;
1644 object_ref(OBJECT(client->tlscreds));
1646 client->tlsaclname = g_strdup(tlsaclname);
1647 client->sioc = sioc;
1648 object_ref(OBJECT(client->sioc));
1649 client->ioc = QIO_CHANNEL(sioc);
1650 object_ref(OBJECT(client->ioc));
1651 client->close_fn = close_fn;
1653 co = qemu_coroutine_create(nbd_co_client_start, client);
1654 qemu_coroutine_enter(co);