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"
38 #include "qemu/atomic.h"
40 #include "qapi/qapi-visit-sockets.h"
41 #include "qapi/qmp/qstring.h"
42 #include "qapi/clone-visitor.h"
44 #include "block/qdict.h"
45 #include "block/nbd.h"
46 #include "block/block_int.h"
48 #include "qemu/yank.h"
50 #define EN_OPTSTR ":exportname="
51 #define MAX_NBD_REQUESTS 16
53 #define HANDLE_TO_INDEX(bs, handle) ((handle) ^ (uint64_t)(intptr_t)(bs))
54 #define INDEX_TO_HANDLE(bs, index) ((index) ^ (uint64_t)(intptr_t)(bs))
58 uint64_t offset
; /* original offset of the request */
59 bool receiving
; /* waiting for connection_co? */
62 typedef enum NBDClientState
{
63 NBD_CLIENT_CONNECTING_WAIT
,
64 NBD_CLIENT_CONNECTING_NOWAIT
,
69 typedef struct BDRVNBDState
{
70 QIOChannelSocket
*sioc
; /* The master data channel */
71 QIOChannel
*ioc
; /* The current I/O channel which may differ (eg TLS) */
76 Coroutine
*connection_co
;
77 Coroutine
*teardown_co
;
78 QemuCoSleep reconnect_sleep
;
80 bool wait_drained_end
;
85 QEMUTimer
*reconnect_delay_timer
;
87 NBDClientRequest requests
[MAX_NBD_REQUESTS
];
91 /* Connection parameters */
92 uint32_t reconnect_delay
;
94 char *export
, *tlscredsid
;
95 QCryptoTLSCreds
*tlscreds
;
100 NBDClientConnection
*conn
;
103 static int nbd_establish_connection(BlockDriverState
*bs
, SocketAddress
*saddr
,
105 static int nbd_client_handshake(BlockDriverState
*bs
, Error
**errp
);
106 static void nbd_yank(void *opaque
);
108 static void nbd_clear_bdrvstate(BlockDriverState
*bs
)
110 BDRVNBDState
*s
= (BDRVNBDState
*)bs
->opaque
;
112 nbd_client_connection_release(s
->conn
);
115 yank_unregister_instance(BLOCKDEV_YANK_INSTANCE(bs
->node_name
));
117 object_unref(OBJECT(s
->tlscreds
));
118 qapi_free_SocketAddress(s
->saddr
);
122 g_free(s
->tlscredsid
);
123 s
->tlscredsid
= NULL
;
124 g_free(s
->x_dirty_bitmap
);
125 s
->x_dirty_bitmap
= NULL
;
128 static void nbd_channel_error(BDRVNBDState
*s
, int ret
)
131 if (qatomic_load_acquire(&s
->state
) == NBD_CLIENT_CONNECTED
) {
132 s
->state
= s
->reconnect_delay
? NBD_CLIENT_CONNECTING_WAIT
:
133 NBD_CLIENT_CONNECTING_NOWAIT
;
136 if (qatomic_load_acquire(&s
->state
) == NBD_CLIENT_CONNECTED
) {
137 qio_channel_shutdown(s
->ioc
, QIO_CHANNEL_SHUTDOWN_BOTH
, NULL
);
139 s
->state
= NBD_CLIENT_QUIT
;
143 static void nbd_recv_coroutines_wake_all(BDRVNBDState
*s
)
147 for (i
= 0; i
< MAX_NBD_REQUESTS
; i
++) {
148 NBDClientRequest
*req
= &s
->requests
[i
];
150 if (req
->coroutine
&& req
->receiving
) {
151 aio_co_wake(req
->coroutine
);
156 static void reconnect_delay_timer_del(BDRVNBDState
*s
)
158 if (s
->reconnect_delay_timer
) {
159 timer_free(s
->reconnect_delay_timer
);
160 s
->reconnect_delay_timer
= NULL
;
164 static void reconnect_delay_timer_cb(void *opaque
)
166 BDRVNBDState
*s
= opaque
;
168 if (qatomic_load_acquire(&s
->state
) == NBD_CLIENT_CONNECTING_WAIT
) {
169 s
->state
= NBD_CLIENT_CONNECTING_NOWAIT
;
170 while (qemu_co_enter_next(&s
->free_sema
, NULL
)) {
171 /* Resume all queued requests */
175 reconnect_delay_timer_del(s
);
178 static void reconnect_delay_timer_init(BDRVNBDState
*s
, uint64_t expire_time_ns
)
180 if (qatomic_load_acquire(&s
->state
) != NBD_CLIENT_CONNECTING_WAIT
) {
184 assert(!s
->reconnect_delay_timer
);
185 s
->reconnect_delay_timer
= aio_timer_new(bdrv_get_aio_context(s
->bs
),
188 reconnect_delay_timer_cb
, s
);
189 timer_mod(s
->reconnect_delay_timer
, expire_time_ns
);
192 static void nbd_client_detach_aio_context(BlockDriverState
*bs
)
194 BDRVNBDState
*s
= (BDRVNBDState
*)bs
->opaque
;
196 /* Timer is deleted in nbd_client_co_drain_begin() */
197 assert(!s
->reconnect_delay_timer
);
199 * If reconnect is in progress we may have no ->ioc. It will be
200 * re-instantiated in the proper aio context once the connection is
204 qio_channel_detach_aio_context(QIO_CHANNEL(s
->ioc
));
208 static void nbd_client_attach_aio_context_bh(void *opaque
)
210 BlockDriverState
*bs
= opaque
;
211 BDRVNBDState
*s
= (BDRVNBDState
*)bs
->opaque
;
213 if (s
->connection_co
) {
215 * The node is still drained, so we know the coroutine has yielded in
216 * nbd_read_eof(), the only place where bs->in_flight can reach 0, or
217 * it is entered for the first time. Both places are safe for entering
220 qemu_aio_coroutine_enter(bs
->aio_context
, s
->connection_co
);
222 bdrv_dec_in_flight(bs
);
225 static void nbd_client_attach_aio_context(BlockDriverState
*bs
,
226 AioContext
*new_context
)
228 BDRVNBDState
*s
= (BDRVNBDState
*)bs
->opaque
;
231 * s->connection_co is either yielded from nbd_receive_reply or from
232 * nbd_co_reconnect_loop()
234 if (qatomic_load_acquire(&s
->state
) == NBD_CLIENT_CONNECTED
) {
235 qio_channel_attach_aio_context(QIO_CHANNEL(s
->ioc
), new_context
);
238 bdrv_inc_in_flight(bs
);
241 * Need to wait here for the BH to run because the BH must run while the
242 * node is still drained.
244 aio_wait_bh_oneshot(new_context
, nbd_client_attach_aio_context_bh
, bs
);
247 static void coroutine_fn
nbd_client_co_drain_begin(BlockDriverState
*bs
)
249 BDRVNBDState
*s
= (BDRVNBDState
*)bs
->opaque
;
252 qemu_co_sleep_wake(&s
->reconnect_sleep
);
254 nbd_co_establish_connection_cancel(s
->conn
);
256 reconnect_delay_timer_del(s
);
258 if (qatomic_load_acquire(&s
->state
) == NBD_CLIENT_CONNECTING_WAIT
) {
259 s
->state
= NBD_CLIENT_CONNECTING_NOWAIT
;
260 qemu_co_queue_restart_all(&s
->free_sema
);
264 static void coroutine_fn
nbd_client_co_drain_end(BlockDriverState
*bs
)
266 BDRVNBDState
*s
= (BDRVNBDState
*)bs
->opaque
;
269 if (s
->wait_drained_end
) {
270 s
->wait_drained_end
= false;
271 aio_co_wake(s
->connection_co
);
276 static void nbd_teardown_connection(BlockDriverState
*bs
)
278 BDRVNBDState
*s
= (BDRVNBDState
*)bs
->opaque
;
281 /* finish any pending coroutines */
282 qio_channel_shutdown(s
->ioc
, QIO_CHANNEL_SHUTDOWN_BOTH
, NULL
);
283 } else if (s
->sioc
) {
284 /* abort negotiation */
285 qio_channel_shutdown(QIO_CHANNEL(s
->sioc
), QIO_CHANNEL_SHUTDOWN_BOTH
,
289 s
->state
= NBD_CLIENT_QUIT
;
290 if (s
->connection_co
) {
291 qemu_co_sleep_wake(&s
->reconnect_sleep
);
292 nbd_co_establish_connection_cancel(s
->conn
);
294 if (qemu_in_coroutine()) {
295 s
->teardown_co
= qemu_coroutine_self();
296 /* connection_co resumes us when it terminates */
297 qemu_coroutine_yield();
298 s
->teardown_co
= NULL
;
300 BDRV_POLL_WHILE(bs
, s
->connection_co
);
302 assert(!s
->connection_co
);
305 static bool nbd_client_connecting(BDRVNBDState
*s
)
307 NBDClientState state
= qatomic_load_acquire(&s
->state
);
308 return state
== NBD_CLIENT_CONNECTING_WAIT
||
309 state
== NBD_CLIENT_CONNECTING_NOWAIT
;
312 static bool nbd_client_connecting_wait(BDRVNBDState
*s
)
314 return qatomic_load_acquire(&s
->state
) == NBD_CLIENT_CONNECTING_WAIT
;
317 static coroutine_fn
void nbd_reconnect_attempt(BDRVNBDState
*s
)
321 if (!nbd_client_connecting(s
)) {
325 /* Wait for completion of all in-flight requests */
327 qemu_co_mutex_lock(&s
->send_mutex
);
329 while (s
->in_flight
> 0) {
330 qemu_co_mutex_unlock(&s
->send_mutex
);
331 nbd_recv_coroutines_wake_all(s
);
332 s
->wait_in_flight
= true;
333 qemu_coroutine_yield();
334 s
->wait_in_flight
= false;
335 qemu_co_mutex_lock(&s
->send_mutex
);
338 qemu_co_mutex_unlock(&s
->send_mutex
);
340 if (!nbd_client_connecting(s
)) {
345 * Now we are sure that nobody is accessing the channel, and no one will
346 * try until we set the state to CONNECTED.
349 /* Finalize previous connection if any */
351 qio_channel_detach_aio_context(QIO_CHANNEL(s
->ioc
));
352 yank_unregister_function(BLOCKDEV_YANK_INSTANCE(s
->bs
->node_name
),
354 object_unref(OBJECT(s
->sioc
));
356 object_unref(OBJECT(s
->ioc
));
360 s
->sioc
= nbd_co_establish_connection(s
->conn
, NULL
);
366 yank_register_function(BLOCKDEV_YANK_INSTANCE(s
->bs
->node_name
), nbd_yank
,
369 bdrv_dec_in_flight(s
->bs
);
371 ret
= nbd_client_handshake(s
->bs
, NULL
);
374 s
->wait_drained_end
= true;
377 * We may be entered once from nbd_client_attach_aio_context_bh
378 * and then from nbd_client_co_drain_end. So here is a loop.
380 qemu_coroutine_yield();
383 bdrv_inc_in_flight(s
->bs
);
387 /* successfully connected */
388 s
->state
= NBD_CLIENT_CONNECTED
;
389 qemu_co_queue_restart_all(&s
->free_sema
);
393 static coroutine_fn
void nbd_co_reconnect_loop(BDRVNBDState
*s
)
395 uint64_t timeout
= 1 * NANOSECONDS_PER_SECOND
;
396 uint64_t max_timeout
= 16 * NANOSECONDS_PER_SECOND
;
398 if (qatomic_load_acquire(&s
->state
) == NBD_CLIENT_CONNECTING_WAIT
) {
399 reconnect_delay_timer_init(s
, qemu_clock_get_ns(QEMU_CLOCK_REALTIME
) +
400 s
->reconnect_delay
* NANOSECONDS_PER_SECOND
);
403 nbd_reconnect_attempt(s
);
405 while (nbd_client_connecting(s
)) {
407 bdrv_dec_in_flight(s
->bs
);
408 s
->wait_drained_end
= true;
411 * We may be entered once from nbd_client_attach_aio_context_bh
412 * and then from nbd_client_co_drain_end. So here is a loop.
414 qemu_coroutine_yield();
416 bdrv_inc_in_flight(s
->bs
);
418 qemu_co_sleep_ns_wakeable(&s
->reconnect_sleep
,
419 QEMU_CLOCK_REALTIME
, timeout
);
423 if (timeout
< max_timeout
) {
428 nbd_reconnect_attempt(s
);
431 reconnect_delay_timer_del(s
);
434 static coroutine_fn
void nbd_connection_entry(void *opaque
)
436 BDRVNBDState
*s
= opaque
;
439 Error
*local_err
= NULL
;
441 while (qatomic_load_acquire(&s
->state
) != NBD_CLIENT_QUIT
) {
443 * The NBD client can only really be considered idle when it has
444 * yielded from qio_channel_readv_all_eof(), waiting for data. This is
445 * the point where the additional scheduled coroutine entry happens
446 * after nbd_client_attach_aio_context().
448 * Therefore we keep an additional in_flight reference all the time and
449 * only drop it temporarily here.
452 if (nbd_client_connecting(s
)) {
453 nbd_co_reconnect_loop(s
);
456 if (qatomic_load_acquire(&s
->state
) != NBD_CLIENT_CONNECTED
) {
460 assert(s
->reply
.handle
== 0);
461 ret
= nbd_receive_reply(s
->bs
, s
->ioc
, &s
->reply
, &local_err
);
464 trace_nbd_read_reply_entry_fail(ret
, error_get_pretty(local_err
));
465 error_free(local_err
);
469 nbd_channel_error(s
, ret
? ret
: -EIO
);
474 * There's no need for a mutex on the receive side, because the
475 * handler acts as a synchronization point and ensures that only
476 * one coroutine is called until the reply finishes.
478 i
= HANDLE_TO_INDEX(s
, s
->reply
.handle
);
479 if (i
>= MAX_NBD_REQUESTS
||
480 !s
->requests
[i
].coroutine
||
481 !s
->requests
[i
].receiving
||
482 (nbd_reply_is_structured(&s
->reply
) && !s
->info
.structured_reply
))
484 nbd_channel_error(s
, -EINVAL
);
489 * We're woken up again by the request itself. Note that there
490 * is no race between yielding and reentering connection_co. This
493 * - if the request runs on the same AioContext, it is only
494 * entered after we yield
496 * - if the request runs on a different AioContext, reentering
497 * connection_co happens through a bottom half, which can only
498 * run after we yield.
500 aio_co_wake(s
->requests
[i
].coroutine
);
501 qemu_coroutine_yield();
504 qemu_co_queue_restart_all(&s
->free_sema
);
505 nbd_recv_coroutines_wake_all(s
);
506 bdrv_dec_in_flight(s
->bs
);
508 s
->connection_co
= NULL
;
510 qio_channel_detach_aio_context(QIO_CHANNEL(s
->ioc
));
511 yank_unregister_function(BLOCKDEV_YANK_INSTANCE(s
->bs
->node_name
),
513 object_unref(OBJECT(s
->sioc
));
515 object_unref(OBJECT(s
->ioc
));
519 if (s
->teardown_co
) {
520 aio_co_wake(s
->teardown_co
);
525 static int nbd_co_send_request(BlockDriverState
*bs
,
529 BDRVNBDState
*s
= (BDRVNBDState
*)bs
->opaque
;
532 qemu_co_mutex_lock(&s
->send_mutex
);
533 while (s
->in_flight
== MAX_NBD_REQUESTS
|| nbd_client_connecting_wait(s
)) {
534 qemu_co_queue_wait(&s
->free_sema
, &s
->send_mutex
);
537 if (qatomic_load_acquire(&s
->state
) != NBD_CLIENT_CONNECTED
) {
544 for (i
= 0; i
< MAX_NBD_REQUESTS
; i
++) {
545 if (s
->requests
[i
].coroutine
== NULL
) {
550 g_assert(qemu_in_coroutine());
551 assert(i
< MAX_NBD_REQUESTS
);
553 s
->requests
[i
].coroutine
= qemu_coroutine_self();
554 s
->requests
[i
].offset
= request
->from
;
555 s
->requests
[i
].receiving
= false;
557 request
->handle
= INDEX_TO_HANDLE(s
, i
);
562 qio_channel_set_cork(s
->ioc
, true);
563 rc
= nbd_send_request(s
->ioc
, request
);
564 if (qatomic_load_acquire(&s
->state
) == NBD_CLIENT_CONNECTED
&&
566 if (qio_channel_writev_all(s
->ioc
, qiov
->iov
, qiov
->niov
,
570 } else if (rc
>= 0) {
573 qio_channel_set_cork(s
->ioc
, false);
575 rc
= nbd_send_request(s
->ioc
, request
);
580 nbd_channel_error(s
, rc
);
582 s
->requests
[i
].coroutine
= NULL
;
585 if (s
->in_flight
== 0 && s
->wait_in_flight
) {
586 aio_co_wake(s
->connection_co
);
588 qemu_co_queue_next(&s
->free_sema
);
591 qemu_co_mutex_unlock(&s
->send_mutex
);
595 static inline uint16_t payload_advance16(uint8_t **payload
)
598 return lduw_be_p(*payload
- 2);
601 static inline uint32_t payload_advance32(uint8_t **payload
)
604 return ldl_be_p(*payload
- 4);
607 static inline uint64_t payload_advance64(uint8_t **payload
)
610 return ldq_be_p(*payload
- 8);
613 static int nbd_parse_offset_hole_payload(BDRVNBDState
*s
,
614 NBDStructuredReplyChunk
*chunk
,
615 uint8_t *payload
, uint64_t orig_offset
,
616 QEMUIOVector
*qiov
, Error
**errp
)
621 if (chunk
->length
!= sizeof(offset
) + sizeof(hole_size
)) {
622 error_setg(errp
, "Protocol error: invalid payload for "
623 "NBD_REPLY_TYPE_OFFSET_HOLE");
627 offset
= payload_advance64(&payload
);
628 hole_size
= payload_advance32(&payload
);
630 if (!hole_size
|| offset
< orig_offset
|| hole_size
> qiov
->size
||
631 offset
> orig_offset
+ qiov
->size
- hole_size
) {
632 error_setg(errp
, "Protocol error: server sent chunk exceeding requested"
636 if (s
->info
.min_block
&&
637 !QEMU_IS_ALIGNED(hole_size
, s
->info
.min_block
)) {
638 trace_nbd_structured_read_compliance("hole");
641 qemu_iovec_memset(qiov
, offset
- orig_offset
, 0, hole_size
);
647 * nbd_parse_blockstatus_payload
648 * Based on our request, we expect only one extent in reply, for the
649 * base:allocation context.
651 static int nbd_parse_blockstatus_payload(BDRVNBDState
*s
,
652 NBDStructuredReplyChunk
*chunk
,
653 uint8_t *payload
, uint64_t orig_length
,
654 NBDExtent
*extent
, Error
**errp
)
658 /* The server succeeded, so it must have sent [at least] one extent */
659 if (chunk
->length
< sizeof(context_id
) + sizeof(*extent
)) {
660 error_setg(errp
, "Protocol error: invalid payload for "
661 "NBD_REPLY_TYPE_BLOCK_STATUS");
665 context_id
= payload_advance32(&payload
);
666 if (s
->info
.context_id
!= context_id
) {
667 error_setg(errp
, "Protocol error: unexpected context id %d for "
668 "NBD_REPLY_TYPE_BLOCK_STATUS, when negotiated context "
669 "id is %d", context_id
,
674 extent
->length
= payload_advance32(&payload
);
675 extent
->flags
= payload_advance32(&payload
);
677 if (extent
->length
== 0) {
678 error_setg(errp
, "Protocol error: server sent status chunk with "
684 * A server sending unaligned block status is in violation of the
685 * protocol, but as qemu-nbd 3.1 is such a server (at least for
686 * POSIX files that are not a multiple of 512 bytes, since qemu
687 * rounds files up to 512-byte multiples but lseek(SEEK_HOLE)
688 * still sees an implicit hole beyond the real EOF), it's nicer to
689 * work around the misbehaving server. If the request included
690 * more than the final unaligned block, truncate it back to an
691 * aligned result; if the request was only the final block, round
692 * up to the full block and change the status to fully-allocated
693 * (always a safe status, even if it loses information).
695 if (s
->info
.min_block
&& !QEMU_IS_ALIGNED(extent
->length
,
696 s
->info
.min_block
)) {
697 trace_nbd_parse_blockstatus_compliance("extent length is unaligned");
698 if (extent
->length
> s
->info
.min_block
) {
699 extent
->length
= QEMU_ALIGN_DOWN(extent
->length
,
702 extent
->length
= s
->info
.min_block
;
708 * We used NBD_CMD_FLAG_REQ_ONE, so the server should not have
709 * sent us any more than one extent, nor should it have included
710 * status beyond our request in that extent. However, it's easy
711 * enough to ignore the server's noncompliance without killing the
712 * connection; just ignore trailing extents, and clamp things to
713 * the length of our request.
715 if (chunk
->length
> sizeof(context_id
) + sizeof(*extent
)) {
716 trace_nbd_parse_blockstatus_compliance("more than one extent");
718 if (extent
->length
> orig_length
) {
719 extent
->length
= orig_length
;
720 trace_nbd_parse_blockstatus_compliance("extent length too large");
724 * HACK: if we are using x-dirty-bitmaps to access
725 * qemu:allocation-depth, treat all depths > 2 the same as 2,
726 * since nbd_client_co_block_status is only expecting the low two
729 if (s
->alloc_depth
&& extent
->flags
> 2) {
737 * nbd_parse_error_payload
738 * on success @errp contains message describing nbd error reply
740 static int nbd_parse_error_payload(NBDStructuredReplyChunk
*chunk
,
741 uint8_t *payload
, int *request_ret
,
745 uint16_t message_size
;
747 assert(chunk
->type
& (1 << 15));
749 if (chunk
->length
< sizeof(error
) + sizeof(message_size
)) {
751 "Protocol error: invalid payload for structured error");
755 error
= nbd_errno_to_system_errno(payload_advance32(&payload
));
757 error_setg(errp
, "Protocol error: server sent structured error chunk "
762 *request_ret
= -error
;
763 message_size
= payload_advance16(&payload
);
765 if (message_size
> chunk
->length
- sizeof(error
) - sizeof(message_size
)) {
766 error_setg(errp
, "Protocol error: server sent structured error chunk "
767 "with incorrect message size");
771 /* TODO: Add a trace point to mention the server complaint */
773 /* TODO handle ERROR_OFFSET */
778 static int nbd_co_receive_offset_data_payload(BDRVNBDState
*s
,
779 uint64_t orig_offset
,
780 QEMUIOVector
*qiov
, Error
**errp
)
782 QEMUIOVector sub_qiov
;
786 NBDStructuredReplyChunk
*chunk
= &s
->reply
.structured
;
788 assert(nbd_reply_is_structured(&s
->reply
));
790 /* The NBD spec requires at least one byte of payload */
791 if (chunk
->length
<= sizeof(offset
)) {
792 error_setg(errp
, "Protocol error: invalid payload for "
793 "NBD_REPLY_TYPE_OFFSET_DATA");
797 if (nbd_read64(s
->ioc
, &offset
, "OFFSET_DATA offset", errp
) < 0) {
801 data_size
= chunk
->length
- sizeof(offset
);
803 if (offset
< orig_offset
|| data_size
> qiov
->size
||
804 offset
> orig_offset
+ qiov
->size
- data_size
) {
805 error_setg(errp
, "Protocol error: server sent chunk exceeding requested"
809 if (s
->info
.min_block
&& !QEMU_IS_ALIGNED(data_size
, s
->info
.min_block
)) {
810 trace_nbd_structured_read_compliance("data");
813 qemu_iovec_init(&sub_qiov
, qiov
->niov
);
814 qemu_iovec_concat(&sub_qiov
, qiov
, offset
- orig_offset
, data_size
);
815 ret
= qio_channel_readv_all(s
->ioc
, sub_qiov
.iov
, sub_qiov
.niov
, errp
);
816 qemu_iovec_destroy(&sub_qiov
);
818 return ret
< 0 ? -EIO
: 0;
821 #define NBD_MAX_MALLOC_PAYLOAD 1000
822 static coroutine_fn
int nbd_co_receive_structured_payload(
823 BDRVNBDState
*s
, void **payload
, Error
**errp
)
828 assert(nbd_reply_is_structured(&s
->reply
));
830 len
= s
->reply
.structured
.length
;
836 if (payload
== NULL
) {
837 error_setg(errp
, "Unexpected structured payload");
841 if (len
> NBD_MAX_MALLOC_PAYLOAD
) {
842 error_setg(errp
, "Payload too large");
846 *payload
= g_new(char, len
);
847 ret
= nbd_read(s
->ioc
, *payload
, len
, "structured payload", errp
);
858 * nbd_co_do_receive_one_chunk
860 * set request_ret to received reply error
861 * if qiov is not NULL: read payload to @qiov
862 * for structured reply chunk:
863 * if error chunk: read payload, set @request_ret, do not set @payload
864 * else if offset_data chunk: read payload data to @qiov, do not set @payload
865 * else: read payload to @payload
867 * If function fails, @errp contains corresponding error message, and the
868 * connection with the server is suspect. If it returns 0, then the
869 * transaction succeeded (although @request_ret may be a negative errno
870 * corresponding to the server's error reply), and errp is unchanged.
872 static coroutine_fn
int nbd_co_do_receive_one_chunk(
873 BDRVNBDState
*s
, uint64_t handle
, bool only_structured
,
874 int *request_ret
, QEMUIOVector
*qiov
, void **payload
, Error
**errp
)
877 int i
= HANDLE_TO_INDEX(s
, handle
);
878 void *local_payload
= NULL
;
879 NBDStructuredReplyChunk
*chunk
;
886 /* Wait until we're woken up by nbd_connection_entry. */
887 s
->requests
[i
].receiving
= true;
888 qemu_coroutine_yield();
889 s
->requests
[i
].receiving
= false;
890 if (qatomic_load_acquire(&s
->state
) != NBD_CLIENT_CONNECTED
) {
891 error_setg(errp
, "Connection closed");
896 assert(s
->reply
.handle
== handle
);
898 if (nbd_reply_is_simple(&s
->reply
)) {
899 if (only_structured
) {
900 error_setg(errp
, "Protocol error: simple reply when structured "
901 "reply chunk was expected");
905 *request_ret
= -nbd_errno_to_system_errno(s
->reply
.simple
.error
);
906 if (*request_ret
< 0 || !qiov
) {
910 return qio_channel_readv_all(s
->ioc
, qiov
->iov
, qiov
->niov
,
911 errp
) < 0 ? -EIO
: 0;
914 /* handle structured reply chunk */
915 assert(s
->info
.structured_reply
);
916 chunk
= &s
->reply
.structured
;
918 if (chunk
->type
== NBD_REPLY_TYPE_NONE
) {
919 if (!(chunk
->flags
& NBD_REPLY_FLAG_DONE
)) {
920 error_setg(errp
, "Protocol error: NBD_REPLY_TYPE_NONE chunk without"
921 " NBD_REPLY_FLAG_DONE flag set");
925 error_setg(errp
, "Protocol error: NBD_REPLY_TYPE_NONE chunk with"
932 if (chunk
->type
== NBD_REPLY_TYPE_OFFSET_DATA
) {
934 error_setg(errp
, "Unexpected NBD_REPLY_TYPE_OFFSET_DATA chunk");
938 return nbd_co_receive_offset_data_payload(s
, s
->requests
[i
].offset
,
942 if (nbd_reply_type_is_error(chunk
->type
)) {
943 payload
= &local_payload
;
946 ret
= nbd_co_receive_structured_payload(s
, payload
, errp
);
951 if (nbd_reply_type_is_error(chunk
->type
)) {
952 ret
= nbd_parse_error_payload(chunk
, local_payload
, request_ret
, errp
);
953 g_free(local_payload
);
961 * nbd_co_receive_one_chunk
962 * Read reply, wake up connection_co and set s->quit if needed.
963 * Return value is a fatal error code or normal nbd reply error code
965 static coroutine_fn
int nbd_co_receive_one_chunk(
966 BDRVNBDState
*s
, uint64_t handle
, bool only_structured
,
967 int *request_ret
, QEMUIOVector
*qiov
, NBDReply
*reply
, void **payload
,
970 int ret
= nbd_co_do_receive_one_chunk(s
, handle
, only_structured
,
971 request_ret
, qiov
, payload
, errp
);
974 memset(reply
, 0, sizeof(*reply
));
975 nbd_channel_error(s
, ret
);
977 /* For assert at loop start in nbd_connection_entry */
982 if (s
->connection_co
&& !s
->wait_in_flight
) {
984 * We must check s->wait_in_flight, because we may entered by
985 * nbd_recv_coroutines_wake_all(), in this case we should not
986 * wake connection_co here, it will woken by last request.
988 aio_co_wake(s
->connection_co
);
994 typedef struct NBDReplyChunkIter
{
998 bool done
, only_structured
;
1001 static void nbd_iter_channel_error(NBDReplyChunkIter
*iter
,
1002 int ret
, Error
**local_err
)
1004 assert(local_err
&& *local_err
);
1009 error_propagate(&iter
->err
, *local_err
);
1011 error_free(*local_err
);
1017 static void nbd_iter_request_error(NBDReplyChunkIter
*iter
, int ret
)
1021 if (!iter
->request_ret
) {
1022 iter
->request_ret
= ret
;
1027 * NBD_FOREACH_REPLY_CHUNK
1028 * The pointer stored in @payload requires g_free() to free it.
1030 #define NBD_FOREACH_REPLY_CHUNK(s, iter, handle, structured, \
1031 qiov, reply, payload) \
1032 for (iter = (NBDReplyChunkIter) { .only_structured = structured }; \
1033 nbd_reply_chunk_iter_receive(s, &iter, handle, qiov, reply, payload);)
1036 * nbd_reply_chunk_iter_receive
1037 * The pointer stored in @payload requires g_free() to free it.
1039 static bool nbd_reply_chunk_iter_receive(BDRVNBDState
*s
,
1040 NBDReplyChunkIter
*iter
,
1042 QEMUIOVector
*qiov
, NBDReply
*reply
,
1045 int ret
, request_ret
;
1046 NBDReply local_reply
;
1047 NBDStructuredReplyChunk
*chunk
;
1048 Error
*local_err
= NULL
;
1049 if (qatomic_load_acquire(&s
->state
) != NBD_CLIENT_CONNECTED
) {
1050 error_setg(&local_err
, "Connection closed");
1051 nbd_iter_channel_error(iter
, -EIO
, &local_err
);
1056 /* Previous iteration was last. */
1060 if (reply
== NULL
) {
1061 reply
= &local_reply
;
1064 ret
= nbd_co_receive_one_chunk(s
, handle
, iter
->only_structured
,
1065 &request_ret
, qiov
, reply
, payload
,
1068 nbd_iter_channel_error(iter
, ret
, &local_err
);
1069 } else if (request_ret
< 0) {
1070 nbd_iter_request_error(iter
, request_ret
);
1073 /* Do not execute the body of NBD_FOREACH_REPLY_CHUNK for simple reply. */
1074 if (nbd_reply_is_simple(reply
) ||
1075 qatomic_load_acquire(&s
->state
) != NBD_CLIENT_CONNECTED
) {
1079 chunk
= &reply
->structured
;
1080 iter
->only_structured
= true;
1082 if (chunk
->type
== NBD_REPLY_TYPE_NONE
) {
1083 /* NBD_REPLY_FLAG_DONE is already checked in nbd_co_receive_one_chunk */
1084 assert(chunk
->flags
& NBD_REPLY_FLAG_DONE
);
1088 if (chunk
->flags
& NBD_REPLY_FLAG_DONE
) {
1089 /* This iteration is last. */
1093 /* Execute the loop body */
1097 s
->requests
[HANDLE_TO_INDEX(s
, handle
)].coroutine
= NULL
;
1099 qemu_co_mutex_lock(&s
->send_mutex
);
1101 if (s
->in_flight
== 0 && s
->wait_in_flight
) {
1102 aio_co_wake(s
->connection_co
);
1104 qemu_co_queue_next(&s
->free_sema
);
1106 qemu_co_mutex_unlock(&s
->send_mutex
);
1111 static int nbd_co_receive_return_code(BDRVNBDState
*s
, uint64_t handle
,
1112 int *request_ret
, Error
**errp
)
1114 NBDReplyChunkIter iter
;
1116 NBD_FOREACH_REPLY_CHUNK(s
, iter
, handle
, false, NULL
, NULL
, NULL
) {
1117 /* nbd_reply_chunk_iter_receive does all the work */
1120 error_propagate(errp
, iter
.err
);
1121 *request_ret
= iter
.request_ret
;
1125 static int nbd_co_receive_cmdread_reply(BDRVNBDState
*s
, uint64_t handle
,
1126 uint64_t offset
, QEMUIOVector
*qiov
,
1127 int *request_ret
, Error
**errp
)
1129 NBDReplyChunkIter iter
;
1131 void *payload
= NULL
;
1132 Error
*local_err
= NULL
;
1134 NBD_FOREACH_REPLY_CHUNK(s
, iter
, handle
, s
->info
.structured_reply
,
1135 qiov
, &reply
, &payload
)
1138 NBDStructuredReplyChunk
*chunk
= &reply
.structured
;
1140 assert(nbd_reply_is_structured(&reply
));
1142 switch (chunk
->type
) {
1143 case NBD_REPLY_TYPE_OFFSET_DATA
:
1145 * special cased in nbd_co_receive_one_chunk, data is already
1149 case NBD_REPLY_TYPE_OFFSET_HOLE
:
1150 ret
= nbd_parse_offset_hole_payload(s
, &reply
.structured
, payload
,
1151 offset
, qiov
, &local_err
);
1153 nbd_channel_error(s
, ret
);
1154 nbd_iter_channel_error(&iter
, ret
, &local_err
);
1158 if (!nbd_reply_type_is_error(chunk
->type
)) {
1159 /* not allowed reply type */
1160 nbd_channel_error(s
, -EINVAL
);
1161 error_setg(&local_err
,
1162 "Unexpected reply type: %d (%s) for CMD_READ",
1163 chunk
->type
, nbd_reply_type_lookup(chunk
->type
));
1164 nbd_iter_channel_error(&iter
, -EINVAL
, &local_err
);
1172 error_propagate(errp
, iter
.err
);
1173 *request_ret
= iter
.request_ret
;
1177 static int nbd_co_receive_blockstatus_reply(BDRVNBDState
*s
,
1178 uint64_t handle
, uint64_t length
,
1180 int *request_ret
, Error
**errp
)
1182 NBDReplyChunkIter iter
;
1184 void *payload
= NULL
;
1185 Error
*local_err
= NULL
;
1186 bool received
= false;
1188 assert(!extent
->length
);
1189 NBD_FOREACH_REPLY_CHUNK(s
, iter
, handle
, false, NULL
, &reply
, &payload
) {
1191 NBDStructuredReplyChunk
*chunk
= &reply
.structured
;
1193 assert(nbd_reply_is_structured(&reply
));
1195 switch (chunk
->type
) {
1196 case NBD_REPLY_TYPE_BLOCK_STATUS
:
1198 nbd_channel_error(s
, -EINVAL
);
1199 error_setg(&local_err
, "Several BLOCK_STATUS chunks in reply");
1200 nbd_iter_channel_error(&iter
, -EINVAL
, &local_err
);
1204 ret
= nbd_parse_blockstatus_payload(s
, &reply
.structured
,
1205 payload
, length
, extent
,
1208 nbd_channel_error(s
, ret
);
1209 nbd_iter_channel_error(&iter
, ret
, &local_err
);
1213 if (!nbd_reply_type_is_error(chunk
->type
)) {
1214 nbd_channel_error(s
, -EINVAL
);
1215 error_setg(&local_err
,
1216 "Unexpected reply type: %d (%s) "
1217 "for CMD_BLOCK_STATUS",
1218 chunk
->type
, nbd_reply_type_lookup(chunk
->type
));
1219 nbd_iter_channel_error(&iter
, -EINVAL
, &local_err
);
1227 if (!extent
->length
&& !iter
.request_ret
) {
1228 error_setg(&local_err
, "Server did not reply with any status extents");
1229 nbd_iter_channel_error(&iter
, -EIO
, &local_err
);
1232 error_propagate(errp
, iter
.err
);
1233 *request_ret
= iter
.request_ret
;
1237 static int nbd_co_request(BlockDriverState
*bs
, NBDRequest
*request
,
1238 QEMUIOVector
*write_qiov
)
1240 int ret
, request_ret
;
1241 Error
*local_err
= NULL
;
1242 BDRVNBDState
*s
= (BDRVNBDState
*)bs
->opaque
;
1244 assert(request
->type
!= NBD_CMD_READ
);
1246 assert(request
->type
== NBD_CMD_WRITE
);
1247 assert(request
->len
== iov_size(write_qiov
->iov
, write_qiov
->niov
));
1249 assert(request
->type
!= NBD_CMD_WRITE
);
1253 ret
= nbd_co_send_request(bs
, request
, write_qiov
);
1258 ret
= nbd_co_receive_return_code(s
, request
->handle
,
1259 &request_ret
, &local_err
);
1261 trace_nbd_co_request_fail(request
->from
, request
->len
,
1262 request
->handle
, request
->flags
,
1264 nbd_cmd_lookup(request
->type
),
1265 ret
, error_get_pretty(local_err
));
1266 error_free(local_err
);
1269 } while (ret
< 0 && nbd_client_connecting_wait(s
));
1271 return ret
? ret
: request_ret
;
1274 static int nbd_client_co_preadv(BlockDriverState
*bs
, uint64_t offset
,
1275 uint64_t bytes
, QEMUIOVector
*qiov
, int flags
)
1277 int ret
, request_ret
;
1278 Error
*local_err
= NULL
;
1279 BDRVNBDState
*s
= (BDRVNBDState
*)bs
->opaque
;
1280 NBDRequest request
= {
1281 .type
= NBD_CMD_READ
,
1286 assert(bytes
<= NBD_MAX_BUFFER_SIZE
);
1293 * Work around the fact that the block layer doesn't do
1294 * byte-accurate sizing yet - if the read exceeds the server's
1295 * advertised size because the block layer rounded size up, then
1296 * truncate the request to the server and tail-pad with zero.
1298 if (offset
>= s
->info
.size
) {
1299 assert(bytes
< BDRV_SECTOR_SIZE
);
1300 qemu_iovec_memset(qiov
, 0, 0, bytes
);
1303 if (offset
+ bytes
> s
->info
.size
) {
1304 uint64_t slop
= offset
+ bytes
- s
->info
.size
;
1306 assert(slop
< BDRV_SECTOR_SIZE
);
1307 qemu_iovec_memset(qiov
, bytes
- slop
, 0, slop
);
1308 request
.len
-= slop
;
1312 ret
= nbd_co_send_request(bs
, &request
, NULL
);
1317 ret
= nbd_co_receive_cmdread_reply(s
, request
.handle
, offset
, qiov
,
1318 &request_ret
, &local_err
);
1320 trace_nbd_co_request_fail(request
.from
, request
.len
, request
.handle
,
1321 request
.flags
, request
.type
,
1322 nbd_cmd_lookup(request
.type
),
1323 ret
, error_get_pretty(local_err
));
1324 error_free(local_err
);
1327 } while (ret
< 0 && nbd_client_connecting_wait(s
));
1329 return ret
? ret
: request_ret
;
1332 static int nbd_client_co_pwritev(BlockDriverState
*bs
, uint64_t offset
,
1333 uint64_t bytes
, QEMUIOVector
*qiov
, int flags
)
1335 BDRVNBDState
*s
= (BDRVNBDState
*)bs
->opaque
;
1336 NBDRequest request
= {
1337 .type
= NBD_CMD_WRITE
,
1342 assert(!(s
->info
.flags
& NBD_FLAG_READ_ONLY
));
1343 if (flags
& BDRV_REQ_FUA
) {
1344 assert(s
->info
.flags
& NBD_FLAG_SEND_FUA
);
1345 request
.flags
|= NBD_CMD_FLAG_FUA
;
1348 assert(bytes
<= NBD_MAX_BUFFER_SIZE
);
1353 return nbd_co_request(bs
, &request
, qiov
);
1356 static int nbd_client_co_pwrite_zeroes(BlockDriverState
*bs
, int64_t offset
,
1357 int bytes
, BdrvRequestFlags flags
)
1359 BDRVNBDState
*s
= (BDRVNBDState
*)bs
->opaque
;
1360 NBDRequest request
= {
1361 .type
= NBD_CMD_WRITE_ZEROES
,
1366 assert(!(s
->info
.flags
& NBD_FLAG_READ_ONLY
));
1367 if (!(s
->info
.flags
& NBD_FLAG_SEND_WRITE_ZEROES
)) {
1371 if (flags
& BDRV_REQ_FUA
) {
1372 assert(s
->info
.flags
& NBD_FLAG_SEND_FUA
);
1373 request
.flags
|= NBD_CMD_FLAG_FUA
;
1375 if (!(flags
& BDRV_REQ_MAY_UNMAP
)) {
1376 request
.flags
|= NBD_CMD_FLAG_NO_HOLE
;
1378 if (flags
& BDRV_REQ_NO_FALLBACK
) {
1379 assert(s
->info
.flags
& NBD_FLAG_SEND_FAST_ZERO
);
1380 request
.flags
|= NBD_CMD_FLAG_FAST_ZERO
;
1386 return nbd_co_request(bs
, &request
, NULL
);
1389 static int nbd_client_co_flush(BlockDriverState
*bs
)
1391 BDRVNBDState
*s
= (BDRVNBDState
*)bs
->opaque
;
1392 NBDRequest request
= { .type
= NBD_CMD_FLUSH
};
1394 if (!(s
->info
.flags
& NBD_FLAG_SEND_FLUSH
)) {
1401 return nbd_co_request(bs
, &request
, NULL
);
1404 static int nbd_client_co_pdiscard(BlockDriverState
*bs
, int64_t offset
,
1407 BDRVNBDState
*s
= (BDRVNBDState
*)bs
->opaque
;
1408 NBDRequest request
= {
1409 .type
= NBD_CMD_TRIM
,
1414 assert(!(s
->info
.flags
& NBD_FLAG_READ_ONLY
));
1415 if (!(s
->info
.flags
& NBD_FLAG_SEND_TRIM
) || !bytes
) {
1419 return nbd_co_request(bs
, &request
, NULL
);
1422 static int coroutine_fn
nbd_client_co_block_status(
1423 BlockDriverState
*bs
, bool want_zero
, int64_t offset
, int64_t bytes
,
1424 int64_t *pnum
, int64_t *map
, BlockDriverState
**file
)
1426 int ret
, request_ret
;
1427 NBDExtent extent
= { 0 };
1428 BDRVNBDState
*s
= (BDRVNBDState
*)bs
->opaque
;
1429 Error
*local_err
= NULL
;
1431 NBDRequest request
= {
1432 .type
= NBD_CMD_BLOCK_STATUS
,
1434 .len
= MIN(QEMU_ALIGN_DOWN(INT_MAX
, bs
->bl
.request_alignment
),
1435 MIN(bytes
, s
->info
.size
- offset
)),
1436 .flags
= NBD_CMD_FLAG_REQ_ONE
,
1439 if (!s
->info
.base_allocation
) {
1443 return BDRV_BLOCK_DATA
| BDRV_BLOCK_OFFSET_VALID
;
1447 * Work around the fact that the block layer doesn't do
1448 * byte-accurate sizing yet - if the status request exceeds the
1449 * server's advertised size because the block layer rounded size
1450 * up, we truncated the request to the server (above), or are
1451 * called on just the hole.
1453 if (offset
>= s
->info
.size
) {
1455 assert(bytes
< BDRV_SECTOR_SIZE
);
1456 /* Intentionally don't report offset_valid for the hole */
1457 return BDRV_BLOCK_ZERO
;
1460 if (s
->info
.min_block
) {
1461 assert(QEMU_IS_ALIGNED(request
.len
, s
->info
.min_block
));
1464 ret
= nbd_co_send_request(bs
, &request
, NULL
);
1469 ret
= nbd_co_receive_blockstatus_reply(s
, request
.handle
, bytes
,
1470 &extent
, &request_ret
,
1473 trace_nbd_co_request_fail(request
.from
, request
.len
, request
.handle
,
1474 request
.flags
, request
.type
,
1475 nbd_cmd_lookup(request
.type
),
1476 ret
, error_get_pretty(local_err
));
1477 error_free(local_err
);
1480 } while (ret
< 0 && nbd_client_connecting_wait(s
));
1482 if (ret
< 0 || request_ret
< 0) {
1483 return ret
? ret
: request_ret
;
1486 assert(extent
.length
);
1487 *pnum
= extent
.length
;
1490 return (extent
.flags
& NBD_STATE_HOLE
? 0 : BDRV_BLOCK_DATA
) |
1491 (extent
.flags
& NBD_STATE_ZERO
? BDRV_BLOCK_ZERO
: 0) |
1492 BDRV_BLOCK_OFFSET_VALID
;
1495 static int nbd_client_reopen_prepare(BDRVReopenState
*state
,
1496 BlockReopenQueue
*queue
, Error
**errp
)
1498 BDRVNBDState
*s
= (BDRVNBDState
*)state
->bs
->opaque
;
1500 if ((state
->flags
& BDRV_O_RDWR
) && (s
->info
.flags
& NBD_FLAG_READ_ONLY
)) {
1501 error_setg(errp
, "Can't reopen read-only NBD mount as read/write");
1507 static void nbd_yank(void *opaque
)
1509 BlockDriverState
*bs
= opaque
;
1510 BDRVNBDState
*s
= (BDRVNBDState
*)bs
->opaque
;
1512 qatomic_store_release(&s
->state
, NBD_CLIENT_QUIT
);
1513 qio_channel_shutdown(QIO_CHANNEL(s
->sioc
), QIO_CHANNEL_SHUTDOWN_BOTH
, NULL
);
1516 static void nbd_client_close(BlockDriverState
*bs
)
1518 BDRVNBDState
*s
= (BDRVNBDState
*)bs
->opaque
;
1519 NBDRequest request
= { .type
= NBD_CMD_DISC
};
1522 nbd_send_request(s
->ioc
, &request
);
1525 nbd_teardown_connection(bs
);
1528 static int nbd_establish_connection(BlockDriverState
*bs
,
1529 SocketAddress
*saddr
,
1533 BDRVNBDState
*s
= (BDRVNBDState
*)bs
->opaque
;
1535 s
->sioc
= qio_channel_socket_new();
1536 qio_channel_set_name(QIO_CHANNEL(s
->sioc
), "nbd-client");
1538 qio_channel_socket_connect_sync(s
->sioc
, saddr
, errp
);
1540 object_unref(OBJECT(s
->sioc
));
1545 yank_register_function(BLOCKDEV_YANK_INSTANCE(bs
->node_name
), nbd_yank
, bs
);
1546 qio_channel_set_delay(QIO_CHANNEL(s
->sioc
), false);
1551 /* nbd_client_handshake takes ownership on s->sioc. On failure it's unref'ed. */
1552 static int nbd_client_handshake(BlockDriverState
*bs
, Error
**errp
)
1554 BDRVNBDState
*s
= (BDRVNBDState
*)bs
->opaque
;
1555 AioContext
*aio_context
= bdrv_get_aio_context(bs
);
1558 trace_nbd_client_handshake(s
->export
);
1559 qio_channel_set_blocking(QIO_CHANNEL(s
->sioc
), false, NULL
);
1560 qio_channel_attach_aio_context(QIO_CHANNEL(s
->sioc
), aio_context
);
1562 s
->info
.request_sizes
= true;
1563 s
->info
.structured_reply
= true;
1564 s
->info
.base_allocation
= true;
1565 s
->info
.x_dirty_bitmap
= g_strdup(s
->x_dirty_bitmap
);
1566 s
->info
.name
= g_strdup(s
->export
?: "");
1567 ret
= nbd_receive_negotiate(aio_context
, QIO_CHANNEL(s
->sioc
), s
->tlscreds
,
1568 s
->hostname
, &s
->ioc
, &s
->info
, errp
);
1569 g_free(s
->info
.x_dirty_bitmap
);
1570 g_free(s
->info
.name
);
1572 yank_unregister_function(BLOCKDEV_YANK_INSTANCE(bs
->node_name
),
1574 object_unref(OBJECT(s
->sioc
));
1578 if (s
->x_dirty_bitmap
) {
1579 if (!s
->info
.base_allocation
) {
1580 error_setg(errp
, "requested x-dirty-bitmap %s not found",
1585 if (strcmp(s
->x_dirty_bitmap
, "qemu:allocation-depth") == 0) {
1586 s
->alloc_depth
= true;
1589 if (s
->info
.flags
& NBD_FLAG_READ_ONLY
) {
1590 ret
= bdrv_apply_auto_read_only(bs
, "NBD export is read-only", errp
);
1595 if (s
->info
.flags
& NBD_FLAG_SEND_FUA
) {
1596 bs
->supported_write_flags
= BDRV_REQ_FUA
;
1597 bs
->supported_zero_flags
|= BDRV_REQ_FUA
;
1599 if (s
->info
.flags
& NBD_FLAG_SEND_WRITE_ZEROES
) {
1600 bs
->supported_zero_flags
|= BDRV_REQ_MAY_UNMAP
;
1601 if (s
->info
.flags
& NBD_FLAG_SEND_FAST_ZERO
) {
1602 bs
->supported_zero_flags
|= BDRV_REQ_NO_FALLBACK
;
1607 s
->ioc
= QIO_CHANNEL(s
->sioc
);
1608 object_ref(OBJECT(s
->ioc
));
1611 trace_nbd_client_handshake_success(s
->export
);
1617 * We have connected, but must fail for other reasons.
1618 * Send NBD_CMD_DISC as a courtesy to the server.
1621 NBDRequest request
= { .type
= NBD_CMD_DISC
};
1623 nbd_send_request(s
->ioc
?: QIO_CHANNEL(s
->sioc
), &request
);
1625 yank_unregister_function(BLOCKDEV_YANK_INSTANCE(bs
->node_name
),
1627 object_unref(OBJECT(s
->sioc
));
1629 object_unref(OBJECT(s
->ioc
));
1637 * Parse nbd_open options
1640 static int nbd_parse_uri(const char *filename
, QDict
*options
)
1644 QueryParams
*qp
= NULL
;
1648 uri
= uri_parse(filename
);
1654 if (!g_strcmp0(uri
->scheme
, "nbd")) {
1656 } else if (!g_strcmp0(uri
->scheme
, "nbd+tcp")) {
1658 } else if (!g_strcmp0(uri
->scheme
, "nbd+unix")) {
1665 p
= uri
->path
? uri
->path
: "";
1670 qdict_put_str(options
, "export", p
);
1673 qp
= query_params_parse(uri
->query
);
1674 if (qp
->n
> 1 || (is_unix
&& !qp
->n
) || (!is_unix
&& qp
->n
)) {
1680 /* nbd+unix:///export?socket=path */
1681 if (uri
->server
|| uri
->port
|| strcmp(qp
->p
[0].name
, "socket")) {
1685 qdict_put_str(options
, "server.type", "unix");
1686 qdict_put_str(options
, "server.path", qp
->p
[0].value
);
1691 /* nbd[+tcp]://host[:port]/export */
1697 /* strip braces from literal IPv6 address */
1698 if (uri
->server
[0] == '[') {
1699 host
= qstring_from_substr(uri
->server
, 1,
1700 strlen(uri
->server
) - 1);
1702 host
= qstring_from_str(uri
->server
);
1705 qdict_put_str(options
, "server.type", "inet");
1706 qdict_put(options
, "server.host", host
);
1708 port_str
= g_strdup_printf("%d", uri
->port
?: NBD_DEFAULT_PORT
);
1709 qdict_put_str(options
, "server.port", port_str
);
1715 query_params_free(qp
);
1721 static bool nbd_has_filename_options_conflict(QDict
*options
, Error
**errp
)
1723 const QDictEntry
*e
;
1725 for (e
= qdict_first(options
); e
; e
= qdict_next(options
, e
)) {
1726 if (!strcmp(e
->key
, "host") ||
1727 !strcmp(e
->key
, "port") ||
1728 !strcmp(e
->key
, "path") ||
1729 !strcmp(e
->key
, "export") ||
1730 strstart(e
->key
, "server.", NULL
))
1732 error_setg(errp
, "Option '%s' cannot be used with a file name",
1741 static void nbd_parse_filename(const char *filename
, QDict
*options
,
1744 g_autofree
char *file
= NULL
;
1746 const char *host_spec
;
1747 const char *unixpath
;
1749 if (nbd_has_filename_options_conflict(options
, errp
)) {
1753 if (strstr(filename
, "://")) {
1754 int ret
= nbd_parse_uri(filename
, options
);
1756 error_setg(errp
, "No valid URL specified");
1761 file
= g_strdup(filename
);
1763 export_name
= strstr(file
, EN_OPTSTR
);
1765 if (export_name
[strlen(EN_OPTSTR
)] == 0) {
1768 export_name
[0] = 0; /* truncate 'file' */
1769 export_name
+= strlen(EN_OPTSTR
);
1771 qdict_put_str(options
, "export", export_name
);
1774 /* extract the host_spec - fail if it's not nbd:... */
1775 if (!strstart(file
, "nbd:", &host_spec
)) {
1776 error_setg(errp
, "File name string for NBD must start with 'nbd:'");
1784 /* are we a UNIX or TCP socket? */
1785 if (strstart(host_spec
, "unix:", &unixpath
)) {
1786 qdict_put_str(options
, "server.type", "unix");
1787 qdict_put_str(options
, "server.path", unixpath
);
1789 InetSocketAddress
*addr
= g_new(InetSocketAddress
, 1);
1791 if (inet_parse(addr
, host_spec
, errp
)) {
1795 qdict_put_str(options
, "server.type", "inet");
1796 qdict_put_str(options
, "server.host", addr
->host
);
1797 qdict_put_str(options
, "server.port", addr
->port
);
1799 qapi_free_InetSocketAddress(addr
);
1803 static bool nbd_process_legacy_socket_options(QDict
*output_options
,
1804 QemuOpts
*legacy_opts
,
1807 const char *path
= qemu_opt_get(legacy_opts
, "path");
1808 const char *host
= qemu_opt_get(legacy_opts
, "host");
1809 const char *port
= qemu_opt_get(legacy_opts
, "port");
1810 const QDictEntry
*e
;
1812 if (!path
&& !host
&& !port
) {
1816 for (e
= qdict_first(output_options
); e
; e
= qdict_next(output_options
, e
))
1818 if (strstart(e
->key
, "server.", NULL
)) {
1819 error_setg(errp
, "Cannot use 'server' and path/host/port at the "
1826 error_setg(errp
, "path and host may not be used at the same time");
1830 error_setg(errp
, "port may not be used without host");
1834 qdict_put_str(output_options
, "server.type", "unix");
1835 qdict_put_str(output_options
, "server.path", path
);
1837 qdict_put_str(output_options
, "server.type", "inet");
1838 qdict_put_str(output_options
, "server.host", host
);
1839 qdict_put_str(output_options
, "server.port",
1840 port
?: stringify(NBD_DEFAULT_PORT
));
1846 static SocketAddress
*nbd_config(BDRVNBDState
*s
, QDict
*options
,
1849 SocketAddress
*saddr
= NULL
;
1853 qdict_extract_subqdict(options
, &addr
, "server.");
1854 if (!qdict_size(addr
)) {
1855 error_setg(errp
, "NBD server address missing");
1859 iv
= qobject_input_visitor_new_flat_confused(addr
, errp
);
1864 if (!visit_type_SocketAddress(iv
, NULL
, &saddr
, errp
)) {
1868 if (socket_address_parse_named_fd(saddr
, errp
) < 0) {
1869 qapi_free_SocketAddress(saddr
);
1875 qobject_unref(addr
);
1880 static QCryptoTLSCreds
*nbd_get_tls_creds(const char *id
, Error
**errp
)
1883 QCryptoTLSCreds
*creds
;
1885 obj
= object_resolve_path_component(
1886 object_get_objects_root(), id
);
1888 error_setg(errp
, "No TLS credentials with id '%s'",
1892 creds
= (QCryptoTLSCreds
*)
1893 object_dynamic_cast(obj
, TYPE_QCRYPTO_TLS_CREDS
);
1895 error_setg(errp
, "Object with id '%s' is not TLS credentials",
1900 if (creds
->endpoint
!= QCRYPTO_TLS_CREDS_ENDPOINT_CLIENT
) {
1902 "Expecting TLS credentials with a client endpoint");
1910 static QemuOptsList nbd_runtime_opts
= {
1912 .head
= QTAILQ_HEAD_INITIALIZER(nbd_runtime_opts
.head
),
1916 .type
= QEMU_OPT_STRING
,
1917 .help
= "TCP host to connect to",
1921 .type
= QEMU_OPT_STRING
,
1922 .help
= "TCP port to connect to",
1926 .type
= QEMU_OPT_STRING
,
1927 .help
= "Unix socket path to connect to",
1931 .type
= QEMU_OPT_STRING
,
1932 .help
= "Name of the NBD export to open",
1935 .name
= "tls-creds",
1936 .type
= QEMU_OPT_STRING
,
1937 .help
= "ID of the TLS credentials to use",
1940 .name
= "x-dirty-bitmap",
1941 .type
= QEMU_OPT_STRING
,
1942 .help
= "experimental: expose named dirty bitmap in place of "
1946 .name
= "reconnect-delay",
1947 .type
= QEMU_OPT_NUMBER
,
1948 .help
= "On an unexpected disconnect, the nbd client tries to "
1949 "connect again until succeeding or encountering a serious "
1950 "error. During the first @reconnect-delay seconds, all "
1951 "requests are paused and will be rerun on a successful "
1952 "reconnect. After that time, any delayed requests and all "
1953 "future requests before a successful reconnect will "
1954 "immediately fail. Default 0",
1956 { /* end of list */ }
1960 static int nbd_process_options(BlockDriverState
*bs
, QDict
*options
,
1963 BDRVNBDState
*s
= bs
->opaque
;
1967 opts
= qemu_opts_create(&nbd_runtime_opts
, NULL
, 0, &error_abort
);
1968 if (!qemu_opts_absorb_qdict(opts
, options
, errp
)) {
1972 /* Translate @host, @port, and @path to a SocketAddress */
1973 if (!nbd_process_legacy_socket_options(options
, opts
, errp
)) {
1977 /* Pop the config into our state object. Exit if invalid. */
1978 s
->saddr
= nbd_config(s
, options
, errp
);
1983 s
->export
= g_strdup(qemu_opt_get(opts
, "export"));
1984 if (s
->export
&& strlen(s
->export
) > NBD_MAX_STRING_SIZE
) {
1985 error_setg(errp
, "export name too long to send to server");
1989 s
->tlscredsid
= g_strdup(qemu_opt_get(opts
, "tls-creds"));
1990 if (s
->tlscredsid
) {
1991 s
->tlscreds
= nbd_get_tls_creds(s
->tlscredsid
, errp
);
1996 /* TODO SOCKET_ADDRESS_KIND_FD where fd has AF_INET or AF_INET6 */
1997 if (s
->saddr
->type
!= SOCKET_ADDRESS_TYPE_INET
) {
1998 error_setg(errp
, "TLS only supported over IP sockets");
2001 s
->hostname
= s
->saddr
->u
.inet
.host
;
2004 s
->x_dirty_bitmap
= g_strdup(qemu_opt_get(opts
, "x-dirty-bitmap"));
2005 if (s
->x_dirty_bitmap
&& strlen(s
->x_dirty_bitmap
) > NBD_MAX_STRING_SIZE
) {
2006 error_setg(errp
, "x-dirty-bitmap query too long to send to server");
2010 s
->reconnect_delay
= qemu_opt_get_number(opts
, "reconnect-delay", 0);
2015 qemu_opts_del(opts
);
2019 static int nbd_open(BlockDriverState
*bs
, QDict
*options
, int flags
,
2023 BDRVNBDState
*s
= (BDRVNBDState
*)bs
->opaque
;
2026 qemu_co_mutex_init(&s
->send_mutex
);
2027 qemu_co_queue_init(&s
->free_sema
);
2029 if (!yank_register_instance(BLOCKDEV_YANK_INSTANCE(bs
->node_name
), errp
)) {
2033 ret
= nbd_process_options(bs
, options
, errp
);
2038 s
->conn
= nbd_client_connection_new(s
->saddr
);
2041 * establish TCP connection, return error if it fails
2042 * TODO: Configurable retry-until-timeout behaviour.
2044 if (nbd_establish_connection(bs
, s
->saddr
, errp
) < 0) {
2045 ret
= -ECONNREFUSED
;
2049 ret
= nbd_client_handshake(bs
, errp
);
2053 /* successfully connected */
2054 s
->state
= NBD_CLIENT_CONNECTED
;
2056 s
->connection_co
= qemu_coroutine_create(nbd_connection_entry
, s
);
2057 bdrv_inc_in_flight(bs
);
2058 aio_co_schedule(bdrv_get_aio_context(bs
), s
->connection_co
);
2063 nbd_clear_bdrvstate(bs
);
2067 static int nbd_co_flush(BlockDriverState
*bs
)
2069 return nbd_client_co_flush(bs
);
2072 static void nbd_refresh_limits(BlockDriverState
*bs
, Error
**errp
)
2074 BDRVNBDState
*s
= (BDRVNBDState
*)bs
->opaque
;
2075 uint32_t min
= s
->info
.min_block
;
2076 uint32_t max
= MIN_NON_ZERO(NBD_MAX_BUFFER_SIZE
, s
->info
.max_block
);
2079 * If the server did not advertise an alignment:
2080 * - a size that is not sector-aligned implies that an alignment
2081 * of 1 can be used to access those tail bytes
2082 * - advertisement of block status requires an alignment of 1, so
2083 * that we don't violate block layer constraints that block
2084 * status is always aligned (as we can't control whether the
2085 * server will report sub-sector extents, such as a hole at EOF
2086 * on an unaligned POSIX file)
2087 * - otherwise, assume the server is so old that we are safer avoiding
2088 * sub-sector requests
2091 min
= (!QEMU_IS_ALIGNED(s
->info
.size
, BDRV_SECTOR_SIZE
) ||
2092 s
->info
.base_allocation
) ? 1 : BDRV_SECTOR_SIZE
;
2095 bs
->bl
.request_alignment
= min
;
2096 bs
->bl
.max_pdiscard
= QEMU_ALIGN_DOWN(INT_MAX
, min
);
2097 bs
->bl
.max_pwrite_zeroes
= max
;
2098 bs
->bl
.max_transfer
= max
;
2100 if (s
->info
.opt_block
&&
2101 s
->info
.opt_block
> bs
->bl
.opt_transfer
) {
2102 bs
->bl
.opt_transfer
= s
->info
.opt_block
;
2106 static void nbd_close(BlockDriverState
*bs
)
2108 nbd_client_close(bs
);
2109 nbd_clear_bdrvstate(bs
);
2113 * NBD cannot truncate, but if the caller asks to truncate to the same size, or
2114 * to a smaller size with exact=false, there is no reason to fail the
2117 * Preallocation mode is ignored since it does not seems useful to fail when
2118 * we never change anything.
2120 static int coroutine_fn
nbd_co_truncate(BlockDriverState
*bs
, int64_t offset
,
2121 bool exact
, PreallocMode prealloc
,
2122 BdrvRequestFlags flags
, Error
**errp
)
2124 BDRVNBDState
*s
= bs
->opaque
;
2126 if (offset
!= s
->info
.size
&& exact
) {
2127 error_setg(errp
, "Cannot resize NBD nodes");
2131 if (offset
> s
->info
.size
) {
2132 error_setg(errp
, "Cannot grow NBD nodes");
2139 static int64_t nbd_getlength(BlockDriverState
*bs
)
2141 BDRVNBDState
*s
= bs
->opaque
;
2143 return s
->info
.size
;
2146 static void nbd_refresh_filename(BlockDriverState
*bs
)
2148 BDRVNBDState
*s
= bs
->opaque
;
2149 const char *host
= NULL
, *port
= NULL
, *path
= NULL
;
2152 if (s
->saddr
->type
== SOCKET_ADDRESS_TYPE_INET
) {
2153 const InetSocketAddress
*inet
= &s
->saddr
->u
.inet
;
2154 if (!inet
->has_ipv4
&& !inet
->has_ipv6
&& !inet
->has_to
) {
2158 } else if (s
->saddr
->type
== SOCKET_ADDRESS_TYPE_UNIX
) {
2159 path
= s
->saddr
->u
.q_unix
.path
;
2160 } /* else can't represent as pseudo-filename */
2162 if (path
&& s
->export
) {
2163 len
= snprintf(bs
->exact_filename
, sizeof(bs
->exact_filename
),
2164 "nbd+unix:///%s?socket=%s", s
->export
, path
);
2165 } else if (path
&& !s
->export
) {
2166 len
= snprintf(bs
->exact_filename
, sizeof(bs
->exact_filename
),
2167 "nbd+unix://?socket=%s", path
);
2168 } else if (host
&& s
->export
) {
2169 len
= snprintf(bs
->exact_filename
, sizeof(bs
->exact_filename
),
2170 "nbd://%s:%s/%s", host
, port
, s
->export
);
2171 } else if (host
&& !s
->export
) {
2172 len
= snprintf(bs
->exact_filename
, sizeof(bs
->exact_filename
),
2173 "nbd://%s:%s", host
, port
);
2175 if (len
>= sizeof(bs
->exact_filename
)) {
2176 /* Name is too long to represent exactly, so leave it empty. */
2177 bs
->exact_filename
[0] = '\0';
2181 static char *nbd_dirname(BlockDriverState
*bs
, Error
**errp
)
2183 /* The generic bdrv_dirname() implementation is able to work out some
2184 * directory name for NBD nodes, but that would be wrong. So far there is no
2185 * specification for how "export paths" would work, so NBD does not have
2186 * directory names. */
2187 error_setg(errp
, "Cannot generate a base directory for NBD nodes");
2191 static const char *const nbd_strong_runtime_opts
[] = {
2202 static void nbd_cancel_in_flight(BlockDriverState
*bs
)
2204 BDRVNBDState
*s
= (BDRVNBDState
*)bs
->opaque
;
2206 reconnect_delay_timer_del(s
);
2208 if (s
->state
== NBD_CLIENT_CONNECTING_WAIT
) {
2209 s
->state
= NBD_CLIENT_CONNECTING_NOWAIT
;
2210 qemu_co_queue_restart_all(&s
->free_sema
);
2214 static BlockDriver bdrv_nbd
= {
2215 .format_name
= "nbd",
2216 .protocol_name
= "nbd",
2217 .instance_size
= sizeof(BDRVNBDState
),
2218 .bdrv_parse_filename
= nbd_parse_filename
,
2219 .bdrv_co_create_opts
= bdrv_co_create_opts_simple
,
2220 .create_opts
= &bdrv_create_opts_simple
,
2221 .bdrv_file_open
= nbd_open
,
2222 .bdrv_reopen_prepare
= nbd_client_reopen_prepare
,
2223 .bdrv_co_preadv
= nbd_client_co_preadv
,
2224 .bdrv_co_pwritev
= nbd_client_co_pwritev
,
2225 .bdrv_co_pwrite_zeroes
= nbd_client_co_pwrite_zeroes
,
2226 .bdrv_close
= nbd_close
,
2227 .bdrv_co_flush_to_os
= nbd_co_flush
,
2228 .bdrv_co_pdiscard
= nbd_client_co_pdiscard
,
2229 .bdrv_refresh_limits
= nbd_refresh_limits
,
2230 .bdrv_co_truncate
= nbd_co_truncate
,
2231 .bdrv_getlength
= nbd_getlength
,
2232 .bdrv_detach_aio_context
= nbd_client_detach_aio_context
,
2233 .bdrv_attach_aio_context
= nbd_client_attach_aio_context
,
2234 .bdrv_co_drain_begin
= nbd_client_co_drain_begin
,
2235 .bdrv_co_drain_end
= nbd_client_co_drain_end
,
2236 .bdrv_refresh_filename
= nbd_refresh_filename
,
2237 .bdrv_co_block_status
= nbd_client_co_block_status
,
2238 .bdrv_dirname
= nbd_dirname
,
2239 .strong_runtime_opts
= nbd_strong_runtime_opts
,
2240 .bdrv_cancel_in_flight
= nbd_cancel_in_flight
,
2243 static BlockDriver bdrv_nbd_tcp
= {
2244 .format_name
= "nbd",
2245 .protocol_name
= "nbd+tcp",
2246 .instance_size
= sizeof(BDRVNBDState
),
2247 .bdrv_parse_filename
= nbd_parse_filename
,
2248 .bdrv_co_create_opts
= bdrv_co_create_opts_simple
,
2249 .create_opts
= &bdrv_create_opts_simple
,
2250 .bdrv_file_open
= nbd_open
,
2251 .bdrv_reopen_prepare
= nbd_client_reopen_prepare
,
2252 .bdrv_co_preadv
= nbd_client_co_preadv
,
2253 .bdrv_co_pwritev
= nbd_client_co_pwritev
,
2254 .bdrv_co_pwrite_zeroes
= nbd_client_co_pwrite_zeroes
,
2255 .bdrv_close
= nbd_close
,
2256 .bdrv_co_flush_to_os
= nbd_co_flush
,
2257 .bdrv_co_pdiscard
= nbd_client_co_pdiscard
,
2258 .bdrv_refresh_limits
= nbd_refresh_limits
,
2259 .bdrv_co_truncate
= nbd_co_truncate
,
2260 .bdrv_getlength
= nbd_getlength
,
2261 .bdrv_detach_aio_context
= nbd_client_detach_aio_context
,
2262 .bdrv_attach_aio_context
= nbd_client_attach_aio_context
,
2263 .bdrv_co_drain_begin
= nbd_client_co_drain_begin
,
2264 .bdrv_co_drain_end
= nbd_client_co_drain_end
,
2265 .bdrv_refresh_filename
= nbd_refresh_filename
,
2266 .bdrv_co_block_status
= nbd_client_co_block_status
,
2267 .bdrv_dirname
= nbd_dirname
,
2268 .strong_runtime_opts
= nbd_strong_runtime_opts
,
2269 .bdrv_cancel_in_flight
= nbd_cancel_in_flight
,
2272 static BlockDriver bdrv_nbd_unix
= {
2273 .format_name
= "nbd",
2274 .protocol_name
= "nbd+unix",
2275 .instance_size
= sizeof(BDRVNBDState
),
2276 .bdrv_parse_filename
= nbd_parse_filename
,
2277 .bdrv_co_create_opts
= bdrv_co_create_opts_simple
,
2278 .create_opts
= &bdrv_create_opts_simple
,
2279 .bdrv_file_open
= nbd_open
,
2280 .bdrv_reopen_prepare
= nbd_client_reopen_prepare
,
2281 .bdrv_co_preadv
= nbd_client_co_preadv
,
2282 .bdrv_co_pwritev
= nbd_client_co_pwritev
,
2283 .bdrv_co_pwrite_zeroes
= nbd_client_co_pwrite_zeroes
,
2284 .bdrv_close
= nbd_close
,
2285 .bdrv_co_flush_to_os
= nbd_co_flush
,
2286 .bdrv_co_pdiscard
= nbd_client_co_pdiscard
,
2287 .bdrv_refresh_limits
= nbd_refresh_limits
,
2288 .bdrv_co_truncate
= nbd_co_truncate
,
2289 .bdrv_getlength
= nbd_getlength
,
2290 .bdrv_detach_aio_context
= nbd_client_detach_aio_context
,
2291 .bdrv_attach_aio_context
= nbd_client_attach_aio_context
,
2292 .bdrv_co_drain_begin
= nbd_client_co_drain_begin
,
2293 .bdrv_co_drain_end
= nbd_client_co_drain_end
,
2294 .bdrv_refresh_filename
= nbd_refresh_filename
,
2295 .bdrv_co_block_status
= nbd_client_co_block_status
,
2296 .bdrv_dirname
= nbd_dirname
,
2297 .strong_runtime_opts
= nbd_strong_runtime_opts
,
2298 .bdrv_cancel_in_flight
= nbd_cancel_in_flight
,
2301 static void bdrv_nbd_init(void)
2303 bdrv_register(&bdrv_nbd
);
2304 bdrv_register(&bdrv_nbd_tcp
);
2305 bdrv_register(&bdrv_nbd_unix
);
2308 block_init(bdrv_nbd_init
);