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"
23 #include "nbd-internal.h"
25 static int system_errno_to_nbd_errno(int err
)
53 /* Definitions for opaque data types */
55 typedef struct NBDRequestData NBDRequestData
;
57 struct NBDRequestData
{
58 QSIMPLEQ_ENTRY(NBDRequestData
) entry
;
66 void (*close
)(NBDExport
*exp
);
74 QTAILQ_HEAD(, NBDClient
) clients
;
75 QTAILQ_ENTRY(NBDExport
) next
;
79 BlockBackend
*eject_notifier_blk
;
80 Notifier eject_notifier
;
83 static QTAILQ_HEAD(, NBDExport
) exports
= QTAILQ_HEAD_INITIALIZER(exports
);
87 void (*close_fn
)(NBDClient
*client
, bool negotiated
);
90 QCryptoTLSCreds
*tlscreds
;
92 QIOChannelSocket
*sioc
; /* The underlying data channel */
93 QIOChannel
*ioc
; /* The current I/O channel which may differ (eg TLS) */
95 Coroutine
*recv_coroutine
;
98 Coroutine
*send_coroutine
;
100 QTAILQ_ENTRY(NBDClient
) next
;
105 /* That's all folks */
107 static void nbd_client_receive_next_request(NBDClient
*client
);
109 /* Basic flow for negotiation
136 /* Send a reply header, including length, but no payload.
137 * Return -errno on error, 0 on success. */
138 static int nbd_negotiate_send_rep_len(QIOChannel
*ioc
, uint32_t type
,
139 uint32_t opt
, uint32_t len
, Error
**errp
)
143 trace_nbd_negotiate_send_rep_len(opt
, nbd_opt_lookup(opt
),
144 type
, nbd_rep_lookup(type
), len
);
146 assert(len
< NBD_MAX_BUFFER_SIZE
);
147 magic
= cpu_to_be64(NBD_REP_MAGIC
);
148 if (nbd_write(ioc
, &magic
, sizeof(magic
), errp
) < 0) {
149 error_prepend(errp
, "write failed (rep magic): ");
153 opt
= cpu_to_be32(opt
);
154 if (nbd_write(ioc
, &opt
, sizeof(opt
), errp
) < 0) {
155 error_prepend(errp
, "write failed (rep opt): ");
159 type
= cpu_to_be32(type
);
160 if (nbd_write(ioc
, &type
, sizeof(type
), errp
) < 0) {
161 error_prepend(errp
, "write failed (rep type): ");
165 len
= cpu_to_be32(len
);
166 if (nbd_write(ioc
, &len
, sizeof(len
), errp
) < 0) {
167 error_prepend(errp
, "write failed (rep data length): ");
173 /* Send a reply header with default 0 length.
174 * Return -errno on error, 0 on success. */
175 static int nbd_negotiate_send_rep(QIOChannel
*ioc
, uint32_t type
, uint32_t opt
,
178 return nbd_negotiate_send_rep_len(ioc
, type
, opt
, 0, errp
);
181 /* Send an error reply.
182 * Return -errno on error, 0 on success. */
183 static int GCC_FMT_ATTR(5, 6)
184 nbd_negotiate_send_rep_err(QIOChannel
*ioc
, uint32_t type
,
185 uint32_t opt
, Error
**errp
, const char *fmt
, ...)
193 msg
= g_strdup_vprintf(fmt
, va
);
197 trace_nbd_negotiate_send_rep_err(msg
);
198 ret
= nbd_negotiate_send_rep_len(ioc
, type
, opt
, len
, errp
);
202 if (nbd_write(ioc
, msg
, len
, errp
) < 0) {
203 error_prepend(errp
, "write failed (error message): ");
214 /* Send a single NBD_REP_SERVER reply to NBD_OPT_LIST, including payload.
215 * Return -errno on error, 0 on success. */
216 static int nbd_negotiate_send_rep_list(QIOChannel
*ioc
, NBDExport
*exp
,
219 size_t name_len
, desc_len
;
221 const char *name
= exp
->name
? exp
->name
: "";
222 const char *desc
= exp
->description
? exp
->description
: "";
225 trace_nbd_negotiate_send_rep_list(name
, desc
);
226 name_len
= strlen(name
);
227 desc_len
= strlen(desc
);
228 len
= name_len
+ desc_len
+ sizeof(len
);
229 ret
= nbd_negotiate_send_rep_len(ioc
, NBD_REP_SERVER
, NBD_OPT_LIST
, len
,
235 len
= cpu_to_be32(name_len
);
236 if (nbd_write(ioc
, &len
, sizeof(len
), errp
) < 0) {
237 error_prepend(errp
, "write failed (name length): ");
241 if (nbd_write(ioc
, name
, name_len
, errp
) < 0) {
242 error_prepend(errp
, "write failed (name buffer): ");
246 if (nbd_write(ioc
, desc
, desc_len
, errp
) < 0) {
247 error_prepend(errp
, "write failed (description buffer): ");
254 /* Process the NBD_OPT_LIST command, with a potential series of replies.
255 * Return -errno on error, 0 on success. */
256 static int nbd_negotiate_handle_list(NBDClient
*client
, uint32_t length
,
262 if (nbd_drop(client
->ioc
, length
, errp
) < 0) {
265 return nbd_negotiate_send_rep_err(client
->ioc
,
266 NBD_REP_ERR_INVALID
, NBD_OPT_LIST
,
268 "OPT_LIST should not have length");
271 /* For each export, send a NBD_REP_SERVER reply. */
272 QTAILQ_FOREACH(exp
, &exports
, next
) {
273 if (nbd_negotiate_send_rep_list(client
->ioc
, exp
, errp
)) {
277 /* Finish with a NBD_REP_ACK. */
278 return nbd_negotiate_send_rep(client
->ioc
, NBD_REP_ACK
, NBD_OPT_LIST
, errp
);
281 /* Send a reply to NBD_OPT_EXPORT_NAME.
282 * Return -errno on error, 0 on success. */
283 static int nbd_negotiate_handle_export_name(NBDClient
*client
, uint32_t length
,
284 uint16_t myflags
, bool no_zeroes
,
287 char name
[NBD_MAX_NAME_SIZE
+ 1];
288 char buf
[NBD_REPLY_EXPORT_NAME_SIZE
] = "";
293 [20 .. xx] export name (length bytes)
296 [ 8 .. 9] export flags
297 [10 .. 133] reserved (0) [unless no_zeroes]
299 trace_nbd_negotiate_handle_export_name();
300 if (length
>= sizeof(name
)) {
301 error_setg(errp
, "Bad length received");
304 if (nbd_read(client
->ioc
, name
, length
, errp
) < 0) {
305 error_prepend(errp
, "read failed: ");
310 trace_nbd_negotiate_handle_export_name_request(name
);
312 client
->exp
= nbd_export_find(name
);
314 error_setg(errp
, "export not found");
318 trace_nbd_negotiate_new_style_size_flags(client
->exp
->size
,
319 client
->exp
->nbdflags
| myflags
);
320 stq_be_p(buf
, client
->exp
->size
);
321 stw_be_p(buf
+ 8, client
->exp
->nbdflags
| myflags
);
322 len
= no_zeroes
? 10 : sizeof(buf
);
323 ret
= nbd_write(client
->ioc
, buf
, len
, errp
);
325 error_prepend(errp
, "write failed: ");
329 QTAILQ_INSERT_TAIL(&client
->exp
->clients
, client
, next
);
330 nbd_export_get(client
->exp
);
335 /* Send a single NBD_REP_INFO, with a buffer @buf of @length bytes.
336 * The buffer does NOT include the info type prefix.
337 * Return -errno on error, 0 if ready to send more. */
338 static int nbd_negotiate_send_info(NBDClient
*client
, uint32_t opt
,
339 uint16_t info
, uint32_t length
, void *buf
,
344 trace_nbd_negotiate_send_info(info
, nbd_info_lookup(info
), length
);
345 rc
= nbd_negotiate_send_rep_len(client
->ioc
, NBD_REP_INFO
, opt
,
346 sizeof(info
) + length
, errp
);
351 if (nbd_write(client
->ioc
, &info
, sizeof(info
), errp
) < 0) {
354 if (nbd_write(client
->ioc
, buf
, length
, errp
) < 0) {
360 /* Handle NBD_OPT_INFO and NBD_OPT_GO.
361 * Return -errno on error, 0 if ready for next option, and 1 to move
362 * into transmission phase. */
363 static int nbd_negotiate_handle_info(NBDClient
*client
, uint32_t length
,
364 uint32_t opt
, uint16_t myflags
,
368 char name
[NBD_MAX_NAME_SIZE
+ 1];
373 bool sendname
= false;
374 bool blocksize
= false;
376 char buf
[sizeof(uint64_t) + sizeof(uint16_t)];
380 4 bytes: L, name length (can be 0)
382 2 bytes: N, number of requests (can be 0)
383 N * 2 bytes: N requests
385 if (length
< sizeof(namelen
) + sizeof(requests
)) {
386 msg
= "overall request too short";
389 if (nbd_read(client
->ioc
, &namelen
, sizeof(namelen
), errp
) < 0) {
392 be32_to_cpus(&namelen
);
393 length
-= sizeof(namelen
);
394 if (namelen
> length
- sizeof(requests
) || (length
- namelen
) % 2) {
395 msg
= "name length is incorrect";
398 if (nbd_read(client
->ioc
, name
, namelen
, errp
) < 0) {
401 name
[namelen
] = '\0';
403 trace_nbd_negotiate_handle_export_name_request(name
);
405 if (nbd_read(client
->ioc
, &requests
, sizeof(requests
), errp
) < 0) {
408 be16_to_cpus(&requests
);
409 length
-= sizeof(requests
);
410 trace_nbd_negotiate_handle_info_requests(requests
);
411 if (requests
!= length
/ sizeof(request
)) {
412 msg
= "incorrect number of requests for overall length";
416 if (nbd_read(client
->ioc
, &request
, sizeof(request
), errp
) < 0) {
419 be16_to_cpus(&request
);
420 length
-= sizeof(request
);
421 trace_nbd_negotiate_handle_info_request(request
,
422 nbd_info_lookup(request
));
423 /* We care about NBD_INFO_NAME and NBD_INFO_BLOCK_SIZE;
424 * everything else is either a request we don't know or
425 * something we send regardless of request */
430 case NBD_INFO_BLOCK_SIZE
:
436 exp
= nbd_export_find(name
);
438 return nbd_negotiate_send_rep_err(client
->ioc
, NBD_REP_ERR_UNKNOWN
,
439 opt
, errp
, "export '%s' not present",
443 /* Don't bother sending NBD_INFO_NAME unless client requested it */
445 rc
= nbd_negotiate_send_info(client
, opt
, NBD_INFO_NAME
, length
, name
,
452 /* Send NBD_INFO_DESCRIPTION only if available, regardless of
454 if (exp
->description
) {
455 size_t len
= strlen(exp
->description
);
457 rc
= nbd_negotiate_send_info(client
, opt
, NBD_INFO_DESCRIPTION
,
458 len
, exp
->description
, errp
);
464 /* Send NBD_INFO_BLOCK_SIZE always, but tweak the minimum size
465 * according to whether the client requested it, and according to
466 * whether this is OPT_INFO or OPT_GO. */
467 /* minimum - 1 for back-compat, or 512 if client is new enough.
468 * TODO: consult blk_bs(blk)->bl.request_alignment? */
469 sizes
[0] = (opt
== NBD_OPT_INFO
|| blocksize
) ? BDRV_SECTOR_SIZE
: 1;
470 /* preferred - Hard-code to 4096 for now.
471 * TODO: is blk_bs(blk)->bl.opt_transfer appropriate? */
473 /* maximum - At most 32M, but smaller as appropriate. */
474 sizes
[2] = MIN(blk_get_max_transfer(exp
->blk
), NBD_MAX_BUFFER_SIZE
);
475 trace_nbd_negotiate_handle_info_block_size(sizes
[0], sizes
[1], sizes
[2]);
476 cpu_to_be32s(&sizes
[0]);
477 cpu_to_be32s(&sizes
[1]);
478 cpu_to_be32s(&sizes
[2]);
479 rc
= nbd_negotiate_send_info(client
, opt
, NBD_INFO_BLOCK_SIZE
,
480 sizeof(sizes
), sizes
, errp
);
485 /* Send NBD_INFO_EXPORT always */
486 trace_nbd_negotiate_new_style_size_flags(exp
->size
,
487 exp
->nbdflags
| myflags
);
488 stq_be_p(buf
, exp
->size
);
489 stw_be_p(buf
+ 8, exp
->nbdflags
| myflags
);
490 rc
= nbd_negotiate_send_info(client
, opt
, NBD_INFO_EXPORT
,
491 sizeof(buf
), buf
, errp
);
496 /* If the client is just asking for NBD_OPT_INFO, but forgot to
497 * request block sizes, return an error.
498 * TODO: consult blk_bs(blk)->request_align, and only error if it
500 if (opt
== NBD_OPT_INFO
&& !blocksize
) {
501 return nbd_negotiate_send_rep_err(client
->ioc
,
502 NBD_REP_ERR_BLOCK_SIZE_REQD
, opt
,
504 "request NBD_INFO_BLOCK_SIZE to "
509 rc
= nbd_negotiate_send_rep(client
->ioc
, NBD_REP_ACK
, opt
, errp
);
514 if (opt
== NBD_OPT_GO
) {
516 QTAILQ_INSERT_TAIL(&client
->exp
->clients
, client
, next
);
517 nbd_export_get(client
->exp
);
523 if (nbd_drop(client
->ioc
, length
, errp
) < 0) {
526 return nbd_negotiate_send_rep_err(client
->ioc
, NBD_REP_ERR_INVALID
, opt
,
531 /* Handle NBD_OPT_STARTTLS. Return NULL to drop connection, or else the
532 * new channel for all further (now-encrypted) communication. */
533 static QIOChannel
*nbd_negotiate_handle_starttls(NBDClient
*client
,
539 struct NBDTLSHandshakeData data
= { 0 };
541 trace_nbd_negotiate_handle_starttls();
544 if (nbd_drop(ioc
, length
, errp
) < 0) {
547 nbd_negotiate_send_rep_err(ioc
, NBD_REP_ERR_INVALID
, NBD_OPT_STARTTLS
,
549 "OPT_STARTTLS should not have length");
553 if (nbd_negotiate_send_rep(client
->ioc
, NBD_REP_ACK
,
554 NBD_OPT_STARTTLS
, errp
) < 0) {
558 tioc
= qio_channel_tls_new_server(ioc
,
566 qio_channel_set_name(QIO_CHANNEL(tioc
), "nbd-server-tls");
567 trace_nbd_negotiate_handle_starttls_handshake();
568 data
.loop
= g_main_loop_new(g_main_context_default(), FALSE
);
569 qio_channel_tls_handshake(tioc
,
574 if (!data
.complete
) {
575 g_main_loop_run(data
.loop
);
577 g_main_loop_unref(data
.loop
);
579 object_unref(OBJECT(tioc
));
580 error_propagate(errp
, data
.error
);
584 return QIO_CHANNEL(tioc
);
587 /* nbd_negotiate_options
588 * Process all NBD_OPT_* client option commands, during fixed newstyle
591 * -errno on error, errp is set
592 * 0 on successful negotiation, errp is not set
593 * 1 if client sent NBD_OPT_ABORT, i.e. on valid disconnect,
596 static int nbd_negotiate_options(NBDClient
*client
, uint16_t myflags
,
600 bool fixedNewstyle
= false;
601 bool no_zeroes
= false;
604 [ 0 .. 3] client flags
606 Then we loop until NBD_OPT_EXPORT_NAME or NBD_OPT_GO:
607 [ 0 .. 7] NBD_OPTS_MAGIC
608 [ 8 .. 11] NBD option
609 [12 .. 15] Data length
612 [ 0 .. 7] NBD_OPTS_MAGIC
613 [ 8 .. 11] Second NBD option
614 [12 .. 15] Data length
618 if (nbd_read(client
->ioc
, &flags
, sizeof(flags
), errp
) < 0) {
619 error_prepend(errp
, "read failed: ");
622 be32_to_cpus(&flags
);
623 trace_nbd_negotiate_options_flags(flags
);
624 if (flags
& NBD_FLAG_C_FIXED_NEWSTYLE
) {
625 fixedNewstyle
= true;
626 flags
&= ~NBD_FLAG_C_FIXED_NEWSTYLE
;
628 if (flags
& NBD_FLAG_C_NO_ZEROES
) {
630 flags
&= ~NBD_FLAG_C_NO_ZEROES
;
633 error_setg(errp
, "Unknown client flags 0x%" PRIx32
" received", flags
);
639 uint32_t option
, length
;
642 if (nbd_read(client
->ioc
, &magic
, sizeof(magic
), errp
) < 0) {
643 error_prepend(errp
, "read failed: ");
646 magic
= be64_to_cpu(magic
);
647 trace_nbd_negotiate_options_check_magic(magic
);
648 if (magic
!= NBD_OPTS_MAGIC
) {
649 error_setg(errp
, "Bad magic received");
653 if (nbd_read(client
->ioc
, &option
,
654 sizeof(option
), errp
) < 0) {
655 error_prepend(errp
, "read failed: ");
658 option
= be32_to_cpu(option
);
660 if (nbd_read(client
->ioc
, &length
, sizeof(length
), errp
) < 0) {
661 error_prepend(errp
, "read failed: ");
664 length
= be32_to_cpu(length
);
666 trace_nbd_negotiate_options_check_option(option
,
667 nbd_opt_lookup(option
));
668 if (client
->tlscreds
&&
669 client
->ioc
== (QIOChannel
*)client
->sioc
) {
671 if (!fixedNewstyle
) {
672 error_setg(errp
, "Unsupported option 0x%" PRIx32
, option
);
676 case NBD_OPT_STARTTLS
:
677 tioc
= nbd_negotiate_handle_starttls(client
, length
, errp
);
682 object_unref(OBJECT(client
->ioc
));
683 client
->ioc
= QIO_CHANNEL(tioc
);
686 case NBD_OPT_EXPORT_NAME
:
687 /* No way to return an error to client, so drop connection */
688 error_setg(errp
, "Option 0x%x not permitted before TLS",
693 if (nbd_drop(client
->ioc
, length
, errp
) < 0) {
696 ret
= nbd_negotiate_send_rep_err(client
->ioc
,
697 NBD_REP_ERR_TLS_REQD
,
700 "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
);
717 /* NBD spec says we must try to reply before
718 * disconnecting, but that we must also tolerate
719 * guests that don't wait for our reply. */
720 nbd_negotiate_send_rep(client
->ioc
, NBD_REP_ACK
, option
, NULL
);
723 case NBD_OPT_EXPORT_NAME
:
724 return nbd_negotiate_handle_export_name(client
, length
,
730 ret
= nbd_negotiate_handle_info(client
, length
, option
,
733 assert(option
== NBD_OPT_GO
);
738 case NBD_OPT_STARTTLS
:
739 if (nbd_drop(client
->ioc
, length
, errp
) < 0) {
742 if (client
->tlscreds
) {
743 ret
= nbd_negotiate_send_rep_err(client
->ioc
,
746 "TLS already enabled");
748 ret
= nbd_negotiate_send_rep_err(client
->ioc
,
751 "TLS not configured");
755 if (nbd_drop(client
->ioc
, length
, errp
) < 0) {
758 ret
= nbd_negotiate_send_rep_err(client
->ioc
,
761 "Unsupported option 0x%"
762 PRIx32
" (%s)", option
,
763 nbd_opt_lookup(option
));
768 * If broken new-style we should drop the connection
769 * for anything except NBD_OPT_EXPORT_NAME
772 case NBD_OPT_EXPORT_NAME
:
773 return nbd_negotiate_handle_export_name(client
, length
,
778 error_setg(errp
, "Unsupported option 0x%" PRIx32
" (%s)",
779 option
, nbd_opt_lookup(option
));
791 * -errno on error, errp is set
792 * 0 on successful negotiation, errp is not set
793 * 1 if client sent NBD_OPT_ABORT, i.e. on valid disconnect,
796 static coroutine_fn
int nbd_negotiate(NBDClient
*client
, Error
**errp
)
798 char buf
[NBD_OLDSTYLE_NEGOTIATE_SIZE
] = "";
800 const uint16_t myflags
= (NBD_FLAG_HAS_FLAGS
| NBD_FLAG_SEND_TRIM
|
801 NBD_FLAG_SEND_FLUSH
| NBD_FLAG_SEND_FUA
|
802 NBD_FLAG_SEND_WRITE_ZEROES
);
805 /* Old style negotiation header, no room for options
806 [ 0 .. 7] passwd ("NBDMAGIC")
807 [ 8 .. 15] magic (NBD_CLIENT_MAGIC)
809 [24 .. 27] export flags (zero-extended)
810 [28 .. 151] reserved (0)
812 New style negotiation header, client can send options
813 [ 0 .. 7] passwd ("NBDMAGIC")
814 [ 8 .. 15] magic (NBD_OPTS_MAGIC)
815 [16 .. 17] server flags (0)
816 ....options sent, ending in NBD_OPT_EXPORT_NAME or NBD_OPT_GO....
819 qio_channel_set_blocking(client
->ioc
, false, NULL
);
821 trace_nbd_negotiate_begin();
822 memcpy(buf
, "NBDMAGIC", 8);
824 oldStyle
= client
->exp
!= NULL
&& !client
->tlscreds
;
826 trace_nbd_negotiate_old_style(client
->exp
->size
,
827 client
->exp
->nbdflags
| myflags
);
828 stq_be_p(buf
+ 8, NBD_CLIENT_MAGIC
);
829 stq_be_p(buf
+ 16, client
->exp
->size
);
830 stl_be_p(buf
+ 24, client
->exp
->nbdflags
| myflags
);
832 if (nbd_write(client
->ioc
, buf
, sizeof(buf
), errp
) < 0) {
833 error_prepend(errp
, "write failed: ");
837 stq_be_p(buf
+ 8, NBD_OPTS_MAGIC
);
838 stw_be_p(buf
+ 16, NBD_FLAG_FIXED_NEWSTYLE
| NBD_FLAG_NO_ZEROES
);
840 if (nbd_write(client
->ioc
, buf
, 18, errp
) < 0) {
841 error_prepend(errp
, "write failed: ");
844 ret
= nbd_negotiate_options(client
, myflags
, errp
);
847 error_prepend(errp
, "option negotiation failed: ");
853 trace_nbd_negotiate_success();
858 static int nbd_receive_request(QIOChannel
*ioc
, NBDRequest
*request
,
861 uint8_t buf
[NBD_REQUEST_SIZE
];
865 ret
= nbd_read(ioc
, buf
, sizeof(buf
), errp
);
871 [ 0 .. 3] magic (NBD_REQUEST_MAGIC)
872 [ 4 .. 5] flags (NBD_CMD_FLAG_FUA, ...)
873 [ 6 .. 7] type (NBD_CMD_READ, ...)
879 magic
= ldl_be_p(buf
);
880 request
->flags
= lduw_be_p(buf
+ 4);
881 request
->type
= lduw_be_p(buf
+ 6);
882 request
->handle
= ldq_be_p(buf
+ 8);
883 request
->from
= ldq_be_p(buf
+ 16);
884 request
->len
= ldl_be_p(buf
+ 24);
886 trace_nbd_receive_request(magic
, request
->flags
, request
->type
,
887 request
->from
, request
->len
);
889 if (magic
!= NBD_REQUEST_MAGIC
) {
890 error_setg(errp
, "invalid magic (got 0x%" PRIx32
")", magic
);
896 #define MAX_NBD_REQUESTS 16
898 void nbd_client_get(NBDClient
*client
)
903 void nbd_client_put(NBDClient
*client
)
905 if (--client
->refcount
== 0) {
906 /* The last reference should be dropped by client->close,
907 * which is called by client_close.
909 assert(client
->closing
);
911 qio_channel_detach_aio_context(client
->ioc
);
912 object_unref(OBJECT(client
->sioc
));
913 object_unref(OBJECT(client
->ioc
));
914 if (client
->tlscreds
) {
915 object_unref(OBJECT(client
->tlscreds
));
917 g_free(client
->tlsaclname
);
919 QTAILQ_REMOVE(&client
->exp
->clients
, client
, next
);
920 nbd_export_put(client
->exp
);
926 static void client_close(NBDClient
*client
, bool negotiated
)
928 if (client
->closing
) {
932 client
->closing
= true;
934 /* Force requests to finish. They will drop their own references,
935 * then we'll close the socket and free the NBDClient.
937 qio_channel_shutdown(client
->ioc
, QIO_CHANNEL_SHUTDOWN_BOTH
,
940 /* Also tell the client, so that they release their reference. */
941 if (client
->close_fn
) {
942 client
->close_fn(client
, negotiated
);
946 static NBDRequestData
*nbd_request_get(NBDClient
*client
)
950 assert(client
->nb_requests
<= MAX_NBD_REQUESTS
- 1);
951 client
->nb_requests
++;
953 req
= g_new0(NBDRequestData
, 1);
954 nbd_client_get(client
);
955 req
->client
= client
;
959 static void nbd_request_put(NBDRequestData
*req
)
961 NBDClient
*client
= req
->client
;
964 qemu_vfree(req
->data
);
968 client
->nb_requests
--;
969 nbd_client_receive_next_request(client
);
971 nbd_client_put(client
);
974 static void blk_aio_attached(AioContext
*ctx
, void *opaque
)
976 NBDExport
*exp
= opaque
;
979 trace_nbd_blk_aio_attached(exp
->name
, ctx
);
983 QTAILQ_FOREACH(client
, &exp
->clients
, next
) {
984 qio_channel_attach_aio_context(client
->ioc
, ctx
);
985 if (client
->recv_coroutine
) {
986 aio_co_schedule(ctx
, client
->recv_coroutine
);
988 if (client
->send_coroutine
) {
989 aio_co_schedule(ctx
, client
->send_coroutine
);
994 static void blk_aio_detach(void *opaque
)
996 NBDExport
*exp
= opaque
;
999 trace_nbd_blk_aio_detach(exp
->name
, exp
->ctx
);
1001 QTAILQ_FOREACH(client
, &exp
->clients
, next
) {
1002 qio_channel_detach_aio_context(client
->ioc
);
1008 static void nbd_eject_notifier(Notifier
*n
, void *data
)
1010 NBDExport
*exp
= container_of(n
, NBDExport
, eject_notifier
);
1011 nbd_export_close(exp
);
1014 NBDExport
*nbd_export_new(BlockDriverState
*bs
, off_t dev_offset
, off_t size
,
1015 uint16_t nbdflags
, void (*close
)(NBDExport
*),
1016 bool writethrough
, BlockBackend
*on_eject_blk
,
1021 NBDExport
*exp
= g_new0(NBDExport
, 1);
1026 * NBD exports are used for non-shared storage migration. Make sure
1027 * that BDRV_O_INACTIVE is cleared and the image is ready for write
1028 * access since the export could be available before migration handover.
1030 ctx
= bdrv_get_aio_context(bs
);
1031 aio_context_acquire(ctx
);
1032 bdrv_invalidate_cache(bs
, NULL
);
1033 aio_context_release(ctx
);
1035 /* Don't allow resize while the NBD server is running, otherwise we don't
1036 * care what happens with the node. */
1037 perm
= BLK_PERM_CONSISTENT_READ
;
1038 if ((nbdflags
& NBD_FLAG_READ_ONLY
) == 0) {
1039 perm
|= BLK_PERM_WRITE
;
1041 blk
= blk_new(perm
, BLK_PERM_CONSISTENT_READ
| BLK_PERM_WRITE_UNCHANGED
|
1042 BLK_PERM_WRITE
| BLK_PERM_GRAPH_MOD
);
1043 ret
= blk_insert_bs(blk
, bs
, errp
);
1047 blk_set_enable_write_cache(blk
, !writethrough
);
1050 QTAILQ_INIT(&exp
->clients
);
1052 exp
->dev_offset
= dev_offset
;
1053 exp
->nbdflags
= nbdflags
;
1054 exp
->size
= size
< 0 ? blk_getlength(blk
) : size
;
1055 if (exp
->size
< 0) {
1056 error_setg_errno(errp
, -exp
->size
,
1057 "Failed to determine the NBD export's length");
1060 exp
->size
-= exp
->size
% BDRV_SECTOR_SIZE
;
1063 exp
->ctx
= blk_get_aio_context(blk
);
1064 blk_add_aio_context_notifier(blk
, blk_aio_attached
, blk_aio_detach
, exp
);
1067 blk_ref(on_eject_blk
);
1068 exp
->eject_notifier_blk
= on_eject_blk
;
1069 exp
->eject_notifier
.notify
= nbd_eject_notifier
;
1070 blk_add_remove_bs_notifier(on_eject_blk
, &exp
->eject_notifier
);
1080 NBDExport
*nbd_export_find(const char *name
)
1083 QTAILQ_FOREACH(exp
, &exports
, next
) {
1084 if (strcmp(name
, exp
->name
) == 0) {
1092 void nbd_export_set_name(NBDExport
*exp
, const char *name
)
1094 if (exp
->name
== name
) {
1098 nbd_export_get(exp
);
1099 if (exp
->name
!= NULL
) {
1102 QTAILQ_REMOVE(&exports
, exp
, next
);
1103 nbd_export_put(exp
);
1106 nbd_export_get(exp
);
1107 exp
->name
= g_strdup(name
);
1108 QTAILQ_INSERT_TAIL(&exports
, exp
, next
);
1110 nbd_export_put(exp
);
1113 void nbd_export_set_description(NBDExport
*exp
, const char *description
)
1115 g_free(exp
->description
);
1116 exp
->description
= g_strdup(description
);
1119 void nbd_export_close(NBDExport
*exp
)
1121 NBDClient
*client
, *next
;
1123 nbd_export_get(exp
);
1124 QTAILQ_FOREACH_SAFE(client
, &exp
->clients
, next
, next
) {
1125 client_close(client
, true);
1127 nbd_export_set_name(exp
, NULL
);
1128 nbd_export_set_description(exp
, NULL
);
1129 nbd_export_put(exp
);
1132 void nbd_export_get(NBDExport
*exp
)
1134 assert(exp
->refcount
> 0);
1138 void nbd_export_put(NBDExport
*exp
)
1140 assert(exp
->refcount
> 0);
1141 if (exp
->refcount
== 1) {
1142 nbd_export_close(exp
);
1145 if (--exp
->refcount
== 0) {
1146 assert(exp
->name
== NULL
);
1147 assert(exp
->description
== NULL
);
1154 if (exp
->eject_notifier_blk
) {
1155 notifier_remove(&exp
->eject_notifier
);
1156 blk_unref(exp
->eject_notifier_blk
);
1158 blk_remove_aio_context_notifier(exp
->blk
, blk_aio_attached
,
1159 blk_aio_detach
, exp
);
1160 blk_unref(exp
->blk
);
1168 BlockBackend
*nbd_export_get_blockdev(NBDExport
*exp
)
1173 void nbd_export_close_all(void)
1175 NBDExport
*exp
, *next
;
1177 QTAILQ_FOREACH_SAFE(exp
, &exports
, next
, next
) {
1178 nbd_export_close(exp
);
1182 static int coroutine_fn
nbd_co_send_iov(NBDClient
*client
, struct iovec
*iov
,
1183 unsigned niov
, Error
**errp
)
1187 g_assert(qemu_in_coroutine());
1188 qemu_co_mutex_lock(&client
->send_lock
);
1189 client
->send_coroutine
= qemu_coroutine_self();
1191 ret
= qio_channel_writev_all(client
->ioc
, iov
, niov
, errp
) < 0 ? -EIO
: 0;
1193 client
->send_coroutine
= NULL
;
1194 qemu_co_mutex_unlock(&client
->send_lock
);
1199 static inline void set_be_simple_reply(NBDSimpleReply
*reply
, uint64_t error
,
1202 stl_be_p(&reply
->magic
, NBD_SIMPLE_REPLY_MAGIC
);
1203 stl_be_p(&reply
->error
, error
);
1204 stq_be_p(&reply
->handle
, handle
);
1207 static int nbd_co_send_simple_reply(NBDClient
*client
,
1214 NBDSimpleReply reply
;
1215 int nbd_err
= system_errno_to_nbd_errno(error
);
1216 struct iovec iov
[] = {
1217 {.iov_base
= &reply
, .iov_len
= sizeof(reply
)},
1218 {.iov_base
= data
, .iov_len
= len
}
1221 trace_nbd_co_send_simple_reply(handle
, nbd_err
, nbd_err_lookup(nbd_err
),
1223 set_be_simple_reply(&reply
, nbd_err
, handle
);
1225 return nbd_co_send_iov(client
, iov
, len
? 2 : 1, errp
);
1228 /* nbd_co_receive_request
1229 * Collect a client request. Return 0 if request looks valid, -EIO to drop
1230 * connection right away, and any other negative value to report an error to
1231 * the client (although the caller may still need to disconnect after reporting
1234 static int nbd_co_receive_request(NBDRequestData
*req
, NBDRequest
*request
,
1237 NBDClient
*client
= req
->client
;
1239 g_assert(qemu_in_coroutine());
1240 assert(client
->recv_coroutine
== qemu_coroutine_self());
1241 if (nbd_receive_request(client
->ioc
, request
, errp
) < 0) {
1245 trace_nbd_co_receive_request_decode_type(request
->handle
, request
->type
,
1246 nbd_cmd_lookup(request
->type
));
1248 if (request
->type
!= NBD_CMD_WRITE
) {
1249 /* No payload, we are ready to read the next request. */
1250 req
->complete
= true;
1253 if (request
->type
== NBD_CMD_DISC
) {
1254 /* Special case: we're going to disconnect without a reply,
1255 * whether or not flags, from, or len are bogus */
1259 /* Check for sanity in the parameters, part 1. Defer as many
1260 * checks as possible until after reading any NBD_CMD_WRITE
1261 * payload, so we can try and keep the connection alive. */
1262 if ((request
->from
+ request
->len
) < request
->from
) {
1264 "integer overflow detected, you're probably being attacked");
1268 if (request
->type
== NBD_CMD_READ
|| request
->type
== NBD_CMD_WRITE
) {
1269 if (request
->len
> NBD_MAX_BUFFER_SIZE
) {
1270 error_setg(errp
, "len (%" PRIu32
" ) is larger than max len (%u)",
1271 request
->len
, NBD_MAX_BUFFER_SIZE
);
1275 req
->data
= blk_try_blockalign(client
->exp
->blk
, request
->len
);
1276 if (req
->data
== NULL
) {
1277 error_setg(errp
, "No memory");
1281 if (request
->type
== NBD_CMD_WRITE
) {
1282 if (nbd_read(client
->ioc
, req
->data
, request
->len
, errp
) < 0) {
1283 error_prepend(errp
, "reading from socket failed: ");
1286 req
->complete
= true;
1288 trace_nbd_co_receive_request_payload_received(request
->handle
,
1292 /* Sanity checks, part 2. */
1293 if (request
->from
+ request
->len
> client
->exp
->size
) {
1294 error_setg(errp
, "operation past EOF; From: %" PRIu64
", Len: %" PRIu32
1295 ", Size: %" PRIu64
, request
->from
, request
->len
,
1296 (uint64_t)client
->exp
->size
);
1297 return request
->type
== NBD_CMD_WRITE
? -ENOSPC
: -EINVAL
;
1299 if (request
->flags
& ~(NBD_CMD_FLAG_FUA
| NBD_CMD_FLAG_NO_HOLE
)) {
1300 error_setg(errp
, "unsupported flags (got 0x%x)", request
->flags
);
1303 if (request
->type
!= NBD_CMD_WRITE_ZEROES
&&
1304 (request
->flags
& NBD_CMD_FLAG_NO_HOLE
)) {
1305 error_setg(errp
, "unexpected flags (got 0x%x)", request
->flags
);
1312 /* Owns a reference to the NBDClient passed as opaque. */
1313 static coroutine_fn
void nbd_trip(void *opaque
)
1315 NBDClient
*client
= opaque
;
1316 NBDExport
*exp
= client
->exp
;
1317 NBDRequestData
*req
;
1318 NBDRequest request
= { 0 }; /* GCC thinks it can be used uninitialized */
1321 int reply_data_len
= 0;
1322 Error
*local_err
= NULL
;
1325 if (client
->closing
) {
1326 nbd_client_put(client
);
1330 req
= nbd_request_get(client
);
1331 ret
= nbd_co_receive_request(req
, &request
, &local_err
);
1332 client
->recv_coroutine
= NULL
;
1333 nbd_client_receive_next_request(client
);
1342 if (client
->closing
) {
1344 * The client may be closed when we are blocked in
1345 * nbd_co_receive_request()
1350 switch (request
.type
) {
1352 /* XXX: NBD Protocol only documents use of FUA with WRITE */
1353 if (request
.flags
& NBD_CMD_FLAG_FUA
) {
1354 ret
= blk_co_flush(exp
->blk
);
1356 error_setg_errno(&local_err
, -ret
, "flush failed");
1361 ret
= blk_pread(exp
->blk
, request
.from
+ exp
->dev_offset
,
1362 req
->data
, request
.len
);
1364 error_setg_errno(&local_err
, -ret
, "reading from file failed");
1368 reply_data_len
= request
.len
;
1372 if (exp
->nbdflags
& NBD_FLAG_READ_ONLY
) {
1373 error_setg(&local_err
, "Export is read-only");
1379 if (request
.flags
& NBD_CMD_FLAG_FUA
) {
1380 flags
|= BDRV_REQ_FUA
;
1382 ret
= blk_pwrite(exp
->blk
, request
.from
+ exp
->dev_offset
,
1383 req
->data
, request
.len
, flags
);
1385 error_setg_errno(&local_err
, -ret
, "writing to file failed");
1389 case NBD_CMD_WRITE_ZEROES
:
1390 if (exp
->nbdflags
& NBD_FLAG_READ_ONLY
) {
1391 error_setg(&local_err
, "Export is read-only");
1397 if (request
.flags
& NBD_CMD_FLAG_FUA
) {
1398 flags
|= BDRV_REQ_FUA
;
1400 if (!(request
.flags
& NBD_CMD_FLAG_NO_HOLE
)) {
1401 flags
|= BDRV_REQ_MAY_UNMAP
;
1403 ret
= blk_pwrite_zeroes(exp
->blk
, request
.from
+ exp
->dev_offset
,
1404 request
.len
, flags
);
1406 error_setg_errno(&local_err
, -ret
, "writing to file failed");
1411 /* unreachable, thanks to special case in nbd_co_receive_request() */
1415 ret
= blk_co_flush(exp
->blk
);
1417 error_setg_errno(&local_err
, -ret
, "flush failed");
1422 ret
= blk_co_pdiscard(exp
->blk
, request
.from
+ exp
->dev_offset
,
1425 error_setg_errno(&local_err
, -ret
, "discard failed");
1430 error_setg(&local_err
, "invalid request type (%" PRIu32
") received",
1437 /* If we get here, local_err was not a fatal error, and should be sent
1439 error_report_err(local_err
);
1443 if (nbd_co_send_simple_reply(req
->client
, request
.handle
,
1445 req
->data
, reply_data_len
, &local_err
) < 0)
1447 error_prepend(&local_err
, "Failed to send reply: ");
1451 /* We must disconnect after NBD_CMD_WRITE if we did not
1454 if (!req
->complete
) {
1455 error_setg(&local_err
, "Request handling failed in intermediate state");
1460 nbd_request_put(req
);
1461 nbd_client_put(client
);
1466 error_reportf_err(local_err
, "Disconnect client, due to: ");
1468 nbd_request_put(req
);
1469 client_close(client
, true);
1470 nbd_client_put(client
);
1473 static void nbd_client_receive_next_request(NBDClient
*client
)
1475 if (!client
->recv_coroutine
&& client
->nb_requests
< MAX_NBD_REQUESTS
) {
1476 nbd_client_get(client
);
1477 client
->recv_coroutine
= qemu_coroutine_create(nbd_trip
, client
);
1478 aio_co_schedule(client
->exp
->ctx
, client
->recv_coroutine
);
1482 static coroutine_fn
void nbd_co_client_start(void *opaque
)
1484 NBDClient
*client
= opaque
;
1485 NBDExport
*exp
= client
->exp
;
1486 Error
*local_err
= NULL
;
1489 nbd_export_get(exp
);
1490 QTAILQ_INSERT_TAIL(&exp
->clients
, client
, next
);
1492 qemu_co_mutex_init(&client
->send_lock
);
1494 if (nbd_negotiate(client
, &local_err
)) {
1496 error_report_err(local_err
);
1498 client_close(client
, false);
1502 nbd_client_receive_next_request(client
);
1506 * Create a new client listener on the given export @exp, using the
1507 * given channel @sioc. Begin servicing it in a coroutine. When the
1508 * connection closes, call @close_fn with an indication of whether the
1509 * client completed negotiation.
1511 void nbd_client_new(NBDExport
*exp
,
1512 QIOChannelSocket
*sioc
,
1513 QCryptoTLSCreds
*tlscreds
,
1514 const char *tlsaclname
,
1515 void (*close_fn
)(NBDClient
*, bool))
1520 client
= g_new0(NBDClient
, 1);
1521 client
->refcount
= 1;
1523 client
->tlscreds
= tlscreds
;
1525 object_ref(OBJECT(client
->tlscreds
));
1527 client
->tlsaclname
= g_strdup(tlsaclname
);
1528 client
->sioc
= sioc
;
1529 object_ref(OBJECT(client
->sioc
));
1530 client
->ioc
= QIO_CHANNEL(sioc
);
1531 object_ref(OBJECT(client
->ioc
));
1532 client
->close_fn
= close_fn
;
1534 co
= qemu_coroutine_create(nbd_co_client_start
, client
);
1535 qemu_coroutine_enter(co
);