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)
51 /* Definitions for opaque data types */
53 typedef struct NBDRequestData NBDRequestData;
55 struct NBDRequestData {
56 QSIMPLEQ_ENTRY(NBDRequestData) entry;
64 void (*close)(NBDExport *exp);
72 QTAILQ_HEAD(, NBDClient) clients;
73 QTAILQ_ENTRY(NBDExport) next;
77 BlockBackend *eject_notifier_blk;
78 Notifier eject_notifier;
81 static QTAILQ_HEAD(, NBDExport) exports = QTAILQ_HEAD_INITIALIZER(exports);
85 void (*close_fn)(NBDClient *client, bool negotiated);
88 QCryptoTLSCreds *tlscreds;
90 QIOChannelSocket *sioc; /* The underlying data channel */
91 QIOChannel *ioc; /* The current I/O channel which may differ (eg TLS) */
93 Coroutine *recv_coroutine;
96 Coroutine *send_coroutine;
98 QTAILQ_ENTRY(NBDClient) next;
103 /* That's all folks */
105 static void nbd_client_receive_next_request(NBDClient *client);
107 /* Basic flow for negotiation
134 /* Send a reply header, including length, but no payload.
135 * Return -errno on error, 0 on success. */
136 static int nbd_negotiate_send_rep_len(QIOChannel *ioc, uint32_t type,
137 uint32_t opt, uint32_t len, Error **errp)
141 trace_nbd_negotiate_send_rep_len(opt, nbd_opt_lookup(opt),
142 type, nbd_rep_lookup(type), len);
144 assert(len < NBD_MAX_BUFFER_SIZE);
145 magic = cpu_to_be64(NBD_REP_MAGIC);
146 if (nbd_write(ioc, &magic, sizeof(magic), errp) < 0) {
147 error_prepend(errp, "write failed (rep magic): ");
151 opt = cpu_to_be32(opt);
152 if (nbd_write(ioc, &opt, sizeof(opt), errp) < 0) {
153 error_prepend(errp, "write failed (rep opt): ");
157 type = cpu_to_be32(type);
158 if (nbd_write(ioc, &type, sizeof(type), errp) < 0) {
159 error_prepend(errp, "write failed (rep type): ");
163 len = cpu_to_be32(len);
164 if (nbd_write(ioc, &len, sizeof(len), errp) < 0) {
165 error_prepend(errp, "write failed (rep data length): ");
171 /* Send a reply header with default 0 length.
172 * Return -errno on error, 0 on success. */
173 static int nbd_negotiate_send_rep(QIOChannel *ioc, uint32_t type, uint32_t opt,
176 return nbd_negotiate_send_rep_len(ioc, type, opt, 0, errp);
179 /* Send an error reply.
180 * Return -errno on error, 0 on success. */
181 static int GCC_FMT_ATTR(5, 6)
182 nbd_negotiate_send_rep_err(QIOChannel *ioc, uint32_t type,
183 uint32_t opt, Error **errp, const char *fmt, ...)
191 msg = g_strdup_vprintf(fmt, va);
195 trace_nbd_negotiate_send_rep_err(msg);
196 ret = nbd_negotiate_send_rep_len(ioc, type, opt, len, errp);
200 if (nbd_write(ioc, msg, len, errp) < 0) {
201 error_prepend(errp, "write failed (error message): ");
212 /* Send a single NBD_REP_SERVER reply to NBD_OPT_LIST, including payload.
213 * Return -errno on error, 0 on success. */
214 static int nbd_negotiate_send_rep_list(QIOChannel *ioc, NBDExport *exp,
217 size_t name_len, desc_len;
219 const char *name = exp->name ? exp->name : "";
220 const char *desc = exp->description ? exp->description : "";
223 trace_nbd_negotiate_send_rep_list(name, desc);
224 name_len = strlen(name);
225 desc_len = strlen(desc);
226 len = name_len + desc_len + sizeof(len);
227 ret = nbd_negotiate_send_rep_len(ioc, NBD_REP_SERVER, NBD_OPT_LIST, len,
233 len = cpu_to_be32(name_len);
234 if (nbd_write(ioc, &len, sizeof(len), errp) < 0) {
235 error_prepend(errp, "write failed (name length): ");
239 if (nbd_write(ioc, name, name_len, errp) < 0) {
240 error_prepend(errp, "write failed (name buffer): ");
244 if (nbd_write(ioc, desc, desc_len, errp) < 0) {
245 error_prepend(errp, "write failed (description buffer): ");
252 /* Process the NBD_OPT_LIST command, with a potential series of replies.
253 * Return -errno on error, 0 on success. */
254 static int nbd_negotiate_handle_list(NBDClient *client, uint32_t length,
260 if (nbd_drop(client->ioc, length, errp) < 0) {
263 return nbd_negotiate_send_rep_err(client->ioc,
264 NBD_REP_ERR_INVALID, NBD_OPT_LIST,
266 "OPT_LIST should not have length");
269 /* For each export, send a NBD_REP_SERVER reply. */
270 QTAILQ_FOREACH(exp, &exports, next) {
271 if (nbd_negotiate_send_rep_list(client->ioc, exp, errp)) {
275 /* Finish with a NBD_REP_ACK. */
276 return nbd_negotiate_send_rep(client->ioc, NBD_REP_ACK, NBD_OPT_LIST, errp);
279 /* Send a reply to NBD_OPT_EXPORT_NAME.
280 * Return -errno on error, 0 on success. */
281 static int nbd_negotiate_handle_export_name(NBDClient *client, uint32_t length,
282 uint16_t myflags, bool no_zeroes,
285 char name[NBD_MAX_NAME_SIZE + 1];
286 char buf[NBD_REPLY_EXPORT_NAME_SIZE] = "";
291 [20 .. xx] export name (length bytes)
294 [ 8 .. 9] export flags
295 [10 .. 133] reserved (0) [unless no_zeroes]
297 trace_nbd_negotiate_handle_export_name();
298 if (length >= sizeof(name)) {
299 error_setg(errp, "Bad length received");
302 if (nbd_read(client->ioc, name, length, errp) < 0) {
303 error_prepend(errp, "read failed: ");
308 trace_nbd_negotiate_handle_export_name_request(name);
310 client->exp = nbd_export_find(name);
312 error_setg(errp, "export not found");
316 trace_nbd_negotiate_new_style_size_flags(client->exp->size,
317 client->exp->nbdflags | myflags);
318 stq_be_p(buf, client->exp->size);
319 stw_be_p(buf + 8, client->exp->nbdflags | myflags);
320 len = no_zeroes ? 10 : sizeof(buf);
321 ret = nbd_write(client->ioc, buf, len, errp);
323 error_prepend(errp, "write failed: ");
327 QTAILQ_INSERT_TAIL(&client->exp->clients, client, next);
328 nbd_export_get(client->exp);
333 /* Send a single NBD_REP_INFO, with a buffer @buf of @length bytes.
334 * The buffer does NOT include the info type prefix.
335 * Return -errno on error, 0 if ready to send more. */
336 static int nbd_negotiate_send_info(NBDClient *client, uint32_t opt,
337 uint16_t info, uint32_t length, void *buf,
342 trace_nbd_negotiate_send_info(info, nbd_info_lookup(info), length);
343 rc = nbd_negotiate_send_rep_len(client->ioc, NBD_REP_INFO, opt,
344 sizeof(info) + length, errp);
349 if (nbd_write(client->ioc, &info, sizeof(info), errp) < 0) {
352 if (nbd_write(client->ioc, buf, length, errp) < 0) {
358 /* Handle NBD_OPT_INFO and NBD_OPT_GO.
359 * Return -errno on error, 0 if ready for next option, and 1 to move
360 * into transmission phase. */
361 static int nbd_negotiate_handle_info(NBDClient *client, uint32_t length,
362 uint32_t opt, uint16_t myflags,
366 char name[NBD_MAX_NAME_SIZE + 1];
371 bool sendname = false;
372 bool blocksize = false;
374 char buf[sizeof(uint64_t) + sizeof(uint16_t)];
378 4 bytes: L, name length (can be 0)
380 2 bytes: N, number of requests (can be 0)
381 N * 2 bytes: N requests
383 if (length < sizeof(namelen) + sizeof(requests)) {
384 msg = "overall request too short";
387 if (nbd_read(client->ioc, &namelen, sizeof(namelen), errp) < 0) {
390 be32_to_cpus(&namelen);
391 length -= sizeof(namelen);
392 if (namelen > length - sizeof(requests) || (length - namelen) % 2) {
393 msg = "name length is incorrect";
396 if (nbd_read(client->ioc, name, namelen, errp) < 0) {
399 name[namelen] = '\0';
401 trace_nbd_negotiate_handle_export_name_request(name);
403 if (nbd_read(client->ioc, &requests, sizeof(requests), errp) < 0) {
406 be16_to_cpus(&requests);
407 length -= sizeof(requests);
408 trace_nbd_negotiate_handle_info_requests(requests);
409 if (requests != length / sizeof(request)) {
410 msg = "incorrect number of requests for overall length";
414 if (nbd_read(client->ioc, &request, sizeof(request), errp) < 0) {
417 be16_to_cpus(&request);
418 length -= sizeof(request);
419 trace_nbd_negotiate_handle_info_request(request,
420 nbd_info_lookup(request));
421 /* We care about NBD_INFO_NAME and NBD_INFO_BLOCK_SIZE;
422 * everything else is either a request we don't know or
423 * something we send regardless of request */
428 case NBD_INFO_BLOCK_SIZE:
434 exp = nbd_export_find(name);
436 return nbd_negotiate_send_rep_err(client->ioc, NBD_REP_ERR_UNKNOWN,
437 opt, errp, "export '%s' not present",
441 /* Don't bother sending NBD_INFO_NAME unless client requested it */
443 rc = nbd_negotiate_send_info(client, opt, NBD_INFO_NAME, length, name,
450 /* Send NBD_INFO_DESCRIPTION only if available, regardless of
452 if (exp->description) {
453 size_t len = strlen(exp->description);
455 rc = nbd_negotiate_send_info(client, opt, NBD_INFO_DESCRIPTION,
456 len, exp->description, errp);
462 /* Send NBD_INFO_BLOCK_SIZE always, but tweak the minimum size
463 * according to whether the client requested it, and according to
464 * whether this is OPT_INFO or OPT_GO. */
465 /* minimum - 1 for back-compat, or 512 if client is new enough.
466 * TODO: consult blk_bs(blk)->bl.request_alignment? */
467 sizes[0] = (opt == NBD_OPT_INFO || blocksize) ? BDRV_SECTOR_SIZE : 1;
468 /* preferred - Hard-code to 4096 for now.
469 * TODO: is blk_bs(blk)->bl.opt_transfer appropriate? */
471 /* maximum - At most 32M, but smaller as appropriate. */
472 sizes[2] = MIN(blk_get_max_transfer(exp->blk), NBD_MAX_BUFFER_SIZE);
473 trace_nbd_negotiate_handle_info_block_size(sizes[0], sizes[1], sizes[2]);
474 cpu_to_be32s(&sizes[0]);
475 cpu_to_be32s(&sizes[1]);
476 cpu_to_be32s(&sizes[2]);
477 rc = nbd_negotiate_send_info(client, opt, NBD_INFO_BLOCK_SIZE,
478 sizeof(sizes), sizes, errp);
483 /* Send NBD_INFO_EXPORT always */
484 trace_nbd_negotiate_new_style_size_flags(exp->size,
485 exp->nbdflags | myflags);
486 stq_be_p(buf, exp->size);
487 stw_be_p(buf + 8, exp->nbdflags | myflags);
488 rc = nbd_negotiate_send_info(client, opt, NBD_INFO_EXPORT,
489 sizeof(buf), buf, errp);
494 /* If the client is just asking for NBD_OPT_INFO, but forgot to
495 * request block sizes, return an error.
496 * TODO: consult blk_bs(blk)->request_align, and only error if it
498 if (opt == NBD_OPT_INFO && !blocksize) {
499 return nbd_negotiate_send_rep_err(client->ioc,
500 NBD_REP_ERR_BLOCK_SIZE_REQD, opt,
502 "request NBD_INFO_BLOCK_SIZE to "
507 rc = nbd_negotiate_send_rep(client->ioc, NBD_REP_ACK, opt, errp);
512 if (opt == NBD_OPT_GO) {
514 QTAILQ_INSERT_TAIL(&client->exp->clients, client, next);
515 nbd_export_get(client->exp);
521 if (nbd_drop(client->ioc, length, errp) < 0) {
524 return nbd_negotiate_send_rep_err(client->ioc, NBD_REP_ERR_INVALID, opt,
529 /* Handle NBD_OPT_STARTTLS. Return NULL to drop connection, or else the
530 * new channel for all further (now-encrypted) communication. */
531 static QIOChannel *nbd_negotiate_handle_starttls(NBDClient *client,
537 struct NBDTLSHandshakeData data = { 0 };
539 trace_nbd_negotiate_handle_starttls();
542 if (nbd_drop(ioc, length, errp) < 0) {
545 nbd_negotiate_send_rep_err(ioc, NBD_REP_ERR_INVALID, NBD_OPT_STARTTLS,
547 "OPT_STARTTLS should not have length");
551 if (nbd_negotiate_send_rep(client->ioc, NBD_REP_ACK,
552 NBD_OPT_STARTTLS, errp) < 0) {
556 tioc = qio_channel_tls_new_server(ioc,
564 qio_channel_set_name(QIO_CHANNEL(tioc), "nbd-server-tls");
565 trace_nbd_negotiate_handle_starttls_handshake();
566 data.loop = g_main_loop_new(g_main_context_default(), FALSE);
567 qio_channel_tls_handshake(tioc,
572 if (!data.complete) {
573 g_main_loop_run(data.loop);
575 g_main_loop_unref(data.loop);
577 object_unref(OBJECT(tioc));
578 error_propagate(errp, data.error);
582 return QIO_CHANNEL(tioc);
585 /* nbd_negotiate_options
586 * Process all NBD_OPT_* client option commands, during fixed newstyle
589 * -errno on error, errp is set
590 * 0 on successful negotiation, errp is not set
591 * 1 if client sent NBD_OPT_ABORT, i.e. on valid disconnect,
594 static int nbd_negotiate_options(NBDClient *client, uint16_t myflags,
598 bool fixedNewstyle = false;
599 bool no_zeroes = false;
602 [ 0 .. 3] client flags
604 Then we loop until NBD_OPT_EXPORT_NAME or NBD_OPT_GO:
605 [ 0 .. 7] NBD_OPTS_MAGIC
606 [ 8 .. 11] NBD option
607 [12 .. 15] Data length
610 [ 0 .. 7] NBD_OPTS_MAGIC
611 [ 8 .. 11] Second NBD option
612 [12 .. 15] Data length
616 if (nbd_read(client->ioc, &flags, sizeof(flags), errp) < 0) {
617 error_prepend(errp, "read failed: ");
620 be32_to_cpus(&flags);
621 trace_nbd_negotiate_options_flags(flags);
622 if (flags & NBD_FLAG_C_FIXED_NEWSTYLE) {
623 fixedNewstyle = true;
624 flags &= ~NBD_FLAG_C_FIXED_NEWSTYLE;
626 if (flags & NBD_FLAG_C_NO_ZEROES) {
628 flags &= ~NBD_FLAG_C_NO_ZEROES;
631 error_setg(errp, "Unknown client flags 0x%" PRIx32 " received", flags);
637 uint32_t option, length;
640 if (nbd_read(client->ioc, &magic, sizeof(magic), errp) < 0) {
641 error_prepend(errp, "read failed: ");
644 magic = be64_to_cpu(magic);
645 trace_nbd_negotiate_options_check_magic(magic);
646 if (magic != NBD_OPTS_MAGIC) {
647 error_setg(errp, "Bad magic received");
651 if (nbd_read(client->ioc, &option,
652 sizeof(option), errp) < 0) {
653 error_prepend(errp, "read failed: ");
656 option = be32_to_cpu(option);
658 if (nbd_read(client->ioc, &length, sizeof(length), errp) < 0) {
659 error_prepend(errp, "read failed: ");
662 length = be32_to_cpu(length);
664 trace_nbd_negotiate_options_check_option(option,
665 nbd_opt_lookup(option));
666 if (client->tlscreds &&
667 client->ioc == (QIOChannel *)client->sioc) {
669 if (!fixedNewstyle) {
670 error_setg(errp, "Unsupported option 0x%" PRIx32, option);
674 case NBD_OPT_STARTTLS:
675 tioc = nbd_negotiate_handle_starttls(client, length, errp);
679 object_unref(OBJECT(client->ioc));
680 client->ioc = QIO_CHANNEL(tioc);
683 case NBD_OPT_EXPORT_NAME:
684 /* No way to return an error to client, so drop connection */
685 error_setg(errp, "Option 0x%x not permitted before TLS",
690 if (nbd_drop(client->ioc, length, errp) < 0) {
693 ret = nbd_negotiate_send_rep_err(client->ioc,
694 NBD_REP_ERR_TLS_REQD,
697 "not permitted before TLS",
702 /* Let the client keep trying, unless they asked to
703 * quit. In this mode, we've already sent an error, so
704 * we can't ack the abort. */
705 if (option == NBD_OPT_ABORT) {
710 } else if (fixedNewstyle) {
713 ret = nbd_negotiate_handle_list(client, length, errp);
720 /* NBD spec says we must try to reply before
721 * disconnecting, but that we must also tolerate
722 * guests that don't wait for our reply. */
723 nbd_negotiate_send_rep(client->ioc, NBD_REP_ACK, option, NULL);
726 case NBD_OPT_EXPORT_NAME:
727 return nbd_negotiate_handle_export_name(client, length,
733 ret = nbd_negotiate_handle_info(client, length, option,
736 assert(option == NBD_OPT_GO);
744 case NBD_OPT_STARTTLS:
745 if (nbd_drop(client->ioc, length, errp) < 0) {
748 if (client->tlscreds) {
749 ret = nbd_negotiate_send_rep_err(client->ioc,
752 "TLS already enabled");
754 ret = nbd_negotiate_send_rep_err(client->ioc,
757 "TLS not configured");
764 if (nbd_drop(client->ioc, length, errp) < 0) {
767 ret = nbd_negotiate_send_rep_err(client->ioc,
770 "Unsupported option 0x%"
771 PRIx32 " (%s)", option,
772 nbd_opt_lookup(option));
780 * If broken new-style we should drop the connection
781 * for anything except NBD_OPT_EXPORT_NAME
784 case NBD_OPT_EXPORT_NAME:
785 return nbd_negotiate_handle_export_name(client, length,
790 error_setg(errp, "Unsupported option 0x%" PRIx32 " (%s)",
791 option, nbd_opt_lookup(option));
800 * -errno on error, errp is set
801 * 0 on successful negotiation, errp is not set
802 * 1 if client sent NBD_OPT_ABORT, i.e. on valid disconnect,
805 static coroutine_fn int nbd_negotiate(NBDClient *client, Error **errp)
807 char buf[NBD_OLDSTYLE_NEGOTIATE_SIZE] = "";
809 const uint16_t myflags = (NBD_FLAG_HAS_FLAGS | NBD_FLAG_SEND_TRIM |
810 NBD_FLAG_SEND_FLUSH | NBD_FLAG_SEND_FUA |
811 NBD_FLAG_SEND_WRITE_ZEROES);
814 /* Old style negotiation header, no room for options
815 [ 0 .. 7] passwd ("NBDMAGIC")
816 [ 8 .. 15] magic (NBD_CLIENT_MAGIC)
818 [24 .. 27] export flags (zero-extended)
819 [28 .. 151] reserved (0)
821 New style negotiation header, client can send options
822 [ 0 .. 7] passwd ("NBDMAGIC")
823 [ 8 .. 15] magic (NBD_OPTS_MAGIC)
824 [16 .. 17] server flags (0)
825 ....options sent, ending in NBD_OPT_EXPORT_NAME or NBD_OPT_GO....
828 qio_channel_set_blocking(client->ioc, false, NULL);
830 trace_nbd_negotiate_begin();
831 memcpy(buf, "NBDMAGIC", 8);
833 oldStyle = client->exp != NULL && !client->tlscreds;
835 trace_nbd_negotiate_old_style(client->exp->size,
836 client->exp->nbdflags | myflags);
837 stq_be_p(buf + 8, NBD_CLIENT_MAGIC);
838 stq_be_p(buf + 16, client->exp->size);
839 stl_be_p(buf + 24, client->exp->nbdflags | myflags);
841 if (nbd_write(client->ioc, buf, sizeof(buf), errp) < 0) {
842 error_prepend(errp, "write failed: ");
846 stq_be_p(buf + 8, NBD_OPTS_MAGIC);
847 stw_be_p(buf + 16, NBD_FLAG_FIXED_NEWSTYLE | NBD_FLAG_NO_ZEROES);
849 if (nbd_write(client->ioc, buf, 18, errp) < 0) {
850 error_prepend(errp, "write failed: ");
853 ret = nbd_negotiate_options(client, myflags, errp);
856 error_prepend(errp, "option negotiation failed: ");
862 trace_nbd_negotiate_success();
867 static int nbd_receive_request(QIOChannel *ioc, NBDRequest *request,
870 uint8_t buf[NBD_REQUEST_SIZE];
874 ret = nbd_read(ioc, buf, sizeof(buf), errp);
880 [ 0 .. 3] magic (NBD_REQUEST_MAGIC)
881 [ 4 .. 5] flags (NBD_CMD_FLAG_FUA, ...)
882 [ 6 .. 7] type (NBD_CMD_READ, ...)
888 magic = ldl_be_p(buf);
889 request->flags = lduw_be_p(buf + 4);
890 request->type = lduw_be_p(buf + 6);
891 request->handle = ldq_be_p(buf + 8);
892 request->from = ldq_be_p(buf + 16);
893 request->len = ldl_be_p(buf + 24);
895 trace_nbd_receive_request(magic, request->flags, request->type,
896 request->from, request->len);
898 if (magic != NBD_REQUEST_MAGIC) {
899 error_setg(errp, "invalid magic (got 0x%" PRIx32 ")", magic);
905 #define MAX_NBD_REQUESTS 16
907 void nbd_client_get(NBDClient *client)
912 void nbd_client_put(NBDClient *client)
914 if (--client->refcount == 0) {
915 /* The last reference should be dropped by client->close,
916 * which is called by client_close.
918 assert(client->closing);
920 qio_channel_detach_aio_context(client->ioc);
921 object_unref(OBJECT(client->sioc));
922 object_unref(OBJECT(client->ioc));
923 if (client->tlscreds) {
924 object_unref(OBJECT(client->tlscreds));
926 g_free(client->tlsaclname);
928 QTAILQ_REMOVE(&client->exp->clients, client, next);
929 nbd_export_put(client->exp);
935 static void client_close(NBDClient *client, bool negotiated)
937 if (client->closing) {
941 client->closing = true;
943 /* Force requests to finish. They will drop their own references,
944 * then we'll close the socket and free the NBDClient.
946 qio_channel_shutdown(client->ioc, QIO_CHANNEL_SHUTDOWN_BOTH,
949 /* Also tell the client, so that they release their reference. */
950 if (client->close_fn) {
951 client->close_fn(client, negotiated);
955 static NBDRequestData *nbd_request_get(NBDClient *client)
959 assert(client->nb_requests <= MAX_NBD_REQUESTS - 1);
960 client->nb_requests++;
962 req = g_new0(NBDRequestData, 1);
963 nbd_client_get(client);
964 req->client = client;
968 static void nbd_request_put(NBDRequestData *req)
970 NBDClient *client = req->client;
973 qemu_vfree(req->data);
977 client->nb_requests--;
978 nbd_client_receive_next_request(client);
980 nbd_client_put(client);
983 static void blk_aio_attached(AioContext *ctx, void *opaque)
985 NBDExport *exp = opaque;
988 trace_nbd_blk_aio_attached(exp->name, ctx);
992 QTAILQ_FOREACH(client, &exp->clients, next) {
993 qio_channel_attach_aio_context(client->ioc, ctx);
994 if (client->recv_coroutine) {
995 aio_co_schedule(ctx, client->recv_coroutine);
997 if (client->send_coroutine) {
998 aio_co_schedule(ctx, client->send_coroutine);
1003 static void blk_aio_detach(void *opaque)
1005 NBDExport *exp = opaque;
1008 trace_nbd_blk_aio_detach(exp->name, exp->ctx);
1010 QTAILQ_FOREACH(client, &exp->clients, next) {
1011 qio_channel_detach_aio_context(client->ioc);
1017 static void nbd_eject_notifier(Notifier *n, void *data)
1019 NBDExport *exp = container_of(n, NBDExport, eject_notifier);
1020 nbd_export_close(exp);
1023 NBDExport *nbd_export_new(BlockDriverState *bs, off_t dev_offset, off_t size,
1024 uint16_t nbdflags, void (*close)(NBDExport *),
1025 bool writethrough, BlockBackend *on_eject_blk,
1030 NBDExport *exp = g_new0(NBDExport, 1);
1035 * NBD exports are used for non-shared storage migration. Make sure
1036 * that BDRV_O_INACTIVE is cleared and the image is ready for write
1037 * access since the export could be available before migration handover.
1039 ctx = bdrv_get_aio_context(bs);
1040 aio_context_acquire(ctx);
1041 bdrv_invalidate_cache(bs, NULL);
1042 aio_context_release(ctx);
1044 /* Don't allow resize while the NBD server is running, otherwise we don't
1045 * care what happens with the node. */
1046 perm = BLK_PERM_CONSISTENT_READ;
1047 if ((nbdflags & NBD_FLAG_READ_ONLY) == 0) {
1048 perm |= BLK_PERM_WRITE;
1050 blk = blk_new(perm, BLK_PERM_CONSISTENT_READ | BLK_PERM_WRITE_UNCHANGED |
1051 BLK_PERM_WRITE | BLK_PERM_GRAPH_MOD);
1052 ret = blk_insert_bs(blk, bs, errp);
1056 blk_set_enable_write_cache(blk, !writethrough);
1059 QTAILQ_INIT(&exp->clients);
1061 exp->dev_offset = dev_offset;
1062 exp->nbdflags = nbdflags;
1063 exp->size = size < 0 ? blk_getlength(blk) : size;
1064 if (exp->size < 0) {
1065 error_setg_errno(errp, -exp->size,
1066 "Failed to determine the NBD export's length");
1069 exp->size -= exp->size % BDRV_SECTOR_SIZE;
1072 exp->ctx = blk_get_aio_context(blk);
1073 blk_add_aio_context_notifier(blk, blk_aio_attached, blk_aio_detach, exp);
1076 blk_ref(on_eject_blk);
1077 exp->eject_notifier_blk = on_eject_blk;
1078 exp->eject_notifier.notify = nbd_eject_notifier;
1079 blk_add_remove_bs_notifier(on_eject_blk, &exp->eject_notifier);
1089 NBDExport *nbd_export_find(const char *name)
1092 QTAILQ_FOREACH(exp, &exports, next) {
1093 if (strcmp(name, exp->name) == 0) {
1101 void nbd_export_set_name(NBDExport *exp, const char *name)
1103 if (exp->name == name) {
1107 nbd_export_get(exp);
1108 if (exp->name != NULL) {
1111 QTAILQ_REMOVE(&exports, exp, next);
1112 nbd_export_put(exp);
1115 nbd_export_get(exp);
1116 exp->name = g_strdup(name);
1117 QTAILQ_INSERT_TAIL(&exports, exp, next);
1119 nbd_export_put(exp);
1122 void nbd_export_set_description(NBDExport *exp, const char *description)
1124 g_free(exp->description);
1125 exp->description = g_strdup(description);
1128 void nbd_export_close(NBDExport *exp)
1130 NBDClient *client, *next;
1132 nbd_export_get(exp);
1133 QTAILQ_FOREACH_SAFE(client, &exp->clients, next, next) {
1134 client_close(client, true);
1136 nbd_export_set_name(exp, NULL);
1137 nbd_export_set_description(exp, NULL);
1138 nbd_export_put(exp);
1141 void nbd_export_get(NBDExport *exp)
1143 assert(exp->refcount > 0);
1147 void nbd_export_put(NBDExport *exp)
1149 assert(exp->refcount > 0);
1150 if (exp->refcount == 1) {
1151 nbd_export_close(exp);
1154 if (--exp->refcount == 0) {
1155 assert(exp->name == NULL);
1156 assert(exp->description == NULL);
1163 if (exp->eject_notifier_blk) {
1164 notifier_remove(&exp->eject_notifier);
1165 blk_unref(exp->eject_notifier_blk);
1167 blk_remove_aio_context_notifier(exp->blk, blk_aio_attached,
1168 blk_aio_detach, exp);
1169 blk_unref(exp->blk);
1177 BlockBackend *nbd_export_get_blockdev(NBDExport *exp)
1182 void nbd_export_close_all(void)
1184 NBDExport *exp, *next;
1186 QTAILQ_FOREACH_SAFE(exp, &exports, next, next) {
1187 nbd_export_close(exp);
1191 static inline void set_be_simple_reply(NBDSimpleReply *reply, uint64_t error,
1194 stl_be_p(&reply->magic, NBD_SIMPLE_REPLY_MAGIC);
1195 stl_be_p(&reply->error, error);
1196 stq_be_p(&reply->handle, handle);
1199 static int nbd_co_send_simple_reply(NBDClient *client,
1206 NBDSimpleReply simple_reply;
1207 int nbd_err = system_errno_to_nbd_errno(error);
1210 g_assert(qemu_in_coroutine());
1212 trace_nbd_co_send_simple_reply(handle, nbd_err, len);
1213 set_be_simple_reply(&simple_reply, nbd_err, handle);
1215 qemu_co_mutex_lock(&client->send_lock);
1216 client->send_coroutine = qemu_coroutine_self();
1219 ret = nbd_write(client->ioc, &simple_reply, sizeof(simple_reply), errp);
1221 qio_channel_set_cork(client->ioc, true);
1222 ret = nbd_write(client->ioc, &simple_reply, sizeof(simple_reply), errp);
1224 ret = nbd_write(client->ioc, data, len, errp);
1229 qio_channel_set_cork(client->ioc, false);
1232 client->send_coroutine = NULL;
1233 qemu_co_mutex_unlock(&client->send_lock);
1237 /* nbd_co_receive_request
1238 * Collect a client request. Return 0 if request looks valid, -EIO to drop
1239 * connection right away, and any other negative value to report an error to
1240 * the client (although the caller may still need to disconnect after reporting
1243 static int nbd_co_receive_request(NBDRequestData *req, NBDRequest *request,
1246 NBDClient *client = req->client;
1248 g_assert(qemu_in_coroutine());
1249 assert(client->recv_coroutine == qemu_coroutine_self());
1250 if (nbd_receive_request(client->ioc, request, errp) < 0) {
1254 trace_nbd_co_receive_request_decode_type(request->handle, request->type,
1255 nbd_cmd_lookup(request->type));
1257 if (request->type != NBD_CMD_WRITE) {
1258 /* No payload, we are ready to read the next request. */
1259 req->complete = true;
1262 if (request->type == NBD_CMD_DISC) {
1263 /* Special case: we're going to disconnect without a reply,
1264 * whether or not flags, from, or len are bogus */
1268 /* Check for sanity in the parameters, part 1. Defer as many
1269 * checks as possible until after reading any NBD_CMD_WRITE
1270 * payload, so we can try and keep the connection alive. */
1271 if ((request->from + request->len) < request->from) {
1273 "integer overflow detected, you're probably being attacked");
1277 if (request->type == NBD_CMD_READ || request->type == NBD_CMD_WRITE) {
1278 if (request->len > NBD_MAX_BUFFER_SIZE) {
1279 error_setg(errp, "len (%" PRIu32" ) is larger than max len (%u)",
1280 request->len, NBD_MAX_BUFFER_SIZE);
1284 req->data = blk_try_blockalign(client->exp->blk, request->len);
1285 if (req->data == NULL) {
1286 error_setg(errp, "No memory");
1290 if (request->type == NBD_CMD_WRITE) {
1291 if (nbd_read(client->ioc, req->data, request->len, errp) < 0) {
1292 error_prepend(errp, "reading from socket failed: ");
1295 req->complete = true;
1297 trace_nbd_co_receive_request_payload_received(request->handle,
1301 /* Sanity checks, part 2. */
1302 if (request->from + request->len > client->exp->size) {
1303 error_setg(errp, "operation past EOF; From: %" PRIu64 ", Len: %" PRIu32
1304 ", Size: %" PRIu64, request->from, request->len,
1305 (uint64_t)client->exp->size);
1306 return request->type == NBD_CMD_WRITE ? -ENOSPC : -EINVAL;
1308 if (request->flags & ~(NBD_CMD_FLAG_FUA | NBD_CMD_FLAG_NO_HOLE)) {
1309 error_setg(errp, "unsupported flags (got 0x%x)", request->flags);
1312 if (request->type != NBD_CMD_WRITE_ZEROES &&
1313 (request->flags & NBD_CMD_FLAG_NO_HOLE)) {
1314 error_setg(errp, "unexpected flags (got 0x%x)", request->flags);
1321 /* Owns a reference to the NBDClient passed as opaque. */
1322 static coroutine_fn void nbd_trip(void *opaque)
1324 NBDClient *client = opaque;
1325 NBDExport *exp = client->exp;
1326 NBDRequestData *req;
1327 NBDRequest request = { 0 }; /* GCC thinks it can be used uninitialized */
1330 int reply_data_len = 0;
1331 Error *local_err = NULL;
1334 if (client->closing) {
1335 nbd_client_put(client);
1339 req = nbd_request_get(client);
1340 ret = nbd_co_receive_request(req, &request, &local_err);
1341 client->recv_coroutine = NULL;
1342 nbd_client_receive_next_request(client);
1351 if (client->closing) {
1353 * The client may be closed when we are blocked in
1354 * nbd_co_receive_request()
1359 switch (request.type) {
1361 /* XXX: NBD Protocol only documents use of FUA with WRITE */
1362 if (request.flags & NBD_CMD_FLAG_FUA) {
1363 ret = blk_co_flush(exp->blk);
1365 error_setg_errno(&local_err, -ret, "flush failed");
1370 ret = blk_pread(exp->blk, request.from + exp->dev_offset,
1371 req->data, request.len);
1373 error_setg_errno(&local_err, -ret, "reading from file failed");
1377 reply_data_len = request.len;
1381 if (exp->nbdflags & NBD_FLAG_READ_ONLY) {
1387 if (request.flags & NBD_CMD_FLAG_FUA) {
1388 flags |= BDRV_REQ_FUA;
1390 ret = blk_pwrite(exp->blk, request.from + exp->dev_offset,
1391 req->data, request.len, flags);
1393 error_setg_errno(&local_err, -ret, "writing to file failed");
1397 case NBD_CMD_WRITE_ZEROES:
1398 if (exp->nbdflags & NBD_FLAG_READ_ONLY) {
1399 error_setg(&local_err, "Server is read-only, return error");
1405 if (request.flags & NBD_CMD_FLAG_FUA) {
1406 flags |= BDRV_REQ_FUA;
1408 if (!(request.flags & NBD_CMD_FLAG_NO_HOLE)) {
1409 flags |= BDRV_REQ_MAY_UNMAP;
1411 ret = blk_pwrite_zeroes(exp->blk, request.from + exp->dev_offset,
1412 request.len, flags);
1414 error_setg_errno(&local_err, -ret, "writing to file failed");
1419 /* unreachable, thanks to special case in nbd_co_receive_request() */
1423 ret = blk_co_flush(exp->blk);
1425 error_setg_errno(&local_err, -ret, "flush failed");
1430 ret = blk_co_pdiscard(exp->blk, request.from + exp->dev_offset,
1433 error_setg_errno(&local_err, -ret, "discard failed");
1438 error_setg(&local_err, "invalid request type (%" PRIu32 ") received",
1445 /* If we get here, local_err was not a fatal error, and should be sent
1447 error_report_err(local_err);
1451 if (nbd_co_send_simple_reply(req->client, request.handle,
1453 req->data, reply_data_len, &local_err) < 0)
1455 error_prepend(&local_err, "Failed to send reply: ");
1459 /* We must disconnect after NBD_CMD_WRITE if we did not
1462 if (!req->complete) {
1463 error_setg(&local_err, "Request handling failed in intermediate state");
1468 nbd_request_put(req);
1469 nbd_client_put(client);
1474 error_reportf_err(local_err, "Disconnect client, due to: ");
1476 nbd_request_put(req);
1477 client_close(client, true);
1478 nbd_client_put(client);
1481 static void nbd_client_receive_next_request(NBDClient *client)
1483 if (!client->recv_coroutine && client->nb_requests < MAX_NBD_REQUESTS) {
1484 nbd_client_get(client);
1485 client->recv_coroutine = qemu_coroutine_create(nbd_trip, client);
1486 aio_co_schedule(client->exp->ctx, client->recv_coroutine);
1490 static coroutine_fn void nbd_co_client_start(void *opaque)
1492 NBDClient *client = opaque;
1493 NBDExport *exp = client->exp;
1494 Error *local_err = NULL;
1497 nbd_export_get(exp);
1498 QTAILQ_INSERT_TAIL(&exp->clients, client, next);
1500 qemu_co_mutex_init(&client->send_lock);
1502 if (nbd_negotiate(client, &local_err)) {
1504 error_report_err(local_err);
1506 client_close(client, false);
1510 nbd_client_receive_next_request(client);
1514 * Create a new client listener on the given export @exp, using the
1515 * given channel @sioc. Begin servicing it in a coroutine. When the
1516 * connection closes, call @close_fn with an indication of whether the
1517 * client completed negotiation.
1519 void nbd_client_new(NBDExport *exp,
1520 QIOChannelSocket *sioc,
1521 QCryptoTLSCreds *tlscreds,
1522 const char *tlsaclname,
1523 void (*close_fn)(NBDClient *, bool))
1528 client = g_new0(NBDClient, 1);
1529 client->refcount = 1;
1531 client->tlscreds = tlscreds;
1533 object_ref(OBJECT(client->tlscreds));
1535 client->tlsaclname = g_strdup(tlsaclname);
1536 client->sioc = sioc;
1537 object_ref(OBJECT(client->sioc));
1538 client->ioc = QIO_CHANNEL(sioc);
1539 object_ref(OBJECT(client->ioc));
1540 client->close_fn = close_fn;
1542 co = qemu_coroutine_create(nbd_co_client_start, client);
1543 qemu_coroutine_enter(co);