qcow2: Add iotest for an empty refcount table
[qemu/ar7.git] / nbd / server.c
blobdf771fd42fc2f793586168fcd3c8cc4d17f759f3
1 /*
2 * Copyright (C) 2016-2017 Red Hat, Inc.
3 * Copyright (C) 2005 Anthony Liguori <anthony@codemonkey.ws>
5 * Network Block Device Server Side
7 * This program is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; under version 2 of the License.
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License
17 * along with this program; if not, see <http://www.gnu.org/licenses/>.
20 #include "qemu/osdep.h"
21 #include "qapi/error.h"
22 #include "trace.h"
23 #include "nbd-internal.h"
25 static int system_errno_to_nbd_errno(int err)
27 switch (err) {
28 case 0:
29 return NBD_SUCCESS;
30 case EPERM:
31 case EROFS:
32 return NBD_EPERM;
33 case EIO:
34 return NBD_EIO;
35 case ENOMEM:
36 return NBD_ENOMEM;
37 #ifdef EDQUOT
38 case EDQUOT:
39 #endif
40 case EFBIG:
41 case ENOSPC:
42 return NBD_ENOSPC;
43 case EOVERFLOW:
44 return NBD_EOVERFLOW;
45 case ESHUTDOWN:
46 return NBD_ESHUTDOWN;
47 case EINVAL:
48 default:
49 return NBD_EINVAL;
53 /* Definitions for opaque data types */
55 typedef struct NBDRequestData NBDRequestData;
57 struct NBDRequestData {
58 QSIMPLEQ_ENTRY(NBDRequestData) entry;
59 NBDClient *client;
60 uint8_t *data;
61 bool complete;
64 struct NBDExport {
65 int refcount;
66 void (*close)(NBDExport *exp);
68 BlockBackend *blk;
69 char *name;
70 char *description;
71 off_t dev_offset;
72 off_t size;
73 uint16_t nbdflags;
74 QTAILQ_HEAD(, NBDClient) clients;
75 QTAILQ_ENTRY(NBDExport) next;
77 AioContext *ctx;
79 BlockBackend *eject_notifier_blk;
80 Notifier eject_notifier;
83 static QTAILQ_HEAD(, NBDExport) exports = QTAILQ_HEAD_INITIALIZER(exports);
85 struct NBDClient {
86 int refcount;
87 void (*close_fn)(NBDClient *client, bool negotiated);
89 NBDExport *exp;
90 QCryptoTLSCreds *tlscreds;
91 char *tlsaclname;
92 QIOChannelSocket *sioc; /* The underlying data channel */
93 QIOChannel *ioc; /* The current I/O channel which may differ (eg TLS) */
95 Coroutine *recv_coroutine;
97 CoMutex send_lock;
98 Coroutine *send_coroutine;
100 QTAILQ_ENTRY(NBDClient) next;
101 int nb_requests;
102 bool closing;
104 bool structured_reply;
107 /* That's all folks */
109 static void nbd_client_receive_next_request(NBDClient *client);
111 /* Basic flow for negotiation
113 Server Client
114 Negotiate
118 Server Client
119 Negotiate #1
120 Option
121 Negotiate #2
123 ----
125 followed by
127 Server Client
128 Request
129 Response
130 Request
131 Response
134 Request (type == 2)
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)
143 uint64_t magic;
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): ");
152 return -EINVAL;
155 opt = cpu_to_be32(opt);
156 if (nbd_write(ioc, &opt, sizeof(opt), errp) < 0) {
157 error_prepend(errp, "write failed (rep opt): ");
158 return -EINVAL;
161 type = cpu_to_be32(type);
162 if (nbd_write(ioc, &type, sizeof(type), errp) < 0) {
163 error_prepend(errp, "write failed (rep type): ");
164 return -EINVAL;
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): ");
170 return -EINVAL;
172 return 0;
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,
178 Error **errp)
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, ...)
189 va_list va;
190 char *msg;
191 int ret;
192 size_t len;
194 va_start(va, fmt);
195 msg = g_strdup_vprintf(fmt, va);
196 va_end(va);
197 len = strlen(msg);
198 assert(len < 4096);
199 trace_nbd_negotiate_send_rep_err(msg);
200 ret = nbd_negotiate_send_rep_len(ioc, type, opt, len, errp);
201 if (ret < 0) {
202 goto out;
204 if (nbd_write(ioc, msg, len, errp) < 0) {
205 error_prepend(errp, "write failed (error message): ");
206 ret = -EIO;
207 } else {
208 ret = 0;
211 out:
212 g_free(msg);
213 return ret;
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,
219 Error **errp)
221 size_t name_len, desc_len;
222 uint32_t len;
223 const char *name = exp->name ? exp->name : "";
224 const char *desc = exp->description ? exp->description : "";
225 int ret;
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,
232 errp);
233 if (ret < 0) {
234 return ret;
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): ");
240 return -EINVAL;
243 if (nbd_write(ioc, name, name_len, errp) < 0) {
244 error_prepend(errp, "write failed (name buffer): ");
245 return -EINVAL;
248 if (nbd_write(ioc, desc, desc_len, errp) < 0) {
249 error_prepend(errp, "write failed (description buffer): ");
250 return -EINVAL;
253 return 0;
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)
260 NBDExport *exp;
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)) {
265 return -EINVAL;
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,
276 Error **errp)
278 char name[NBD_MAX_NAME_SIZE + 1];
279 char buf[NBD_REPLY_EXPORT_NAME_SIZE] = "";
280 size_t len;
281 int ret;
283 /* Client sends:
284 [20 .. xx] export name (length bytes)
285 Server replies:
286 [ 0 .. 7] size
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");
293 return -EINVAL;
295 if (nbd_read(client->ioc, name, length, errp) < 0) {
296 error_prepend(errp, "read failed: ");
297 return -EINVAL;
299 name[length] = '\0';
301 trace_nbd_negotiate_handle_export_name_request(name);
303 client->exp = nbd_export_find(name);
304 if (!client->exp) {
305 error_setg(errp, "export not found");
306 return -EINVAL;
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);
315 if (ret < 0) {
316 error_prepend(errp, "write failed: ");
317 return ret;
320 QTAILQ_INSERT_TAIL(&client->exp->clients, client, next);
321 nbd_export_get(client->exp);
323 return 0;
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,
331 Error **errp)
333 int rc;
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);
338 if (rc < 0) {
339 return rc;
341 cpu_to_be16s(&info);
342 if (nbd_write(client->ioc, &info, sizeof(info), errp) < 0) {
343 return -EIO;
345 if (nbd_write(client->ioc, buf, length, errp) < 0) {
346 return -EIO;
348 return 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,
356 Error **errp)
358 int rc;
359 char name[NBD_MAX_NAME_SIZE + 1];
360 NBDExport *exp;
361 uint16_t requests;
362 uint16_t request;
363 uint32_t namelen;
364 bool sendname = false;
365 bool blocksize = false;
366 uint32_t sizes[3];
367 char buf[sizeof(uint64_t) + sizeof(uint16_t)];
368 const char *msg;
370 /* Client sends:
371 4 bytes: L, name length (can be 0)
372 L bytes: export name
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";
378 goto invalid;
380 if (nbd_read(client->ioc, &namelen, sizeof(namelen), errp) < 0) {
381 return -EIO;
383 be32_to_cpus(&namelen);
384 length -= sizeof(namelen);
385 if (namelen > length - sizeof(requests) || (length - namelen) % 2) {
386 msg = "name length is incorrect";
387 goto invalid;
389 if (nbd_read(client->ioc, name, namelen, errp) < 0) {
390 return -EIO;
392 name[namelen] = '\0';
393 length -= namelen;
394 trace_nbd_negotiate_handle_export_name_request(name);
396 if (nbd_read(client->ioc, &requests, sizeof(requests), errp) < 0) {
397 return -EIO;
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";
404 goto invalid;
406 while (requests--) {
407 if (nbd_read(client->ioc, &request, sizeof(request), errp) < 0) {
408 return -EIO;
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 */
417 switch (request) {
418 case NBD_INFO_NAME:
419 sendname = true;
420 break;
421 case NBD_INFO_BLOCK_SIZE:
422 blocksize = true;
423 break;
426 assert(length == 0);
428 exp = nbd_export_find(name);
429 if (!exp) {
430 return nbd_negotiate_send_rep_err(client->ioc, NBD_REP_ERR_UNKNOWN,
431 opt, errp, "export '%s' not present",
432 name);
435 /* Don't bother sending NBD_INFO_NAME unless client requested it */
436 if (sendname) {
437 rc = nbd_negotiate_send_info(client, opt, NBD_INFO_NAME, namelen, name,
438 errp);
439 if (rc < 0) {
440 return rc;
444 /* Send NBD_INFO_DESCRIPTION only if available, regardless of
445 * client request */
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);
451 if (rc < 0) {
452 return rc;
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? */
464 sizes[1] = 4096;
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);
473 if (rc < 0) {
474 return rc;
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);
484 if (rc < 0) {
485 return rc;
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
491 * is not 1? */
492 if (opt == NBD_OPT_INFO && !blocksize) {
493 return nbd_negotiate_send_rep_err(client->ioc,
494 NBD_REP_ERR_BLOCK_SIZE_REQD, opt,
495 errp,
496 "request NBD_INFO_BLOCK_SIZE to "
497 "use this export");
500 /* Final reply */
501 rc = nbd_negotiate_send_rep(client->ioc, NBD_REP_ACK, opt, errp);
502 if (rc < 0) {
503 return rc;
506 if (opt == NBD_OPT_GO) {
507 client->exp = exp;
508 QTAILQ_INSERT_TAIL(&client->exp->clients, client, next);
509 nbd_export_get(client->exp);
510 rc = 1;
512 return rc;
514 invalid:
515 if (nbd_drop(client->ioc, length, errp) < 0) {
516 return -EIO;
518 return nbd_negotiate_send_rep_err(client->ioc, NBD_REP_ERR_INVALID, opt,
519 errp, "%s", msg);
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,
526 Error **errp)
528 QIOChannel *ioc;
529 QIOChannelTLS *tioc;
530 struct NBDTLSHandshakeData data = { 0 };
532 trace_nbd_negotiate_handle_starttls();
533 ioc = client->ioc;
535 if (nbd_negotiate_send_rep(client->ioc, NBD_REP_ACK,
536 NBD_OPT_STARTTLS, errp) < 0) {
537 return NULL;
540 tioc = qio_channel_tls_new_server(ioc,
541 client->tlscreds,
542 client->tlsaclname,
543 errp);
544 if (!tioc) {
545 return NULL;
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,
552 nbd_tls_handshake,
553 &data,
554 NULL);
556 if (!data.complete) {
557 g_main_loop_run(data.loop);
559 g_main_loop_unref(data.loop);
560 if (data.error) {
561 object_unref(OBJECT(tioc));
562 error_propagate(errp, data.error);
563 return NULL;
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.
572 * Return:
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)
579 int ret;
581 assert(length);
582 if (nbd_drop(client->ioc, length, errp) < 0) {
583 return -EIO;
585 ret = nbd_negotiate_send_rep_err(client->ioc, NBD_REP_ERR_INVALID,
586 option, errp,
587 "option '%s' should have zero length",
588 nbd_opt_lookup(option));
589 if (fatal && !ret) {
590 error_setg(errp, "option '%s' should have zero length",
591 nbd_opt_lookup(option));
592 return -EINVAL;
594 return ret;
597 /* nbd_negotiate_options
598 * Process all NBD_OPT_* client option commands, during fixed newstyle
599 * negotiation.
600 * Return:
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,
604 * errp is not set
606 static int nbd_negotiate_options(NBDClient *client, uint16_t myflags,
607 Error **errp)
609 uint32_t flags;
610 bool fixedNewstyle = false;
611 bool no_zeroes = false;
613 /* Client sends:
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
620 ... Rest of request
622 [ 0 .. 7] NBD_OPTS_MAGIC
623 [ 8 .. 11] Second NBD option
624 [12 .. 15] Data length
625 ... Rest of request
628 if (nbd_read(client->ioc, &flags, sizeof(flags), errp) < 0) {
629 error_prepend(errp, "read failed: ");
630 return -EIO;
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) {
639 no_zeroes = true;
640 flags &= ~NBD_FLAG_C_NO_ZEROES;
642 if (flags != 0) {
643 error_setg(errp, "Unknown client flags 0x%" PRIx32 " received", flags);
644 return -EINVAL;
647 while (1) {
648 int ret;
649 uint32_t option, length;
650 uint64_t magic;
652 if (nbd_read(client->ioc, &magic, sizeof(magic), errp) < 0) {
653 error_prepend(errp, "read failed: ");
654 return -EINVAL;
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");
660 return -EINVAL;
663 if (nbd_read(client->ioc, &option,
664 sizeof(option), errp) < 0) {
665 error_prepend(errp, "read failed: ");
666 return -EINVAL;
668 option = be32_to_cpu(option);
670 if (nbd_read(client->ioc, &length, sizeof(length), errp) < 0) {
671 error_prepend(errp, "read failed: ");
672 return -EINVAL;
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) {
680 QIOChannel *tioc;
681 if (!fixedNewstyle) {
682 error_setg(errp, "Unsupported option 0x%" PRIx32, option);
683 return -EINVAL;
685 switch (option) {
686 case NBD_OPT_STARTTLS:
687 if (length) {
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,
691 errp);
693 tioc = nbd_negotiate_handle_starttls(client, errp);
694 if (!tioc) {
695 return -EIO;
697 ret = 0;
698 object_unref(OBJECT(client->ioc));
699 client->ioc = QIO_CHANNEL(tioc);
700 break;
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",
705 option);
706 return -EINVAL;
708 default:
709 if (nbd_drop(client->ioc, length, errp) < 0) {
710 return -EIO;
712 ret = nbd_negotiate_send_rep_err(client->ioc,
713 NBD_REP_ERR_TLS_REQD,
714 option, errp,
715 "Option 0x%" PRIx32
716 "not permitted before TLS",
717 option);
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) {
722 return 1;
724 break;
726 } else if (fixedNewstyle) {
727 switch (option) {
728 case NBD_OPT_LIST:
729 if (length) {
730 ret = nbd_reject_length(client, length, option, false,
731 errp);
732 } else {
733 ret = nbd_negotiate_handle_list(client, errp);
735 break;
737 case NBD_OPT_ABORT:
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);
742 return 1;
744 case NBD_OPT_EXPORT_NAME:
745 return nbd_negotiate_handle_export_name(client, length,
746 myflags, no_zeroes,
747 errp);
749 case NBD_OPT_INFO:
750 case NBD_OPT_GO:
751 ret = nbd_negotiate_handle_info(client, length, option,
752 myflags, errp);
753 if (ret == 1) {
754 assert(option == NBD_OPT_GO);
755 return 0;
757 break;
759 case NBD_OPT_STARTTLS:
760 if (length) {
761 ret = nbd_reject_length(client, length, option, false,
762 errp);
763 } else if (client->tlscreds) {
764 ret = nbd_negotiate_send_rep_err(client->ioc,
765 NBD_REP_ERR_INVALID,
766 option, errp,
767 "TLS already enabled");
768 } else {
769 ret = nbd_negotiate_send_rep_err(client->ioc,
770 NBD_REP_ERR_POLICY,
771 option, errp,
772 "TLS not configured");
774 break;
776 case NBD_OPT_STRUCTURED_REPLY:
777 if (length) {
778 ret = nbd_reject_length(client, length, option, false,
779 errp);
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");
784 } else {
785 ret = nbd_negotiate_send_rep(client->ioc, NBD_REP_ACK,
786 option, errp);
787 client->structured_reply = true;
788 myflags |= NBD_FLAG_SEND_DF;
790 break;
792 default:
793 if (nbd_drop(client->ioc, length, errp) < 0) {
794 return -EIO;
796 ret = nbd_negotiate_send_rep_err(client->ioc,
797 NBD_REP_ERR_UNSUP,
798 option, errp,
799 "Unsupported option 0x%"
800 PRIx32 " (%s)", option,
801 nbd_opt_lookup(option));
802 break;
804 } else {
806 * If broken new-style we should drop the connection
807 * for anything except NBD_OPT_EXPORT_NAME
809 switch (option) {
810 case NBD_OPT_EXPORT_NAME:
811 return nbd_negotiate_handle_export_name(client, length,
812 myflags, no_zeroes,
813 errp);
815 default:
816 error_setg(errp, "Unsupported option 0x%" PRIx32 " (%s)",
817 option, nbd_opt_lookup(option));
818 return -EINVAL;
821 if (ret < 0) {
822 return ret;
827 /* nbd_negotiate
828 * Return:
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,
832 * errp is not set
834 static coroutine_fn int nbd_negotiate(NBDClient *client, Error **errp)
836 char buf[NBD_OLDSTYLE_NEGOTIATE_SIZE] = "";
837 int ret;
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);
841 bool oldStyle;
843 /* Old style negotiation header, no room for options
844 [ 0 .. 7] passwd ("NBDMAGIC")
845 [ 8 .. 15] magic (NBD_CLIENT_MAGIC)
846 [16 .. 23] size
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;
863 if (oldStyle) {
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: ");
872 return -EINVAL;
874 } else {
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: ");
880 return -EINVAL;
882 ret = nbd_negotiate_options(client, myflags, errp);
883 if (ret != 0) {
884 if (ret < 0) {
885 error_prepend(errp, "option negotiation failed: ");
887 return ret;
891 trace_nbd_negotiate_success();
893 return 0;
896 static int nbd_receive_request(QIOChannel *ioc, NBDRequest *request,
897 Error **errp)
899 uint8_t buf[NBD_REQUEST_SIZE];
900 uint32_t magic;
901 int ret;
903 ret = nbd_read(ioc, buf, sizeof(buf), errp);
904 if (ret < 0) {
905 return ret;
908 /* Request
909 [ 0 .. 3] magic (NBD_REQUEST_MAGIC)
910 [ 4 .. 5] flags (NBD_CMD_FLAG_FUA, ...)
911 [ 6 .. 7] type (NBD_CMD_READ, ...)
912 [ 8 .. 15] handle
913 [16 .. 23] from
914 [24 .. 27] len
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);
929 return -EINVAL;
931 return 0;
934 #define MAX_NBD_REQUESTS 16
936 void nbd_client_get(NBDClient *client)
938 client->refcount++;
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);
956 if (client->exp) {
957 QTAILQ_REMOVE(&client->exp->clients, client, next);
958 nbd_export_put(client->exp);
960 g_free(client);
964 static void client_close(NBDClient *client, bool negotiated)
966 if (client->closing) {
967 return;
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,
976 NULL);
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)
986 NBDRequestData *req;
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;
994 return req;
997 static void nbd_request_put(NBDRequestData *req)
999 NBDClient *client = req->client;
1001 if (req->data) {
1002 qemu_vfree(req->data);
1004 g_free(req);
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;
1015 NBDClient *client;
1017 trace_nbd_blk_aio_attached(exp->name, ctx);
1019 exp->ctx = 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;
1035 NBDClient *client;
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);
1043 exp->ctx = NULL;
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,
1055 Error **errp)
1057 AioContext *ctx;
1058 BlockBackend *blk;
1059 NBDExport *exp = g_new0(NBDExport, 1);
1060 uint64_t perm;
1061 int ret;
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);
1082 if (ret < 0) {
1083 goto fail;
1085 blk_set_enable_write_cache(blk, !writethrough);
1087 exp->refcount = 1;
1088 QTAILQ_INIT(&exp->clients);
1089 exp->blk = blk;
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");
1096 goto fail;
1098 exp->size -= exp->size % BDRV_SECTOR_SIZE;
1100 exp->close = close;
1101 exp->ctx = blk_get_aio_context(blk);
1102 blk_add_aio_context_notifier(blk, blk_aio_attached, blk_aio_detach, exp);
1104 if (on_eject_blk) {
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);
1110 return exp;
1112 fail:
1113 blk_unref(blk);
1114 g_free(exp);
1115 return NULL;
1118 NBDExport *nbd_export_find(const char *name)
1120 NBDExport *exp;
1121 QTAILQ_FOREACH(exp, &exports, next) {
1122 if (strcmp(name, exp->name) == 0) {
1123 return exp;
1127 return NULL;
1130 void nbd_export_set_name(NBDExport *exp, const char *name)
1132 if (exp->name == name) {
1133 return;
1136 nbd_export_get(exp);
1137 if (exp->name != NULL) {
1138 g_free(exp->name);
1139 exp->name = NULL;
1140 QTAILQ_REMOVE(&exports, exp, next);
1141 nbd_export_put(exp);
1143 if (name != NULL) {
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);
1173 exp->refcount++;
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);
1187 if (exp->close) {
1188 exp->close(exp);
1191 if (exp->blk) {
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);
1199 exp->blk = NULL;
1202 g_free(exp);
1206 BlockBackend *nbd_export_get_blockdev(NBDExport *exp)
1208 return exp->blk;
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)
1223 int ret;
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);
1234 return ret;
1237 static inline void set_be_simple_reply(NBDSimpleReply *reply, uint64_t error,
1238 uint64_t handle)
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,
1246 uint64_t handle,
1247 uint32_t error,
1248 void *data,
1249 size_t len,
1250 Error **errp)
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),
1260 len);
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,
1277 uint64_t handle,
1278 Error **errp)
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,
1292 uint64_t handle,
1293 uint64_t offset,
1294 void *data,
1295 size_t size,
1296 Error **errp)
1298 NBDStructuredReadData chunk;
1299 struct iovec iov[] = {
1300 {.iov_base = &chunk, .iov_len = sizeof(chunk)},
1301 {.iov_base = data, .iov_len = size}
1304 assert(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,
1314 uint64_t handle,
1315 uint32_t error,
1316 const char *msg,
1317 Error **errp)
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},
1326 assert(nbd_err);
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
1341 * the error).
1343 static int nbd_co_receive_request(NBDRequestData *req, NBDRequest *request,
1344 Error **errp)
1346 NBDClient *client = req->client;
1347 int valid_flags;
1349 g_assert(qemu_in_coroutine());
1350 assert(client->recv_coroutine == qemu_coroutine_self());
1351 if (nbd_receive_request(client->ioc, request, errp) < 0) {
1352 return -EIO;
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 */
1366 return -EIO;
1369 /* Check for sanity in the parameters, part 1. Defer as many
1370 * checks as possible until after reading any NBD_CMD_WRITE
1371 * payload, so we can try and keep the connection alive. */
1372 if ((request->from + request->len) < request->from) {
1373 error_setg(errp,
1374 "integer overflow detected, you're probably being attacked");
1375 return -EINVAL;
1378 if (request->type == NBD_CMD_READ || request->type == NBD_CMD_WRITE) {
1379 if (request->len > NBD_MAX_BUFFER_SIZE) {
1380 error_setg(errp, "len (%" PRIu32" ) is larger than max len (%u)",
1381 request->len, NBD_MAX_BUFFER_SIZE);
1382 return -EINVAL;
1385 req->data = blk_try_blockalign(client->exp->blk, request->len);
1386 if (req->data == NULL) {
1387 error_setg(errp, "No memory");
1388 return -ENOMEM;
1391 if (request->type == NBD_CMD_WRITE) {
1392 if (nbd_read(client->ioc, req->data, request->len, errp) < 0) {
1393 error_prepend(errp, "reading from socket failed: ");
1394 return -EIO;
1396 req->complete = true;
1398 trace_nbd_co_receive_request_payload_received(request->handle,
1399 request->len);
1402 /* Sanity checks, part 2. */
1403 if (request->from + request->len > client->exp->size) {
1404 error_setg(errp, "operation past EOF; From: %" PRIu64 ", Len: %" PRIu32
1405 ", Size: %" PRIu64, request->from, request->len,
1406 (uint64_t)client->exp->size);
1407 return request->type == NBD_CMD_WRITE ? -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);
1418 return -EINVAL;
1421 return 0;
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 */
1431 int ret;
1432 int flags;
1433 int reply_data_len = 0;
1434 Error *local_err = NULL;
1435 char *msg = NULL;
1437 trace_nbd_trip();
1438 if (client->closing) {
1439 nbd_client_put(client);
1440 return;
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);
1447 if (ret == -EIO) {
1448 goto disconnect;
1451 if (ret < 0) {
1452 goto reply;
1455 if (client->closing) {
1457 * The client may be closed when we are blocked in
1458 * nbd_co_receive_request()
1460 goto done;
1463 switch (request.type) {
1464 case NBD_CMD_READ:
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);
1468 if (ret < 0) {
1469 error_setg_errno(&local_err, -ret, "flush failed");
1470 break;
1474 ret = blk_pread(exp->blk, request.from + exp->dev_offset,
1475 req->data, request.len);
1476 if (ret < 0) {
1477 error_setg_errno(&local_err, -ret, "reading from file failed");
1478 break;
1481 reply_data_len = request.len;
1483 break;
1484 case NBD_CMD_WRITE:
1485 if (exp->nbdflags & NBD_FLAG_READ_ONLY) {
1486 error_setg(&local_err, "Export is read-only");
1487 ret = -EROFS;
1488 break;
1491 flags = 0;
1492 if (request.flags & NBD_CMD_FLAG_FUA) {
1493 flags |= BDRV_REQ_FUA;
1495 ret = blk_pwrite(exp->blk, request.from + exp->dev_offset,
1496 req->data, request.len, flags);
1497 if (ret < 0) {
1498 error_setg_errno(&local_err, -ret, "writing to file failed");
1501 break;
1502 case NBD_CMD_WRITE_ZEROES:
1503 if (exp->nbdflags & NBD_FLAG_READ_ONLY) {
1504 error_setg(&local_err, "Export is read-only");
1505 ret = -EROFS;
1506 break;
1509 flags = 0;
1510 if (request.flags & NBD_CMD_FLAG_FUA) {
1511 flags |= BDRV_REQ_FUA;
1513 if (!(request.flags & NBD_CMD_FLAG_NO_HOLE)) {
1514 flags |= BDRV_REQ_MAY_UNMAP;
1516 ret = blk_pwrite_zeroes(exp->blk, request.from + exp->dev_offset,
1517 request.len, flags);
1518 if (ret < 0) {
1519 error_setg_errno(&local_err, -ret, "writing to file failed");
1522 break;
1523 case NBD_CMD_DISC:
1524 /* unreachable, thanks to special case in nbd_co_receive_request() */
1525 abort();
1527 case NBD_CMD_FLUSH:
1528 ret = blk_co_flush(exp->blk);
1529 if (ret < 0) {
1530 error_setg_errno(&local_err, -ret, "flush failed");
1533 break;
1534 case NBD_CMD_TRIM:
1535 ret = blk_co_pdiscard(exp->blk, request.from + exp->dev_offset,
1536 request.len);
1537 if (ret < 0) {
1538 error_setg_errno(&local_err, -ret, "discard failed");
1541 break;
1542 default:
1543 error_setg(&local_err, "invalid request type (%" PRIu32 ") received",
1544 request.type);
1545 ret = -EINVAL;
1548 reply:
1549 if (local_err) {
1550 /* If we get here, local_err was not a fatal error, and should be sent
1551 * to the client. */
1552 assert(ret < 0);
1553 msg = g_strdup(error_get_pretty(local_err));
1554 error_report_err(local_err);
1555 local_err = NULL;
1558 if (client->structured_reply &&
1559 (ret < 0 || request.type == NBD_CMD_READ)) {
1560 if (ret < 0) {
1561 ret = nbd_co_send_structured_error(req->client, request.handle,
1562 -ret, msg, &local_err);
1563 } else if (reply_data_len) {
1564 ret = nbd_co_send_structured_read(req->client, request.handle,
1565 request.from, req->data,
1566 reply_data_len, &local_err);
1567 } else {
1568 ret = nbd_co_send_structured_done(req->client, request.handle,
1569 &local_err);
1571 } else {
1572 ret = nbd_co_send_simple_reply(req->client, request.handle,
1573 ret < 0 ? -ret : 0,
1574 req->data, reply_data_len, &local_err);
1576 g_free(msg);
1577 if (ret < 0) {
1578 error_prepend(&local_err, "Failed to send reply: ");
1579 goto disconnect;
1582 /* We must disconnect after NBD_CMD_WRITE if we did not
1583 * read the payload.
1585 if (!req->complete) {
1586 error_setg(&local_err, "Request handling failed in intermediate state");
1587 goto disconnect;
1590 done:
1591 nbd_request_put(req);
1592 nbd_client_put(client);
1593 return;
1595 disconnect:
1596 if (local_err) {
1597 error_reportf_err(local_err, "Disconnect client, due to: ");
1599 nbd_request_put(req);
1600 client_close(client, true);
1601 nbd_client_put(client);
1604 static void nbd_client_receive_next_request(NBDClient *client)
1606 if (!client->recv_coroutine && client->nb_requests < MAX_NBD_REQUESTS) {
1607 nbd_client_get(client);
1608 client->recv_coroutine = qemu_coroutine_create(nbd_trip, client);
1609 aio_co_schedule(client->exp->ctx, client->recv_coroutine);
1613 static coroutine_fn void nbd_co_client_start(void *opaque)
1615 NBDClient *client = opaque;
1616 NBDExport *exp = client->exp;
1617 Error *local_err = NULL;
1619 if (exp) {
1620 nbd_export_get(exp);
1621 QTAILQ_INSERT_TAIL(&exp->clients, client, next);
1623 qemu_co_mutex_init(&client->send_lock);
1625 if (nbd_negotiate(client, &local_err)) {
1626 if (local_err) {
1627 error_report_err(local_err);
1629 client_close(client, false);
1630 return;
1633 nbd_client_receive_next_request(client);
1637 * Create a new client listener on the given export @exp, using the
1638 * given channel @sioc. Begin servicing it in a coroutine. When the
1639 * connection closes, call @close_fn with an indication of whether the
1640 * client completed negotiation.
1642 void nbd_client_new(NBDExport *exp,
1643 QIOChannelSocket *sioc,
1644 QCryptoTLSCreds *tlscreds,
1645 const char *tlsaclname,
1646 void (*close_fn)(NBDClient *, bool))
1648 NBDClient *client;
1649 Coroutine *co;
1651 client = g_new0(NBDClient, 1);
1652 client->refcount = 1;
1653 client->exp = exp;
1654 client->tlscreds = tlscreds;
1655 if (tlscreds) {
1656 object_ref(OBJECT(client->tlscreds));
1658 client->tlsaclname = g_strdup(tlsaclname);
1659 client->sioc = sioc;
1660 object_ref(OBJECT(client->sioc));
1661 client->ioc = QIO_CHANNEL(sioc);
1662 object_ref(OBJECT(client->ioc));
1663 client->close_fn = close_fn;
1665 co = qemu_coroutine_create(nbd_co_client_start, client);
1666 qemu_coroutine_enter(co);