2 * QEMU Block driver for NBD
4 * Copyright (c) 2019 Virtuozzo International GmbH.
5 * Copyright (C) 2016 Red Hat, Inc.
6 * Copyright (C) 2008 Bull S.A.S.
7 * Author: Laurent Vivier <Laurent.Vivier@bull.net>
10 * Copyright (C) 2007 Anthony Liguori <anthony@codemonkey.ws>
12 * Permission is hereby granted, free of charge, to any person obtaining a copy
13 * of this software and associated documentation files (the "Software"), to deal
14 * in the Software without restriction, including without limitation the rights
15 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
16 * copies of the Software, and to permit persons to whom the Software is
17 * furnished to do so, subject to the following conditions:
19 * The above copyright notice and this permission notice shall be included in
20 * all copies or substantial portions of the Software.
22 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
23 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
24 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
25 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
26 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
27 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
31 #include "qemu/osdep.h"
35 #include "qemu/option.h"
36 #include "qemu/cutils.h"
37 #include "qemu/main-loop.h"
39 #include "qapi/qapi-visit-sockets.h"
40 #include "qapi/qmp/qstring.h"
42 #include "block/qdict.h"
43 #include "block/nbd.h"
44 #include "block/block_int.h"
46 #define EN_OPTSTR ":exportname="
47 #define MAX_NBD_REQUESTS 16
49 #define HANDLE_TO_INDEX(bs, handle) ((handle) ^ (uint64_t)(intptr_t)(bs))
50 #define INDEX_TO_HANDLE(bs, index) ((index) ^ (uint64_t)(intptr_t)(bs))
54 uint64_t offset
; /* original offset of the request */
55 bool receiving
; /* waiting for connection_co? */
58 typedef enum NBDClientState
{
59 NBD_CLIENT_CONNECTING_WAIT
,
60 NBD_CLIENT_CONNECTING_NOWAIT
,
65 typedef struct BDRVNBDState
{
66 QIOChannelSocket
*sioc
; /* The master data channel */
67 QIOChannel
*ioc
; /* The current I/O channel which may differ (eg TLS) */
72 Coroutine
*connection_co
;
73 Coroutine
*teardown_co
;
74 QemuCoSleepState
*connection_co_sleep_ns_state
;
76 bool wait_drained_end
;
83 NBDClientRequest requests
[MAX_NBD_REQUESTS
];
87 /* Connection parameters */
88 uint32_t reconnect_delay
;
90 char *export
, *tlscredsid
;
91 QCryptoTLSCreds
*tlscreds
;
96 static int nbd_client_connect(BlockDriverState
*bs
, Error
**errp
);
98 static void nbd_channel_error(BDRVNBDState
*s
, int ret
)
101 if (s
->state
== NBD_CLIENT_CONNECTED
) {
102 s
->state
= s
->reconnect_delay
? NBD_CLIENT_CONNECTING_WAIT
:
103 NBD_CLIENT_CONNECTING_NOWAIT
;
106 if (s
->state
== NBD_CLIENT_CONNECTED
) {
107 qio_channel_shutdown(s
->ioc
, QIO_CHANNEL_SHUTDOWN_BOTH
, NULL
);
109 s
->state
= NBD_CLIENT_QUIT
;
113 static void nbd_recv_coroutines_wake_all(BDRVNBDState
*s
)
117 for (i
= 0; i
< MAX_NBD_REQUESTS
; i
++) {
118 NBDClientRequest
*req
= &s
->requests
[i
];
120 if (req
->coroutine
&& req
->receiving
) {
121 aio_co_wake(req
->coroutine
);
126 static void nbd_client_detach_aio_context(BlockDriverState
*bs
)
128 BDRVNBDState
*s
= (BDRVNBDState
*)bs
->opaque
;
130 qio_channel_detach_aio_context(QIO_CHANNEL(s
->ioc
));
133 static void nbd_client_attach_aio_context_bh(void *opaque
)
135 BlockDriverState
*bs
= opaque
;
136 BDRVNBDState
*s
= (BDRVNBDState
*)bs
->opaque
;
139 * The node is still drained, so we know the coroutine has yielded in
140 * nbd_read_eof(), the only place where bs->in_flight can reach 0, or it is
141 * entered for the first time. Both places are safe for entering the
144 qemu_aio_coroutine_enter(bs
->aio_context
, s
->connection_co
);
145 bdrv_dec_in_flight(bs
);
148 static void nbd_client_attach_aio_context(BlockDriverState
*bs
,
149 AioContext
*new_context
)
151 BDRVNBDState
*s
= (BDRVNBDState
*)bs
->opaque
;
154 * s->connection_co is either yielded from nbd_receive_reply or from
155 * nbd_co_reconnect_loop()
157 if (s
->state
== NBD_CLIENT_CONNECTED
) {
158 qio_channel_attach_aio_context(QIO_CHANNEL(s
->ioc
), new_context
);
161 bdrv_inc_in_flight(bs
);
164 * Need to wait here for the BH to run because the BH must run while the
165 * node is still drained.
167 aio_wait_bh_oneshot(new_context
, nbd_client_attach_aio_context_bh
, bs
);
170 static void coroutine_fn
nbd_client_co_drain_begin(BlockDriverState
*bs
)
172 BDRVNBDState
*s
= (BDRVNBDState
*)bs
->opaque
;
175 if (s
->connection_co_sleep_ns_state
) {
176 qemu_co_sleep_wake(s
->connection_co_sleep_ns_state
);
180 static void coroutine_fn
nbd_client_co_drain_end(BlockDriverState
*bs
)
182 BDRVNBDState
*s
= (BDRVNBDState
*)bs
->opaque
;
185 if (s
->wait_drained_end
) {
186 s
->wait_drained_end
= false;
187 aio_co_wake(s
->connection_co
);
192 static void nbd_teardown_connection(BlockDriverState
*bs
)
194 BDRVNBDState
*s
= (BDRVNBDState
*)bs
->opaque
;
196 if (s
->state
== NBD_CLIENT_CONNECTED
) {
197 /* finish any pending coroutines */
199 qio_channel_shutdown(s
->ioc
, QIO_CHANNEL_SHUTDOWN_BOTH
, NULL
);
201 s
->state
= NBD_CLIENT_QUIT
;
202 if (s
->connection_co
) {
203 if (s
->connection_co_sleep_ns_state
) {
204 qemu_co_sleep_wake(s
->connection_co_sleep_ns_state
);
207 if (qemu_in_coroutine()) {
208 s
->teardown_co
= qemu_coroutine_self();
209 /* connection_co resumes us when it terminates */
210 qemu_coroutine_yield();
211 s
->teardown_co
= NULL
;
213 BDRV_POLL_WHILE(bs
, s
->connection_co
);
215 assert(!s
->connection_co
);
218 static bool nbd_client_connecting(BDRVNBDState
*s
)
220 return s
->state
== NBD_CLIENT_CONNECTING_WAIT
||
221 s
->state
== NBD_CLIENT_CONNECTING_NOWAIT
;
224 static bool nbd_client_connecting_wait(BDRVNBDState
*s
)
226 return s
->state
== NBD_CLIENT_CONNECTING_WAIT
;
229 static coroutine_fn
void nbd_reconnect_attempt(BDRVNBDState
*s
)
231 Error
*local_err
= NULL
;
233 if (!nbd_client_connecting(s
)) {
237 /* Wait for completion of all in-flight requests */
239 qemu_co_mutex_lock(&s
->send_mutex
);
241 while (s
->in_flight
> 0) {
242 qemu_co_mutex_unlock(&s
->send_mutex
);
243 nbd_recv_coroutines_wake_all(s
);
244 s
->wait_in_flight
= true;
245 qemu_coroutine_yield();
246 s
->wait_in_flight
= false;
247 qemu_co_mutex_lock(&s
->send_mutex
);
250 qemu_co_mutex_unlock(&s
->send_mutex
);
252 if (!nbd_client_connecting(s
)) {
257 * Now we are sure that nobody is accessing the channel, and no one will
258 * try until we set the state to CONNECTED.
261 /* Finalize previous connection if any */
263 nbd_client_detach_aio_context(s
->bs
);
264 object_unref(OBJECT(s
->sioc
));
266 object_unref(OBJECT(s
->ioc
));
270 s
->connect_status
= nbd_client_connect(s
->bs
, &local_err
);
271 error_free(s
->connect_err
);
272 s
->connect_err
= NULL
;
273 error_propagate(&s
->connect_err
, local_err
);
275 if (s
->connect_status
< 0) {
280 /* successfully connected */
281 s
->state
= NBD_CLIENT_CONNECTED
;
282 qemu_co_queue_restart_all(&s
->free_sema
);
285 static coroutine_fn
void nbd_co_reconnect_loop(BDRVNBDState
*s
)
287 uint64_t start_time_ns
= qemu_clock_get_ns(QEMU_CLOCK_REALTIME
);
288 uint64_t delay_ns
= s
->reconnect_delay
* NANOSECONDS_PER_SECOND
;
289 uint64_t timeout
= 1 * NANOSECONDS_PER_SECOND
;
290 uint64_t max_timeout
= 16 * NANOSECONDS_PER_SECOND
;
292 nbd_reconnect_attempt(s
);
294 while (nbd_client_connecting(s
)) {
295 if (s
->state
== NBD_CLIENT_CONNECTING_WAIT
&&
296 qemu_clock_get_ns(QEMU_CLOCK_REALTIME
) - start_time_ns
> delay_ns
)
298 s
->state
= NBD_CLIENT_CONNECTING_NOWAIT
;
299 qemu_co_queue_restart_all(&s
->free_sema
);
302 qemu_co_sleep_ns_wakeable(QEMU_CLOCK_REALTIME
, timeout
,
303 &s
->connection_co_sleep_ns_state
);
305 bdrv_dec_in_flight(s
->bs
);
306 s
->wait_drained_end
= true;
309 * We may be entered once from nbd_client_attach_aio_context_bh
310 * and then from nbd_client_co_drain_end. So here is a loop.
312 qemu_coroutine_yield();
314 bdrv_inc_in_flight(s
->bs
);
316 if (timeout
< max_timeout
) {
320 nbd_reconnect_attempt(s
);
324 static coroutine_fn
void nbd_connection_entry(void *opaque
)
326 BDRVNBDState
*s
= opaque
;
329 Error
*local_err
= NULL
;
331 while (s
->state
!= NBD_CLIENT_QUIT
) {
333 * The NBD client can only really be considered idle when it has
334 * yielded from qio_channel_readv_all_eof(), waiting for data. This is
335 * the point where the additional scheduled coroutine entry happens
336 * after nbd_client_attach_aio_context().
338 * Therefore we keep an additional in_flight reference all the time and
339 * only drop it temporarily here.
342 if (nbd_client_connecting(s
)) {
343 nbd_co_reconnect_loop(s
);
346 if (s
->state
!= NBD_CLIENT_CONNECTED
) {
350 assert(s
->reply
.handle
== 0);
351 ret
= nbd_receive_reply(s
->bs
, s
->ioc
, &s
->reply
, &local_err
);
354 trace_nbd_read_reply_entry_fail(ret
, error_get_pretty(local_err
));
355 error_free(local_err
);
359 nbd_channel_error(s
, ret
? ret
: -EIO
);
364 * There's no need for a mutex on the receive side, because the
365 * handler acts as a synchronization point and ensures that only
366 * one coroutine is called until the reply finishes.
368 i
= HANDLE_TO_INDEX(s
, s
->reply
.handle
);
369 if (i
>= MAX_NBD_REQUESTS
||
370 !s
->requests
[i
].coroutine
||
371 !s
->requests
[i
].receiving
||
372 (nbd_reply_is_structured(&s
->reply
) && !s
->info
.structured_reply
))
374 nbd_channel_error(s
, -EINVAL
);
379 * We're woken up again by the request itself. Note that there
380 * is no race between yielding and reentering connection_co. This
383 * - if the request runs on the same AioContext, it is only
384 * entered after we yield
386 * - if the request runs on a different AioContext, reentering
387 * connection_co happens through a bottom half, which can only
388 * run after we yield.
390 aio_co_wake(s
->requests
[i
].coroutine
);
391 qemu_coroutine_yield();
394 qemu_co_queue_restart_all(&s
->free_sema
);
395 nbd_recv_coroutines_wake_all(s
);
396 bdrv_dec_in_flight(s
->bs
);
398 s
->connection_co
= NULL
;
400 nbd_client_detach_aio_context(s
->bs
);
401 object_unref(OBJECT(s
->sioc
));
403 object_unref(OBJECT(s
->ioc
));
407 if (s
->teardown_co
) {
408 aio_co_wake(s
->teardown_co
);
413 static int nbd_co_send_request(BlockDriverState
*bs
,
417 BDRVNBDState
*s
= (BDRVNBDState
*)bs
->opaque
;
420 qemu_co_mutex_lock(&s
->send_mutex
);
421 while (s
->in_flight
== MAX_NBD_REQUESTS
|| nbd_client_connecting_wait(s
)) {
422 qemu_co_queue_wait(&s
->free_sema
, &s
->send_mutex
);
425 if (s
->state
!= NBD_CLIENT_CONNECTED
) {
432 for (i
= 0; i
< MAX_NBD_REQUESTS
; i
++) {
433 if (s
->requests
[i
].coroutine
== NULL
) {
438 g_assert(qemu_in_coroutine());
439 assert(i
< MAX_NBD_REQUESTS
);
441 s
->requests
[i
].coroutine
= qemu_coroutine_self();
442 s
->requests
[i
].offset
= request
->from
;
443 s
->requests
[i
].receiving
= false;
445 request
->handle
= INDEX_TO_HANDLE(s
, i
);
450 qio_channel_set_cork(s
->ioc
, true);
451 rc
= nbd_send_request(s
->ioc
, request
);
452 if (rc
>= 0 && s
->state
== NBD_CLIENT_CONNECTED
) {
453 if (qio_channel_writev_all(s
->ioc
, qiov
->iov
, qiov
->niov
,
457 } else if (rc
>= 0) {
460 qio_channel_set_cork(s
->ioc
, false);
462 rc
= nbd_send_request(s
->ioc
, request
);
467 nbd_channel_error(s
, rc
);
469 s
->requests
[i
].coroutine
= NULL
;
472 if (s
->in_flight
== 0 && s
->wait_in_flight
) {
473 aio_co_wake(s
->connection_co
);
475 qemu_co_queue_next(&s
->free_sema
);
478 qemu_co_mutex_unlock(&s
->send_mutex
);
482 static inline uint16_t payload_advance16(uint8_t **payload
)
485 return lduw_be_p(*payload
- 2);
488 static inline uint32_t payload_advance32(uint8_t **payload
)
491 return ldl_be_p(*payload
- 4);
494 static inline uint64_t payload_advance64(uint8_t **payload
)
497 return ldq_be_p(*payload
- 8);
500 static int nbd_parse_offset_hole_payload(BDRVNBDState
*s
,
501 NBDStructuredReplyChunk
*chunk
,
502 uint8_t *payload
, uint64_t orig_offset
,
503 QEMUIOVector
*qiov
, Error
**errp
)
508 if (chunk
->length
!= sizeof(offset
) + sizeof(hole_size
)) {
509 error_setg(errp
, "Protocol error: invalid payload for "
510 "NBD_REPLY_TYPE_OFFSET_HOLE");
514 offset
= payload_advance64(&payload
);
515 hole_size
= payload_advance32(&payload
);
517 if (!hole_size
|| offset
< orig_offset
|| hole_size
> qiov
->size
||
518 offset
> orig_offset
+ qiov
->size
- hole_size
) {
519 error_setg(errp
, "Protocol error: server sent chunk exceeding requested"
523 if (s
->info
.min_block
&&
524 !QEMU_IS_ALIGNED(hole_size
, s
->info
.min_block
)) {
525 trace_nbd_structured_read_compliance("hole");
528 qemu_iovec_memset(qiov
, offset
- orig_offset
, 0, hole_size
);
534 * nbd_parse_blockstatus_payload
535 * Based on our request, we expect only one extent in reply, for the
536 * base:allocation context.
538 static int nbd_parse_blockstatus_payload(BDRVNBDState
*s
,
539 NBDStructuredReplyChunk
*chunk
,
540 uint8_t *payload
, uint64_t orig_length
,
541 NBDExtent
*extent
, Error
**errp
)
545 /* The server succeeded, so it must have sent [at least] one extent */
546 if (chunk
->length
< sizeof(context_id
) + sizeof(*extent
)) {
547 error_setg(errp
, "Protocol error: invalid payload for "
548 "NBD_REPLY_TYPE_BLOCK_STATUS");
552 context_id
= payload_advance32(&payload
);
553 if (s
->info
.context_id
!= context_id
) {
554 error_setg(errp
, "Protocol error: unexpected context id %d for "
555 "NBD_REPLY_TYPE_BLOCK_STATUS, when negotiated context "
556 "id is %d", context_id
,
561 extent
->length
= payload_advance32(&payload
);
562 extent
->flags
= payload_advance32(&payload
);
564 if (extent
->length
== 0) {
565 error_setg(errp
, "Protocol error: server sent status chunk with "
571 * A server sending unaligned block status is in violation of the
572 * protocol, but as qemu-nbd 3.1 is such a server (at least for
573 * POSIX files that are not a multiple of 512 bytes, since qemu
574 * rounds files up to 512-byte multiples but lseek(SEEK_HOLE)
575 * still sees an implicit hole beyond the real EOF), it's nicer to
576 * work around the misbehaving server. If the request included
577 * more than the final unaligned block, truncate it back to an
578 * aligned result; if the request was only the final block, round
579 * up to the full block and change the status to fully-allocated
580 * (always a safe status, even if it loses information).
582 if (s
->info
.min_block
&& !QEMU_IS_ALIGNED(extent
->length
,
583 s
->info
.min_block
)) {
584 trace_nbd_parse_blockstatus_compliance("extent length is unaligned");
585 if (extent
->length
> s
->info
.min_block
) {
586 extent
->length
= QEMU_ALIGN_DOWN(extent
->length
,
589 extent
->length
= s
->info
.min_block
;
595 * We used NBD_CMD_FLAG_REQ_ONE, so the server should not have
596 * sent us any more than one extent, nor should it have included
597 * status beyond our request in that extent. However, it's easy
598 * enough to ignore the server's noncompliance without killing the
599 * connection; just ignore trailing extents, and clamp things to
600 * the length of our request.
602 if (chunk
->length
> sizeof(context_id
) + sizeof(*extent
)) {
603 trace_nbd_parse_blockstatus_compliance("more than one extent");
605 if (extent
->length
> orig_length
) {
606 extent
->length
= orig_length
;
607 trace_nbd_parse_blockstatus_compliance("extent length too large");
614 * nbd_parse_error_payload
615 * on success @errp contains message describing nbd error reply
617 static int nbd_parse_error_payload(NBDStructuredReplyChunk
*chunk
,
618 uint8_t *payload
, int *request_ret
,
622 uint16_t message_size
;
624 assert(chunk
->type
& (1 << 15));
626 if (chunk
->length
< sizeof(error
) + sizeof(message_size
)) {
628 "Protocol error: invalid payload for structured error");
632 error
= nbd_errno_to_system_errno(payload_advance32(&payload
));
634 error_setg(errp
, "Protocol error: server sent structured error chunk "
639 *request_ret
= -error
;
640 message_size
= payload_advance16(&payload
);
642 if (message_size
> chunk
->length
- sizeof(error
) - sizeof(message_size
)) {
643 error_setg(errp
, "Protocol error: server sent structured error chunk "
644 "with incorrect message size");
648 /* TODO: Add a trace point to mention the server complaint */
650 /* TODO handle ERROR_OFFSET */
655 static int nbd_co_receive_offset_data_payload(BDRVNBDState
*s
,
656 uint64_t orig_offset
,
657 QEMUIOVector
*qiov
, Error
**errp
)
659 QEMUIOVector sub_qiov
;
663 NBDStructuredReplyChunk
*chunk
= &s
->reply
.structured
;
665 assert(nbd_reply_is_structured(&s
->reply
));
667 /* The NBD spec requires at least one byte of payload */
668 if (chunk
->length
<= sizeof(offset
)) {
669 error_setg(errp
, "Protocol error: invalid payload for "
670 "NBD_REPLY_TYPE_OFFSET_DATA");
674 if (nbd_read64(s
->ioc
, &offset
, "OFFSET_DATA offset", errp
) < 0) {
678 data_size
= chunk
->length
- sizeof(offset
);
680 if (offset
< orig_offset
|| data_size
> qiov
->size
||
681 offset
> orig_offset
+ qiov
->size
- data_size
) {
682 error_setg(errp
, "Protocol error: server sent chunk exceeding requested"
686 if (s
->info
.min_block
&& !QEMU_IS_ALIGNED(data_size
, s
->info
.min_block
)) {
687 trace_nbd_structured_read_compliance("data");
690 qemu_iovec_init(&sub_qiov
, qiov
->niov
);
691 qemu_iovec_concat(&sub_qiov
, qiov
, offset
- orig_offset
, data_size
);
692 ret
= qio_channel_readv_all(s
->ioc
, sub_qiov
.iov
, sub_qiov
.niov
, errp
);
693 qemu_iovec_destroy(&sub_qiov
);
695 return ret
< 0 ? -EIO
: 0;
698 #define NBD_MAX_MALLOC_PAYLOAD 1000
699 static coroutine_fn
int nbd_co_receive_structured_payload(
700 BDRVNBDState
*s
, void **payload
, Error
**errp
)
705 assert(nbd_reply_is_structured(&s
->reply
));
707 len
= s
->reply
.structured
.length
;
713 if (payload
== NULL
) {
714 error_setg(errp
, "Unexpected structured payload");
718 if (len
> NBD_MAX_MALLOC_PAYLOAD
) {
719 error_setg(errp
, "Payload too large");
723 *payload
= g_new(char, len
);
724 ret
= nbd_read(s
->ioc
, *payload
, len
, "structured payload", errp
);
735 * nbd_co_do_receive_one_chunk
737 * set request_ret to received reply error
738 * if qiov is not NULL: read payload to @qiov
739 * for structured reply chunk:
740 * if error chunk: read payload, set @request_ret, do not set @payload
741 * else if offset_data chunk: read payload data to @qiov, do not set @payload
742 * else: read payload to @payload
744 * If function fails, @errp contains corresponding error message, and the
745 * connection with the server is suspect. If it returns 0, then the
746 * transaction succeeded (although @request_ret may be a negative errno
747 * corresponding to the server's error reply), and errp is unchanged.
749 static coroutine_fn
int nbd_co_do_receive_one_chunk(
750 BDRVNBDState
*s
, uint64_t handle
, bool only_structured
,
751 int *request_ret
, QEMUIOVector
*qiov
, void **payload
, Error
**errp
)
754 int i
= HANDLE_TO_INDEX(s
, handle
);
755 void *local_payload
= NULL
;
756 NBDStructuredReplyChunk
*chunk
;
763 /* Wait until we're woken up by nbd_connection_entry. */
764 s
->requests
[i
].receiving
= true;
765 qemu_coroutine_yield();
766 s
->requests
[i
].receiving
= false;
767 if (s
->state
!= NBD_CLIENT_CONNECTED
) {
768 error_setg(errp
, "Connection closed");
773 assert(s
->reply
.handle
== handle
);
775 if (nbd_reply_is_simple(&s
->reply
)) {
776 if (only_structured
) {
777 error_setg(errp
, "Protocol error: simple reply when structured "
778 "reply chunk was expected");
782 *request_ret
= -nbd_errno_to_system_errno(s
->reply
.simple
.error
);
783 if (*request_ret
< 0 || !qiov
) {
787 return qio_channel_readv_all(s
->ioc
, qiov
->iov
, qiov
->niov
,
788 errp
) < 0 ? -EIO
: 0;
791 /* handle structured reply chunk */
792 assert(s
->info
.structured_reply
);
793 chunk
= &s
->reply
.structured
;
795 if (chunk
->type
== NBD_REPLY_TYPE_NONE
) {
796 if (!(chunk
->flags
& NBD_REPLY_FLAG_DONE
)) {
797 error_setg(errp
, "Protocol error: NBD_REPLY_TYPE_NONE chunk without"
798 " NBD_REPLY_FLAG_DONE flag set");
802 error_setg(errp
, "Protocol error: NBD_REPLY_TYPE_NONE chunk with"
809 if (chunk
->type
== NBD_REPLY_TYPE_OFFSET_DATA
) {
811 error_setg(errp
, "Unexpected NBD_REPLY_TYPE_OFFSET_DATA chunk");
815 return nbd_co_receive_offset_data_payload(s
, s
->requests
[i
].offset
,
819 if (nbd_reply_type_is_error(chunk
->type
)) {
820 payload
= &local_payload
;
823 ret
= nbd_co_receive_structured_payload(s
, payload
, errp
);
828 if (nbd_reply_type_is_error(chunk
->type
)) {
829 ret
= nbd_parse_error_payload(chunk
, local_payload
, request_ret
, errp
);
830 g_free(local_payload
);
838 * nbd_co_receive_one_chunk
839 * Read reply, wake up connection_co and set s->quit if needed.
840 * Return value is a fatal error code or normal nbd reply error code
842 static coroutine_fn
int nbd_co_receive_one_chunk(
843 BDRVNBDState
*s
, uint64_t handle
, bool only_structured
,
844 int *request_ret
, QEMUIOVector
*qiov
, NBDReply
*reply
, void **payload
,
847 int ret
= nbd_co_do_receive_one_chunk(s
, handle
, only_structured
,
848 request_ret
, qiov
, payload
, errp
);
851 memset(reply
, 0, sizeof(*reply
));
852 nbd_channel_error(s
, ret
);
854 /* For assert at loop start in nbd_connection_entry */
859 if (s
->connection_co
&& !s
->wait_in_flight
) {
861 * We must check s->wait_in_flight, because we may entered by
862 * nbd_recv_coroutines_wake_all(), in this case we should not
863 * wake connection_co here, it will woken by last request.
865 aio_co_wake(s
->connection_co
);
871 typedef struct NBDReplyChunkIter
{
875 bool done
, only_structured
;
878 static void nbd_iter_channel_error(NBDReplyChunkIter
*iter
,
879 int ret
, Error
**local_err
)
881 assert(local_err
&& *local_err
);
886 error_propagate(&iter
->err
, *local_err
);
888 error_free(*local_err
);
894 static void nbd_iter_request_error(NBDReplyChunkIter
*iter
, int ret
)
898 if (!iter
->request_ret
) {
899 iter
->request_ret
= ret
;
904 * NBD_FOREACH_REPLY_CHUNK
905 * The pointer stored in @payload requires g_free() to free it.
907 #define NBD_FOREACH_REPLY_CHUNK(s, iter, handle, structured, \
908 qiov, reply, payload) \
909 for (iter = (NBDReplyChunkIter) { .only_structured = structured }; \
910 nbd_reply_chunk_iter_receive(s, &iter, handle, qiov, reply, payload);)
913 * nbd_reply_chunk_iter_receive
914 * The pointer stored in @payload requires g_free() to free it.
916 static bool nbd_reply_chunk_iter_receive(BDRVNBDState
*s
,
917 NBDReplyChunkIter
*iter
,
919 QEMUIOVector
*qiov
, NBDReply
*reply
,
922 int ret
, request_ret
;
923 NBDReply local_reply
;
924 NBDStructuredReplyChunk
*chunk
;
925 Error
*local_err
= NULL
;
926 if (s
->state
!= NBD_CLIENT_CONNECTED
) {
927 error_setg(&local_err
, "Connection closed");
928 nbd_iter_channel_error(iter
, -EIO
, &local_err
);
933 /* Previous iteration was last. */
938 reply
= &local_reply
;
941 ret
= nbd_co_receive_one_chunk(s
, handle
, iter
->only_structured
,
942 &request_ret
, qiov
, reply
, payload
,
945 nbd_iter_channel_error(iter
, ret
, &local_err
);
946 } else if (request_ret
< 0) {
947 nbd_iter_request_error(iter
, request_ret
);
950 /* Do not execute the body of NBD_FOREACH_REPLY_CHUNK for simple reply. */
951 if (nbd_reply_is_simple(reply
) || s
->state
!= NBD_CLIENT_CONNECTED
) {
955 chunk
= &reply
->structured
;
956 iter
->only_structured
= true;
958 if (chunk
->type
== NBD_REPLY_TYPE_NONE
) {
959 /* NBD_REPLY_FLAG_DONE is already checked in nbd_co_receive_one_chunk */
960 assert(chunk
->flags
& NBD_REPLY_FLAG_DONE
);
964 if (chunk
->flags
& NBD_REPLY_FLAG_DONE
) {
965 /* This iteration is last. */
969 /* Execute the loop body */
973 s
->requests
[HANDLE_TO_INDEX(s
, handle
)].coroutine
= NULL
;
975 qemu_co_mutex_lock(&s
->send_mutex
);
977 if (s
->in_flight
== 0 && s
->wait_in_flight
) {
978 aio_co_wake(s
->connection_co
);
980 qemu_co_queue_next(&s
->free_sema
);
982 qemu_co_mutex_unlock(&s
->send_mutex
);
987 static int nbd_co_receive_return_code(BDRVNBDState
*s
, uint64_t handle
,
988 int *request_ret
, Error
**errp
)
990 NBDReplyChunkIter iter
;
992 NBD_FOREACH_REPLY_CHUNK(s
, iter
, handle
, false, NULL
, NULL
, NULL
) {
993 /* nbd_reply_chunk_iter_receive does all the work */
996 error_propagate(errp
, iter
.err
);
997 *request_ret
= iter
.request_ret
;
1001 static int nbd_co_receive_cmdread_reply(BDRVNBDState
*s
, uint64_t handle
,
1002 uint64_t offset
, QEMUIOVector
*qiov
,
1003 int *request_ret
, Error
**errp
)
1005 NBDReplyChunkIter iter
;
1007 void *payload
= NULL
;
1008 Error
*local_err
= NULL
;
1010 NBD_FOREACH_REPLY_CHUNK(s
, iter
, handle
, s
->info
.structured_reply
,
1011 qiov
, &reply
, &payload
)
1014 NBDStructuredReplyChunk
*chunk
= &reply
.structured
;
1016 assert(nbd_reply_is_structured(&reply
));
1018 switch (chunk
->type
) {
1019 case NBD_REPLY_TYPE_OFFSET_DATA
:
1021 * special cased in nbd_co_receive_one_chunk, data is already
1025 case NBD_REPLY_TYPE_OFFSET_HOLE
:
1026 ret
= nbd_parse_offset_hole_payload(s
, &reply
.structured
, payload
,
1027 offset
, qiov
, &local_err
);
1029 nbd_channel_error(s
, ret
);
1030 nbd_iter_channel_error(&iter
, ret
, &local_err
);
1034 if (!nbd_reply_type_is_error(chunk
->type
)) {
1035 /* not allowed reply type */
1036 nbd_channel_error(s
, -EINVAL
);
1037 error_setg(&local_err
,
1038 "Unexpected reply type: %d (%s) for CMD_READ",
1039 chunk
->type
, nbd_reply_type_lookup(chunk
->type
));
1040 nbd_iter_channel_error(&iter
, -EINVAL
, &local_err
);
1048 error_propagate(errp
, iter
.err
);
1049 *request_ret
= iter
.request_ret
;
1053 static int nbd_co_receive_blockstatus_reply(BDRVNBDState
*s
,
1054 uint64_t handle
, uint64_t length
,
1056 int *request_ret
, Error
**errp
)
1058 NBDReplyChunkIter iter
;
1060 void *payload
= NULL
;
1061 Error
*local_err
= NULL
;
1062 bool received
= false;
1064 assert(!extent
->length
);
1065 NBD_FOREACH_REPLY_CHUNK(s
, iter
, handle
, false, NULL
, &reply
, &payload
) {
1067 NBDStructuredReplyChunk
*chunk
= &reply
.structured
;
1069 assert(nbd_reply_is_structured(&reply
));
1071 switch (chunk
->type
) {
1072 case NBD_REPLY_TYPE_BLOCK_STATUS
:
1074 nbd_channel_error(s
, -EINVAL
);
1075 error_setg(&local_err
, "Several BLOCK_STATUS chunks in reply");
1076 nbd_iter_channel_error(&iter
, -EINVAL
, &local_err
);
1080 ret
= nbd_parse_blockstatus_payload(s
, &reply
.structured
,
1081 payload
, length
, extent
,
1084 nbd_channel_error(s
, ret
);
1085 nbd_iter_channel_error(&iter
, ret
, &local_err
);
1089 if (!nbd_reply_type_is_error(chunk
->type
)) {
1090 nbd_channel_error(s
, -EINVAL
);
1091 error_setg(&local_err
,
1092 "Unexpected reply type: %d (%s) "
1093 "for CMD_BLOCK_STATUS",
1094 chunk
->type
, nbd_reply_type_lookup(chunk
->type
));
1095 nbd_iter_channel_error(&iter
, -EINVAL
, &local_err
);
1103 if (!extent
->length
&& !iter
.request_ret
) {
1104 error_setg(&local_err
, "Server did not reply with any status extents");
1105 nbd_iter_channel_error(&iter
, -EIO
, &local_err
);
1108 error_propagate(errp
, iter
.err
);
1109 *request_ret
= iter
.request_ret
;
1113 static int nbd_co_request(BlockDriverState
*bs
, NBDRequest
*request
,
1114 QEMUIOVector
*write_qiov
)
1116 int ret
, request_ret
;
1117 Error
*local_err
= NULL
;
1118 BDRVNBDState
*s
= (BDRVNBDState
*)bs
->opaque
;
1120 assert(request
->type
!= NBD_CMD_READ
);
1122 assert(request
->type
== NBD_CMD_WRITE
);
1123 assert(request
->len
== iov_size(write_qiov
->iov
, write_qiov
->niov
));
1125 assert(request
->type
!= NBD_CMD_WRITE
);
1129 ret
= nbd_co_send_request(bs
, request
, write_qiov
);
1134 ret
= nbd_co_receive_return_code(s
, request
->handle
,
1135 &request_ret
, &local_err
);
1137 trace_nbd_co_request_fail(request
->from
, request
->len
,
1138 request
->handle
, request
->flags
,
1140 nbd_cmd_lookup(request
->type
),
1141 ret
, error_get_pretty(local_err
));
1142 error_free(local_err
);
1145 } while (ret
< 0 && nbd_client_connecting_wait(s
));
1147 return ret
? ret
: request_ret
;
1150 static int nbd_client_co_preadv(BlockDriverState
*bs
, uint64_t offset
,
1151 uint64_t bytes
, QEMUIOVector
*qiov
, int flags
)
1153 int ret
, request_ret
;
1154 Error
*local_err
= NULL
;
1155 BDRVNBDState
*s
= (BDRVNBDState
*)bs
->opaque
;
1156 NBDRequest request
= {
1157 .type
= NBD_CMD_READ
,
1162 assert(bytes
<= NBD_MAX_BUFFER_SIZE
);
1169 * Work around the fact that the block layer doesn't do
1170 * byte-accurate sizing yet - if the read exceeds the server's
1171 * advertised size because the block layer rounded size up, then
1172 * truncate the request to the server and tail-pad with zero.
1174 if (offset
>= s
->info
.size
) {
1175 assert(bytes
< BDRV_SECTOR_SIZE
);
1176 qemu_iovec_memset(qiov
, 0, 0, bytes
);
1179 if (offset
+ bytes
> s
->info
.size
) {
1180 uint64_t slop
= offset
+ bytes
- s
->info
.size
;
1182 assert(slop
< BDRV_SECTOR_SIZE
);
1183 qemu_iovec_memset(qiov
, bytes
- slop
, 0, slop
);
1184 request
.len
-= slop
;
1188 ret
= nbd_co_send_request(bs
, &request
, NULL
);
1193 ret
= nbd_co_receive_cmdread_reply(s
, request
.handle
, offset
, qiov
,
1194 &request_ret
, &local_err
);
1196 trace_nbd_co_request_fail(request
.from
, request
.len
, request
.handle
,
1197 request
.flags
, request
.type
,
1198 nbd_cmd_lookup(request
.type
),
1199 ret
, error_get_pretty(local_err
));
1200 error_free(local_err
);
1203 } while (ret
< 0 && nbd_client_connecting_wait(s
));
1205 return ret
? ret
: request_ret
;
1208 static int nbd_client_co_pwritev(BlockDriverState
*bs
, uint64_t offset
,
1209 uint64_t bytes
, QEMUIOVector
*qiov
, int flags
)
1211 BDRVNBDState
*s
= (BDRVNBDState
*)bs
->opaque
;
1212 NBDRequest request
= {
1213 .type
= NBD_CMD_WRITE
,
1218 assert(!(s
->info
.flags
& NBD_FLAG_READ_ONLY
));
1219 if (flags
& BDRV_REQ_FUA
) {
1220 assert(s
->info
.flags
& NBD_FLAG_SEND_FUA
);
1221 request
.flags
|= NBD_CMD_FLAG_FUA
;
1224 assert(bytes
<= NBD_MAX_BUFFER_SIZE
);
1229 return nbd_co_request(bs
, &request
, qiov
);
1232 static int nbd_client_co_pwrite_zeroes(BlockDriverState
*bs
, int64_t offset
,
1233 int bytes
, BdrvRequestFlags flags
)
1235 BDRVNBDState
*s
= (BDRVNBDState
*)bs
->opaque
;
1236 NBDRequest request
= {
1237 .type
= NBD_CMD_WRITE_ZEROES
,
1242 assert(!(s
->info
.flags
& NBD_FLAG_READ_ONLY
));
1243 if (!(s
->info
.flags
& NBD_FLAG_SEND_WRITE_ZEROES
)) {
1247 if (flags
& BDRV_REQ_FUA
) {
1248 assert(s
->info
.flags
& NBD_FLAG_SEND_FUA
);
1249 request
.flags
|= NBD_CMD_FLAG_FUA
;
1251 if (!(flags
& BDRV_REQ_MAY_UNMAP
)) {
1252 request
.flags
|= NBD_CMD_FLAG_NO_HOLE
;
1254 if (flags
& BDRV_REQ_NO_FALLBACK
) {
1255 assert(s
->info
.flags
& NBD_FLAG_SEND_FAST_ZERO
);
1256 request
.flags
|= NBD_CMD_FLAG_FAST_ZERO
;
1262 return nbd_co_request(bs
, &request
, NULL
);
1265 static int nbd_client_co_flush(BlockDriverState
*bs
)
1267 BDRVNBDState
*s
= (BDRVNBDState
*)bs
->opaque
;
1268 NBDRequest request
= { .type
= NBD_CMD_FLUSH
};
1270 if (!(s
->info
.flags
& NBD_FLAG_SEND_FLUSH
)) {
1277 return nbd_co_request(bs
, &request
, NULL
);
1280 static int nbd_client_co_pdiscard(BlockDriverState
*bs
, int64_t offset
,
1283 BDRVNBDState
*s
= (BDRVNBDState
*)bs
->opaque
;
1284 NBDRequest request
= {
1285 .type
= NBD_CMD_TRIM
,
1290 assert(!(s
->info
.flags
& NBD_FLAG_READ_ONLY
));
1291 if (!(s
->info
.flags
& NBD_FLAG_SEND_TRIM
) || !bytes
) {
1295 return nbd_co_request(bs
, &request
, NULL
);
1298 static int coroutine_fn
nbd_client_co_block_status(
1299 BlockDriverState
*bs
, bool want_zero
, int64_t offset
, int64_t bytes
,
1300 int64_t *pnum
, int64_t *map
, BlockDriverState
**file
)
1302 int ret
, request_ret
;
1303 NBDExtent extent
= { 0 };
1304 BDRVNBDState
*s
= (BDRVNBDState
*)bs
->opaque
;
1305 Error
*local_err
= NULL
;
1307 NBDRequest request
= {
1308 .type
= NBD_CMD_BLOCK_STATUS
,
1310 .len
= MIN(MIN_NON_ZERO(QEMU_ALIGN_DOWN(INT_MAX
,
1311 bs
->bl
.request_alignment
),
1313 MIN(bytes
, s
->info
.size
- offset
)),
1314 .flags
= NBD_CMD_FLAG_REQ_ONE
,
1317 if (!s
->info
.base_allocation
) {
1321 return BDRV_BLOCK_DATA
| BDRV_BLOCK_OFFSET_VALID
;
1325 * Work around the fact that the block layer doesn't do
1326 * byte-accurate sizing yet - if the status request exceeds the
1327 * server's advertised size because the block layer rounded size
1328 * up, we truncated the request to the server (above), or are
1329 * called on just the hole.
1331 if (offset
>= s
->info
.size
) {
1333 assert(bytes
< BDRV_SECTOR_SIZE
);
1334 /* Intentionally don't report offset_valid for the hole */
1335 return BDRV_BLOCK_ZERO
;
1338 if (s
->info
.min_block
) {
1339 assert(QEMU_IS_ALIGNED(request
.len
, s
->info
.min_block
));
1342 ret
= nbd_co_send_request(bs
, &request
, NULL
);
1347 ret
= nbd_co_receive_blockstatus_reply(s
, request
.handle
, bytes
,
1348 &extent
, &request_ret
,
1351 trace_nbd_co_request_fail(request
.from
, request
.len
, request
.handle
,
1352 request
.flags
, request
.type
,
1353 nbd_cmd_lookup(request
.type
),
1354 ret
, error_get_pretty(local_err
));
1355 error_free(local_err
);
1358 } while (ret
< 0 && nbd_client_connecting_wait(s
));
1360 if (ret
< 0 || request_ret
< 0) {
1361 return ret
? ret
: request_ret
;
1364 assert(extent
.length
);
1365 *pnum
= extent
.length
;
1368 return (extent
.flags
& NBD_STATE_HOLE
? 0 : BDRV_BLOCK_DATA
) |
1369 (extent
.flags
& NBD_STATE_ZERO
? BDRV_BLOCK_ZERO
: 0) |
1370 BDRV_BLOCK_OFFSET_VALID
;
1373 static int nbd_client_reopen_prepare(BDRVReopenState
*state
,
1374 BlockReopenQueue
*queue
, Error
**errp
)
1376 BDRVNBDState
*s
= (BDRVNBDState
*)state
->bs
->opaque
;
1378 if ((state
->flags
& BDRV_O_RDWR
) && (s
->info
.flags
& NBD_FLAG_READ_ONLY
)) {
1379 error_setg(errp
, "Can't reopen read-only NBD mount as read/write");
1385 static void nbd_client_close(BlockDriverState
*bs
)
1387 BDRVNBDState
*s
= (BDRVNBDState
*)bs
->opaque
;
1388 NBDRequest request
= { .type
= NBD_CMD_DISC
};
1391 nbd_send_request(s
->ioc
, &request
);
1394 nbd_teardown_connection(bs
);
1397 static QIOChannelSocket
*nbd_establish_connection(SocketAddress
*saddr
,
1400 QIOChannelSocket
*sioc
;
1401 Error
*local_err
= NULL
;
1403 sioc
= qio_channel_socket_new();
1404 qio_channel_set_name(QIO_CHANNEL(sioc
), "nbd-client");
1406 qio_channel_socket_connect_sync(sioc
, saddr
, &local_err
);
1408 object_unref(OBJECT(sioc
));
1409 error_propagate(errp
, local_err
);
1413 qio_channel_set_delay(QIO_CHANNEL(sioc
), false);
1418 static int nbd_client_connect(BlockDriverState
*bs
, Error
**errp
)
1420 BDRVNBDState
*s
= (BDRVNBDState
*)bs
->opaque
;
1421 AioContext
*aio_context
= bdrv_get_aio_context(bs
);
1425 * establish TCP connection, return error if it fails
1426 * TODO: Configurable retry-until-timeout behaviour.
1428 QIOChannelSocket
*sioc
= nbd_establish_connection(s
->saddr
, errp
);
1431 return -ECONNREFUSED
;
1435 trace_nbd_client_connect(s
->export
);
1436 qio_channel_set_blocking(QIO_CHANNEL(sioc
), false, NULL
);
1437 qio_channel_attach_aio_context(QIO_CHANNEL(sioc
), aio_context
);
1439 s
->info
.request_sizes
= true;
1440 s
->info
.structured_reply
= true;
1441 s
->info
.base_allocation
= true;
1442 s
->info
.x_dirty_bitmap
= g_strdup(s
->x_dirty_bitmap
);
1443 s
->info
.name
= g_strdup(s
->export
?: "");
1444 ret
= nbd_receive_negotiate(aio_context
, QIO_CHANNEL(sioc
), s
->tlscreds
,
1445 s
->hostname
, &s
->ioc
, &s
->info
, errp
);
1446 g_free(s
->info
.x_dirty_bitmap
);
1447 g_free(s
->info
.name
);
1449 object_unref(OBJECT(sioc
));
1452 if (s
->x_dirty_bitmap
&& !s
->info
.base_allocation
) {
1453 error_setg(errp
, "requested x-dirty-bitmap %s not found",
1458 if (s
->info
.flags
& NBD_FLAG_READ_ONLY
) {
1459 ret
= bdrv_apply_auto_read_only(bs
, "NBD export is read-only", errp
);
1464 if (s
->info
.flags
& NBD_FLAG_SEND_FUA
) {
1465 bs
->supported_write_flags
= BDRV_REQ_FUA
;
1466 bs
->supported_zero_flags
|= BDRV_REQ_FUA
;
1468 if (s
->info
.flags
& NBD_FLAG_SEND_WRITE_ZEROES
) {
1469 bs
->supported_zero_flags
|= BDRV_REQ_MAY_UNMAP
;
1470 if (s
->info
.flags
& NBD_FLAG_SEND_FAST_ZERO
) {
1471 bs
->supported_zero_flags
|= BDRV_REQ_NO_FALLBACK
;
1478 s
->ioc
= QIO_CHANNEL(sioc
);
1479 object_ref(OBJECT(s
->ioc
));
1482 trace_nbd_client_connect_success(s
->export
);
1488 * We have connected, but must fail for other reasons.
1489 * Send NBD_CMD_DISC as a courtesy to the server.
1492 NBDRequest request
= { .type
= NBD_CMD_DISC
};
1494 nbd_send_request(s
->ioc
?: QIO_CHANNEL(sioc
), &request
);
1496 object_unref(OBJECT(sioc
));
1503 * Parse nbd_open options
1506 static int nbd_parse_uri(const char *filename
, QDict
*options
)
1510 QueryParams
*qp
= NULL
;
1514 uri
= uri_parse(filename
);
1520 if (!g_strcmp0(uri
->scheme
, "nbd")) {
1522 } else if (!g_strcmp0(uri
->scheme
, "nbd+tcp")) {
1524 } else if (!g_strcmp0(uri
->scheme
, "nbd+unix")) {
1531 p
= uri
->path
? uri
->path
: "/";
1532 p
+= strspn(p
, "/");
1534 qdict_put_str(options
, "export", p
);
1537 qp
= query_params_parse(uri
->query
);
1538 if (qp
->n
> 1 || (is_unix
&& !qp
->n
) || (!is_unix
&& qp
->n
)) {
1544 /* nbd+unix:///export?socket=path */
1545 if (uri
->server
|| uri
->port
|| strcmp(qp
->p
[0].name
, "socket")) {
1549 qdict_put_str(options
, "server.type", "unix");
1550 qdict_put_str(options
, "server.path", qp
->p
[0].value
);
1555 /* nbd[+tcp]://host[:port]/export */
1561 /* strip braces from literal IPv6 address */
1562 if (uri
->server
[0] == '[') {
1563 host
= qstring_from_substr(uri
->server
, 1,
1564 strlen(uri
->server
) - 1);
1566 host
= qstring_from_str(uri
->server
);
1569 qdict_put_str(options
, "server.type", "inet");
1570 qdict_put(options
, "server.host", host
);
1572 port_str
= g_strdup_printf("%d", uri
->port
?: NBD_DEFAULT_PORT
);
1573 qdict_put_str(options
, "server.port", port_str
);
1579 query_params_free(qp
);
1585 static bool nbd_has_filename_options_conflict(QDict
*options
, Error
**errp
)
1587 const QDictEntry
*e
;
1589 for (e
= qdict_first(options
); e
; e
= qdict_next(options
, e
)) {
1590 if (!strcmp(e
->key
, "host") ||
1591 !strcmp(e
->key
, "port") ||
1592 !strcmp(e
->key
, "path") ||
1593 !strcmp(e
->key
, "export") ||
1594 strstart(e
->key
, "server.", NULL
))
1596 error_setg(errp
, "Option '%s' cannot be used with a file name",
1605 static void nbd_parse_filename(const char *filename
, QDict
*options
,
1608 g_autofree
char *file
= NULL
;
1610 const char *host_spec
;
1611 const char *unixpath
;
1613 if (nbd_has_filename_options_conflict(options
, errp
)) {
1617 if (strstr(filename
, "://")) {
1618 int ret
= nbd_parse_uri(filename
, options
);
1620 error_setg(errp
, "No valid URL specified");
1625 file
= g_strdup(filename
);
1627 export_name
= strstr(file
, EN_OPTSTR
);
1629 if (export_name
[strlen(EN_OPTSTR
)] == 0) {
1632 export_name
[0] = 0; /* truncate 'file' */
1633 export_name
+= strlen(EN_OPTSTR
);
1635 qdict_put_str(options
, "export", export_name
);
1638 /* extract the host_spec - fail if it's not nbd:... */
1639 if (!strstart(file
, "nbd:", &host_spec
)) {
1640 error_setg(errp
, "File name string for NBD must start with 'nbd:'");
1648 /* are we a UNIX or TCP socket? */
1649 if (strstart(host_spec
, "unix:", &unixpath
)) {
1650 qdict_put_str(options
, "server.type", "unix");
1651 qdict_put_str(options
, "server.path", unixpath
);
1653 InetSocketAddress
*addr
= g_new(InetSocketAddress
, 1);
1655 if (inet_parse(addr
, host_spec
, errp
)) {
1659 qdict_put_str(options
, "server.type", "inet");
1660 qdict_put_str(options
, "server.host", addr
->host
);
1661 qdict_put_str(options
, "server.port", addr
->port
);
1663 qapi_free_InetSocketAddress(addr
);
1667 static bool nbd_process_legacy_socket_options(QDict
*output_options
,
1668 QemuOpts
*legacy_opts
,
1671 const char *path
= qemu_opt_get(legacy_opts
, "path");
1672 const char *host
= qemu_opt_get(legacy_opts
, "host");
1673 const char *port
= qemu_opt_get(legacy_opts
, "port");
1674 const QDictEntry
*e
;
1676 if (!path
&& !host
&& !port
) {
1680 for (e
= qdict_first(output_options
); e
; e
= qdict_next(output_options
, e
))
1682 if (strstart(e
->key
, "server.", NULL
)) {
1683 error_setg(errp
, "Cannot use 'server' and path/host/port at the "
1690 error_setg(errp
, "path and host may not be used at the same time");
1694 error_setg(errp
, "port may not be used without host");
1698 qdict_put_str(output_options
, "server.type", "unix");
1699 qdict_put_str(output_options
, "server.path", path
);
1701 qdict_put_str(output_options
, "server.type", "inet");
1702 qdict_put_str(output_options
, "server.host", host
);
1703 qdict_put_str(output_options
, "server.port",
1704 port
?: stringify(NBD_DEFAULT_PORT
));
1710 static SocketAddress
*nbd_config(BDRVNBDState
*s
, QDict
*options
,
1713 SocketAddress
*saddr
= NULL
;
1716 Error
*local_err
= NULL
;
1718 qdict_extract_subqdict(options
, &addr
, "server.");
1719 if (!qdict_size(addr
)) {
1720 error_setg(errp
, "NBD server address missing");
1724 iv
= qobject_input_visitor_new_flat_confused(addr
, errp
);
1729 visit_type_SocketAddress(iv
, NULL
, &saddr
, &local_err
);
1731 error_propagate(errp
, local_err
);
1736 qobject_unref(addr
);
1741 static QCryptoTLSCreds
*nbd_get_tls_creds(const char *id
, Error
**errp
)
1744 QCryptoTLSCreds
*creds
;
1746 obj
= object_resolve_path_component(
1747 object_get_objects_root(), id
);
1749 error_setg(errp
, "No TLS credentials with id '%s'",
1753 creds
= (QCryptoTLSCreds
*)
1754 object_dynamic_cast(obj
, TYPE_QCRYPTO_TLS_CREDS
);
1756 error_setg(errp
, "Object with id '%s' is not TLS credentials",
1761 if (creds
->endpoint
!= QCRYPTO_TLS_CREDS_ENDPOINT_CLIENT
) {
1763 "Expecting TLS credentials with a client endpoint");
1771 static QemuOptsList nbd_runtime_opts
= {
1773 .head
= QTAILQ_HEAD_INITIALIZER(nbd_runtime_opts
.head
),
1777 .type
= QEMU_OPT_STRING
,
1778 .help
= "TCP host to connect to",
1782 .type
= QEMU_OPT_STRING
,
1783 .help
= "TCP port to connect to",
1787 .type
= QEMU_OPT_STRING
,
1788 .help
= "Unix socket path to connect to",
1792 .type
= QEMU_OPT_STRING
,
1793 .help
= "Name of the NBD export to open",
1796 .name
= "tls-creds",
1797 .type
= QEMU_OPT_STRING
,
1798 .help
= "ID of the TLS credentials to use",
1801 .name
= "x-dirty-bitmap",
1802 .type
= QEMU_OPT_STRING
,
1803 .help
= "experimental: expose named dirty bitmap in place of "
1807 .name
= "reconnect-delay",
1808 .type
= QEMU_OPT_NUMBER
,
1809 .help
= "On an unexpected disconnect, the nbd client tries to "
1810 "connect again until succeeding or encountering a serious "
1811 "error. During the first @reconnect-delay seconds, all "
1812 "requests are paused and will be rerun on a successful "
1813 "reconnect. After that time, any delayed requests and all "
1814 "future requests before a successful reconnect will "
1815 "immediately fail. Default 0",
1817 { /* end of list */ }
1821 static int nbd_process_options(BlockDriverState
*bs
, QDict
*options
,
1824 BDRVNBDState
*s
= bs
->opaque
;
1826 Error
*local_err
= NULL
;
1829 opts
= qemu_opts_create(&nbd_runtime_opts
, NULL
, 0, &error_abort
);
1830 qemu_opts_absorb_qdict(opts
, options
, &local_err
);
1832 error_propagate(errp
, local_err
);
1836 /* Translate @host, @port, and @path to a SocketAddress */
1837 if (!nbd_process_legacy_socket_options(options
, opts
, errp
)) {
1841 /* Pop the config into our state object. Exit if invalid. */
1842 s
->saddr
= nbd_config(s
, options
, errp
);
1847 s
->export
= g_strdup(qemu_opt_get(opts
, "export"));
1848 if (s
->export
&& strlen(s
->export
) > NBD_MAX_STRING_SIZE
) {
1849 error_setg(errp
, "export name too long to send to server");
1853 s
->tlscredsid
= g_strdup(qemu_opt_get(opts
, "tls-creds"));
1854 if (s
->tlscredsid
) {
1855 s
->tlscreds
= nbd_get_tls_creds(s
->tlscredsid
, errp
);
1860 /* TODO SOCKET_ADDRESS_KIND_FD where fd has AF_INET or AF_INET6 */
1861 if (s
->saddr
->type
!= SOCKET_ADDRESS_TYPE_INET
) {
1862 error_setg(errp
, "TLS only supported over IP sockets");
1865 s
->hostname
= s
->saddr
->u
.inet
.host
;
1868 s
->x_dirty_bitmap
= g_strdup(qemu_opt_get(opts
, "x-dirty-bitmap"));
1869 if (s
->x_dirty_bitmap
&& strlen(s
->x_dirty_bitmap
) > NBD_MAX_STRING_SIZE
) {
1870 error_setg(errp
, "x-dirty-bitmap query too long to send to server");
1874 s
->reconnect_delay
= qemu_opt_get_number(opts
, "reconnect-delay", 0);
1880 object_unref(OBJECT(s
->tlscreds
));
1881 qapi_free_SocketAddress(s
->saddr
);
1883 g_free(s
->tlscredsid
);
1884 g_free(s
->x_dirty_bitmap
);
1886 qemu_opts_del(opts
);
1890 static int nbd_open(BlockDriverState
*bs
, QDict
*options
, int flags
,
1894 BDRVNBDState
*s
= (BDRVNBDState
*)bs
->opaque
;
1896 ret
= nbd_process_options(bs
, options
, errp
);
1902 qemu_co_mutex_init(&s
->send_mutex
);
1903 qemu_co_queue_init(&s
->free_sema
);
1905 ret
= nbd_client_connect(bs
, errp
);
1909 /* successfully connected */
1910 s
->state
= NBD_CLIENT_CONNECTED
;
1912 s
->connection_co
= qemu_coroutine_create(nbd_connection_entry
, s
);
1913 bdrv_inc_in_flight(bs
);
1914 aio_co_schedule(bdrv_get_aio_context(bs
), s
->connection_co
);
1919 static int nbd_co_flush(BlockDriverState
*bs
)
1921 return nbd_client_co_flush(bs
);
1924 static void nbd_refresh_limits(BlockDriverState
*bs
, Error
**errp
)
1926 BDRVNBDState
*s
= (BDRVNBDState
*)bs
->opaque
;
1927 uint32_t min
= s
->info
.min_block
;
1928 uint32_t max
= MIN_NON_ZERO(NBD_MAX_BUFFER_SIZE
, s
->info
.max_block
);
1931 * If the server did not advertise an alignment:
1932 * - a size that is not sector-aligned implies that an alignment
1933 * of 1 can be used to access those tail bytes
1934 * - advertisement of block status requires an alignment of 1, so
1935 * that we don't violate block layer constraints that block
1936 * status is always aligned (as we can't control whether the
1937 * server will report sub-sector extents, such as a hole at EOF
1938 * on an unaligned POSIX file)
1939 * - otherwise, assume the server is so old that we are safer avoiding
1940 * sub-sector requests
1943 min
= (!QEMU_IS_ALIGNED(s
->info
.size
, BDRV_SECTOR_SIZE
) ||
1944 s
->info
.base_allocation
) ? 1 : BDRV_SECTOR_SIZE
;
1947 bs
->bl
.request_alignment
= min
;
1948 bs
->bl
.max_pdiscard
= max
;
1949 bs
->bl
.max_pwrite_zeroes
= max
;
1950 bs
->bl
.max_transfer
= max
;
1952 if (s
->info
.opt_block
&&
1953 s
->info
.opt_block
> bs
->bl
.opt_transfer
) {
1954 bs
->bl
.opt_transfer
= s
->info
.opt_block
;
1958 static void nbd_close(BlockDriverState
*bs
)
1960 BDRVNBDState
*s
= bs
->opaque
;
1962 nbd_client_close(bs
);
1964 object_unref(OBJECT(s
->tlscreds
));
1965 qapi_free_SocketAddress(s
->saddr
);
1967 g_free(s
->tlscredsid
);
1968 g_free(s
->x_dirty_bitmap
);
1971 static int64_t nbd_getlength(BlockDriverState
*bs
)
1973 BDRVNBDState
*s
= bs
->opaque
;
1975 return s
->info
.size
;
1978 static void nbd_refresh_filename(BlockDriverState
*bs
)
1980 BDRVNBDState
*s
= bs
->opaque
;
1981 const char *host
= NULL
, *port
= NULL
, *path
= NULL
;
1983 if (s
->saddr
->type
== SOCKET_ADDRESS_TYPE_INET
) {
1984 const InetSocketAddress
*inet
= &s
->saddr
->u
.inet
;
1985 if (!inet
->has_ipv4
&& !inet
->has_ipv6
&& !inet
->has_to
) {
1989 } else if (s
->saddr
->type
== SOCKET_ADDRESS_TYPE_UNIX
) {
1990 path
= s
->saddr
->u
.q_unix
.path
;
1991 } /* else can't represent as pseudo-filename */
1993 if (path
&& s
->export
) {
1994 snprintf(bs
->exact_filename
, sizeof(bs
->exact_filename
),
1995 "nbd+unix:///%s?socket=%s", s
->export
, path
);
1996 } else if (path
&& !s
->export
) {
1997 snprintf(bs
->exact_filename
, sizeof(bs
->exact_filename
),
1998 "nbd+unix://?socket=%s", path
);
1999 } else if (host
&& s
->export
) {
2000 snprintf(bs
->exact_filename
, sizeof(bs
->exact_filename
),
2001 "nbd://%s:%s/%s", host
, port
, s
->export
);
2002 } else if (host
&& !s
->export
) {
2003 snprintf(bs
->exact_filename
, sizeof(bs
->exact_filename
),
2004 "nbd://%s:%s", host
, port
);
2008 static char *nbd_dirname(BlockDriverState
*bs
, Error
**errp
)
2010 /* The generic bdrv_dirname() implementation is able to work out some
2011 * directory name for NBD nodes, but that would be wrong. So far there is no
2012 * specification for how "export paths" would work, so NBD does not have
2013 * directory names. */
2014 error_setg(errp
, "Cannot generate a base directory for NBD nodes");
2018 static const char *const nbd_strong_runtime_opts
[] = {
2029 static BlockDriver bdrv_nbd
= {
2030 .format_name
= "nbd",
2031 .protocol_name
= "nbd",
2032 .instance_size
= sizeof(BDRVNBDState
),
2033 .bdrv_parse_filename
= nbd_parse_filename
,
2034 .bdrv_file_open
= nbd_open
,
2035 .bdrv_reopen_prepare
= nbd_client_reopen_prepare
,
2036 .bdrv_co_preadv
= nbd_client_co_preadv
,
2037 .bdrv_co_pwritev
= nbd_client_co_pwritev
,
2038 .bdrv_co_pwrite_zeroes
= nbd_client_co_pwrite_zeroes
,
2039 .bdrv_close
= nbd_close
,
2040 .bdrv_co_flush_to_os
= nbd_co_flush
,
2041 .bdrv_co_pdiscard
= nbd_client_co_pdiscard
,
2042 .bdrv_refresh_limits
= nbd_refresh_limits
,
2043 .bdrv_getlength
= nbd_getlength
,
2044 .bdrv_detach_aio_context
= nbd_client_detach_aio_context
,
2045 .bdrv_attach_aio_context
= nbd_client_attach_aio_context
,
2046 .bdrv_co_drain_begin
= nbd_client_co_drain_begin
,
2047 .bdrv_co_drain_end
= nbd_client_co_drain_end
,
2048 .bdrv_refresh_filename
= nbd_refresh_filename
,
2049 .bdrv_co_block_status
= nbd_client_co_block_status
,
2050 .bdrv_dirname
= nbd_dirname
,
2051 .strong_runtime_opts
= nbd_strong_runtime_opts
,
2054 static BlockDriver bdrv_nbd_tcp
= {
2055 .format_name
= "nbd",
2056 .protocol_name
= "nbd+tcp",
2057 .instance_size
= sizeof(BDRVNBDState
),
2058 .bdrv_parse_filename
= nbd_parse_filename
,
2059 .bdrv_file_open
= nbd_open
,
2060 .bdrv_reopen_prepare
= nbd_client_reopen_prepare
,
2061 .bdrv_co_preadv
= nbd_client_co_preadv
,
2062 .bdrv_co_pwritev
= nbd_client_co_pwritev
,
2063 .bdrv_co_pwrite_zeroes
= nbd_client_co_pwrite_zeroes
,
2064 .bdrv_close
= nbd_close
,
2065 .bdrv_co_flush_to_os
= nbd_co_flush
,
2066 .bdrv_co_pdiscard
= nbd_client_co_pdiscard
,
2067 .bdrv_refresh_limits
= nbd_refresh_limits
,
2068 .bdrv_getlength
= nbd_getlength
,
2069 .bdrv_detach_aio_context
= nbd_client_detach_aio_context
,
2070 .bdrv_attach_aio_context
= nbd_client_attach_aio_context
,
2071 .bdrv_co_drain_begin
= nbd_client_co_drain_begin
,
2072 .bdrv_co_drain_end
= nbd_client_co_drain_end
,
2073 .bdrv_refresh_filename
= nbd_refresh_filename
,
2074 .bdrv_co_block_status
= nbd_client_co_block_status
,
2075 .bdrv_dirname
= nbd_dirname
,
2076 .strong_runtime_opts
= nbd_strong_runtime_opts
,
2079 static BlockDriver bdrv_nbd_unix
= {
2080 .format_name
= "nbd",
2081 .protocol_name
= "nbd+unix",
2082 .instance_size
= sizeof(BDRVNBDState
),
2083 .bdrv_parse_filename
= nbd_parse_filename
,
2084 .bdrv_file_open
= nbd_open
,
2085 .bdrv_reopen_prepare
= nbd_client_reopen_prepare
,
2086 .bdrv_co_preadv
= nbd_client_co_preadv
,
2087 .bdrv_co_pwritev
= nbd_client_co_pwritev
,
2088 .bdrv_co_pwrite_zeroes
= nbd_client_co_pwrite_zeroes
,
2089 .bdrv_close
= nbd_close
,
2090 .bdrv_co_flush_to_os
= nbd_co_flush
,
2091 .bdrv_co_pdiscard
= nbd_client_co_pdiscard
,
2092 .bdrv_refresh_limits
= nbd_refresh_limits
,
2093 .bdrv_getlength
= nbd_getlength
,
2094 .bdrv_detach_aio_context
= nbd_client_detach_aio_context
,
2095 .bdrv_attach_aio_context
= nbd_client_attach_aio_context
,
2096 .bdrv_co_drain_begin
= nbd_client_co_drain_begin
,
2097 .bdrv_co_drain_end
= nbd_client_co_drain_end
,
2098 .bdrv_refresh_filename
= nbd_refresh_filename
,
2099 .bdrv_co_block_status
= nbd_client_co_block_status
,
2100 .bdrv_dirname
= nbd_dirname
,
2101 .strong_runtime_opts
= nbd_strong_runtime_opts
,
2104 static void bdrv_nbd_init(void)
2106 bdrv_register(&bdrv_nbd
);
2107 bdrv_register(&bdrv_nbd_tcp
);
2108 bdrv_register(&bdrv_nbd_unix
);
2111 block_init(bdrv_nbd_init
);