nbd/server: fix TRACE in nbd_negotiate_send_rep_len
[qemu/ar7.git] / nbd / server.c
blob1eeafccaca7a1d2c5c91571be96c30eed7a372c8
1 /*
2 * Copyright (C) 2016 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 "nbd-internal.h"
24 static int system_errno_to_nbd_errno(int err)
26 switch (err) {
27 case 0:
28 return NBD_SUCCESS;
29 case EPERM:
30 case EROFS:
31 return NBD_EPERM;
32 case EIO:
33 return NBD_EIO;
34 case ENOMEM:
35 return NBD_ENOMEM;
36 #ifdef EDQUOT
37 case EDQUOT:
38 #endif
39 case EFBIG:
40 case ENOSPC:
41 return NBD_ENOSPC;
42 case ESHUTDOWN:
43 return NBD_ESHUTDOWN;
44 case EINVAL:
45 default:
46 return NBD_EINVAL;
50 /* Definitions for opaque data types */
52 typedef struct NBDRequestData NBDRequestData;
54 struct NBDRequestData {
55 QSIMPLEQ_ENTRY(NBDRequestData) entry;
56 NBDClient *client;
57 uint8_t *data;
58 bool complete;
61 struct NBDExport {
62 int refcount;
63 void (*close)(NBDExport *exp);
65 BlockBackend *blk;
66 char *name;
67 char *description;
68 off_t dev_offset;
69 off_t size;
70 uint16_t nbdflags;
71 QTAILQ_HEAD(, NBDClient) clients;
72 QTAILQ_ENTRY(NBDExport) next;
74 AioContext *ctx;
76 BlockBackend *eject_notifier_blk;
77 Notifier eject_notifier;
80 static QTAILQ_HEAD(, NBDExport) exports = QTAILQ_HEAD_INITIALIZER(exports);
82 struct NBDClient {
83 int refcount;
84 void (*close_fn)(NBDClient *client, bool negotiated);
86 bool no_zeroes;
87 NBDExport *exp;
88 QCryptoTLSCreds *tlscreds;
89 char *tlsaclname;
90 QIOChannelSocket *sioc; /* The underlying data channel */
91 QIOChannel *ioc; /* The current I/O channel which may differ (eg TLS) */
93 Coroutine *recv_coroutine;
95 CoMutex send_lock;
96 Coroutine *send_coroutine;
98 QTAILQ_ENTRY(NBDClient) next;
99 int nb_requests;
100 bool closing;
103 /* That's all folks */
105 static void nbd_client_receive_next_request(NBDClient *client);
107 /* Basic flow for negotiation
109 Server Client
110 Negotiate
114 Server Client
115 Negotiate #1
116 Option
117 Negotiate #2
119 ----
121 followed by
123 Server Client
124 Request
125 Response
126 Request
127 Response
130 Request (type == 2)
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)
139 uint64_t magic;
141 TRACE("Reply opt=%" PRIx32 " type=%" PRIx32 " len=%" PRIu32,
142 opt, type, len);
144 magic = cpu_to_be64(NBD_REP_MAGIC);
145 if (nbd_write(ioc, &magic, sizeof(magic), errp) < 0) {
146 error_prepend(errp, "write failed (rep magic): ");
147 return -EINVAL;
150 opt = cpu_to_be32(opt);
151 if (nbd_write(ioc, &opt, sizeof(opt), errp) < 0) {
152 error_prepend(errp, "write failed (rep opt): ");
153 return -EINVAL;
156 type = cpu_to_be32(type);
157 if (nbd_write(ioc, &type, sizeof(type), errp) < 0) {
158 error_prepend(errp, "write failed (rep type): ");
159 return -EINVAL;
162 len = cpu_to_be32(len);
163 if (nbd_write(ioc, &len, sizeof(len), errp) < 0) {
164 error_prepend(errp, "write failed (rep data length): ");
165 return -EINVAL;
167 return 0;
170 /* Send a reply header with default 0 length.
171 * Return -errno on error, 0 on success. */
172 static int nbd_negotiate_send_rep(QIOChannel *ioc, uint32_t type, uint32_t opt,
173 Error **errp)
175 return nbd_negotiate_send_rep_len(ioc, type, opt, 0, errp);
178 /* Send an error reply.
179 * Return -errno on error, 0 on success. */
180 static int GCC_FMT_ATTR(5, 6)
181 nbd_negotiate_send_rep_err(QIOChannel *ioc, uint32_t type,
182 uint32_t opt, Error **errp, const char *fmt, ...)
184 va_list va;
185 char *msg;
186 int ret;
187 size_t len;
189 va_start(va, fmt);
190 msg = g_strdup_vprintf(fmt, va);
191 va_end(va);
192 len = strlen(msg);
193 assert(len < 4096);
194 TRACE("sending error message \"%s\"", msg);
195 ret = nbd_negotiate_send_rep_len(ioc, type, opt, len, errp);
196 if (ret < 0) {
197 goto out;
199 if (nbd_write(ioc, msg, len, errp) < 0) {
200 error_prepend(errp, "write failed (error message): ");
201 ret = -EIO;
202 } else {
203 ret = 0;
206 out:
207 g_free(msg);
208 return ret;
211 /* Send a single NBD_REP_SERVER reply to NBD_OPT_LIST, including payload.
212 * Return -errno on error, 0 on success. */
213 static int nbd_negotiate_send_rep_list(QIOChannel *ioc, NBDExport *exp,
214 Error **errp)
216 size_t name_len, desc_len;
217 uint32_t len;
218 const char *name = exp->name ? exp->name : "";
219 const char *desc = exp->description ? exp->description : "";
220 int ret;
222 TRACE("Advertising export name '%s' description '%s'", name, desc);
223 name_len = strlen(name);
224 desc_len = strlen(desc);
225 len = name_len + desc_len + sizeof(len);
226 ret = nbd_negotiate_send_rep_len(ioc, NBD_REP_SERVER, NBD_OPT_LIST, len,
227 errp);
228 if (ret < 0) {
229 return ret;
232 len = cpu_to_be32(name_len);
233 if (nbd_write(ioc, &len, sizeof(len), errp) < 0) {
234 error_prepend(errp, "write failed (name length): ");
235 return -EINVAL;
238 if (nbd_write(ioc, name, name_len, errp) < 0) {
239 error_prepend(errp, "write failed (name buffer): ");
240 return -EINVAL;
243 if (nbd_write(ioc, desc, desc_len, errp) < 0) {
244 error_prepend(errp, "write failed (description buffer): ");
245 return -EINVAL;
248 return 0;
251 /* Process the NBD_OPT_LIST command, with a potential series of replies.
252 * Return -errno on error, 0 on success. */
253 static int nbd_negotiate_handle_list(NBDClient *client, uint32_t length,
254 Error **errp)
256 NBDExport *exp;
258 if (length) {
259 if (nbd_drop(client->ioc, length, errp) < 0) {
260 return -EIO;
262 return nbd_negotiate_send_rep_err(client->ioc,
263 NBD_REP_ERR_INVALID, NBD_OPT_LIST,
264 errp,
265 "OPT_LIST should not have length");
268 /* For each export, send a NBD_REP_SERVER reply. */
269 QTAILQ_FOREACH(exp, &exports, next) {
270 if (nbd_negotiate_send_rep_list(client->ioc, exp, errp)) {
271 return -EINVAL;
274 /* Finish with a NBD_REP_ACK. */
275 return nbd_negotiate_send_rep(client->ioc, NBD_REP_ACK, NBD_OPT_LIST, errp);
278 static int nbd_negotiate_handle_export_name(NBDClient *client, uint32_t length,
279 Error **errp)
281 char name[NBD_MAX_NAME_SIZE + 1];
283 /* Client sends:
284 [20 .. xx] export name (length bytes)
286 TRACE("Checking length");
287 if (length >= sizeof(name)) {
288 error_setg(errp, "Bad length received");
289 return -EINVAL;
291 if (nbd_read(client->ioc, name, length, errp) < 0) {
292 error_prepend(errp, "read failed: ");
293 return -EINVAL;
295 name[length] = '\0';
297 TRACE("Client requested export '%s'", name);
299 client->exp = nbd_export_find(name);
300 if (!client->exp) {
301 error_setg(errp, "export not found");
302 return -EINVAL;
305 QTAILQ_INSERT_TAIL(&client->exp->clients, client, next);
306 nbd_export_get(client->exp);
308 return 0;
311 /* Handle NBD_OPT_STARTTLS. Return NULL to drop connection, or else the
312 * new channel for all further (now-encrypted) communication. */
313 static QIOChannel *nbd_negotiate_handle_starttls(NBDClient *client,
314 uint32_t length,
315 Error **errp)
317 QIOChannel *ioc;
318 QIOChannelTLS *tioc;
319 struct NBDTLSHandshakeData data = { 0 };
321 TRACE("Setting up TLS");
322 ioc = client->ioc;
323 if (length) {
324 if (nbd_drop(ioc, length, errp) < 0) {
325 return NULL;
327 nbd_negotiate_send_rep_err(ioc, NBD_REP_ERR_INVALID, NBD_OPT_STARTTLS,
328 errp,
329 "OPT_STARTTLS should not have length");
330 return NULL;
333 if (nbd_negotiate_send_rep(client->ioc, NBD_REP_ACK,
334 NBD_OPT_STARTTLS, errp) < 0) {
335 return NULL;
338 tioc = qio_channel_tls_new_server(ioc,
339 client->tlscreds,
340 client->tlsaclname,
341 errp);
342 if (!tioc) {
343 return NULL;
346 qio_channel_set_name(QIO_CHANNEL(tioc), "nbd-server-tls");
347 TRACE("Starting TLS handshake");
348 data.loop = g_main_loop_new(g_main_context_default(), FALSE);
349 qio_channel_tls_handshake(tioc,
350 nbd_tls_handshake,
351 &data,
352 NULL);
354 if (!data.complete) {
355 g_main_loop_run(data.loop);
357 g_main_loop_unref(data.loop);
358 if (data.error) {
359 object_unref(OBJECT(tioc));
360 error_propagate(errp, data.error);
361 return NULL;
364 return QIO_CHANNEL(tioc);
367 /* nbd_negotiate_options
368 * Process all NBD_OPT_* client option commands.
369 * Return:
370 * -errno on error, errp is set
371 * 0 on successful negotiation, errp is not set
372 * 1 if client sent NBD_OPT_ABORT, i.e. on valid disconnect,
373 * errp is not set
375 static int nbd_negotiate_options(NBDClient *client, Error **errp)
377 uint32_t flags;
378 bool fixedNewstyle = false;
379 Error *local_err = NULL;
381 /* Client sends:
382 [ 0 .. 3] client flags
384 [ 0 .. 7] NBD_OPTS_MAGIC
385 [ 8 .. 11] NBD option
386 [12 .. 15] Data length
387 ... Rest of request
389 [ 0 .. 7] NBD_OPTS_MAGIC
390 [ 8 .. 11] Second NBD option
391 [12 .. 15] Data length
392 ... Rest of request
395 if (nbd_read(client->ioc, &flags, sizeof(flags), errp) < 0) {
396 error_prepend(errp, "read failed: ");
397 return -EIO;
399 TRACE("Checking client flags");
400 be32_to_cpus(&flags);
401 if (flags & NBD_FLAG_C_FIXED_NEWSTYLE) {
402 TRACE("Client supports fixed newstyle handshake");
403 fixedNewstyle = true;
404 flags &= ~NBD_FLAG_C_FIXED_NEWSTYLE;
406 if (flags & NBD_FLAG_C_NO_ZEROES) {
407 TRACE("Client supports no zeroes at handshake end");
408 client->no_zeroes = true;
409 flags &= ~NBD_FLAG_C_NO_ZEROES;
411 if (flags != 0) {
412 error_setg(errp, "Unknown client flags 0x%" PRIx32 " received", flags);
413 return -EIO;
416 while (1) {
417 int ret;
418 uint32_t clientflags, length;
419 uint64_t magic;
421 if (nbd_read(client->ioc, &magic, sizeof(magic), errp) < 0) {
422 error_prepend(errp, "read failed: ");
423 return -EINVAL;
425 TRACE("Checking opts magic");
426 if (magic != be64_to_cpu(NBD_OPTS_MAGIC)) {
427 error_setg(errp, "Bad magic received");
428 return -EINVAL;
431 if (nbd_read(client->ioc, &clientflags,
432 sizeof(clientflags), errp) < 0) {
433 error_prepend(errp, "read failed: ");
434 return -EINVAL;
436 clientflags = be32_to_cpu(clientflags);
438 if (nbd_read(client->ioc, &length, sizeof(length), errp) < 0) {
439 error_prepend(errp, "read failed: ");
440 return -EINVAL;
442 length = be32_to_cpu(length);
444 TRACE("Checking option 0x%" PRIx32, clientflags);
445 if (client->tlscreds &&
446 client->ioc == (QIOChannel *)client->sioc) {
447 QIOChannel *tioc;
448 if (!fixedNewstyle) {
449 error_setg(errp, "Unsupported option 0x%" PRIx32, clientflags);
450 return -EINVAL;
452 switch (clientflags) {
453 case NBD_OPT_STARTTLS:
454 tioc = nbd_negotiate_handle_starttls(client, length, errp);
455 if (!tioc) {
456 return -EIO;
458 object_unref(OBJECT(client->ioc));
459 client->ioc = QIO_CHANNEL(tioc);
460 break;
462 case NBD_OPT_EXPORT_NAME:
463 /* No way to return an error to client, so drop connection */
464 error_setg(errp, "Option 0x%x not permitted before TLS",
465 clientflags);
466 return -EINVAL;
468 default:
469 if (nbd_drop(client->ioc, length, errp) < 0) {
470 return -EIO;
472 ret = nbd_negotiate_send_rep_err(client->ioc,
473 NBD_REP_ERR_TLS_REQD,
474 clientflags, errp,
475 "Option 0x%" PRIx32
476 "not permitted before TLS",
477 clientflags);
478 if (ret < 0) {
479 return ret;
481 /* Let the client keep trying, unless they asked to quit */
482 if (clientflags == NBD_OPT_ABORT) {
483 return 1;
485 break;
487 } else if (fixedNewstyle) {
488 switch (clientflags) {
489 case NBD_OPT_LIST:
490 ret = nbd_negotiate_handle_list(client, length, errp);
491 if (ret < 0) {
492 return ret;
494 break;
496 case NBD_OPT_ABORT:
497 /* NBD spec says we must try to reply before
498 * disconnecting, but that we must also tolerate
499 * guests that don't wait for our reply. */
500 nbd_negotiate_send_rep(client->ioc, NBD_REP_ACK, clientflags,
501 &local_err);
503 if (local_err != NULL) {
504 TRACE("Reply to NBD_OPT_ABORT request failed: %s",
505 error_get_pretty(local_err));
506 error_free(local_err);
509 return 1;
511 case NBD_OPT_EXPORT_NAME:
512 return nbd_negotiate_handle_export_name(client, length, errp);
514 case NBD_OPT_STARTTLS:
515 if (nbd_drop(client->ioc, length, errp) < 0) {
516 return -EIO;
518 if (client->tlscreds) {
519 ret = nbd_negotiate_send_rep_err(client->ioc,
520 NBD_REP_ERR_INVALID,
521 clientflags, errp,
522 "TLS already enabled");
523 } else {
524 ret = nbd_negotiate_send_rep_err(client->ioc,
525 NBD_REP_ERR_POLICY,
526 clientflags, errp,
527 "TLS not configured");
529 if (ret < 0) {
530 return ret;
532 break;
533 default:
534 if (nbd_drop(client->ioc, length, errp) < 0) {
535 return -EIO;
537 ret = nbd_negotiate_send_rep_err(client->ioc,
538 NBD_REP_ERR_UNSUP,
539 clientflags, errp,
540 "Unsupported option 0x%"
541 PRIx32,
542 clientflags);
543 if (ret < 0) {
544 return ret;
546 break;
548 } else {
550 * If broken new-style we should drop the connection
551 * for anything except NBD_OPT_EXPORT_NAME
553 switch (clientflags) {
554 case NBD_OPT_EXPORT_NAME:
555 return nbd_negotiate_handle_export_name(client, length, errp);
557 default:
558 error_setg(errp, "Unsupported option 0x%" PRIx32, clientflags);
559 return -EINVAL;
565 /* nbd_negotiate
566 * Return:
567 * -errno on error, errp is set
568 * 0 on successful negotiation, errp is not set
569 * 1 if client sent NBD_OPT_ABORT, i.e. on valid disconnect,
570 * errp is not set
572 static coroutine_fn int nbd_negotiate(NBDClient *client, Error **errp)
574 char buf[8 + 8 + 8 + 128];
575 int ret;
576 const uint16_t myflags = (NBD_FLAG_HAS_FLAGS | NBD_FLAG_SEND_TRIM |
577 NBD_FLAG_SEND_FLUSH | NBD_FLAG_SEND_FUA |
578 NBD_FLAG_SEND_WRITE_ZEROES);
579 bool oldStyle;
580 size_t len;
582 /* Old style negotiation header without options
583 [ 0 .. 7] passwd ("NBDMAGIC")
584 [ 8 .. 15] magic (NBD_CLIENT_MAGIC)
585 [16 .. 23] size
586 [24 .. 25] server flags (0)
587 [26 .. 27] export flags
588 [28 .. 151] reserved (0)
590 New style negotiation header with options
591 [ 0 .. 7] passwd ("NBDMAGIC")
592 [ 8 .. 15] magic (NBD_OPTS_MAGIC)
593 [16 .. 17] server flags (0)
594 ....options sent....
595 [18 .. 25] size
596 [26 .. 27] export flags
597 [28 .. 151] reserved (0, omit if no_zeroes)
600 qio_channel_set_blocking(client->ioc, false, NULL);
602 TRACE("Beginning negotiation.");
603 memset(buf, 0, sizeof(buf));
604 memcpy(buf, "NBDMAGIC", 8);
606 oldStyle = client->exp != NULL && !client->tlscreds;
607 if (oldStyle) {
608 TRACE("advertising size %" PRIu64 " and flags %x",
609 client->exp->size, client->exp->nbdflags | myflags);
610 stq_be_p(buf + 8, NBD_CLIENT_MAGIC);
611 stq_be_p(buf + 16, client->exp->size);
612 stw_be_p(buf + 26, client->exp->nbdflags | myflags);
614 if (nbd_write(client->ioc, buf, sizeof(buf), errp) < 0) {
615 error_prepend(errp, "write failed: ");
616 return -EINVAL;
618 } else {
619 stq_be_p(buf + 8, NBD_OPTS_MAGIC);
620 stw_be_p(buf + 16, NBD_FLAG_FIXED_NEWSTYLE | NBD_FLAG_NO_ZEROES);
622 if (nbd_write(client->ioc, buf, 18, errp) < 0) {
623 error_prepend(errp, "write failed: ");
624 return -EINVAL;
626 ret = nbd_negotiate_options(client, errp);
627 if (ret != 0) {
628 if (ret < 0) {
629 error_prepend(errp, "option negotiation failed: ");
631 return ret;
634 TRACE("advertising size %" PRIu64 " and flags %x",
635 client->exp->size, client->exp->nbdflags | myflags);
636 stq_be_p(buf + 18, client->exp->size);
637 stw_be_p(buf + 26, client->exp->nbdflags | myflags);
638 len = client->no_zeroes ? 10 : sizeof(buf) - 18;
639 ret = nbd_write(client->ioc, buf + 18, len, errp);
640 if (ret < 0) {
641 error_prepend(errp, "write failed: ");
642 return ret;
646 TRACE("Negotiation succeeded.");
648 return 0;
651 static int nbd_receive_request(QIOChannel *ioc, NBDRequest *request,
652 Error **errp)
654 uint8_t buf[NBD_REQUEST_SIZE];
655 uint32_t magic;
656 int ret;
658 ret = nbd_read(ioc, buf, sizeof(buf), errp);
659 if (ret < 0) {
660 return ret;
663 /* Request
664 [ 0 .. 3] magic (NBD_REQUEST_MAGIC)
665 [ 4 .. 5] flags (NBD_CMD_FLAG_FUA, ...)
666 [ 6 .. 7] type (NBD_CMD_READ, ...)
667 [ 8 .. 15] handle
668 [16 .. 23] from
669 [24 .. 27] len
672 magic = ldl_be_p(buf);
673 request->flags = lduw_be_p(buf + 4);
674 request->type = lduw_be_p(buf + 6);
675 request->handle = ldq_be_p(buf + 8);
676 request->from = ldq_be_p(buf + 16);
677 request->len = ldl_be_p(buf + 24);
679 TRACE("Got request: { magic = 0x%" PRIx32 ", .flags = %" PRIx16
680 ", .type = %" PRIx16 ", from = %" PRIu64 ", len = %" PRIu32 " }",
681 magic, request->flags, request->type, request->from, request->len);
683 if (magic != NBD_REQUEST_MAGIC) {
684 error_setg(errp, "invalid magic (got 0x%" PRIx32 ")", magic);
685 return -EINVAL;
687 return 0;
690 static int nbd_send_reply(QIOChannel *ioc, NBDReply *reply, Error **errp)
692 uint8_t buf[NBD_REPLY_SIZE];
694 reply->error = system_errno_to_nbd_errno(reply->error);
696 TRACE("Sending response to client: { .error = %" PRId32
697 ", handle = %" PRIu64 " }",
698 reply->error, reply->handle);
700 /* Reply
701 [ 0 .. 3] magic (NBD_REPLY_MAGIC)
702 [ 4 .. 7] error (0 == no error)
703 [ 7 .. 15] handle
705 stl_be_p(buf, NBD_REPLY_MAGIC);
706 stl_be_p(buf + 4, reply->error);
707 stq_be_p(buf + 8, reply->handle);
709 return nbd_write(ioc, buf, sizeof(buf), errp);
712 #define MAX_NBD_REQUESTS 16
714 void nbd_client_get(NBDClient *client)
716 client->refcount++;
719 void nbd_client_put(NBDClient *client)
721 if (--client->refcount == 0) {
722 /* The last reference should be dropped by client->close,
723 * which is called by client_close.
725 assert(client->closing);
727 qio_channel_detach_aio_context(client->ioc);
728 object_unref(OBJECT(client->sioc));
729 object_unref(OBJECT(client->ioc));
730 if (client->tlscreds) {
731 object_unref(OBJECT(client->tlscreds));
733 g_free(client->tlsaclname);
734 if (client->exp) {
735 QTAILQ_REMOVE(&client->exp->clients, client, next);
736 nbd_export_put(client->exp);
738 g_free(client);
742 static void client_close(NBDClient *client, bool negotiated)
744 if (client->closing) {
745 return;
748 client->closing = true;
750 /* Force requests to finish. They will drop their own references,
751 * then we'll close the socket and free the NBDClient.
753 qio_channel_shutdown(client->ioc, QIO_CHANNEL_SHUTDOWN_BOTH,
754 NULL);
756 /* Also tell the client, so that they release their reference. */
757 if (client->close_fn) {
758 client->close_fn(client, negotiated);
762 static NBDRequestData *nbd_request_get(NBDClient *client)
764 NBDRequestData *req;
766 assert(client->nb_requests <= MAX_NBD_REQUESTS - 1);
767 client->nb_requests++;
769 req = g_new0(NBDRequestData, 1);
770 nbd_client_get(client);
771 req->client = client;
772 return req;
775 static void nbd_request_put(NBDRequestData *req)
777 NBDClient *client = req->client;
779 if (req->data) {
780 qemu_vfree(req->data);
782 g_free(req);
784 client->nb_requests--;
785 nbd_client_receive_next_request(client);
787 nbd_client_put(client);
790 static void blk_aio_attached(AioContext *ctx, void *opaque)
792 NBDExport *exp = opaque;
793 NBDClient *client;
795 TRACE("Export %s: Attaching clients to AIO context %p\n", exp->name, ctx);
797 exp->ctx = ctx;
799 QTAILQ_FOREACH(client, &exp->clients, next) {
800 qio_channel_attach_aio_context(client->ioc, ctx);
801 if (client->recv_coroutine) {
802 aio_co_schedule(ctx, client->recv_coroutine);
804 if (client->send_coroutine) {
805 aio_co_schedule(ctx, client->send_coroutine);
810 static void blk_aio_detach(void *opaque)
812 NBDExport *exp = opaque;
813 NBDClient *client;
815 TRACE("Export %s: Detaching clients from AIO context %p\n", exp->name, exp->ctx);
817 QTAILQ_FOREACH(client, &exp->clients, next) {
818 qio_channel_detach_aio_context(client->ioc);
821 exp->ctx = NULL;
824 static void nbd_eject_notifier(Notifier *n, void *data)
826 NBDExport *exp = container_of(n, NBDExport, eject_notifier);
827 nbd_export_close(exp);
830 NBDExport *nbd_export_new(BlockDriverState *bs, off_t dev_offset, off_t size,
831 uint16_t nbdflags, void (*close)(NBDExport *),
832 bool writethrough, BlockBackend *on_eject_blk,
833 Error **errp)
835 BlockBackend *blk;
836 NBDExport *exp = g_malloc0(sizeof(NBDExport));
837 uint64_t perm;
838 int ret;
840 /* Don't allow resize while the NBD server is running, otherwise we don't
841 * care what happens with the node. */
842 perm = BLK_PERM_CONSISTENT_READ;
843 if ((nbdflags & NBD_FLAG_READ_ONLY) == 0) {
844 perm |= BLK_PERM_WRITE;
846 blk = blk_new(perm, BLK_PERM_CONSISTENT_READ | BLK_PERM_WRITE_UNCHANGED |
847 BLK_PERM_WRITE | BLK_PERM_GRAPH_MOD);
848 ret = blk_insert_bs(blk, bs, errp);
849 if (ret < 0) {
850 goto fail;
852 blk_set_enable_write_cache(blk, !writethrough);
854 exp->refcount = 1;
855 QTAILQ_INIT(&exp->clients);
856 exp->blk = blk;
857 exp->dev_offset = dev_offset;
858 exp->nbdflags = nbdflags;
859 exp->size = size < 0 ? blk_getlength(blk) : size;
860 if (exp->size < 0) {
861 error_setg_errno(errp, -exp->size,
862 "Failed to determine the NBD export's length");
863 goto fail;
865 exp->size -= exp->size % BDRV_SECTOR_SIZE;
867 exp->close = close;
868 exp->ctx = blk_get_aio_context(blk);
869 blk_add_aio_context_notifier(blk, blk_aio_attached, blk_aio_detach, exp);
871 if (on_eject_blk) {
872 blk_ref(on_eject_blk);
873 exp->eject_notifier_blk = on_eject_blk;
874 exp->eject_notifier.notify = nbd_eject_notifier;
875 blk_add_remove_bs_notifier(on_eject_blk, &exp->eject_notifier);
879 * NBD exports are used for non-shared storage migration. Make sure
880 * that BDRV_O_INACTIVE is cleared and the image is ready for write
881 * access since the export could be available before migration handover.
883 aio_context_acquire(exp->ctx);
884 blk_invalidate_cache(blk, NULL);
885 aio_context_release(exp->ctx);
886 return exp;
888 fail:
889 blk_unref(blk);
890 g_free(exp);
891 return NULL;
894 NBDExport *nbd_export_find(const char *name)
896 NBDExport *exp;
897 QTAILQ_FOREACH(exp, &exports, next) {
898 if (strcmp(name, exp->name) == 0) {
899 return exp;
903 return NULL;
906 void nbd_export_set_name(NBDExport *exp, const char *name)
908 if (exp->name == name) {
909 return;
912 nbd_export_get(exp);
913 if (exp->name != NULL) {
914 g_free(exp->name);
915 exp->name = NULL;
916 QTAILQ_REMOVE(&exports, exp, next);
917 nbd_export_put(exp);
919 if (name != NULL) {
920 nbd_export_get(exp);
921 exp->name = g_strdup(name);
922 QTAILQ_INSERT_TAIL(&exports, exp, next);
924 nbd_export_put(exp);
927 void nbd_export_set_description(NBDExport *exp, const char *description)
929 g_free(exp->description);
930 exp->description = g_strdup(description);
933 void nbd_export_close(NBDExport *exp)
935 NBDClient *client, *next;
937 nbd_export_get(exp);
938 QTAILQ_FOREACH_SAFE(client, &exp->clients, next, next) {
939 client_close(client, true);
941 nbd_export_set_name(exp, NULL);
942 nbd_export_set_description(exp, NULL);
943 nbd_export_put(exp);
946 void nbd_export_get(NBDExport *exp)
948 assert(exp->refcount > 0);
949 exp->refcount++;
952 void nbd_export_put(NBDExport *exp)
954 assert(exp->refcount > 0);
955 if (exp->refcount == 1) {
956 nbd_export_close(exp);
959 if (--exp->refcount == 0) {
960 assert(exp->name == NULL);
961 assert(exp->description == NULL);
963 if (exp->close) {
964 exp->close(exp);
967 if (exp->blk) {
968 if (exp->eject_notifier_blk) {
969 notifier_remove(&exp->eject_notifier);
970 blk_unref(exp->eject_notifier_blk);
972 blk_remove_aio_context_notifier(exp->blk, blk_aio_attached,
973 blk_aio_detach, exp);
974 blk_unref(exp->blk);
975 exp->blk = NULL;
978 g_free(exp);
982 BlockBackend *nbd_export_get_blockdev(NBDExport *exp)
984 return exp->blk;
987 void nbd_export_close_all(void)
989 NBDExport *exp, *next;
991 QTAILQ_FOREACH_SAFE(exp, &exports, next, next) {
992 nbd_export_close(exp);
996 static int nbd_co_send_reply(NBDRequestData *req, NBDReply *reply, int len,
997 Error **errp)
999 NBDClient *client = req->client;
1000 int ret;
1002 g_assert(qemu_in_coroutine());
1003 qemu_co_mutex_lock(&client->send_lock);
1004 client->send_coroutine = qemu_coroutine_self();
1006 if (!len) {
1007 ret = nbd_send_reply(client->ioc, reply, errp);
1008 } else {
1009 qio_channel_set_cork(client->ioc, true);
1010 ret = nbd_send_reply(client->ioc, reply, errp);
1011 if (ret == 0) {
1012 ret = nbd_write(client->ioc, req->data, len, errp);
1013 if (ret < 0) {
1014 ret = -EIO;
1017 qio_channel_set_cork(client->ioc, false);
1020 client->send_coroutine = NULL;
1021 qemu_co_mutex_unlock(&client->send_lock);
1022 return ret;
1025 /* nbd_co_receive_request
1026 * Collect a client request. Return 0 if request looks valid, -EIO to drop
1027 * connection right away, and any other negative value to report an error to
1028 * the client (although the caller may still need to disconnect after reporting
1029 * the error).
1031 static int nbd_co_receive_request(NBDRequestData *req, NBDRequest *request,
1032 Error **errp)
1034 NBDClient *client = req->client;
1036 g_assert(qemu_in_coroutine());
1037 assert(client->recv_coroutine == qemu_coroutine_self());
1038 if (nbd_receive_request(client->ioc, request, errp) < 0) {
1039 return -EIO;
1042 TRACE("Decoding type");
1044 if (request->type != NBD_CMD_WRITE) {
1045 /* No payload, we are ready to read the next request. */
1046 req->complete = true;
1049 if (request->type == NBD_CMD_DISC) {
1050 /* Special case: we're going to disconnect without a reply,
1051 * whether or not flags, from, or len are bogus */
1052 TRACE("Request type is DISCONNECT");
1053 return -EIO;
1056 /* Check for sanity in the parameters, part 1. Defer as many
1057 * checks as possible until after reading any NBD_CMD_WRITE
1058 * payload, so we can try and keep the connection alive. */
1059 if ((request->from + request->len) < request->from) {
1060 error_setg(errp,
1061 "integer overflow detected, you're probably being attacked");
1062 return -EINVAL;
1065 if (request->type == NBD_CMD_READ || request->type == NBD_CMD_WRITE) {
1066 if (request->len > NBD_MAX_BUFFER_SIZE) {
1067 error_setg(errp, "len (%" PRIu32" ) is larger than max len (%u)",
1068 request->len, NBD_MAX_BUFFER_SIZE);
1069 return -EINVAL;
1072 req->data = blk_try_blockalign(client->exp->blk, request->len);
1073 if (req->data == NULL) {
1074 error_setg(errp, "No memory");
1075 return -ENOMEM;
1078 if (request->type == NBD_CMD_WRITE) {
1079 TRACE("Reading %" PRIu32 " byte(s)", request->len);
1081 if (nbd_read(client->ioc, req->data, request->len, errp) < 0) {
1082 error_prepend(errp, "reading from socket failed: ");
1083 return -EIO;
1085 req->complete = true;
1088 /* Sanity checks, part 2. */
1089 if (request->from + request->len > client->exp->size) {
1090 error_setg(errp, "operation past EOF; From: %" PRIu64 ", Len: %" PRIu32
1091 ", Size: %" PRIu64, request->from, request->len,
1092 (uint64_t)client->exp->size);
1093 return request->type == NBD_CMD_WRITE ? -ENOSPC : -EINVAL;
1095 if (request->flags & ~(NBD_CMD_FLAG_FUA | NBD_CMD_FLAG_NO_HOLE)) {
1096 error_setg(errp, "unsupported flags (got 0x%x)", request->flags);
1097 return -EINVAL;
1099 if (request->type != NBD_CMD_WRITE_ZEROES &&
1100 (request->flags & NBD_CMD_FLAG_NO_HOLE)) {
1101 error_setg(errp, "unexpected flags (got 0x%x)", request->flags);
1102 return -EINVAL;
1105 return 0;
1108 /* Owns a reference to the NBDClient passed as opaque. */
1109 static coroutine_fn void nbd_trip(void *opaque)
1111 NBDClient *client = opaque;
1112 NBDExport *exp = client->exp;
1113 NBDRequestData *req;
1114 NBDRequest request = { 0 }; /* GCC thinks it can be used uninitialized */
1115 NBDReply reply;
1116 int ret;
1117 int flags;
1118 int reply_data_len = 0;
1119 Error *local_err = NULL;
1121 TRACE("Reading request.");
1122 if (client->closing) {
1123 nbd_client_put(client);
1124 return;
1127 req = nbd_request_get(client);
1128 ret = nbd_co_receive_request(req, &request, &local_err);
1129 client->recv_coroutine = NULL;
1130 nbd_client_receive_next_request(client);
1131 if (ret == -EIO) {
1132 goto disconnect;
1135 reply.handle = request.handle;
1136 reply.error = 0;
1138 if (ret < 0) {
1139 reply.error = -ret;
1140 goto reply;
1143 if (client->closing) {
1145 * The client may be closed when we are blocked in
1146 * nbd_co_receive_request()
1148 goto done;
1151 switch (request.type) {
1152 case NBD_CMD_READ:
1153 TRACE("Request type is READ");
1155 /* XXX: NBD Protocol only documents use of FUA with WRITE */
1156 if (request.flags & NBD_CMD_FLAG_FUA) {
1157 ret = blk_co_flush(exp->blk);
1158 if (ret < 0) {
1159 error_setg_errno(&local_err, -ret, "flush failed");
1160 reply.error = -ret;
1161 break;
1165 ret = blk_pread(exp->blk, request.from + exp->dev_offset,
1166 req->data, request.len);
1167 if (ret < 0) {
1168 error_setg_errno(&local_err, -ret, "reading from file failed");
1169 reply.error = -ret;
1170 break;
1173 reply_data_len = request.len;
1174 TRACE("Read %" PRIu32" byte(s)", request.len);
1176 break;
1177 case NBD_CMD_WRITE:
1178 TRACE("Request type is WRITE");
1180 if (exp->nbdflags & NBD_FLAG_READ_ONLY) {
1181 TRACE("Server is read-only, return error");
1182 reply.error = EROFS;
1183 break;
1186 TRACE("Writing to device");
1188 flags = 0;
1189 if (request.flags & NBD_CMD_FLAG_FUA) {
1190 flags |= BDRV_REQ_FUA;
1192 ret = blk_pwrite(exp->blk, request.from + exp->dev_offset,
1193 req->data, request.len, flags);
1194 if (ret < 0) {
1195 error_setg_errno(&local_err, -ret, "writing to file failed");
1196 reply.error = -ret;
1199 break;
1200 case NBD_CMD_WRITE_ZEROES:
1201 TRACE("Request type is WRITE_ZEROES");
1203 if (exp->nbdflags & NBD_FLAG_READ_ONLY) {
1204 error_setg(&local_err, "Server is read-only, return error");
1205 reply.error = EROFS;
1206 break;
1209 TRACE("Writing to device");
1211 flags = 0;
1212 if (request.flags & NBD_CMD_FLAG_FUA) {
1213 flags |= BDRV_REQ_FUA;
1215 if (!(request.flags & NBD_CMD_FLAG_NO_HOLE)) {
1216 flags |= BDRV_REQ_MAY_UNMAP;
1218 ret = blk_pwrite_zeroes(exp->blk, request.from + exp->dev_offset,
1219 request.len, flags);
1220 if (ret < 0) {
1221 error_setg_errno(&local_err, -ret, "writing to file failed");
1222 reply.error = -ret;
1225 break;
1226 case NBD_CMD_DISC:
1227 /* unreachable, thanks to special case in nbd_co_receive_request() */
1228 abort();
1230 case NBD_CMD_FLUSH:
1231 TRACE("Request type is FLUSH");
1233 ret = blk_co_flush(exp->blk);
1234 if (ret < 0) {
1235 error_setg_errno(&local_err, -ret, "flush failed");
1236 reply.error = -ret;
1239 break;
1240 case NBD_CMD_TRIM:
1241 TRACE("Request type is TRIM");
1242 ret = blk_co_pdiscard(exp->blk, request.from + exp->dev_offset,
1243 request.len);
1244 if (ret < 0) {
1245 error_setg_errno(&local_err, -ret, "discard failed");
1246 reply.error = -ret;
1249 break;
1250 default:
1251 error_setg(&local_err, "invalid request type (%" PRIu32 ") received",
1252 request.type);
1253 reply.error = EINVAL;
1256 reply:
1257 if (local_err) {
1258 /* If we are here local_err is not fatal error, already stored in
1259 * reply.error */
1260 error_report_err(local_err);
1261 local_err = NULL;
1264 if (nbd_co_send_reply(req, &reply, reply_data_len, &local_err) < 0) {
1265 error_prepend(&local_err, "Failed to send reply: ");
1266 goto disconnect;
1269 /* We must disconnect after NBD_CMD_WRITE if we did not
1270 * read the payload.
1272 if (!req->complete) {
1273 error_setg(&local_err, "Request handling failed in intermediate state");
1274 goto disconnect;
1277 TRACE("Request/Reply complete");
1279 done:
1280 nbd_request_put(req);
1281 nbd_client_put(client);
1282 return;
1284 disconnect:
1285 if (local_err) {
1286 error_reportf_err(local_err, "Disconnect client, due to: ");
1288 nbd_request_put(req);
1289 client_close(client, true);
1290 nbd_client_put(client);
1293 static void nbd_client_receive_next_request(NBDClient *client)
1295 if (!client->recv_coroutine && client->nb_requests < MAX_NBD_REQUESTS) {
1296 nbd_client_get(client);
1297 client->recv_coroutine = qemu_coroutine_create(nbd_trip, client);
1298 aio_co_schedule(client->exp->ctx, client->recv_coroutine);
1302 static coroutine_fn void nbd_co_client_start(void *opaque)
1304 NBDClient *client = opaque;
1305 NBDExport *exp = client->exp;
1306 Error *local_err = NULL;
1308 if (exp) {
1309 nbd_export_get(exp);
1310 QTAILQ_INSERT_TAIL(&exp->clients, client, next);
1312 qemu_co_mutex_init(&client->send_lock);
1314 if (nbd_negotiate(client, &local_err)) {
1315 if (local_err) {
1316 error_report_err(local_err);
1318 client_close(client, false);
1319 return;
1322 nbd_client_receive_next_request(client);
1326 * Create a new client listener on the given export @exp, using the
1327 * given channel @sioc. Begin servicing it in a coroutine. When the
1328 * connection closes, call @close_fn with an indication of whether the
1329 * client completed negotiation.
1331 void nbd_client_new(NBDExport *exp,
1332 QIOChannelSocket *sioc,
1333 QCryptoTLSCreds *tlscreds,
1334 const char *tlsaclname,
1335 void (*close_fn)(NBDClient *, bool))
1337 NBDClient *client;
1338 Coroutine *co;
1340 client = g_malloc0(sizeof(NBDClient));
1341 client->refcount = 1;
1342 client->exp = exp;
1343 client->tlscreds = tlscreds;
1344 if (tlscreds) {
1345 object_ref(OBJECT(client->tlscreds));
1347 client->tlsaclname = g_strdup(tlsaclname);
1348 client->sioc = sioc;
1349 object_ref(OBJECT(client->sioc));
1350 client->ioc = QIO_CHANNEL(sioc);
1351 object_ref(OBJECT(client->ioc));
1352 client->close_fn = close_fn;
1354 co = qemu_coroutine_create(nbd_co_client_start, client);
1355 qemu_coroutine_enter(co);