2 * QEMU Block driver for NBD
4 * Copyright (c) 2019 Virtuozzo International GmbH.
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"
41 #include "qapi/clone-visitor.h"
43 #include "block/qdict.h"
44 #include "block/nbd.h"
45 #include "block/block_int.h"
46 #include "block/coroutines.h"
48 #include "qemu/yank.h"
50 #define EN_OPTSTR ":exportname="
51 #define MAX_NBD_REQUESTS 16
53 #define COOKIE_TO_INDEX(cookie) ((cookie) - 1)
54 #define INDEX_TO_COOKIE(index) ((index) + 1)
58 uint64_t offset
; /* original offset of the request */
59 bool receiving
; /* sleeping in the yield in nbd_receive_replies */
62 typedef enum NBDClientState
{
63 NBD_CLIENT_CONNECTING_WAIT
,
64 NBD_CLIENT_CONNECTING_NOWAIT
,
69 typedef struct BDRVNBDState
{
70 QIOChannel
*ioc
; /* The current I/O channel */
74 * Protects state, free_sema, in_flight, requests[].coroutine,
75 * reconnect_delay_timer.
77 QemuMutex requests_lock
;
81 NBDClientRequest requests
[MAX_NBD_REQUESTS
];
82 QEMUTimer
*reconnect_delay_timer
;
84 /* Protects sending data on the socket. */
88 * Protects receiving reply headers from the socket, as well as the
89 * fields reply and requests[].receiving
91 CoMutex receive_mutex
;
94 QEMUTimer
*open_timer
;
98 /* Connection parameters */
99 uint32_t reconnect_delay
;
100 uint32_t open_timeout
;
101 SocketAddress
*saddr
;
104 QCryptoTLSCreds
*tlscreds
;
106 char *x_dirty_bitmap
;
109 NBDClientConnection
*conn
;
112 static void nbd_yank(void *opaque
);
114 static void nbd_clear_bdrvstate(BlockDriverState
*bs
)
116 BDRVNBDState
*s
= (BDRVNBDState
*)bs
->opaque
;
118 nbd_client_connection_release(s
->conn
);
121 yank_unregister_instance(BLOCKDEV_YANK_INSTANCE(bs
->node_name
));
123 /* Must not leave timers behind that would access freed data */
124 assert(!s
->reconnect_delay_timer
);
125 assert(!s
->open_timer
);
127 object_unref(OBJECT(s
->tlscreds
));
128 qapi_free_SocketAddress(s
->saddr
);
132 g_free(s
->tlscredsid
);
133 s
->tlscredsid
= NULL
;
134 g_free(s
->tlshostname
);
135 s
->tlshostname
= NULL
;
136 g_free(s
->x_dirty_bitmap
);
137 s
->x_dirty_bitmap
= NULL
;
140 /* Called with s->receive_mutex taken. */
141 static bool coroutine_fn
nbd_recv_coroutine_wake_one(NBDClientRequest
*req
)
143 if (req
->receiving
) {
144 req
->receiving
= false;
145 aio_co_wake(req
->coroutine
);
152 static void coroutine_fn
nbd_recv_coroutines_wake(BDRVNBDState
*s
)
156 QEMU_LOCK_GUARD(&s
->receive_mutex
);
157 for (i
= 0; i
< MAX_NBD_REQUESTS
; i
++) {
158 if (nbd_recv_coroutine_wake_one(&s
->requests
[i
])) {
164 /* Called with s->requests_lock held. */
165 static void coroutine_fn
nbd_channel_error_locked(BDRVNBDState
*s
, int ret
)
167 if (s
->state
== NBD_CLIENT_CONNECTED
) {
168 qio_channel_shutdown(s
->ioc
, QIO_CHANNEL_SHUTDOWN_BOTH
, NULL
);
172 if (s
->state
== NBD_CLIENT_CONNECTED
) {
173 s
->state
= s
->reconnect_delay
? NBD_CLIENT_CONNECTING_WAIT
:
174 NBD_CLIENT_CONNECTING_NOWAIT
;
177 s
->state
= NBD_CLIENT_QUIT
;
181 static void coroutine_fn
nbd_channel_error(BDRVNBDState
*s
, int ret
)
183 QEMU_LOCK_GUARD(&s
->requests_lock
);
184 nbd_channel_error_locked(s
, ret
);
187 static void reconnect_delay_timer_del(BDRVNBDState
*s
)
189 if (s
->reconnect_delay_timer
) {
190 timer_free(s
->reconnect_delay_timer
);
191 s
->reconnect_delay_timer
= NULL
;
195 static void reconnect_delay_timer_cb(void *opaque
)
197 BDRVNBDState
*s
= opaque
;
199 reconnect_delay_timer_del(s
);
200 WITH_QEMU_LOCK_GUARD(&s
->requests_lock
) {
201 if (s
->state
!= NBD_CLIENT_CONNECTING_WAIT
) {
204 s
->state
= NBD_CLIENT_CONNECTING_NOWAIT
;
206 nbd_co_establish_connection_cancel(s
->conn
);
209 static void reconnect_delay_timer_init(BDRVNBDState
*s
, uint64_t expire_time_ns
)
211 assert(!s
->reconnect_delay_timer
);
212 s
->reconnect_delay_timer
= aio_timer_new(bdrv_get_aio_context(s
->bs
),
215 reconnect_delay_timer_cb
, s
);
216 timer_mod(s
->reconnect_delay_timer
, expire_time_ns
);
219 static void nbd_teardown_connection(BlockDriverState
*bs
)
221 BDRVNBDState
*s
= (BDRVNBDState
*)bs
->opaque
;
223 assert(!s
->in_flight
);
226 qio_channel_shutdown(s
->ioc
, QIO_CHANNEL_SHUTDOWN_BOTH
, NULL
);
227 yank_unregister_function(BLOCKDEV_YANK_INSTANCE(s
->bs
->node_name
),
229 object_unref(OBJECT(s
->ioc
));
233 WITH_QEMU_LOCK_GUARD(&s
->requests_lock
) {
234 s
->state
= NBD_CLIENT_QUIT
;
238 static void open_timer_del(BDRVNBDState
*s
)
241 timer_free(s
->open_timer
);
242 s
->open_timer
= NULL
;
246 static void open_timer_cb(void *opaque
)
248 BDRVNBDState
*s
= opaque
;
250 nbd_co_establish_connection_cancel(s
->conn
);
254 static void open_timer_init(BDRVNBDState
*s
, uint64_t expire_time_ns
)
256 assert(!s
->open_timer
);
257 s
->open_timer
= aio_timer_new(bdrv_get_aio_context(s
->bs
),
261 timer_mod(s
->open_timer
, expire_time_ns
);
264 static bool nbd_client_will_reconnect(BDRVNBDState
*s
)
267 * Called only after a socket error, so this is not performance sensitive.
269 QEMU_LOCK_GUARD(&s
->requests_lock
);
270 return s
->state
== NBD_CLIENT_CONNECTING_WAIT
;
274 * Update @bs with information learned during a completed negotiation process.
275 * Return failure if the server's advertised options are incompatible with the
278 static int nbd_handle_updated_info(BlockDriverState
*bs
, Error
**errp
)
280 BDRVNBDState
*s
= (BDRVNBDState
*)bs
->opaque
;
283 if (s
->x_dirty_bitmap
) {
284 if (!s
->info
.base_allocation
) {
285 error_setg(errp
, "requested x-dirty-bitmap %s not found",
289 if (strcmp(s
->x_dirty_bitmap
, "qemu:allocation-depth") == 0) {
290 s
->alloc_depth
= true;
294 if (s
->info
.flags
& NBD_FLAG_READ_ONLY
) {
295 ret
= bdrv_apply_auto_read_only(bs
, "NBD export is read-only", errp
);
301 if (s
->info
.flags
& NBD_FLAG_SEND_FUA
) {
302 bs
->supported_write_flags
= BDRV_REQ_FUA
;
303 bs
->supported_zero_flags
|= BDRV_REQ_FUA
;
306 if (s
->info
.flags
& NBD_FLAG_SEND_WRITE_ZEROES
) {
307 bs
->supported_zero_flags
|= BDRV_REQ_MAY_UNMAP
;
308 if (s
->info
.flags
& NBD_FLAG_SEND_FAST_ZERO
) {
309 bs
->supported_zero_flags
|= BDRV_REQ_NO_FALLBACK
;
313 trace_nbd_client_handshake_success(s
->export
);
318 int coroutine_fn
nbd_co_do_establish_connection(BlockDriverState
*bs
,
319 bool blocking
, Error
**errp
)
321 BDRVNBDState
*s
= (BDRVNBDState
*)bs
->opaque
;
325 assert_bdrv_graph_readable();
328 s
->ioc
= nbd_co_establish_connection(s
->conn
, &s
->info
, blocking
, errp
);
330 return -ECONNREFUSED
;
333 yank_register_function(BLOCKDEV_YANK_INSTANCE(s
->bs
->node_name
), nbd_yank
,
336 ret
= nbd_handle_updated_info(s
->bs
, NULL
);
339 * We have connected, but must fail for other reasons.
340 * Send NBD_CMD_DISC as a courtesy to the server.
342 NBDRequest request
= { .type
= NBD_CMD_DISC
, .mode
= s
->info
.mode
};
344 nbd_send_request(s
->ioc
, &request
);
346 yank_unregister_function(BLOCKDEV_YANK_INSTANCE(s
->bs
->node_name
),
348 object_unref(OBJECT(s
->ioc
));
354 qio_channel_set_blocking(s
->ioc
, false, NULL
);
355 qio_channel_set_follow_coroutine_ctx(s
->ioc
, true);
357 /* successfully connected */
358 WITH_QEMU_LOCK_GUARD(&s
->requests_lock
) {
359 s
->state
= NBD_CLIENT_CONNECTED
;
365 /* Called with s->requests_lock held. */
366 static bool nbd_client_connecting(BDRVNBDState
*s
)
368 return s
->state
== NBD_CLIENT_CONNECTING_WAIT
||
369 s
->state
== NBD_CLIENT_CONNECTING_NOWAIT
;
372 /* Called with s->requests_lock taken. */
373 static void coroutine_fn GRAPH_RDLOCK
nbd_reconnect_attempt(BDRVNBDState
*s
)
376 bool blocking
= s
->state
== NBD_CLIENT_CONNECTING_WAIT
;
379 * Now we are sure that nobody is accessing the channel, and no one will
380 * try until we set the state to CONNECTED.
382 assert(nbd_client_connecting(s
));
383 assert(s
->in_flight
== 1);
385 trace_nbd_reconnect_attempt(s
->bs
->in_flight
);
387 if (blocking
&& !s
->reconnect_delay_timer
) {
389 * It's the first reconnect attempt after switching to
390 * NBD_CLIENT_CONNECTING_WAIT
392 g_assert(s
->reconnect_delay
);
393 reconnect_delay_timer_init(s
,
394 qemu_clock_get_ns(QEMU_CLOCK_REALTIME
) +
395 s
->reconnect_delay
* NANOSECONDS_PER_SECOND
);
398 /* Finalize previous connection if any */
400 yank_unregister_function(BLOCKDEV_YANK_INSTANCE(s
->bs
->node_name
),
402 object_unref(OBJECT(s
->ioc
));
406 qemu_mutex_unlock(&s
->requests_lock
);
407 ret
= nbd_co_do_establish_connection(s
->bs
, blocking
, NULL
);
408 trace_nbd_reconnect_attempt_result(ret
, s
->bs
->in_flight
);
409 qemu_mutex_lock(&s
->requests_lock
);
412 * The reconnect attempt is done (maybe successfully, maybe not), so
413 * we no longer need this timer. Delete it so it will not outlive
414 * this I/O request (so draining removes all timers).
416 reconnect_delay_timer_del(s
);
419 static coroutine_fn
int nbd_receive_replies(BDRVNBDState
*s
, uint64_t cookie
)
422 uint64_t ind
= COOKIE_TO_INDEX(cookie
), ind2
;
423 QEMU_LOCK_GUARD(&s
->receive_mutex
);
426 if (s
->reply
.cookie
== cookie
) {
431 if (s
->reply
.cookie
!= 0) {
433 * Some other request is being handled now. It should already be
434 * woken by whoever set s->reply.cookie (or never wait in this
435 * yield). So, we should not wake it here.
437 ind2
= COOKIE_TO_INDEX(s
->reply
.cookie
);
438 assert(!s
->requests
[ind2
].receiving
);
440 s
->requests
[ind
].receiving
= true;
441 qemu_co_mutex_unlock(&s
->receive_mutex
);
443 qemu_coroutine_yield();
445 * We may be woken for 2 reasons:
446 * 1. From this function, executing in parallel coroutine, when our
447 * cookie is received.
448 * 2. From nbd_co_receive_one_chunk(), when previous request is
449 * finished and s->reply.cookie set to 0.
450 * Anyway, it's OK to lock the mutex and go to the next iteration.
453 qemu_co_mutex_lock(&s
->receive_mutex
);
454 assert(!s
->requests
[ind
].receiving
);
458 /* We are under mutex and cookie is 0. We have to do the dirty work. */
459 assert(s
->reply
.cookie
== 0);
460 ret
= nbd_receive_reply(s
->bs
, s
->ioc
, &s
->reply
, NULL
);
462 ret
= ret
? ret
: -EIO
;
463 nbd_channel_error(s
, ret
);
466 if (nbd_reply_is_structured(&s
->reply
) &&
467 s
->info
.mode
< NBD_MODE_STRUCTURED
) {
468 nbd_channel_error(s
, -EINVAL
);
471 ind2
= COOKIE_TO_INDEX(s
->reply
.cookie
);
472 if (ind2
>= MAX_NBD_REQUESTS
|| !s
->requests
[ind2
].coroutine
) {
473 nbd_channel_error(s
, -EINVAL
);
476 if (s
->reply
.cookie
== cookie
) {
480 nbd_recv_coroutine_wake_one(&s
->requests
[ind2
]);
484 static int coroutine_fn GRAPH_RDLOCK
485 nbd_co_send_request(BlockDriverState
*bs
, NBDRequest
*request
,
488 BDRVNBDState
*s
= (BDRVNBDState
*)bs
->opaque
;
491 qemu_mutex_lock(&s
->requests_lock
);
492 while (s
->in_flight
== MAX_NBD_REQUESTS
||
493 (s
->state
!= NBD_CLIENT_CONNECTED
&& s
->in_flight
> 0)) {
494 qemu_co_queue_wait(&s
->free_sema
, &s
->requests_lock
);
498 if (s
->state
!= NBD_CLIENT_CONNECTED
) {
499 if (nbd_client_connecting(s
)) {
500 nbd_reconnect_attempt(s
);
501 qemu_co_queue_restart_all(&s
->free_sema
);
503 if (s
->state
!= NBD_CLIENT_CONNECTED
) {
509 for (i
= 0; i
< MAX_NBD_REQUESTS
; i
++) {
510 if (s
->requests
[i
].coroutine
== NULL
) {
515 assert(i
< MAX_NBD_REQUESTS
);
516 s
->requests
[i
].coroutine
= qemu_coroutine_self();
517 s
->requests
[i
].offset
= request
->from
;
518 s
->requests
[i
].receiving
= false;
519 qemu_mutex_unlock(&s
->requests_lock
);
521 qemu_co_mutex_lock(&s
->send_mutex
);
522 request
->cookie
= INDEX_TO_COOKIE(i
);
523 request
->mode
= s
->info
.mode
;
528 qio_channel_set_cork(s
->ioc
, true);
529 rc
= nbd_send_request(s
->ioc
, request
);
530 if (rc
>= 0 && qio_channel_writev_all(s
->ioc
, qiov
->iov
, qiov
->niov
,
534 qio_channel_set_cork(s
->ioc
, false);
536 rc
= nbd_send_request(s
->ioc
, request
);
538 qemu_co_mutex_unlock(&s
->send_mutex
);
541 qemu_mutex_lock(&s
->requests_lock
);
543 nbd_channel_error_locked(s
, rc
);
545 s
->requests
[i
].coroutine
= NULL
;
548 qemu_co_queue_next(&s
->free_sema
);
549 qemu_mutex_unlock(&s
->requests_lock
);
554 static inline uint16_t payload_advance16(uint8_t **payload
)
557 return lduw_be_p(*payload
- 2);
560 static inline uint32_t payload_advance32(uint8_t **payload
)
563 return ldl_be_p(*payload
- 4);
566 static inline uint64_t payload_advance64(uint8_t **payload
)
569 return ldq_be_p(*payload
- 8);
572 static int nbd_parse_offset_hole_payload(BDRVNBDState
*s
,
573 NBDStructuredReplyChunk
*chunk
,
574 uint8_t *payload
, uint64_t orig_offset
,
575 QEMUIOVector
*qiov
, Error
**errp
)
580 if (chunk
->length
!= sizeof(offset
) + sizeof(hole_size
)) {
581 error_setg(errp
, "Protocol error: invalid payload for "
582 "NBD_REPLY_TYPE_OFFSET_HOLE");
586 offset
= payload_advance64(&payload
);
587 hole_size
= payload_advance32(&payload
);
589 if (!hole_size
|| offset
< orig_offset
|| hole_size
> qiov
->size
||
590 offset
> orig_offset
+ qiov
->size
- hole_size
) {
591 error_setg(errp
, "Protocol error: server sent chunk exceeding requested"
595 if (s
->info
.min_block
&&
596 !QEMU_IS_ALIGNED(hole_size
, s
->info
.min_block
)) {
597 trace_nbd_structured_read_compliance("hole");
600 qemu_iovec_memset(qiov
, offset
- orig_offset
, 0, hole_size
);
606 * nbd_parse_blockstatus_payload
607 * Based on our request, we expect only one extent in reply, for the
608 * base:allocation context.
610 static int nbd_parse_blockstatus_payload(BDRVNBDState
*s
,
611 NBDStructuredReplyChunk
*chunk
,
612 uint8_t *payload
, uint64_t orig_length
,
613 NBDExtent
*extent
, Error
**errp
)
617 /* The server succeeded, so it must have sent [at least] one extent */
618 if (chunk
->length
< sizeof(context_id
) + sizeof(*extent
)) {
619 error_setg(errp
, "Protocol error: invalid payload for "
620 "NBD_REPLY_TYPE_BLOCK_STATUS");
624 context_id
= payload_advance32(&payload
);
625 if (s
->info
.context_id
!= context_id
) {
626 error_setg(errp
, "Protocol error: unexpected context id %d for "
627 "NBD_REPLY_TYPE_BLOCK_STATUS, when negotiated context "
628 "id is %d", context_id
,
633 extent
->length
= payload_advance32(&payload
);
634 extent
->flags
= payload_advance32(&payload
);
636 if (extent
->length
== 0) {
637 error_setg(errp
, "Protocol error: server sent status chunk with "
643 * A server sending unaligned block status is in violation of the
644 * protocol, but as qemu-nbd 3.1 is such a server (at least for
645 * POSIX files that are not a multiple of 512 bytes, since qemu
646 * rounds files up to 512-byte multiples but lseek(SEEK_HOLE)
647 * still sees an implicit hole beyond the real EOF), it's nicer to
648 * work around the misbehaving server. If the request included
649 * more than the final unaligned block, truncate it back to an
650 * aligned result; if the request was only the final block, round
651 * up to the full block and change the status to fully-allocated
652 * (always a safe status, even if it loses information).
654 if (s
->info
.min_block
&& !QEMU_IS_ALIGNED(extent
->length
,
655 s
->info
.min_block
)) {
656 trace_nbd_parse_blockstatus_compliance("extent length is unaligned");
657 if (extent
->length
> s
->info
.min_block
) {
658 extent
->length
= QEMU_ALIGN_DOWN(extent
->length
,
661 extent
->length
= s
->info
.min_block
;
667 * We used NBD_CMD_FLAG_REQ_ONE, so the server should not have
668 * sent us any more than one extent, nor should it have included
669 * status beyond our request in that extent. However, it's easy
670 * enough to ignore the server's noncompliance without killing the
671 * connection; just ignore trailing extents, and clamp things to
672 * the length of our request.
674 if (chunk
->length
> sizeof(context_id
) + sizeof(*extent
)) {
675 trace_nbd_parse_blockstatus_compliance("more than one extent");
677 if (extent
->length
> orig_length
) {
678 extent
->length
= orig_length
;
679 trace_nbd_parse_blockstatus_compliance("extent length too large");
683 * HACK: if we are using x-dirty-bitmaps to access
684 * qemu:allocation-depth, treat all depths > 2 the same as 2,
685 * since nbd_client_co_block_status is only expecting the low two
688 if (s
->alloc_depth
&& extent
->flags
> 2) {
696 * nbd_parse_error_payload
697 * on success @errp contains message describing nbd error reply
699 static int nbd_parse_error_payload(NBDStructuredReplyChunk
*chunk
,
700 uint8_t *payload
, int *request_ret
,
704 uint16_t message_size
;
706 assert(chunk
->type
& (1 << 15));
708 if (chunk
->length
< sizeof(error
) + sizeof(message_size
)) {
710 "Protocol error: invalid payload for structured error");
714 error
= nbd_errno_to_system_errno(payload_advance32(&payload
));
716 error_setg(errp
, "Protocol error: server sent structured error chunk "
721 *request_ret
= -error
;
722 message_size
= payload_advance16(&payload
);
724 if (message_size
> chunk
->length
- sizeof(error
) - sizeof(message_size
)) {
725 error_setg(errp
, "Protocol error: server sent structured error chunk "
726 "with incorrect message size");
730 /* TODO: Add a trace point to mention the server complaint */
732 /* TODO handle ERROR_OFFSET */
737 static int coroutine_fn
738 nbd_co_receive_offset_data_payload(BDRVNBDState
*s
, uint64_t orig_offset
,
739 QEMUIOVector
*qiov
, Error
**errp
)
741 QEMUIOVector sub_qiov
;
745 NBDStructuredReplyChunk
*chunk
= &s
->reply
.structured
;
747 assert(nbd_reply_is_structured(&s
->reply
));
749 /* The NBD spec requires at least one byte of payload */
750 if (chunk
->length
<= sizeof(offset
)) {
751 error_setg(errp
, "Protocol error: invalid payload for "
752 "NBD_REPLY_TYPE_OFFSET_DATA");
756 if (nbd_read64(s
->ioc
, &offset
, "OFFSET_DATA offset", errp
) < 0) {
760 data_size
= chunk
->length
- sizeof(offset
);
762 if (offset
< orig_offset
|| data_size
> qiov
->size
||
763 offset
> orig_offset
+ qiov
->size
- data_size
) {
764 error_setg(errp
, "Protocol error: server sent chunk exceeding requested"
768 if (s
->info
.min_block
&& !QEMU_IS_ALIGNED(data_size
, s
->info
.min_block
)) {
769 trace_nbd_structured_read_compliance("data");
772 qemu_iovec_init(&sub_qiov
, qiov
->niov
);
773 qemu_iovec_concat(&sub_qiov
, qiov
, offset
- orig_offset
, data_size
);
774 ret
= qio_channel_readv_all(s
->ioc
, sub_qiov
.iov
, sub_qiov
.niov
, errp
);
775 qemu_iovec_destroy(&sub_qiov
);
777 return ret
< 0 ? -EIO
: 0;
780 #define NBD_MAX_MALLOC_PAYLOAD 1000
781 static coroutine_fn
int nbd_co_receive_structured_payload(
782 BDRVNBDState
*s
, void **payload
, Error
**errp
)
787 assert(nbd_reply_is_structured(&s
->reply
));
789 len
= s
->reply
.structured
.length
;
795 if (payload
== NULL
) {
796 error_setg(errp
, "Unexpected structured payload");
800 if (len
> NBD_MAX_MALLOC_PAYLOAD
) {
801 error_setg(errp
, "Payload too large");
805 *payload
= g_new(char, len
);
806 ret
= nbd_read(s
->ioc
, *payload
, len
, "structured payload", errp
);
817 * nbd_co_do_receive_one_chunk
819 * set request_ret to received reply error
820 * if qiov is not NULL: read payload to @qiov
821 * for structured reply chunk:
822 * if error chunk: read payload, set @request_ret, do not set @payload
823 * else if offset_data chunk: read payload data to @qiov, do not set @payload
824 * else: read payload to @payload
826 * If function fails, @errp contains corresponding error message, and the
827 * connection with the server is suspect. If it returns 0, then the
828 * transaction succeeded (although @request_ret may be a negative errno
829 * corresponding to the server's error reply), and errp is unchanged.
831 static coroutine_fn
int nbd_co_do_receive_one_chunk(
832 BDRVNBDState
*s
, uint64_t cookie
, bool only_structured
,
833 int *request_ret
, QEMUIOVector
*qiov
, void **payload
, Error
**errp
)
836 int i
= COOKIE_TO_INDEX(cookie
);
837 void *local_payload
= NULL
;
838 NBDStructuredReplyChunk
*chunk
;
845 ret
= nbd_receive_replies(s
, cookie
);
847 error_setg(errp
, "Connection closed");
852 assert(s
->reply
.cookie
== cookie
);
854 if (nbd_reply_is_simple(&s
->reply
)) {
855 if (only_structured
) {
856 error_setg(errp
, "Protocol error: simple reply when structured "
857 "reply chunk was expected");
861 *request_ret
= -nbd_errno_to_system_errno(s
->reply
.simple
.error
);
862 if (*request_ret
< 0 || !qiov
) {
866 return qio_channel_readv_all(s
->ioc
, qiov
->iov
, qiov
->niov
,
867 errp
) < 0 ? -EIO
: 0;
870 /* handle structured reply chunk */
871 assert(s
->info
.mode
>= NBD_MODE_STRUCTURED
);
872 chunk
= &s
->reply
.structured
;
874 if (chunk
->type
== NBD_REPLY_TYPE_NONE
) {
875 if (!(chunk
->flags
& NBD_REPLY_FLAG_DONE
)) {
876 error_setg(errp
, "Protocol error: NBD_REPLY_TYPE_NONE chunk without"
877 " NBD_REPLY_FLAG_DONE flag set");
881 error_setg(errp
, "Protocol error: NBD_REPLY_TYPE_NONE chunk with"
888 if (chunk
->type
== NBD_REPLY_TYPE_OFFSET_DATA
) {
890 error_setg(errp
, "Unexpected NBD_REPLY_TYPE_OFFSET_DATA chunk");
894 return nbd_co_receive_offset_data_payload(s
, s
->requests
[i
].offset
,
898 if (nbd_reply_type_is_error(chunk
->type
)) {
899 payload
= &local_payload
;
902 ret
= nbd_co_receive_structured_payload(s
, payload
, errp
);
907 if (nbd_reply_type_is_error(chunk
->type
)) {
908 ret
= nbd_parse_error_payload(chunk
, local_payload
, request_ret
, errp
);
909 g_free(local_payload
);
917 * nbd_co_receive_one_chunk
918 * Read reply, wake up connection_co and set s->quit if needed.
919 * Return value is a fatal error code or normal nbd reply error code
921 static coroutine_fn
int nbd_co_receive_one_chunk(
922 BDRVNBDState
*s
, uint64_t cookie
, bool only_structured
,
923 int *request_ret
, QEMUIOVector
*qiov
, NBDReply
*reply
, void **payload
,
926 int ret
= nbd_co_do_receive_one_chunk(s
, cookie
, only_structured
,
927 request_ret
, qiov
, payload
, errp
);
930 memset(reply
, 0, sizeof(*reply
));
931 nbd_channel_error(s
, ret
);
933 /* For assert at loop start in nbd_connection_entry */
938 nbd_recv_coroutines_wake(s
);
943 typedef struct NBDReplyChunkIter
{
947 bool done
, only_structured
;
950 static void nbd_iter_channel_error(NBDReplyChunkIter
*iter
,
951 int ret
, Error
**local_err
)
953 assert(local_err
&& *local_err
);
958 error_propagate(&iter
->err
, *local_err
);
960 error_free(*local_err
);
966 static void nbd_iter_request_error(NBDReplyChunkIter
*iter
, int ret
)
970 if (!iter
->request_ret
) {
971 iter
->request_ret
= ret
;
976 * NBD_FOREACH_REPLY_CHUNK
977 * The pointer stored in @payload requires g_free() to free it.
979 #define NBD_FOREACH_REPLY_CHUNK(s, iter, cookie, structured, \
980 qiov, reply, payload) \
981 for (iter = (NBDReplyChunkIter) { .only_structured = structured }; \
982 nbd_reply_chunk_iter_receive(s, &iter, cookie, qiov, reply, payload);)
985 * nbd_reply_chunk_iter_receive
986 * The pointer stored in @payload requires g_free() to free it.
988 static bool coroutine_fn
nbd_reply_chunk_iter_receive(BDRVNBDState
*s
,
989 NBDReplyChunkIter
*iter
,
995 int ret
, request_ret
;
996 NBDReply local_reply
;
997 NBDStructuredReplyChunk
*chunk
;
998 Error
*local_err
= NULL
;
1001 /* Previous iteration was last. */
1005 if (reply
== NULL
) {
1006 reply
= &local_reply
;
1009 ret
= nbd_co_receive_one_chunk(s
, cookie
, iter
->only_structured
,
1010 &request_ret
, qiov
, reply
, payload
,
1013 nbd_iter_channel_error(iter
, ret
, &local_err
);
1014 } else if (request_ret
< 0) {
1015 nbd_iter_request_error(iter
, request_ret
);
1018 /* Do not execute the body of NBD_FOREACH_REPLY_CHUNK for simple reply. */
1019 if (nbd_reply_is_simple(reply
) || iter
->ret
< 0) {
1023 chunk
= &reply
->structured
;
1024 iter
->only_structured
= true;
1026 if (chunk
->type
== NBD_REPLY_TYPE_NONE
) {
1027 /* NBD_REPLY_FLAG_DONE is already checked in nbd_co_receive_one_chunk */
1028 assert(chunk
->flags
& NBD_REPLY_FLAG_DONE
);
1032 if (chunk
->flags
& NBD_REPLY_FLAG_DONE
) {
1033 /* This iteration is last. */
1037 /* Execute the loop body */
1041 qemu_mutex_lock(&s
->requests_lock
);
1042 s
->requests
[COOKIE_TO_INDEX(cookie
)].coroutine
= NULL
;
1044 qemu_co_queue_next(&s
->free_sema
);
1045 qemu_mutex_unlock(&s
->requests_lock
);
1050 static int coroutine_fn
1051 nbd_co_receive_return_code(BDRVNBDState
*s
, uint64_t cookie
,
1052 int *request_ret
, Error
**errp
)
1054 NBDReplyChunkIter iter
;
1056 NBD_FOREACH_REPLY_CHUNK(s
, iter
, cookie
, false, NULL
, NULL
, NULL
) {
1057 /* nbd_reply_chunk_iter_receive does all the work */
1060 error_propagate(errp
, iter
.err
);
1061 *request_ret
= iter
.request_ret
;
1065 static int coroutine_fn
1066 nbd_co_receive_cmdread_reply(BDRVNBDState
*s
, uint64_t cookie
,
1067 uint64_t offset
, QEMUIOVector
*qiov
,
1068 int *request_ret
, Error
**errp
)
1070 NBDReplyChunkIter iter
;
1072 void *payload
= NULL
;
1073 Error
*local_err
= NULL
;
1075 NBD_FOREACH_REPLY_CHUNK(s
, iter
, cookie
,
1076 s
->info
.mode
>= NBD_MODE_STRUCTURED
,
1077 qiov
, &reply
, &payload
)
1080 NBDStructuredReplyChunk
*chunk
= &reply
.structured
;
1082 assert(nbd_reply_is_structured(&reply
));
1084 switch (chunk
->type
) {
1085 case NBD_REPLY_TYPE_OFFSET_DATA
:
1087 * special cased in nbd_co_receive_one_chunk, data is already
1091 case NBD_REPLY_TYPE_OFFSET_HOLE
:
1092 ret
= nbd_parse_offset_hole_payload(s
, &reply
.structured
, payload
,
1093 offset
, qiov
, &local_err
);
1095 nbd_channel_error(s
, ret
);
1096 nbd_iter_channel_error(&iter
, ret
, &local_err
);
1100 if (!nbd_reply_type_is_error(chunk
->type
)) {
1101 /* not allowed reply type */
1102 nbd_channel_error(s
, -EINVAL
);
1103 error_setg(&local_err
,
1104 "Unexpected reply type: %d (%s) for CMD_READ",
1105 chunk
->type
, nbd_reply_type_lookup(chunk
->type
));
1106 nbd_iter_channel_error(&iter
, -EINVAL
, &local_err
);
1114 error_propagate(errp
, iter
.err
);
1115 *request_ret
= iter
.request_ret
;
1119 static int coroutine_fn
1120 nbd_co_receive_blockstatus_reply(BDRVNBDState
*s
, uint64_t cookie
,
1121 uint64_t length
, NBDExtent
*extent
,
1122 int *request_ret
, Error
**errp
)
1124 NBDReplyChunkIter iter
;
1126 void *payload
= NULL
;
1127 Error
*local_err
= NULL
;
1128 bool received
= false;
1130 assert(!extent
->length
);
1131 NBD_FOREACH_REPLY_CHUNK(s
, iter
, cookie
, false, NULL
, &reply
, &payload
) {
1133 NBDStructuredReplyChunk
*chunk
= &reply
.structured
;
1135 assert(nbd_reply_is_structured(&reply
));
1137 switch (chunk
->type
) {
1138 case NBD_REPLY_TYPE_BLOCK_STATUS
:
1140 nbd_channel_error(s
, -EINVAL
);
1141 error_setg(&local_err
, "Several BLOCK_STATUS chunks in reply");
1142 nbd_iter_channel_error(&iter
, -EINVAL
, &local_err
);
1146 ret
= nbd_parse_blockstatus_payload(s
, &reply
.structured
,
1147 payload
, length
, extent
,
1150 nbd_channel_error(s
, ret
);
1151 nbd_iter_channel_error(&iter
, ret
, &local_err
);
1155 if (!nbd_reply_type_is_error(chunk
->type
)) {
1156 nbd_channel_error(s
, -EINVAL
);
1157 error_setg(&local_err
,
1158 "Unexpected reply type: %d (%s) "
1159 "for CMD_BLOCK_STATUS",
1160 chunk
->type
, nbd_reply_type_lookup(chunk
->type
));
1161 nbd_iter_channel_error(&iter
, -EINVAL
, &local_err
);
1169 if (!extent
->length
&& !iter
.request_ret
) {
1170 error_setg(&local_err
, "Server did not reply with any status extents");
1171 nbd_iter_channel_error(&iter
, -EIO
, &local_err
);
1174 error_propagate(errp
, iter
.err
);
1175 *request_ret
= iter
.request_ret
;
1179 static int coroutine_fn GRAPH_RDLOCK
1180 nbd_co_request(BlockDriverState
*bs
, NBDRequest
*request
,
1181 QEMUIOVector
*write_qiov
)
1183 int ret
, request_ret
;
1184 Error
*local_err
= NULL
;
1185 BDRVNBDState
*s
= (BDRVNBDState
*)bs
->opaque
;
1187 assert(request
->type
!= NBD_CMD_READ
);
1189 assert(request
->type
== NBD_CMD_WRITE
);
1190 assert(request
->len
== iov_size(write_qiov
->iov
, write_qiov
->niov
));
1192 assert(request
->type
!= NBD_CMD_WRITE
);
1196 ret
= nbd_co_send_request(bs
, request
, write_qiov
);
1201 ret
= nbd_co_receive_return_code(s
, request
->cookie
,
1202 &request_ret
, &local_err
);
1204 trace_nbd_co_request_fail(request
->from
, request
->len
,
1205 request
->cookie
, request
->flags
,
1207 nbd_cmd_lookup(request
->type
),
1208 ret
, error_get_pretty(local_err
));
1209 error_free(local_err
);
1212 } while (ret
< 0 && nbd_client_will_reconnect(s
));
1214 return ret
? ret
: request_ret
;
1217 static int coroutine_fn GRAPH_RDLOCK
1218 nbd_client_co_preadv(BlockDriverState
*bs
, int64_t offset
, int64_t bytes
,
1219 QEMUIOVector
*qiov
, BdrvRequestFlags flags
)
1221 int ret
, request_ret
;
1222 Error
*local_err
= NULL
;
1223 BDRVNBDState
*s
= (BDRVNBDState
*)bs
->opaque
;
1224 NBDRequest request
= {
1225 .type
= NBD_CMD_READ
,
1230 assert(bytes
<= NBD_MAX_BUFFER_SIZE
);
1236 * Work around the fact that the block layer doesn't do
1237 * byte-accurate sizing yet - if the read exceeds the server's
1238 * advertised size because the block layer rounded size up, then
1239 * truncate the request to the server and tail-pad with zero.
1241 if (offset
>= s
->info
.size
) {
1242 assert(bytes
< BDRV_SECTOR_SIZE
);
1243 qemu_iovec_memset(qiov
, 0, 0, bytes
);
1246 if (offset
+ bytes
> s
->info
.size
) {
1247 uint64_t slop
= offset
+ bytes
- s
->info
.size
;
1249 assert(slop
< BDRV_SECTOR_SIZE
);
1250 qemu_iovec_memset(qiov
, bytes
- slop
, 0, slop
);
1251 request
.len
-= slop
;
1255 ret
= nbd_co_send_request(bs
, &request
, NULL
);
1260 ret
= nbd_co_receive_cmdread_reply(s
, request
.cookie
, offset
, qiov
,
1261 &request_ret
, &local_err
);
1263 trace_nbd_co_request_fail(request
.from
, request
.len
, request
.cookie
,
1264 request
.flags
, request
.type
,
1265 nbd_cmd_lookup(request
.type
),
1266 ret
, error_get_pretty(local_err
));
1267 error_free(local_err
);
1270 } while (ret
< 0 && nbd_client_will_reconnect(s
));
1272 return ret
? ret
: request_ret
;
1275 static int coroutine_fn GRAPH_RDLOCK
1276 nbd_client_co_pwritev(BlockDriverState
*bs
, int64_t offset
, int64_t bytes
,
1277 QEMUIOVector
*qiov
, BdrvRequestFlags flags
)
1279 BDRVNBDState
*s
= (BDRVNBDState
*)bs
->opaque
;
1280 NBDRequest request
= {
1281 .type
= NBD_CMD_WRITE
,
1286 assert(!(s
->info
.flags
& NBD_FLAG_READ_ONLY
));
1287 if (flags
& BDRV_REQ_FUA
) {
1288 assert(s
->info
.flags
& NBD_FLAG_SEND_FUA
);
1289 request
.flags
|= NBD_CMD_FLAG_FUA
;
1292 assert(bytes
<= NBD_MAX_BUFFER_SIZE
);
1297 return nbd_co_request(bs
, &request
, qiov
);
1300 static int coroutine_fn GRAPH_RDLOCK
1301 nbd_client_co_pwrite_zeroes(BlockDriverState
*bs
, int64_t offset
, int64_t bytes
,
1302 BdrvRequestFlags flags
)
1304 BDRVNBDState
*s
= (BDRVNBDState
*)bs
->opaque
;
1305 NBDRequest request
= {
1306 .type
= NBD_CMD_WRITE_ZEROES
,
1308 .len
= bytes
, /* .len is uint32_t actually */
1311 assert(bytes
<= UINT32_MAX
); /* rely on max_pwrite_zeroes */
1313 assert(!(s
->info
.flags
& NBD_FLAG_READ_ONLY
));
1314 if (!(s
->info
.flags
& NBD_FLAG_SEND_WRITE_ZEROES
)) {
1318 if (flags
& BDRV_REQ_FUA
) {
1319 assert(s
->info
.flags
& NBD_FLAG_SEND_FUA
);
1320 request
.flags
|= NBD_CMD_FLAG_FUA
;
1322 if (!(flags
& BDRV_REQ_MAY_UNMAP
)) {
1323 request
.flags
|= NBD_CMD_FLAG_NO_HOLE
;
1325 if (flags
& BDRV_REQ_NO_FALLBACK
) {
1326 assert(s
->info
.flags
& NBD_FLAG_SEND_FAST_ZERO
);
1327 request
.flags
|= NBD_CMD_FLAG_FAST_ZERO
;
1333 return nbd_co_request(bs
, &request
, NULL
);
1336 static int coroutine_fn GRAPH_RDLOCK
nbd_client_co_flush(BlockDriverState
*bs
)
1338 BDRVNBDState
*s
= (BDRVNBDState
*)bs
->opaque
;
1339 NBDRequest request
= { .type
= NBD_CMD_FLUSH
};
1341 if (!(s
->info
.flags
& NBD_FLAG_SEND_FLUSH
)) {
1348 return nbd_co_request(bs
, &request
, NULL
);
1351 static int coroutine_fn GRAPH_RDLOCK
1352 nbd_client_co_pdiscard(BlockDriverState
*bs
, int64_t offset
, int64_t bytes
)
1354 BDRVNBDState
*s
= (BDRVNBDState
*)bs
->opaque
;
1355 NBDRequest request
= {
1356 .type
= NBD_CMD_TRIM
,
1358 .len
= bytes
, /* len is uint32_t */
1361 assert(bytes
<= UINT32_MAX
); /* rely on max_pdiscard */
1363 assert(!(s
->info
.flags
& NBD_FLAG_READ_ONLY
));
1364 if (!(s
->info
.flags
& NBD_FLAG_SEND_TRIM
) || !bytes
) {
1368 return nbd_co_request(bs
, &request
, NULL
);
1371 static int coroutine_fn GRAPH_RDLOCK
nbd_client_co_block_status(
1372 BlockDriverState
*bs
, bool want_zero
, int64_t offset
, int64_t bytes
,
1373 int64_t *pnum
, int64_t *map
, BlockDriverState
**file
)
1375 int ret
, request_ret
;
1376 NBDExtent extent
= { 0 };
1377 BDRVNBDState
*s
= (BDRVNBDState
*)bs
->opaque
;
1378 Error
*local_err
= NULL
;
1380 NBDRequest request
= {
1381 .type
= NBD_CMD_BLOCK_STATUS
,
1383 .len
= MIN(QEMU_ALIGN_DOWN(INT_MAX
, bs
->bl
.request_alignment
),
1384 MIN(bytes
, s
->info
.size
- offset
)),
1385 .flags
= NBD_CMD_FLAG_REQ_ONE
,
1388 if (!s
->info
.base_allocation
) {
1392 return BDRV_BLOCK_DATA
| BDRV_BLOCK_OFFSET_VALID
;
1396 * Work around the fact that the block layer doesn't do
1397 * byte-accurate sizing yet - if the status request exceeds the
1398 * server's advertised size because the block layer rounded size
1399 * up, we truncated the request to the server (above), or are
1400 * called on just the hole.
1402 if (offset
>= s
->info
.size
) {
1404 assert(bytes
< BDRV_SECTOR_SIZE
);
1405 /* Intentionally don't report offset_valid for the hole */
1406 return BDRV_BLOCK_ZERO
;
1409 if (s
->info
.min_block
) {
1410 assert(QEMU_IS_ALIGNED(request
.len
, s
->info
.min_block
));
1413 ret
= nbd_co_send_request(bs
, &request
, NULL
);
1418 ret
= nbd_co_receive_blockstatus_reply(s
, request
.cookie
, bytes
,
1419 &extent
, &request_ret
,
1422 trace_nbd_co_request_fail(request
.from
, request
.len
, request
.cookie
,
1423 request
.flags
, request
.type
,
1424 nbd_cmd_lookup(request
.type
),
1425 ret
, error_get_pretty(local_err
));
1426 error_free(local_err
);
1429 } while (ret
< 0 && nbd_client_will_reconnect(s
));
1431 if (ret
< 0 || request_ret
< 0) {
1432 return ret
? ret
: request_ret
;
1435 assert(extent
.length
);
1436 *pnum
= extent
.length
;
1439 return (extent
.flags
& NBD_STATE_HOLE
? 0 : BDRV_BLOCK_DATA
) |
1440 (extent
.flags
& NBD_STATE_ZERO
? BDRV_BLOCK_ZERO
: 0) |
1441 BDRV_BLOCK_OFFSET_VALID
;
1444 static int nbd_client_reopen_prepare(BDRVReopenState
*state
,
1445 BlockReopenQueue
*queue
, Error
**errp
)
1447 BDRVNBDState
*s
= (BDRVNBDState
*)state
->bs
->opaque
;
1449 if ((state
->flags
& BDRV_O_RDWR
) && (s
->info
.flags
& NBD_FLAG_READ_ONLY
)) {
1450 error_setg(errp
, "Can't reopen read-only NBD mount as read/write");
1456 static void nbd_yank(void *opaque
)
1458 BlockDriverState
*bs
= opaque
;
1459 BDRVNBDState
*s
= (BDRVNBDState
*)bs
->opaque
;
1461 QEMU_LOCK_GUARD(&s
->requests_lock
);
1462 qio_channel_shutdown(s
->ioc
, QIO_CHANNEL_SHUTDOWN_BOTH
, NULL
);
1463 s
->state
= NBD_CLIENT_QUIT
;
1466 static void nbd_client_close(BlockDriverState
*bs
)
1468 BDRVNBDState
*s
= (BDRVNBDState
*)bs
->opaque
;
1469 NBDRequest request
= { .type
= NBD_CMD_DISC
, .mode
= s
->info
.mode
};
1472 nbd_send_request(s
->ioc
, &request
);
1475 nbd_teardown_connection(bs
);
1480 * Parse nbd_open options
1483 static int nbd_parse_uri(const char *filename
, QDict
*options
)
1487 QueryParams
*qp
= NULL
;
1491 uri
= uri_parse(filename
);
1497 if (!g_strcmp0(uri
->scheme
, "nbd")) {
1499 } else if (!g_strcmp0(uri
->scheme
, "nbd+tcp")) {
1501 } else if (!g_strcmp0(uri
->scheme
, "nbd+unix")) {
1508 p
= uri
->path
? uri
->path
: "";
1513 qdict_put_str(options
, "export", p
);
1516 qp
= query_params_parse(uri
->query
);
1517 if (qp
->n
> 1 || (is_unix
&& !qp
->n
) || (!is_unix
&& qp
->n
)) {
1523 /* nbd+unix:///export?socket=path */
1524 if (uri
->server
|| uri
->port
|| strcmp(qp
->p
[0].name
, "socket")) {
1528 qdict_put_str(options
, "server.type", "unix");
1529 qdict_put_str(options
, "server.path", qp
->p
[0].value
);
1534 /* nbd[+tcp]://host[:port]/export */
1540 /* strip braces from literal IPv6 address */
1541 if (uri
->server
[0] == '[') {
1542 host
= qstring_from_substr(uri
->server
, 1,
1543 strlen(uri
->server
) - 1);
1545 host
= qstring_from_str(uri
->server
);
1548 qdict_put_str(options
, "server.type", "inet");
1549 qdict_put(options
, "server.host", host
);
1551 port_str
= g_strdup_printf("%d", uri
->port
?: NBD_DEFAULT_PORT
);
1552 qdict_put_str(options
, "server.port", port_str
);
1558 query_params_free(qp
);
1564 static bool nbd_has_filename_options_conflict(QDict
*options
, Error
**errp
)
1566 const QDictEntry
*e
;
1568 for (e
= qdict_first(options
); e
; e
= qdict_next(options
, e
)) {
1569 if (!strcmp(e
->key
, "host") ||
1570 !strcmp(e
->key
, "port") ||
1571 !strcmp(e
->key
, "path") ||
1572 !strcmp(e
->key
, "export") ||
1573 strstart(e
->key
, "server.", NULL
))
1575 error_setg(errp
, "Option '%s' cannot be used with a file name",
1584 static void nbd_parse_filename(const char *filename
, QDict
*options
,
1587 g_autofree
char *file
= NULL
;
1589 const char *host_spec
;
1590 const char *unixpath
;
1592 if (nbd_has_filename_options_conflict(options
, errp
)) {
1596 if (strstr(filename
, "://")) {
1597 int ret
= nbd_parse_uri(filename
, options
);
1599 error_setg(errp
, "No valid URL specified");
1604 file
= g_strdup(filename
);
1606 export_name
= strstr(file
, EN_OPTSTR
);
1608 if (export_name
[strlen(EN_OPTSTR
)] == 0) {
1611 export_name
[0] = 0; /* truncate 'file' */
1612 export_name
+= strlen(EN_OPTSTR
);
1614 qdict_put_str(options
, "export", export_name
);
1617 /* extract the host_spec - fail if it's not nbd:... */
1618 if (!strstart(file
, "nbd:", &host_spec
)) {
1619 error_setg(errp
, "File name string for NBD must start with 'nbd:'");
1627 /* are we a UNIX or TCP socket? */
1628 if (strstart(host_spec
, "unix:", &unixpath
)) {
1629 qdict_put_str(options
, "server.type", "unix");
1630 qdict_put_str(options
, "server.path", unixpath
);
1632 InetSocketAddress
*addr
= g_new(InetSocketAddress
, 1);
1634 if (inet_parse(addr
, host_spec
, errp
)) {
1638 qdict_put_str(options
, "server.type", "inet");
1639 qdict_put_str(options
, "server.host", addr
->host
);
1640 qdict_put_str(options
, "server.port", addr
->port
);
1642 qapi_free_InetSocketAddress(addr
);
1646 static bool nbd_process_legacy_socket_options(QDict
*output_options
,
1647 QemuOpts
*legacy_opts
,
1650 const char *path
= qemu_opt_get(legacy_opts
, "path");
1651 const char *host
= qemu_opt_get(legacy_opts
, "host");
1652 const char *port
= qemu_opt_get(legacy_opts
, "port");
1653 const QDictEntry
*e
;
1655 if (!path
&& !host
&& !port
) {
1659 for (e
= qdict_first(output_options
); e
; e
= qdict_next(output_options
, e
))
1661 if (strstart(e
->key
, "server.", NULL
)) {
1662 error_setg(errp
, "Cannot use 'server' and path/host/port at the "
1669 error_setg(errp
, "path and host may not be used at the same time");
1673 error_setg(errp
, "port may not be used without host");
1677 qdict_put_str(output_options
, "server.type", "unix");
1678 qdict_put_str(output_options
, "server.path", path
);
1680 qdict_put_str(output_options
, "server.type", "inet");
1681 qdict_put_str(output_options
, "server.host", host
);
1682 qdict_put_str(output_options
, "server.port",
1683 port
?: stringify(NBD_DEFAULT_PORT
));
1689 static SocketAddress
*nbd_config(BDRVNBDState
*s
, QDict
*options
,
1692 SocketAddress
*saddr
= NULL
;
1696 qdict_extract_subqdict(options
, &addr
, "server.");
1697 if (!qdict_size(addr
)) {
1698 error_setg(errp
, "NBD server address missing");
1702 iv
= qobject_input_visitor_new_flat_confused(addr
, errp
);
1707 if (!visit_type_SocketAddress(iv
, NULL
, &saddr
, errp
)) {
1711 if (socket_address_parse_named_fd(saddr
, errp
) < 0) {
1712 qapi_free_SocketAddress(saddr
);
1718 qobject_unref(addr
);
1723 static QCryptoTLSCreds
*nbd_get_tls_creds(const char *id
, Error
**errp
)
1726 QCryptoTLSCreds
*creds
;
1728 obj
= object_resolve_path_component(
1729 object_get_objects_root(), id
);
1731 error_setg(errp
, "No TLS credentials with id '%s'",
1735 creds
= (QCryptoTLSCreds
*)
1736 object_dynamic_cast(obj
, TYPE_QCRYPTO_TLS_CREDS
);
1738 error_setg(errp
, "Object with id '%s' is not TLS credentials",
1743 if (!qcrypto_tls_creds_check_endpoint(creds
,
1744 QCRYPTO_TLS_CREDS_ENDPOINT_CLIENT
,
1753 static QemuOptsList nbd_runtime_opts
= {
1755 .head
= QTAILQ_HEAD_INITIALIZER(nbd_runtime_opts
.head
),
1759 .type
= QEMU_OPT_STRING
,
1760 .help
= "TCP host to connect to",
1764 .type
= QEMU_OPT_STRING
,
1765 .help
= "TCP port to connect to",
1769 .type
= QEMU_OPT_STRING
,
1770 .help
= "Unix socket path to connect to",
1774 .type
= QEMU_OPT_STRING
,
1775 .help
= "Name of the NBD export to open",
1778 .name
= "tls-creds",
1779 .type
= QEMU_OPT_STRING
,
1780 .help
= "ID of the TLS credentials to use",
1783 .name
= "tls-hostname",
1784 .type
= QEMU_OPT_STRING
,
1785 .help
= "Override hostname for validating TLS x509 certificate",
1788 .name
= "x-dirty-bitmap",
1789 .type
= QEMU_OPT_STRING
,
1790 .help
= "experimental: expose named dirty bitmap in place of "
1794 .name
= "reconnect-delay",
1795 .type
= QEMU_OPT_NUMBER
,
1796 .help
= "On an unexpected disconnect, the nbd client tries to "
1797 "connect again until succeeding or encountering a serious "
1798 "error. During the first @reconnect-delay seconds, all "
1799 "requests are paused and will be rerun on a successful "
1800 "reconnect. After that time, any delayed requests and all "
1801 "future requests before a successful reconnect will "
1802 "immediately fail. Default 0",
1805 .name
= "open-timeout",
1806 .type
= QEMU_OPT_NUMBER
,
1807 .help
= "In seconds. If zero, the nbd driver tries the connection "
1808 "only once, and fails to open if the connection fails. "
1809 "If non-zero, the nbd driver will repeat connection "
1810 "attempts until successful or until @open-timeout seconds "
1811 "have elapsed. Default 0",
1813 { /* end of list */ }
1817 static int nbd_process_options(BlockDriverState
*bs
, QDict
*options
,
1820 BDRVNBDState
*s
= bs
->opaque
;
1824 opts
= qemu_opts_create(&nbd_runtime_opts
, NULL
, 0, &error_abort
);
1825 if (!qemu_opts_absorb_qdict(opts
, options
, errp
)) {
1829 /* Translate @host, @port, and @path to a SocketAddress */
1830 if (!nbd_process_legacy_socket_options(options
, opts
, errp
)) {
1834 /* Pop the config into our state object. Exit if invalid. */
1835 s
->saddr
= nbd_config(s
, options
, errp
);
1840 s
->export
= g_strdup(qemu_opt_get(opts
, "export"));
1841 if (s
->export
&& strlen(s
->export
) > NBD_MAX_STRING_SIZE
) {
1842 error_setg(errp
, "export name too long to send to server");
1846 s
->tlscredsid
= g_strdup(qemu_opt_get(opts
, "tls-creds"));
1847 if (s
->tlscredsid
) {
1848 s
->tlscreds
= nbd_get_tls_creds(s
->tlscredsid
, errp
);
1853 s
->tlshostname
= g_strdup(qemu_opt_get(opts
, "tls-hostname"));
1854 if (!s
->tlshostname
&&
1855 s
->saddr
->type
== SOCKET_ADDRESS_TYPE_INET
) {
1856 s
->tlshostname
= g_strdup(s
->saddr
->u
.inet
.host
);
1860 s
->x_dirty_bitmap
= g_strdup(qemu_opt_get(opts
, "x-dirty-bitmap"));
1861 if (s
->x_dirty_bitmap
&& strlen(s
->x_dirty_bitmap
) > NBD_MAX_STRING_SIZE
) {
1862 error_setg(errp
, "x-dirty-bitmap query too long to send to server");
1866 s
->reconnect_delay
= qemu_opt_get_number(opts
, "reconnect-delay", 0);
1867 s
->open_timeout
= qemu_opt_get_number(opts
, "open-timeout", 0);
1872 qemu_opts_del(opts
);
1876 static int nbd_open(BlockDriverState
*bs
, QDict
*options
, int flags
,
1880 BDRVNBDState
*s
= (BDRVNBDState
*)bs
->opaque
;
1883 qemu_mutex_init(&s
->requests_lock
);
1884 qemu_co_queue_init(&s
->free_sema
);
1885 qemu_co_mutex_init(&s
->send_mutex
);
1886 qemu_co_mutex_init(&s
->receive_mutex
);
1888 if (!yank_register_instance(BLOCKDEV_YANK_INSTANCE(bs
->node_name
), errp
)) {
1892 ret
= nbd_process_options(bs
, options
, errp
);
1897 s
->conn
= nbd_client_connection_new(s
->saddr
, true, s
->export
,
1898 s
->x_dirty_bitmap
, s
->tlscreds
,
1901 if (s
->open_timeout
) {
1902 nbd_client_connection_enable_retry(s
->conn
);
1903 open_timer_init(s
, qemu_clock_get_ns(QEMU_CLOCK_REALTIME
) +
1904 s
->open_timeout
* NANOSECONDS_PER_SECOND
);
1907 s
->state
= NBD_CLIENT_CONNECTING_WAIT
;
1908 ret
= nbd_do_establish_connection(bs
, true, errp
);
1914 * The connect attempt is done, so we no longer need this timer.
1915 * Delete it, because we do not want it to be around when this node
1916 * is drained or closed.
1920 nbd_client_connection_enable_retry(s
->conn
);
1926 nbd_clear_bdrvstate(bs
);
1930 static void nbd_refresh_limits(BlockDriverState
*bs
, Error
**errp
)
1932 BDRVNBDState
*s
= (BDRVNBDState
*)bs
->opaque
;
1933 uint32_t min
= s
->info
.min_block
;
1934 uint32_t max
= MIN_NON_ZERO(NBD_MAX_BUFFER_SIZE
, s
->info
.max_block
);
1937 * If the server did not advertise an alignment:
1938 * - a size that is not sector-aligned implies that an alignment
1939 * of 1 can be used to access those tail bytes
1940 * - advertisement of block status requires an alignment of 1, so
1941 * that we don't violate block layer constraints that block
1942 * status is always aligned (as we can't control whether the
1943 * server will report sub-sector extents, such as a hole at EOF
1944 * on an unaligned POSIX file)
1945 * - otherwise, assume the server is so old that we are safer avoiding
1946 * sub-sector requests
1949 min
= (!QEMU_IS_ALIGNED(s
->info
.size
, BDRV_SECTOR_SIZE
) ||
1950 s
->info
.base_allocation
) ? 1 : BDRV_SECTOR_SIZE
;
1953 bs
->bl
.request_alignment
= min
;
1954 bs
->bl
.max_pdiscard
= QEMU_ALIGN_DOWN(INT_MAX
, min
);
1955 bs
->bl
.max_pwrite_zeroes
= max
;
1956 bs
->bl
.max_transfer
= max
;
1958 if (s
->info
.opt_block
&&
1959 s
->info
.opt_block
> bs
->bl
.opt_transfer
) {
1960 bs
->bl
.opt_transfer
= s
->info
.opt_block
;
1964 static void nbd_close(BlockDriverState
*bs
)
1966 nbd_client_close(bs
);
1967 nbd_clear_bdrvstate(bs
);
1971 * NBD cannot truncate, but if the caller asks to truncate to the same size, or
1972 * to a smaller size with exact=false, there is no reason to fail the
1975 * Preallocation mode is ignored since it does not seems useful to fail when
1976 * we never change anything.
1978 static int coroutine_fn
nbd_co_truncate(BlockDriverState
*bs
, int64_t offset
,
1979 bool exact
, PreallocMode prealloc
,
1980 BdrvRequestFlags flags
, Error
**errp
)
1982 BDRVNBDState
*s
= bs
->opaque
;
1984 if (offset
!= s
->info
.size
&& exact
) {
1985 error_setg(errp
, "Cannot resize NBD nodes");
1989 if (offset
> s
->info
.size
) {
1990 error_setg(errp
, "Cannot grow NBD nodes");
1997 static int64_t coroutine_fn
nbd_co_getlength(BlockDriverState
*bs
)
1999 BDRVNBDState
*s
= bs
->opaque
;
2001 return s
->info
.size
;
2004 static void nbd_refresh_filename(BlockDriverState
*bs
)
2006 BDRVNBDState
*s
= bs
->opaque
;
2007 const char *host
= NULL
, *port
= NULL
, *path
= NULL
;
2010 if (s
->saddr
->type
== SOCKET_ADDRESS_TYPE_INET
) {
2011 const InetSocketAddress
*inet
= &s
->saddr
->u
.inet
;
2012 if (!inet
->has_ipv4
&& !inet
->has_ipv6
&& !inet
->has_to
) {
2016 } else if (s
->saddr
->type
== SOCKET_ADDRESS_TYPE_UNIX
) {
2017 path
= s
->saddr
->u
.q_unix
.path
;
2018 } /* else can't represent as pseudo-filename */
2020 if (path
&& s
->export
) {
2021 len
= snprintf(bs
->exact_filename
, sizeof(bs
->exact_filename
),
2022 "nbd+unix:///%s?socket=%s", s
->export
, path
);
2023 } else if (path
&& !s
->export
) {
2024 len
= snprintf(bs
->exact_filename
, sizeof(bs
->exact_filename
),
2025 "nbd+unix://?socket=%s", path
);
2026 } else if (host
&& s
->export
) {
2027 len
= snprintf(bs
->exact_filename
, sizeof(bs
->exact_filename
),
2028 "nbd://%s:%s/%s", host
, port
, s
->export
);
2029 } else if (host
&& !s
->export
) {
2030 len
= snprintf(bs
->exact_filename
, sizeof(bs
->exact_filename
),
2031 "nbd://%s:%s", host
, port
);
2033 if (len
>= sizeof(bs
->exact_filename
)) {
2034 /* Name is too long to represent exactly, so leave it empty. */
2035 bs
->exact_filename
[0] = '\0';
2039 static char *nbd_dirname(BlockDriverState
*bs
, Error
**errp
)
2041 /* The generic bdrv_dirname() implementation is able to work out some
2042 * directory name for NBD nodes, but that would be wrong. So far there is no
2043 * specification for how "export paths" would work, so NBD does not have
2044 * directory names. */
2045 error_setg(errp
, "Cannot generate a base directory for NBD nodes");
2049 static const char *const nbd_strong_runtime_opts
[] = {
2061 static void nbd_cancel_in_flight(BlockDriverState
*bs
)
2063 BDRVNBDState
*s
= (BDRVNBDState
*)bs
->opaque
;
2065 reconnect_delay_timer_del(s
);
2067 qemu_mutex_lock(&s
->requests_lock
);
2068 if (s
->state
== NBD_CLIENT_CONNECTING_WAIT
) {
2069 s
->state
= NBD_CLIENT_CONNECTING_NOWAIT
;
2071 qemu_mutex_unlock(&s
->requests_lock
);
2073 nbd_co_establish_connection_cancel(s
->conn
);
2076 static void nbd_attach_aio_context(BlockDriverState
*bs
,
2077 AioContext
*new_context
)
2079 BDRVNBDState
*s
= bs
->opaque
;
2081 /* The open_timer is used only during nbd_open() */
2082 assert(!s
->open_timer
);
2085 * The reconnect_delay_timer is scheduled in I/O paths when the
2086 * connection is lost, to cancel the reconnection attempt after a
2087 * given time. Once this attempt is done (successfully or not),
2088 * nbd_reconnect_attempt() ensures the timer is deleted before the
2089 * respective I/O request is resumed.
2090 * Since the AioContext can only be changed when a node is drained,
2091 * the reconnect_delay_timer cannot be active here.
2093 assert(!s
->reconnect_delay_timer
);
2096 static void nbd_detach_aio_context(BlockDriverState
*bs
)
2098 BDRVNBDState
*s
= bs
->opaque
;
2100 assert(!s
->open_timer
);
2101 assert(!s
->reconnect_delay_timer
);
2104 static BlockDriver bdrv_nbd
= {
2105 .format_name
= "nbd",
2106 .protocol_name
= "nbd",
2107 .instance_size
= sizeof(BDRVNBDState
),
2108 .bdrv_parse_filename
= nbd_parse_filename
,
2109 .bdrv_co_create_opts
= bdrv_co_create_opts_simple
,
2110 .create_opts
= &bdrv_create_opts_simple
,
2111 .bdrv_file_open
= nbd_open
,
2112 .bdrv_reopen_prepare
= nbd_client_reopen_prepare
,
2113 .bdrv_co_preadv
= nbd_client_co_preadv
,
2114 .bdrv_co_pwritev
= nbd_client_co_pwritev
,
2115 .bdrv_co_pwrite_zeroes
= nbd_client_co_pwrite_zeroes
,
2116 .bdrv_close
= nbd_close
,
2117 .bdrv_co_flush_to_os
= nbd_client_co_flush
,
2118 .bdrv_co_pdiscard
= nbd_client_co_pdiscard
,
2119 .bdrv_refresh_limits
= nbd_refresh_limits
,
2120 .bdrv_co_truncate
= nbd_co_truncate
,
2121 .bdrv_co_getlength
= nbd_co_getlength
,
2122 .bdrv_refresh_filename
= nbd_refresh_filename
,
2123 .bdrv_co_block_status
= nbd_client_co_block_status
,
2124 .bdrv_dirname
= nbd_dirname
,
2125 .strong_runtime_opts
= nbd_strong_runtime_opts
,
2126 .bdrv_cancel_in_flight
= nbd_cancel_in_flight
,
2128 .bdrv_attach_aio_context
= nbd_attach_aio_context
,
2129 .bdrv_detach_aio_context
= nbd_detach_aio_context
,
2132 static BlockDriver bdrv_nbd_tcp
= {
2133 .format_name
= "nbd",
2134 .protocol_name
= "nbd+tcp",
2135 .instance_size
= sizeof(BDRVNBDState
),
2136 .bdrv_parse_filename
= nbd_parse_filename
,
2137 .bdrv_co_create_opts
= bdrv_co_create_opts_simple
,
2138 .create_opts
= &bdrv_create_opts_simple
,
2139 .bdrv_file_open
= nbd_open
,
2140 .bdrv_reopen_prepare
= nbd_client_reopen_prepare
,
2141 .bdrv_co_preadv
= nbd_client_co_preadv
,
2142 .bdrv_co_pwritev
= nbd_client_co_pwritev
,
2143 .bdrv_co_pwrite_zeroes
= nbd_client_co_pwrite_zeroes
,
2144 .bdrv_close
= nbd_close
,
2145 .bdrv_co_flush_to_os
= nbd_client_co_flush
,
2146 .bdrv_co_pdiscard
= nbd_client_co_pdiscard
,
2147 .bdrv_refresh_limits
= nbd_refresh_limits
,
2148 .bdrv_co_truncate
= nbd_co_truncate
,
2149 .bdrv_co_getlength
= nbd_co_getlength
,
2150 .bdrv_refresh_filename
= nbd_refresh_filename
,
2151 .bdrv_co_block_status
= nbd_client_co_block_status
,
2152 .bdrv_dirname
= nbd_dirname
,
2153 .strong_runtime_opts
= nbd_strong_runtime_opts
,
2154 .bdrv_cancel_in_flight
= nbd_cancel_in_flight
,
2156 .bdrv_attach_aio_context
= nbd_attach_aio_context
,
2157 .bdrv_detach_aio_context
= nbd_detach_aio_context
,
2160 static BlockDriver bdrv_nbd_unix
= {
2161 .format_name
= "nbd",
2162 .protocol_name
= "nbd+unix",
2163 .instance_size
= sizeof(BDRVNBDState
),
2164 .bdrv_parse_filename
= nbd_parse_filename
,
2165 .bdrv_co_create_opts
= bdrv_co_create_opts_simple
,
2166 .create_opts
= &bdrv_create_opts_simple
,
2167 .bdrv_file_open
= nbd_open
,
2168 .bdrv_reopen_prepare
= nbd_client_reopen_prepare
,
2169 .bdrv_co_preadv
= nbd_client_co_preadv
,
2170 .bdrv_co_pwritev
= nbd_client_co_pwritev
,
2171 .bdrv_co_pwrite_zeroes
= nbd_client_co_pwrite_zeroes
,
2172 .bdrv_close
= nbd_close
,
2173 .bdrv_co_flush_to_os
= nbd_client_co_flush
,
2174 .bdrv_co_pdiscard
= nbd_client_co_pdiscard
,
2175 .bdrv_refresh_limits
= nbd_refresh_limits
,
2176 .bdrv_co_truncate
= nbd_co_truncate
,
2177 .bdrv_co_getlength
= nbd_co_getlength
,
2178 .bdrv_refresh_filename
= nbd_refresh_filename
,
2179 .bdrv_co_block_status
= nbd_client_co_block_status
,
2180 .bdrv_dirname
= nbd_dirname
,
2181 .strong_runtime_opts
= nbd_strong_runtime_opts
,
2182 .bdrv_cancel_in_flight
= nbd_cancel_in_flight
,
2184 .bdrv_attach_aio_context
= nbd_attach_aio_context
,
2185 .bdrv_detach_aio_context
= nbd_detach_aio_context
,
2188 static void bdrv_nbd_init(void)
2190 bdrv_register(&bdrv_nbd
);
2191 bdrv_register(&bdrv_nbd_tcp
);
2192 bdrv_register(&bdrv_nbd_unix
);
2195 block_init(bdrv_nbd_init
);