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 enum NBDConnectThreadState
{
70 /* No thread, no pending results */
73 /* Thread is running, no results for now */
74 CONNECT_THREAD_RUNNING
,
77 * Thread is running, but requestor exited. Thread should close
78 * the new socket and free the connect state on exit.
80 CONNECT_THREAD_RUNNING_DETACHED
,
82 /* Thread finished, results are stored in a state */
84 CONNECT_THREAD_SUCCESS
85 } NBDConnectThreadState
;
87 typedef struct NBDConnectThread
{
88 /* Initialization constants */
89 SocketAddress
*saddr
; /* address to connect to */
91 * Bottom half to schedule on completion. Scheduled only if bh_ctx is not
98 * Result of last attempt. Valid in FAIL and SUCCESS states.
99 * If you want to steal error, don't forget to set pointer to NULL.
101 QIOChannelSocket
*sioc
;
104 /* state and bh_ctx are protected by mutex */
106 NBDConnectThreadState state
; /* current state of the thread */
107 AioContext
*bh_ctx
; /* where to schedule bh (NULL means don't schedule) */
110 typedef struct BDRVNBDState
{
111 QIOChannelSocket
*sioc
; /* The master data channel */
112 QIOChannel
*ioc
; /* The current I/O channel which may differ (eg TLS) */
117 Coroutine
*connection_co
;
118 Coroutine
*teardown_co
;
119 QemuCoSleepState
*connection_co_sleep_ns_state
;
121 bool wait_drained_end
;
123 NBDClientState state
;
128 QEMUTimer
*reconnect_delay_timer
;
130 NBDClientRequest requests
[MAX_NBD_REQUESTS
];
132 BlockDriverState
*bs
;
134 /* Connection parameters */
135 uint32_t reconnect_delay
;
136 SocketAddress
*saddr
;
137 char *export
, *tlscredsid
;
138 QCryptoTLSCreds
*tlscreds
;
139 const char *hostname
;
140 char *x_dirty_bitmap
;
144 NBDConnectThread
*connect_thread
;
147 static int nbd_establish_connection(BlockDriverState
*bs
, SocketAddress
*saddr
,
149 static int nbd_co_establish_connection(BlockDriverState
*bs
, Error
**errp
);
150 static void nbd_co_establish_connection_cancel(BlockDriverState
*bs
,
152 static int nbd_client_handshake(BlockDriverState
*bs
, Error
**errp
);
153 static void nbd_yank(void *opaque
);
155 static void nbd_clear_bdrvstate(BDRVNBDState
*s
)
157 object_unref(OBJECT(s
->tlscreds
));
158 qapi_free_SocketAddress(s
->saddr
);
162 g_free(s
->tlscredsid
);
163 s
->tlscredsid
= NULL
;
164 g_free(s
->x_dirty_bitmap
);
165 s
->x_dirty_bitmap
= NULL
;
168 static void nbd_channel_error(BDRVNBDState
*s
, int ret
)
171 if (qatomic_load_acquire(&s
->state
) == NBD_CLIENT_CONNECTED
) {
172 s
->state
= s
->reconnect_delay
? NBD_CLIENT_CONNECTING_WAIT
:
173 NBD_CLIENT_CONNECTING_NOWAIT
;
176 if (qatomic_load_acquire(&s
->state
) == NBD_CLIENT_CONNECTED
) {
177 qio_channel_shutdown(s
->ioc
, QIO_CHANNEL_SHUTDOWN_BOTH
, NULL
);
179 s
->state
= NBD_CLIENT_QUIT
;
183 static void nbd_recv_coroutines_wake_all(BDRVNBDState
*s
)
187 for (i
= 0; i
< MAX_NBD_REQUESTS
; i
++) {
188 NBDClientRequest
*req
= &s
->requests
[i
];
190 if (req
->coroutine
&& req
->receiving
) {
191 aio_co_wake(req
->coroutine
);
196 static void reconnect_delay_timer_del(BDRVNBDState
*s
)
198 if (s
->reconnect_delay_timer
) {
199 timer_free(s
->reconnect_delay_timer
);
200 s
->reconnect_delay_timer
= NULL
;
204 static void reconnect_delay_timer_cb(void *opaque
)
206 BDRVNBDState
*s
= opaque
;
208 if (qatomic_load_acquire(&s
->state
) == NBD_CLIENT_CONNECTING_WAIT
) {
209 s
->state
= NBD_CLIENT_CONNECTING_NOWAIT
;
210 while (qemu_co_enter_next(&s
->free_sema
, NULL
)) {
211 /* Resume all queued requests */
215 reconnect_delay_timer_del(s
);
218 static void reconnect_delay_timer_init(BDRVNBDState
*s
, uint64_t expire_time_ns
)
220 if (qatomic_load_acquire(&s
->state
) != NBD_CLIENT_CONNECTING_WAIT
) {
224 assert(!s
->reconnect_delay_timer
);
225 s
->reconnect_delay_timer
= aio_timer_new(bdrv_get_aio_context(s
->bs
),
228 reconnect_delay_timer_cb
, s
);
229 timer_mod(s
->reconnect_delay_timer
, expire_time_ns
);
232 static void nbd_client_detach_aio_context(BlockDriverState
*bs
)
234 BDRVNBDState
*s
= (BDRVNBDState
*)bs
->opaque
;
236 /* Timer is deleted in nbd_client_co_drain_begin() */
237 assert(!s
->reconnect_delay_timer
);
239 * If reconnect is in progress we may have no ->ioc. It will be
240 * re-instantiated in the proper aio context once the connection is
244 qio_channel_detach_aio_context(QIO_CHANNEL(s
->ioc
));
248 static void nbd_client_attach_aio_context_bh(void *opaque
)
250 BlockDriverState
*bs
= opaque
;
251 BDRVNBDState
*s
= (BDRVNBDState
*)bs
->opaque
;
253 if (s
->connection_co
) {
255 * The node is still drained, so we know the coroutine has yielded in
256 * nbd_read_eof(), the only place where bs->in_flight can reach 0, or
257 * it is entered for the first time. Both places are safe for entering
260 qemu_aio_coroutine_enter(bs
->aio_context
, s
->connection_co
);
262 bdrv_dec_in_flight(bs
);
265 static void nbd_client_attach_aio_context(BlockDriverState
*bs
,
266 AioContext
*new_context
)
268 BDRVNBDState
*s
= (BDRVNBDState
*)bs
->opaque
;
271 * s->connection_co is either yielded from nbd_receive_reply or from
272 * nbd_co_reconnect_loop()
274 if (qatomic_load_acquire(&s
->state
) == NBD_CLIENT_CONNECTED
) {
275 qio_channel_attach_aio_context(QIO_CHANNEL(s
->ioc
), new_context
);
278 bdrv_inc_in_flight(bs
);
281 * Need to wait here for the BH to run because the BH must run while the
282 * node is still drained.
284 aio_wait_bh_oneshot(new_context
, nbd_client_attach_aio_context_bh
, bs
);
287 static void coroutine_fn
nbd_client_co_drain_begin(BlockDriverState
*bs
)
289 BDRVNBDState
*s
= (BDRVNBDState
*)bs
->opaque
;
292 if (s
->connection_co_sleep_ns_state
) {
293 qemu_co_sleep_wake(s
->connection_co_sleep_ns_state
);
296 nbd_co_establish_connection_cancel(bs
, false);
298 reconnect_delay_timer_del(s
);
300 if (qatomic_load_acquire(&s
->state
) == NBD_CLIENT_CONNECTING_WAIT
) {
301 s
->state
= NBD_CLIENT_CONNECTING_NOWAIT
;
302 qemu_co_queue_restart_all(&s
->free_sema
);
306 static void coroutine_fn
nbd_client_co_drain_end(BlockDriverState
*bs
)
308 BDRVNBDState
*s
= (BDRVNBDState
*)bs
->opaque
;
311 if (s
->wait_drained_end
) {
312 s
->wait_drained_end
= false;
313 aio_co_wake(s
->connection_co
);
318 static void nbd_teardown_connection(BlockDriverState
*bs
)
320 BDRVNBDState
*s
= (BDRVNBDState
*)bs
->opaque
;
323 /* finish any pending coroutines */
324 qio_channel_shutdown(s
->ioc
, QIO_CHANNEL_SHUTDOWN_BOTH
, NULL
);
325 } else if (s
->sioc
) {
326 /* abort negotiation */
327 qio_channel_shutdown(QIO_CHANNEL(s
->sioc
), QIO_CHANNEL_SHUTDOWN_BOTH
,
331 s
->state
= NBD_CLIENT_QUIT
;
332 if (s
->connection_co
) {
333 if (s
->connection_co_sleep_ns_state
) {
334 qemu_co_sleep_wake(s
->connection_co_sleep_ns_state
);
336 nbd_co_establish_connection_cancel(bs
, true);
338 if (qemu_in_coroutine()) {
339 s
->teardown_co
= qemu_coroutine_self();
340 /* connection_co resumes us when it terminates */
341 qemu_coroutine_yield();
342 s
->teardown_co
= NULL
;
344 BDRV_POLL_WHILE(bs
, s
->connection_co
);
346 assert(!s
->connection_co
);
349 static bool nbd_client_connecting(BDRVNBDState
*s
)
351 NBDClientState state
= qatomic_load_acquire(&s
->state
);
352 return state
== NBD_CLIENT_CONNECTING_WAIT
||
353 state
== NBD_CLIENT_CONNECTING_NOWAIT
;
356 static bool nbd_client_connecting_wait(BDRVNBDState
*s
)
358 return qatomic_load_acquire(&s
->state
) == NBD_CLIENT_CONNECTING_WAIT
;
361 static void connect_bh(void *opaque
)
363 BDRVNBDState
*state
= opaque
;
365 assert(state
->wait_connect
);
366 state
->wait_connect
= false;
367 aio_co_wake(state
->connection_co
);
370 static void nbd_init_connect_thread(BDRVNBDState
*s
)
372 s
->connect_thread
= g_new(NBDConnectThread
, 1);
374 *s
->connect_thread
= (NBDConnectThread
) {
375 .saddr
= QAPI_CLONE(SocketAddress
, s
->saddr
),
376 .state
= CONNECT_THREAD_NONE
,
377 .bh_func
= connect_bh
,
381 qemu_mutex_init(&s
->connect_thread
->mutex
);
384 static void nbd_free_connect_thread(NBDConnectThread
*thr
)
387 qio_channel_close(QIO_CHANNEL(thr
->sioc
), NULL
);
389 error_free(thr
->err
);
390 qapi_free_SocketAddress(thr
->saddr
);
394 static void *connect_thread_func(void *opaque
)
396 NBDConnectThread
*thr
= opaque
;
398 bool do_free
= false;
400 thr
->sioc
= qio_channel_socket_new();
402 error_free(thr
->err
);
404 ret
= qio_channel_socket_connect_sync(thr
->sioc
, thr
->saddr
, &thr
->err
);
406 object_unref(OBJECT(thr
->sioc
));
410 qemu_mutex_lock(&thr
->mutex
);
412 switch (thr
->state
) {
413 case CONNECT_THREAD_RUNNING
:
414 thr
->state
= ret
< 0 ? CONNECT_THREAD_FAIL
: CONNECT_THREAD_SUCCESS
;
416 aio_bh_schedule_oneshot(thr
->bh_ctx
, thr
->bh_func
, thr
->bh_opaque
);
418 /* play safe, don't reuse bh_ctx on further connection attempts */
422 case CONNECT_THREAD_RUNNING_DETACHED
:
429 qemu_mutex_unlock(&thr
->mutex
);
432 nbd_free_connect_thread(thr
);
438 static int coroutine_fn
439 nbd_co_establish_connection(BlockDriverState
*bs
, Error
**errp
)
443 BDRVNBDState
*s
= bs
->opaque
;
444 NBDConnectThread
*thr
= s
->connect_thread
;
446 qemu_mutex_lock(&thr
->mutex
);
448 switch (thr
->state
) {
449 case CONNECT_THREAD_FAIL
:
450 case CONNECT_THREAD_NONE
:
451 error_free(thr
->err
);
453 thr
->state
= CONNECT_THREAD_RUNNING
;
454 qemu_thread_create(&thread
, "nbd-connect",
455 connect_thread_func
, thr
, QEMU_THREAD_DETACHED
);
457 case CONNECT_THREAD_SUCCESS
:
458 /* Previous attempt finally succeeded in background */
459 thr
->state
= CONNECT_THREAD_NONE
;
462 yank_register_function(BLOCKDEV_YANK_INSTANCE(bs
->node_name
),
464 qemu_mutex_unlock(&thr
->mutex
);
466 case CONNECT_THREAD_RUNNING
:
467 /* Already running, will wait */
473 thr
->bh_ctx
= qemu_get_current_aio_context();
475 qemu_mutex_unlock(&thr
->mutex
);
479 * We are going to wait for connect-thread finish, but
480 * nbd_client_co_drain_begin() can interrupt.
482 * Note that wait_connect variable is not visible for connect-thread. It
483 * doesn't need mutex protection, it used only inside home aio context of
486 s
->wait_connect
= true;
487 qemu_coroutine_yield();
489 qemu_mutex_lock(&thr
->mutex
);
491 switch (thr
->state
) {
492 case CONNECT_THREAD_SUCCESS
:
493 case CONNECT_THREAD_FAIL
:
494 thr
->state
= CONNECT_THREAD_NONE
;
495 error_propagate(errp
, thr
->err
);
500 yank_register_function(BLOCKDEV_YANK_INSTANCE(bs
->node_name
),
503 ret
= (s
->sioc
? 0 : -1);
505 case CONNECT_THREAD_RUNNING
:
506 case CONNECT_THREAD_RUNNING_DETACHED
:
508 * Obviously, drained section wants to start. Report the attempt as
509 * failed. Still connect thread is executing in background, and its
510 * result may be used for next connection attempt.
513 error_setg(errp
, "Connection attempt cancelled by other operation");
516 case CONNECT_THREAD_NONE
:
518 * Impossible. We've seen this thread running. So it should be
519 * running or at least give some results.
527 qemu_mutex_unlock(&thr
->mutex
);
533 * nbd_co_establish_connection_cancel
534 * Cancel nbd_co_establish_connection asynchronously: it will finish soon, to
535 * allow drained section to begin.
537 * If detach is true, also cleanup the state (or if thread is running, move it
538 * to CONNECT_THREAD_RUNNING_DETACHED state). s->connect_thread becomes NULL if
541 static void nbd_co_establish_connection_cancel(BlockDriverState
*bs
,
544 BDRVNBDState
*s
= bs
->opaque
;
545 NBDConnectThread
*thr
= s
->connect_thread
;
547 bool do_free
= false;
549 qemu_mutex_lock(&thr
->mutex
);
551 if (thr
->state
== CONNECT_THREAD_RUNNING
) {
552 /* We can cancel only in running state, when bh is not yet scheduled */
554 if (s
->wait_connect
) {
555 s
->wait_connect
= false;
559 thr
->state
= CONNECT_THREAD_RUNNING_DETACHED
;
560 s
->connect_thread
= NULL
;
566 qemu_mutex_unlock(&thr
->mutex
);
569 nbd_free_connect_thread(thr
);
570 s
->connect_thread
= NULL
;
574 aio_co_wake(s
->connection_co
);
578 static coroutine_fn
void nbd_reconnect_attempt(BDRVNBDState
*s
)
581 Error
*local_err
= NULL
;
583 if (!nbd_client_connecting(s
)) {
587 /* Wait for completion of all in-flight requests */
589 qemu_co_mutex_lock(&s
->send_mutex
);
591 while (s
->in_flight
> 0) {
592 qemu_co_mutex_unlock(&s
->send_mutex
);
593 nbd_recv_coroutines_wake_all(s
);
594 s
->wait_in_flight
= true;
595 qemu_coroutine_yield();
596 s
->wait_in_flight
= false;
597 qemu_co_mutex_lock(&s
->send_mutex
);
600 qemu_co_mutex_unlock(&s
->send_mutex
);
602 if (!nbd_client_connecting(s
)) {
607 * Now we are sure that nobody is accessing the channel, and no one will
608 * try until we set the state to CONNECTED.
611 /* Finalize previous connection if any */
613 qio_channel_detach_aio_context(QIO_CHANNEL(s
->ioc
));
614 yank_unregister_function(BLOCKDEV_YANK_INSTANCE(s
->bs
->node_name
),
616 object_unref(OBJECT(s
->sioc
));
618 object_unref(OBJECT(s
->ioc
));
622 if (nbd_co_establish_connection(s
->bs
, &local_err
) < 0) {
627 bdrv_dec_in_flight(s
->bs
);
629 ret
= nbd_client_handshake(s
->bs
, &local_err
);
632 s
->wait_drained_end
= true;
635 * We may be entered once from nbd_client_attach_aio_context_bh
636 * and then from nbd_client_co_drain_end. So here is a loop.
638 qemu_coroutine_yield();
641 bdrv_inc_in_flight(s
->bs
);
644 s
->connect_status
= ret
;
645 error_free(s
->connect_err
);
646 s
->connect_err
= NULL
;
647 error_propagate(&s
->connect_err
, local_err
);
650 /* successfully connected */
651 s
->state
= NBD_CLIENT_CONNECTED
;
652 qemu_co_queue_restart_all(&s
->free_sema
);
656 static coroutine_fn
void nbd_co_reconnect_loop(BDRVNBDState
*s
)
658 uint64_t timeout
= 1 * NANOSECONDS_PER_SECOND
;
659 uint64_t max_timeout
= 16 * NANOSECONDS_PER_SECOND
;
661 if (qatomic_load_acquire(&s
->state
) == NBD_CLIENT_CONNECTING_WAIT
) {
662 reconnect_delay_timer_init(s
, qemu_clock_get_ns(QEMU_CLOCK_REALTIME
) +
663 s
->reconnect_delay
* NANOSECONDS_PER_SECOND
);
666 nbd_reconnect_attempt(s
);
668 while (nbd_client_connecting(s
)) {
670 bdrv_dec_in_flight(s
->bs
);
671 s
->wait_drained_end
= true;
674 * We may be entered once from nbd_client_attach_aio_context_bh
675 * and then from nbd_client_co_drain_end. So here is a loop.
677 qemu_coroutine_yield();
679 bdrv_inc_in_flight(s
->bs
);
681 qemu_co_sleep_ns_wakeable(QEMU_CLOCK_REALTIME
, timeout
,
682 &s
->connection_co_sleep_ns_state
);
686 if (timeout
< max_timeout
) {
691 nbd_reconnect_attempt(s
);
694 reconnect_delay_timer_del(s
);
697 static coroutine_fn
void nbd_connection_entry(void *opaque
)
699 BDRVNBDState
*s
= opaque
;
702 Error
*local_err
= NULL
;
704 while (qatomic_load_acquire(&s
->state
) != NBD_CLIENT_QUIT
) {
706 * The NBD client can only really be considered idle when it has
707 * yielded from qio_channel_readv_all_eof(), waiting for data. This is
708 * the point where the additional scheduled coroutine entry happens
709 * after nbd_client_attach_aio_context().
711 * Therefore we keep an additional in_flight reference all the time and
712 * only drop it temporarily here.
715 if (nbd_client_connecting(s
)) {
716 nbd_co_reconnect_loop(s
);
719 if (qatomic_load_acquire(&s
->state
) != NBD_CLIENT_CONNECTED
) {
723 assert(s
->reply
.handle
== 0);
724 ret
= nbd_receive_reply(s
->bs
, s
->ioc
, &s
->reply
, &local_err
);
727 trace_nbd_read_reply_entry_fail(ret
, error_get_pretty(local_err
));
728 error_free(local_err
);
732 nbd_channel_error(s
, ret
? ret
: -EIO
);
737 * There's no need for a mutex on the receive side, because the
738 * handler acts as a synchronization point and ensures that only
739 * one coroutine is called until the reply finishes.
741 i
= HANDLE_TO_INDEX(s
, s
->reply
.handle
);
742 if (i
>= MAX_NBD_REQUESTS
||
743 !s
->requests
[i
].coroutine
||
744 !s
->requests
[i
].receiving
||
745 (nbd_reply_is_structured(&s
->reply
) && !s
->info
.structured_reply
))
747 nbd_channel_error(s
, -EINVAL
);
752 * We're woken up again by the request itself. Note that there
753 * is no race between yielding and reentering connection_co. This
756 * - if the request runs on the same AioContext, it is only
757 * entered after we yield
759 * - if the request runs on a different AioContext, reentering
760 * connection_co happens through a bottom half, which can only
761 * run after we yield.
763 aio_co_wake(s
->requests
[i
].coroutine
);
764 qemu_coroutine_yield();
767 qemu_co_queue_restart_all(&s
->free_sema
);
768 nbd_recv_coroutines_wake_all(s
);
769 bdrv_dec_in_flight(s
->bs
);
771 s
->connection_co
= NULL
;
773 qio_channel_detach_aio_context(QIO_CHANNEL(s
->ioc
));
774 yank_unregister_function(BLOCKDEV_YANK_INSTANCE(s
->bs
->node_name
),
776 object_unref(OBJECT(s
->sioc
));
778 object_unref(OBJECT(s
->ioc
));
782 if (s
->teardown_co
) {
783 aio_co_wake(s
->teardown_co
);
788 static int nbd_co_send_request(BlockDriverState
*bs
,
792 BDRVNBDState
*s
= (BDRVNBDState
*)bs
->opaque
;
795 qemu_co_mutex_lock(&s
->send_mutex
);
796 while (s
->in_flight
== MAX_NBD_REQUESTS
|| nbd_client_connecting_wait(s
)) {
797 qemu_co_queue_wait(&s
->free_sema
, &s
->send_mutex
);
800 if (qatomic_load_acquire(&s
->state
) != NBD_CLIENT_CONNECTED
) {
807 for (i
= 0; i
< MAX_NBD_REQUESTS
; i
++) {
808 if (s
->requests
[i
].coroutine
== NULL
) {
813 g_assert(qemu_in_coroutine());
814 assert(i
< MAX_NBD_REQUESTS
);
816 s
->requests
[i
].coroutine
= qemu_coroutine_self();
817 s
->requests
[i
].offset
= request
->from
;
818 s
->requests
[i
].receiving
= false;
820 request
->handle
= INDEX_TO_HANDLE(s
, i
);
825 qio_channel_set_cork(s
->ioc
, true);
826 rc
= nbd_send_request(s
->ioc
, request
);
827 if (qatomic_load_acquire(&s
->state
) == NBD_CLIENT_CONNECTED
&&
829 if (qio_channel_writev_all(s
->ioc
, qiov
->iov
, qiov
->niov
,
833 } else if (rc
>= 0) {
836 qio_channel_set_cork(s
->ioc
, false);
838 rc
= nbd_send_request(s
->ioc
, request
);
843 nbd_channel_error(s
, rc
);
845 s
->requests
[i
].coroutine
= NULL
;
848 if (s
->in_flight
== 0 && s
->wait_in_flight
) {
849 aio_co_wake(s
->connection_co
);
851 qemu_co_queue_next(&s
->free_sema
);
854 qemu_co_mutex_unlock(&s
->send_mutex
);
858 static inline uint16_t payload_advance16(uint8_t **payload
)
861 return lduw_be_p(*payload
- 2);
864 static inline uint32_t payload_advance32(uint8_t **payload
)
867 return ldl_be_p(*payload
- 4);
870 static inline uint64_t payload_advance64(uint8_t **payload
)
873 return ldq_be_p(*payload
- 8);
876 static int nbd_parse_offset_hole_payload(BDRVNBDState
*s
,
877 NBDStructuredReplyChunk
*chunk
,
878 uint8_t *payload
, uint64_t orig_offset
,
879 QEMUIOVector
*qiov
, Error
**errp
)
884 if (chunk
->length
!= sizeof(offset
) + sizeof(hole_size
)) {
885 error_setg(errp
, "Protocol error: invalid payload for "
886 "NBD_REPLY_TYPE_OFFSET_HOLE");
890 offset
= payload_advance64(&payload
);
891 hole_size
= payload_advance32(&payload
);
893 if (!hole_size
|| offset
< orig_offset
|| hole_size
> qiov
->size
||
894 offset
> orig_offset
+ qiov
->size
- hole_size
) {
895 error_setg(errp
, "Protocol error: server sent chunk exceeding requested"
899 if (s
->info
.min_block
&&
900 !QEMU_IS_ALIGNED(hole_size
, s
->info
.min_block
)) {
901 trace_nbd_structured_read_compliance("hole");
904 qemu_iovec_memset(qiov
, offset
- orig_offset
, 0, hole_size
);
910 * nbd_parse_blockstatus_payload
911 * Based on our request, we expect only one extent in reply, for the
912 * base:allocation context.
914 static int nbd_parse_blockstatus_payload(BDRVNBDState
*s
,
915 NBDStructuredReplyChunk
*chunk
,
916 uint8_t *payload
, uint64_t orig_length
,
917 NBDExtent
*extent
, Error
**errp
)
921 /* The server succeeded, so it must have sent [at least] one extent */
922 if (chunk
->length
< sizeof(context_id
) + sizeof(*extent
)) {
923 error_setg(errp
, "Protocol error: invalid payload for "
924 "NBD_REPLY_TYPE_BLOCK_STATUS");
928 context_id
= payload_advance32(&payload
);
929 if (s
->info
.context_id
!= context_id
) {
930 error_setg(errp
, "Protocol error: unexpected context id %d for "
931 "NBD_REPLY_TYPE_BLOCK_STATUS, when negotiated context "
932 "id is %d", context_id
,
937 extent
->length
= payload_advance32(&payload
);
938 extent
->flags
= payload_advance32(&payload
);
940 if (extent
->length
== 0) {
941 error_setg(errp
, "Protocol error: server sent status chunk with "
947 * A server sending unaligned block status is in violation of the
948 * protocol, but as qemu-nbd 3.1 is such a server (at least for
949 * POSIX files that are not a multiple of 512 bytes, since qemu
950 * rounds files up to 512-byte multiples but lseek(SEEK_HOLE)
951 * still sees an implicit hole beyond the real EOF), it's nicer to
952 * work around the misbehaving server. If the request included
953 * more than the final unaligned block, truncate it back to an
954 * aligned result; if the request was only the final block, round
955 * up to the full block and change the status to fully-allocated
956 * (always a safe status, even if it loses information).
958 if (s
->info
.min_block
&& !QEMU_IS_ALIGNED(extent
->length
,
959 s
->info
.min_block
)) {
960 trace_nbd_parse_blockstatus_compliance("extent length is unaligned");
961 if (extent
->length
> s
->info
.min_block
) {
962 extent
->length
= QEMU_ALIGN_DOWN(extent
->length
,
965 extent
->length
= s
->info
.min_block
;
971 * We used NBD_CMD_FLAG_REQ_ONE, so the server should not have
972 * sent us any more than one extent, nor should it have included
973 * status beyond our request in that extent. However, it's easy
974 * enough to ignore the server's noncompliance without killing the
975 * connection; just ignore trailing extents, and clamp things to
976 * the length of our request.
978 if (chunk
->length
> sizeof(context_id
) + sizeof(*extent
)) {
979 trace_nbd_parse_blockstatus_compliance("more than one extent");
981 if (extent
->length
> orig_length
) {
982 extent
->length
= orig_length
;
983 trace_nbd_parse_blockstatus_compliance("extent length too large");
987 * HACK: if we are using x-dirty-bitmaps to access
988 * qemu:allocation-depth, treat all depths > 2 the same as 2,
989 * since nbd_client_co_block_status is only expecting the low two
992 if (s
->alloc_depth
&& extent
->flags
> 2) {
1000 * nbd_parse_error_payload
1001 * on success @errp contains message describing nbd error reply
1003 static int nbd_parse_error_payload(NBDStructuredReplyChunk
*chunk
,
1004 uint8_t *payload
, int *request_ret
,
1008 uint16_t message_size
;
1010 assert(chunk
->type
& (1 << 15));
1012 if (chunk
->length
< sizeof(error
) + sizeof(message_size
)) {
1014 "Protocol error: invalid payload for structured error");
1018 error
= nbd_errno_to_system_errno(payload_advance32(&payload
));
1020 error_setg(errp
, "Protocol error: server sent structured error chunk "
1025 *request_ret
= -error
;
1026 message_size
= payload_advance16(&payload
);
1028 if (message_size
> chunk
->length
- sizeof(error
) - sizeof(message_size
)) {
1029 error_setg(errp
, "Protocol error: server sent structured error chunk "
1030 "with incorrect message size");
1034 /* TODO: Add a trace point to mention the server complaint */
1036 /* TODO handle ERROR_OFFSET */
1041 static int nbd_co_receive_offset_data_payload(BDRVNBDState
*s
,
1042 uint64_t orig_offset
,
1043 QEMUIOVector
*qiov
, Error
**errp
)
1045 QEMUIOVector sub_qiov
;
1049 NBDStructuredReplyChunk
*chunk
= &s
->reply
.structured
;
1051 assert(nbd_reply_is_structured(&s
->reply
));
1053 /* The NBD spec requires at least one byte of payload */
1054 if (chunk
->length
<= sizeof(offset
)) {
1055 error_setg(errp
, "Protocol error: invalid payload for "
1056 "NBD_REPLY_TYPE_OFFSET_DATA");
1060 if (nbd_read64(s
->ioc
, &offset
, "OFFSET_DATA offset", errp
) < 0) {
1064 data_size
= chunk
->length
- sizeof(offset
);
1066 if (offset
< orig_offset
|| data_size
> qiov
->size
||
1067 offset
> orig_offset
+ qiov
->size
- data_size
) {
1068 error_setg(errp
, "Protocol error: server sent chunk exceeding requested"
1072 if (s
->info
.min_block
&& !QEMU_IS_ALIGNED(data_size
, s
->info
.min_block
)) {
1073 trace_nbd_structured_read_compliance("data");
1076 qemu_iovec_init(&sub_qiov
, qiov
->niov
);
1077 qemu_iovec_concat(&sub_qiov
, qiov
, offset
- orig_offset
, data_size
);
1078 ret
= qio_channel_readv_all(s
->ioc
, sub_qiov
.iov
, sub_qiov
.niov
, errp
);
1079 qemu_iovec_destroy(&sub_qiov
);
1081 return ret
< 0 ? -EIO
: 0;
1084 #define NBD_MAX_MALLOC_PAYLOAD 1000
1085 static coroutine_fn
int nbd_co_receive_structured_payload(
1086 BDRVNBDState
*s
, void **payload
, Error
**errp
)
1091 assert(nbd_reply_is_structured(&s
->reply
));
1093 len
= s
->reply
.structured
.length
;
1099 if (payload
== NULL
) {
1100 error_setg(errp
, "Unexpected structured payload");
1104 if (len
> NBD_MAX_MALLOC_PAYLOAD
) {
1105 error_setg(errp
, "Payload too large");
1109 *payload
= g_new(char, len
);
1110 ret
= nbd_read(s
->ioc
, *payload
, len
, "structured payload", errp
);
1121 * nbd_co_do_receive_one_chunk
1123 * set request_ret to received reply error
1124 * if qiov is not NULL: read payload to @qiov
1125 * for structured reply chunk:
1126 * if error chunk: read payload, set @request_ret, do not set @payload
1127 * else if offset_data chunk: read payload data to @qiov, do not set @payload
1128 * else: read payload to @payload
1130 * If function fails, @errp contains corresponding error message, and the
1131 * connection with the server is suspect. If it returns 0, then the
1132 * transaction succeeded (although @request_ret may be a negative errno
1133 * corresponding to the server's error reply), and errp is unchanged.
1135 static coroutine_fn
int nbd_co_do_receive_one_chunk(
1136 BDRVNBDState
*s
, uint64_t handle
, bool only_structured
,
1137 int *request_ret
, QEMUIOVector
*qiov
, void **payload
, Error
**errp
)
1140 int i
= HANDLE_TO_INDEX(s
, handle
);
1141 void *local_payload
= NULL
;
1142 NBDStructuredReplyChunk
*chunk
;
1149 /* Wait until we're woken up by nbd_connection_entry. */
1150 s
->requests
[i
].receiving
= true;
1151 qemu_coroutine_yield();
1152 s
->requests
[i
].receiving
= false;
1153 if (qatomic_load_acquire(&s
->state
) != NBD_CLIENT_CONNECTED
) {
1154 error_setg(errp
, "Connection closed");
1159 assert(s
->reply
.handle
== handle
);
1161 if (nbd_reply_is_simple(&s
->reply
)) {
1162 if (only_structured
) {
1163 error_setg(errp
, "Protocol error: simple reply when structured "
1164 "reply chunk was expected");
1168 *request_ret
= -nbd_errno_to_system_errno(s
->reply
.simple
.error
);
1169 if (*request_ret
< 0 || !qiov
) {
1173 return qio_channel_readv_all(s
->ioc
, qiov
->iov
, qiov
->niov
,
1174 errp
) < 0 ? -EIO
: 0;
1177 /* handle structured reply chunk */
1178 assert(s
->info
.structured_reply
);
1179 chunk
= &s
->reply
.structured
;
1181 if (chunk
->type
== NBD_REPLY_TYPE_NONE
) {
1182 if (!(chunk
->flags
& NBD_REPLY_FLAG_DONE
)) {
1183 error_setg(errp
, "Protocol error: NBD_REPLY_TYPE_NONE chunk without"
1184 " NBD_REPLY_FLAG_DONE flag set");
1187 if (chunk
->length
) {
1188 error_setg(errp
, "Protocol error: NBD_REPLY_TYPE_NONE chunk with"
1195 if (chunk
->type
== NBD_REPLY_TYPE_OFFSET_DATA
) {
1197 error_setg(errp
, "Unexpected NBD_REPLY_TYPE_OFFSET_DATA chunk");
1201 return nbd_co_receive_offset_data_payload(s
, s
->requests
[i
].offset
,
1205 if (nbd_reply_type_is_error(chunk
->type
)) {
1206 payload
= &local_payload
;
1209 ret
= nbd_co_receive_structured_payload(s
, payload
, errp
);
1214 if (nbd_reply_type_is_error(chunk
->type
)) {
1215 ret
= nbd_parse_error_payload(chunk
, local_payload
, request_ret
, errp
);
1216 g_free(local_payload
);
1224 * nbd_co_receive_one_chunk
1225 * Read reply, wake up connection_co and set s->quit if needed.
1226 * Return value is a fatal error code or normal nbd reply error code
1228 static coroutine_fn
int nbd_co_receive_one_chunk(
1229 BDRVNBDState
*s
, uint64_t handle
, bool only_structured
,
1230 int *request_ret
, QEMUIOVector
*qiov
, NBDReply
*reply
, void **payload
,
1233 int ret
= nbd_co_do_receive_one_chunk(s
, handle
, only_structured
,
1234 request_ret
, qiov
, payload
, errp
);
1237 memset(reply
, 0, sizeof(*reply
));
1238 nbd_channel_error(s
, ret
);
1240 /* For assert at loop start in nbd_connection_entry */
1243 s
->reply
.handle
= 0;
1245 if (s
->connection_co
&& !s
->wait_in_flight
) {
1247 * We must check s->wait_in_flight, because we may entered by
1248 * nbd_recv_coroutines_wake_all(), in this case we should not
1249 * wake connection_co here, it will woken by last request.
1251 aio_co_wake(s
->connection_co
);
1257 typedef struct NBDReplyChunkIter
{
1261 bool done
, only_structured
;
1262 } NBDReplyChunkIter
;
1264 static void nbd_iter_channel_error(NBDReplyChunkIter
*iter
,
1265 int ret
, Error
**local_err
)
1267 assert(local_err
&& *local_err
);
1272 error_propagate(&iter
->err
, *local_err
);
1274 error_free(*local_err
);
1280 static void nbd_iter_request_error(NBDReplyChunkIter
*iter
, int ret
)
1284 if (!iter
->request_ret
) {
1285 iter
->request_ret
= ret
;
1290 * NBD_FOREACH_REPLY_CHUNK
1291 * The pointer stored in @payload requires g_free() to free it.
1293 #define NBD_FOREACH_REPLY_CHUNK(s, iter, handle, structured, \
1294 qiov, reply, payload) \
1295 for (iter = (NBDReplyChunkIter) { .only_structured = structured }; \
1296 nbd_reply_chunk_iter_receive(s, &iter, handle, qiov, reply, payload);)
1299 * nbd_reply_chunk_iter_receive
1300 * The pointer stored in @payload requires g_free() to free it.
1302 static bool nbd_reply_chunk_iter_receive(BDRVNBDState
*s
,
1303 NBDReplyChunkIter
*iter
,
1305 QEMUIOVector
*qiov
, NBDReply
*reply
,
1308 int ret
, request_ret
;
1309 NBDReply local_reply
;
1310 NBDStructuredReplyChunk
*chunk
;
1311 Error
*local_err
= NULL
;
1312 if (qatomic_load_acquire(&s
->state
) != NBD_CLIENT_CONNECTED
) {
1313 error_setg(&local_err
, "Connection closed");
1314 nbd_iter_channel_error(iter
, -EIO
, &local_err
);
1319 /* Previous iteration was last. */
1323 if (reply
== NULL
) {
1324 reply
= &local_reply
;
1327 ret
= nbd_co_receive_one_chunk(s
, handle
, iter
->only_structured
,
1328 &request_ret
, qiov
, reply
, payload
,
1331 nbd_iter_channel_error(iter
, ret
, &local_err
);
1332 } else if (request_ret
< 0) {
1333 nbd_iter_request_error(iter
, request_ret
);
1336 /* Do not execute the body of NBD_FOREACH_REPLY_CHUNK for simple reply. */
1337 if (nbd_reply_is_simple(reply
) ||
1338 qatomic_load_acquire(&s
->state
) != NBD_CLIENT_CONNECTED
) {
1342 chunk
= &reply
->structured
;
1343 iter
->only_structured
= true;
1345 if (chunk
->type
== NBD_REPLY_TYPE_NONE
) {
1346 /* NBD_REPLY_FLAG_DONE is already checked in nbd_co_receive_one_chunk */
1347 assert(chunk
->flags
& NBD_REPLY_FLAG_DONE
);
1351 if (chunk
->flags
& NBD_REPLY_FLAG_DONE
) {
1352 /* This iteration is last. */
1356 /* Execute the loop body */
1360 s
->requests
[HANDLE_TO_INDEX(s
, handle
)].coroutine
= NULL
;
1362 qemu_co_mutex_lock(&s
->send_mutex
);
1364 if (s
->in_flight
== 0 && s
->wait_in_flight
) {
1365 aio_co_wake(s
->connection_co
);
1367 qemu_co_queue_next(&s
->free_sema
);
1369 qemu_co_mutex_unlock(&s
->send_mutex
);
1374 static int nbd_co_receive_return_code(BDRVNBDState
*s
, uint64_t handle
,
1375 int *request_ret
, Error
**errp
)
1377 NBDReplyChunkIter iter
;
1379 NBD_FOREACH_REPLY_CHUNK(s
, iter
, handle
, false, NULL
, NULL
, NULL
) {
1380 /* nbd_reply_chunk_iter_receive does all the work */
1383 error_propagate(errp
, iter
.err
);
1384 *request_ret
= iter
.request_ret
;
1388 static int nbd_co_receive_cmdread_reply(BDRVNBDState
*s
, uint64_t handle
,
1389 uint64_t offset
, QEMUIOVector
*qiov
,
1390 int *request_ret
, Error
**errp
)
1392 NBDReplyChunkIter iter
;
1394 void *payload
= NULL
;
1395 Error
*local_err
= NULL
;
1397 NBD_FOREACH_REPLY_CHUNK(s
, iter
, handle
, s
->info
.structured_reply
,
1398 qiov
, &reply
, &payload
)
1401 NBDStructuredReplyChunk
*chunk
= &reply
.structured
;
1403 assert(nbd_reply_is_structured(&reply
));
1405 switch (chunk
->type
) {
1406 case NBD_REPLY_TYPE_OFFSET_DATA
:
1408 * special cased in nbd_co_receive_one_chunk, data is already
1412 case NBD_REPLY_TYPE_OFFSET_HOLE
:
1413 ret
= nbd_parse_offset_hole_payload(s
, &reply
.structured
, payload
,
1414 offset
, qiov
, &local_err
);
1416 nbd_channel_error(s
, ret
);
1417 nbd_iter_channel_error(&iter
, ret
, &local_err
);
1421 if (!nbd_reply_type_is_error(chunk
->type
)) {
1422 /* not allowed reply type */
1423 nbd_channel_error(s
, -EINVAL
);
1424 error_setg(&local_err
,
1425 "Unexpected reply type: %d (%s) for CMD_READ",
1426 chunk
->type
, nbd_reply_type_lookup(chunk
->type
));
1427 nbd_iter_channel_error(&iter
, -EINVAL
, &local_err
);
1435 error_propagate(errp
, iter
.err
);
1436 *request_ret
= iter
.request_ret
;
1440 static int nbd_co_receive_blockstatus_reply(BDRVNBDState
*s
,
1441 uint64_t handle
, uint64_t length
,
1443 int *request_ret
, Error
**errp
)
1445 NBDReplyChunkIter iter
;
1447 void *payload
= NULL
;
1448 Error
*local_err
= NULL
;
1449 bool received
= false;
1451 assert(!extent
->length
);
1452 NBD_FOREACH_REPLY_CHUNK(s
, iter
, handle
, false, NULL
, &reply
, &payload
) {
1454 NBDStructuredReplyChunk
*chunk
= &reply
.structured
;
1456 assert(nbd_reply_is_structured(&reply
));
1458 switch (chunk
->type
) {
1459 case NBD_REPLY_TYPE_BLOCK_STATUS
:
1461 nbd_channel_error(s
, -EINVAL
);
1462 error_setg(&local_err
, "Several BLOCK_STATUS chunks in reply");
1463 nbd_iter_channel_error(&iter
, -EINVAL
, &local_err
);
1467 ret
= nbd_parse_blockstatus_payload(s
, &reply
.structured
,
1468 payload
, length
, extent
,
1471 nbd_channel_error(s
, ret
);
1472 nbd_iter_channel_error(&iter
, ret
, &local_err
);
1476 if (!nbd_reply_type_is_error(chunk
->type
)) {
1477 nbd_channel_error(s
, -EINVAL
);
1478 error_setg(&local_err
,
1479 "Unexpected reply type: %d (%s) "
1480 "for CMD_BLOCK_STATUS",
1481 chunk
->type
, nbd_reply_type_lookup(chunk
->type
));
1482 nbd_iter_channel_error(&iter
, -EINVAL
, &local_err
);
1490 if (!extent
->length
&& !iter
.request_ret
) {
1491 error_setg(&local_err
, "Server did not reply with any status extents");
1492 nbd_iter_channel_error(&iter
, -EIO
, &local_err
);
1495 error_propagate(errp
, iter
.err
);
1496 *request_ret
= iter
.request_ret
;
1500 static int nbd_co_request(BlockDriverState
*bs
, NBDRequest
*request
,
1501 QEMUIOVector
*write_qiov
)
1503 int ret
, request_ret
;
1504 Error
*local_err
= NULL
;
1505 BDRVNBDState
*s
= (BDRVNBDState
*)bs
->opaque
;
1507 assert(request
->type
!= NBD_CMD_READ
);
1509 assert(request
->type
== NBD_CMD_WRITE
);
1510 assert(request
->len
== iov_size(write_qiov
->iov
, write_qiov
->niov
));
1512 assert(request
->type
!= NBD_CMD_WRITE
);
1516 ret
= nbd_co_send_request(bs
, request
, write_qiov
);
1521 ret
= nbd_co_receive_return_code(s
, request
->handle
,
1522 &request_ret
, &local_err
);
1524 trace_nbd_co_request_fail(request
->from
, request
->len
,
1525 request
->handle
, request
->flags
,
1527 nbd_cmd_lookup(request
->type
),
1528 ret
, error_get_pretty(local_err
));
1529 error_free(local_err
);
1532 } while (ret
< 0 && nbd_client_connecting_wait(s
));
1534 return ret
? ret
: request_ret
;
1537 static int nbd_client_co_preadv(BlockDriverState
*bs
, uint64_t offset
,
1538 uint64_t bytes
, QEMUIOVector
*qiov
, int flags
)
1540 int ret
, request_ret
;
1541 Error
*local_err
= NULL
;
1542 BDRVNBDState
*s
= (BDRVNBDState
*)bs
->opaque
;
1543 NBDRequest request
= {
1544 .type
= NBD_CMD_READ
,
1549 assert(bytes
<= NBD_MAX_BUFFER_SIZE
);
1556 * Work around the fact that the block layer doesn't do
1557 * byte-accurate sizing yet - if the read exceeds the server's
1558 * advertised size because the block layer rounded size up, then
1559 * truncate the request to the server and tail-pad with zero.
1561 if (offset
>= s
->info
.size
) {
1562 assert(bytes
< BDRV_SECTOR_SIZE
);
1563 qemu_iovec_memset(qiov
, 0, 0, bytes
);
1566 if (offset
+ bytes
> s
->info
.size
) {
1567 uint64_t slop
= offset
+ bytes
- s
->info
.size
;
1569 assert(slop
< BDRV_SECTOR_SIZE
);
1570 qemu_iovec_memset(qiov
, bytes
- slop
, 0, slop
);
1571 request
.len
-= slop
;
1575 ret
= nbd_co_send_request(bs
, &request
, NULL
);
1580 ret
= nbd_co_receive_cmdread_reply(s
, request
.handle
, offset
, qiov
,
1581 &request_ret
, &local_err
);
1583 trace_nbd_co_request_fail(request
.from
, request
.len
, request
.handle
,
1584 request
.flags
, request
.type
,
1585 nbd_cmd_lookup(request
.type
),
1586 ret
, error_get_pretty(local_err
));
1587 error_free(local_err
);
1590 } while (ret
< 0 && nbd_client_connecting_wait(s
));
1592 return ret
? ret
: request_ret
;
1595 static int nbd_client_co_pwritev(BlockDriverState
*bs
, uint64_t offset
,
1596 uint64_t bytes
, QEMUIOVector
*qiov
, int flags
)
1598 BDRVNBDState
*s
= (BDRVNBDState
*)bs
->opaque
;
1599 NBDRequest request
= {
1600 .type
= NBD_CMD_WRITE
,
1605 assert(!(s
->info
.flags
& NBD_FLAG_READ_ONLY
));
1606 if (flags
& BDRV_REQ_FUA
) {
1607 assert(s
->info
.flags
& NBD_FLAG_SEND_FUA
);
1608 request
.flags
|= NBD_CMD_FLAG_FUA
;
1611 assert(bytes
<= NBD_MAX_BUFFER_SIZE
);
1616 return nbd_co_request(bs
, &request
, qiov
);
1619 static int nbd_client_co_pwrite_zeroes(BlockDriverState
*bs
, int64_t offset
,
1620 int bytes
, BdrvRequestFlags flags
)
1622 BDRVNBDState
*s
= (BDRVNBDState
*)bs
->opaque
;
1623 NBDRequest request
= {
1624 .type
= NBD_CMD_WRITE_ZEROES
,
1629 assert(!(s
->info
.flags
& NBD_FLAG_READ_ONLY
));
1630 if (!(s
->info
.flags
& NBD_FLAG_SEND_WRITE_ZEROES
)) {
1634 if (flags
& BDRV_REQ_FUA
) {
1635 assert(s
->info
.flags
& NBD_FLAG_SEND_FUA
);
1636 request
.flags
|= NBD_CMD_FLAG_FUA
;
1638 if (!(flags
& BDRV_REQ_MAY_UNMAP
)) {
1639 request
.flags
|= NBD_CMD_FLAG_NO_HOLE
;
1641 if (flags
& BDRV_REQ_NO_FALLBACK
) {
1642 assert(s
->info
.flags
& NBD_FLAG_SEND_FAST_ZERO
);
1643 request
.flags
|= NBD_CMD_FLAG_FAST_ZERO
;
1649 return nbd_co_request(bs
, &request
, NULL
);
1652 static int nbd_client_co_flush(BlockDriverState
*bs
)
1654 BDRVNBDState
*s
= (BDRVNBDState
*)bs
->opaque
;
1655 NBDRequest request
= { .type
= NBD_CMD_FLUSH
};
1657 if (!(s
->info
.flags
& NBD_FLAG_SEND_FLUSH
)) {
1664 return nbd_co_request(bs
, &request
, NULL
);
1667 static int nbd_client_co_pdiscard(BlockDriverState
*bs
, int64_t offset
,
1670 BDRVNBDState
*s
= (BDRVNBDState
*)bs
->opaque
;
1671 NBDRequest request
= {
1672 .type
= NBD_CMD_TRIM
,
1677 assert(!(s
->info
.flags
& NBD_FLAG_READ_ONLY
));
1678 if (!(s
->info
.flags
& NBD_FLAG_SEND_TRIM
) || !bytes
) {
1682 return nbd_co_request(bs
, &request
, NULL
);
1685 static int coroutine_fn
nbd_client_co_block_status(
1686 BlockDriverState
*bs
, bool want_zero
, int64_t offset
, int64_t bytes
,
1687 int64_t *pnum
, int64_t *map
, BlockDriverState
**file
)
1689 int ret
, request_ret
;
1690 NBDExtent extent
= { 0 };
1691 BDRVNBDState
*s
= (BDRVNBDState
*)bs
->opaque
;
1692 Error
*local_err
= NULL
;
1694 NBDRequest request
= {
1695 .type
= NBD_CMD_BLOCK_STATUS
,
1697 .len
= MIN(QEMU_ALIGN_DOWN(INT_MAX
, bs
->bl
.request_alignment
),
1698 MIN(bytes
, s
->info
.size
- offset
)),
1699 .flags
= NBD_CMD_FLAG_REQ_ONE
,
1702 if (!s
->info
.base_allocation
) {
1706 return BDRV_BLOCK_DATA
| BDRV_BLOCK_OFFSET_VALID
;
1710 * Work around the fact that the block layer doesn't do
1711 * byte-accurate sizing yet - if the status request exceeds the
1712 * server's advertised size because the block layer rounded size
1713 * up, we truncated the request to the server (above), or are
1714 * called on just the hole.
1716 if (offset
>= s
->info
.size
) {
1718 assert(bytes
< BDRV_SECTOR_SIZE
);
1719 /* Intentionally don't report offset_valid for the hole */
1720 return BDRV_BLOCK_ZERO
;
1723 if (s
->info
.min_block
) {
1724 assert(QEMU_IS_ALIGNED(request
.len
, s
->info
.min_block
));
1727 ret
= nbd_co_send_request(bs
, &request
, NULL
);
1732 ret
= nbd_co_receive_blockstatus_reply(s
, request
.handle
, bytes
,
1733 &extent
, &request_ret
,
1736 trace_nbd_co_request_fail(request
.from
, request
.len
, request
.handle
,
1737 request
.flags
, request
.type
,
1738 nbd_cmd_lookup(request
.type
),
1739 ret
, error_get_pretty(local_err
));
1740 error_free(local_err
);
1743 } while (ret
< 0 && nbd_client_connecting_wait(s
));
1745 if (ret
< 0 || request_ret
< 0) {
1746 return ret
? ret
: request_ret
;
1749 assert(extent
.length
);
1750 *pnum
= extent
.length
;
1753 return (extent
.flags
& NBD_STATE_HOLE
? 0 : BDRV_BLOCK_DATA
) |
1754 (extent
.flags
& NBD_STATE_ZERO
? BDRV_BLOCK_ZERO
: 0) |
1755 BDRV_BLOCK_OFFSET_VALID
;
1758 static int nbd_client_reopen_prepare(BDRVReopenState
*state
,
1759 BlockReopenQueue
*queue
, Error
**errp
)
1761 BDRVNBDState
*s
= (BDRVNBDState
*)state
->bs
->opaque
;
1763 if ((state
->flags
& BDRV_O_RDWR
) && (s
->info
.flags
& NBD_FLAG_READ_ONLY
)) {
1764 error_setg(errp
, "Can't reopen read-only NBD mount as read/write");
1770 static void nbd_yank(void *opaque
)
1772 BlockDriverState
*bs
= opaque
;
1773 BDRVNBDState
*s
= (BDRVNBDState
*)bs
->opaque
;
1775 qatomic_store_release(&s
->state
, NBD_CLIENT_QUIT
);
1776 qio_channel_shutdown(QIO_CHANNEL(s
->sioc
), QIO_CHANNEL_SHUTDOWN_BOTH
, NULL
);
1779 static void nbd_client_close(BlockDriverState
*bs
)
1781 BDRVNBDState
*s
= (BDRVNBDState
*)bs
->opaque
;
1782 NBDRequest request
= { .type
= NBD_CMD_DISC
};
1785 nbd_send_request(s
->ioc
, &request
);
1788 nbd_teardown_connection(bs
);
1791 static int nbd_establish_connection(BlockDriverState
*bs
,
1792 SocketAddress
*saddr
,
1796 BDRVNBDState
*s
= (BDRVNBDState
*)bs
->opaque
;
1798 s
->sioc
= qio_channel_socket_new();
1799 qio_channel_set_name(QIO_CHANNEL(s
->sioc
), "nbd-client");
1801 qio_channel_socket_connect_sync(s
->sioc
, saddr
, errp
);
1803 object_unref(OBJECT(s
->sioc
));
1808 yank_register_function(BLOCKDEV_YANK_INSTANCE(bs
->node_name
), nbd_yank
, bs
);
1809 qio_channel_set_delay(QIO_CHANNEL(s
->sioc
), false);
1814 /* nbd_client_handshake takes ownership on s->sioc. On failure it's unref'ed. */
1815 static int nbd_client_handshake(BlockDriverState
*bs
, Error
**errp
)
1817 BDRVNBDState
*s
= (BDRVNBDState
*)bs
->opaque
;
1818 AioContext
*aio_context
= bdrv_get_aio_context(bs
);
1821 trace_nbd_client_handshake(s
->export
);
1822 qio_channel_set_blocking(QIO_CHANNEL(s
->sioc
), false, NULL
);
1823 qio_channel_attach_aio_context(QIO_CHANNEL(s
->sioc
), aio_context
);
1825 s
->info
.request_sizes
= true;
1826 s
->info
.structured_reply
= true;
1827 s
->info
.base_allocation
= true;
1828 s
->info
.x_dirty_bitmap
= g_strdup(s
->x_dirty_bitmap
);
1829 s
->info
.name
= g_strdup(s
->export
?: "");
1830 ret
= nbd_receive_negotiate(aio_context
, QIO_CHANNEL(s
->sioc
), s
->tlscreds
,
1831 s
->hostname
, &s
->ioc
, &s
->info
, errp
);
1832 g_free(s
->info
.x_dirty_bitmap
);
1833 g_free(s
->info
.name
);
1835 yank_unregister_function(BLOCKDEV_YANK_INSTANCE(bs
->node_name
),
1837 object_unref(OBJECT(s
->sioc
));
1841 if (s
->x_dirty_bitmap
) {
1842 if (!s
->info
.base_allocation
) {
1843 error_setg(errp
, "requested x-dirty-bitmap %s not found",
1848 if (strcmp(s
->x_dirty_bitmap
, "qemu:allocation-depth") == 0) {
1849 s
->alloc_depth
= true;
1852 if (s
->info
.flags
& NBD_FLAG_READ_ONLY
) {
1853 ret
= bdrv_apply_auto_read_only(bs
, "NBD export is read-only", errp
);
1858 if (s
->info
.flags
& NBD_FLAG_SEND_FUA
) {
1859 bs
->supported_write_flags
= BDRV_REQ_FUA
;
1860 bs
->supported_zero_flags
|= BDRV_REQ_FUA
;
1862 if (s
->info
.flags
& NBD_FLAG_SEND_WRITE_ZEROES
) {
1863 bs
->supported_zero_flags
|= BDRV_REQ_MAY_UNMAP
;
1864 if (s
->info
.flags
& NBD_FLAG_SEND_FAST_ZERO
) {
1865 bs
->supported_zero_flags
|= BDRV_REQ_NO_FALLBACK
;
1870 s
->ioc
= QIO_CHANNEL(s
->sioc
);
1871 object_ref(OBJECT(s
->ioc
));
1874 trace_nbd_client_handshake_success(s
->export
);
1880 * We have connected, but must fail for other reasons.
1881 * Send NBD_CMD_DISC as a courtesy to the server.
1884 NBDRequest request
= { .type
= NBD_CMD_DISC
};
1886 nbd_send_request(s
->ioc
?: QIO_CHANNEL(s
->sioc
), &request
);
1888 yank_unregister_function(BLOCKDEV_YANK_INSTANCE(bs
->node_name
),
1890 object_unref(OBJECT(s
->sioc
));
1898 * Parse nbd_open options
1901 static int nbd_parse_uri(const char *filename
, QDict
*options
)
1905 QueryParams
*qp
= NULL
;
1909 uri
= uri_parse(filename
);
1915 if (!g_strcmp0(uri
->scheme
, "nbd")) {
1917 } else if (!g_strcmp0(uri
->scheme
, "nbd+tcp")) {
1919 } else if (!g_strcmp0(uri
->scheme
, "nbd+unix")) {
1926 p
= uri
->path
? uri
->path
: "";
1931 qdict_put_str(options
, "export", p
);
1934 qp
= query_params_parse(uri
->query
);
1935 if (qp
->n
> 1 || (is_unix
&& !qp
->n
) || (!is_unix
&& qp
->n
)) {
1941 /* nbd+unix:///export?socket=path */
1942 if (uri
->server
|| uri
->port
|| strcmp(qp
->p
[0].name
, "socket")) {
1946 qdict_put_str(options
, "server.type", "unix");
1947 qdict_put_str(options
, "server.path", qp
->p
[0].value
);
1952 /* nbd[+tcp]://host[:port]/export */
1958 /* strip braces from literal IPv6 address */
1959 if (uri
->server
[0] == '[') {
1960 host
= qstring_from_substr(uri
->server
, 1,
1961 strlen(uri
->server
) - 1);
1963 host
= qstring_from_str(uri
->server
);
1966 qdict_put_str(options
, "server.type", "inet");
1967 qdict_put(options
, "server.host", host
);
1969 port_str
= g_strdup_printf("%d", uri
->port
?: NBD_DEFAULT_PORT
);
1970 qdict_put_str(options
, "server.port", port_str
);
1976 query_params_free(qp
);
1982 static bool nbd_has_filename_options_conflict(QDict
*options
, Error
**errp
)
1984 const QDictEntry
*e
;
1986 for (e
= qdict_first(options
); e
; e
= qdict_next(options
, e
)) {
1987 if (!strcmp(e
->key
, "host") ||
1988 !strcmp(e
->key
, "port") ||
1989 !strcmp(e
->key
, "path") ||
1990 !strcmp(e
->key
, "export") ||
1991 strstart(e
->key
, "server.", NULL
))
1993 error_setg(errp
, "Option '%s' cannot be used with a file name",
2002 static void nbd_parse_filename(const char *filename
, QDict
*options
,
2005 g_autofree
char *file
= NULL
;
2007 const char *host_spec
;
2008 const char *unixpath
;
2010 if (nbd_has_filename_options_conflict(options
, errp
)) {
2014 if (strstr(filename
, "://")) {
2015 int ret
= nbd_parse_uri(filename
, options
);
2017 error_setg(errp
, "No valid URL specified");
2022 file
= g_strdup(filename
);
2024 export_name
= strstr(file
, EN_OPTSTR
);
2026 if (export_name
[strlen(EN_OPTSTR
)] == 0) {
2029 export_name
[0] = 0; /* truncate 'file' */
2030 export_name
+= strlen(EN_OPTSTR
);
2032 qdict_put_str(options
, "export", export_name
);
2035 /* extract the host_spec - fail if it's not nbd:... */
2036 if (!strstart(file
, "nbd:", &host_spec
)) {
2037 error_setg(errp
, "File name string for NBD must start with 'nbd:'");
2045 /* are we a UNIX or TCP socket? */
2046 if (strstart(host_spec
, "unix:", &unixpath
)) {
2047 qdict_put_str(options
, "server.type", "unix");
2048 qdict_put_str(options
, "server.path", unixpath
);
2050 InetSocketAddress
*addr
= g_new(InetSocketAddress
, 1);
2052 if (inet_parse(addr
, host_spec
, errp
)) {
2056 qdict_put_str(options
, "server.type", "inet");
2057 qdict_put_str(options
, "server.host", addr
->host
);
2058 qdict_put_str(options
, "server.port", addr
->port
);
2060 qapi_free_InetSocketAddress(addr
);
2064 static bool nbd_process_legacy_socket_options(QDict
*output_options
,
2065 QemuOpts
*legacy_opts
,
2068 const char *path
= qemu_opt_get(legacy_opts
, "path");
2069 const char *host
= qemu_opt_get(legacy_opts
, "host");
2070 const char *port
= qemu_opt_get(legacy_opts
, "port");
2071 const QDictEntry
*e
;
2073 if (!path
&& !host
&& !port
) {
2077 for (e
= qdict_first(output_options
); e
; e
= qdict_next(output_options
, e
))
2079 if (strstart(e
->key
, "server.", NULL
)) {
2080 error_setg(errp
, "Cannot use 'server' and path/host/port at the "
2087 error_setg(errp
, "path and host may not be used at the same time");
2091 error_setg(errp
, "port may not be used without host");
2095 qdict_put_str(output_options
, "server.type", "unix");
2096 qdict_put_str(output_options
, "server.path", path
);
2098 qdict_put_str(output_options
, "server.type", "inet");
2099 qdict_put_str(output_options
, "server.host", host
);
2100 qdict_put_str(output_options
, "server.port",
2101 port
?: stringify(NBD_DEFAULT_PORT
));
2107 static SocketAddress
*nbd_config(BDRVNBDState
*s
, QDict
*options
,
2110 SocketAddress
*saddr
= NULL
;
2114 qdict_extract_subqdict(options
, &addr
, "server.");
2115 if (!qdict_size(addr
)) {
2116 error_setg(errp
, "NBD server address missing");
2120 iv
= qobject_input_visitor_new_flat_confused(addr
, errp
);
2125 if (!visit_type_SocketAddress(iv
, NULL
, &saddr
, errp
)) {
2130 qobject_unref(addr
);
2135 static QCryptoTLSCreds
*nbd_get_tls_creds(const char *id
, Error
**errp
)
2138 QCryptoTLSCreds
*creds
;
2140 obj
= object_resolve_path_component(
2141 object_get_objects_root(), id
);
2143 error_setg(errp
, "No TLS credentials with id '%s'",
2147 creds
= (QCryptoTLSCreds
*)
2148 object_dynamic_cast(obj
, TYPE_QCRYPTO_TLS_CREDS
);
2150 error_setg(errp
, "Object with id '%s' is not TLS credentials",
2155 if (creds
->endpoint
!= QCRYPTO_TLS_CREDS_ENDPOINT_CLIENT
) {
2157 "Expecting TLS credentials with a client endpoint");
2165 static QemuOptsList nbd_runtime_opts
= {
2167 .head
= QTAILQ_HEAD_INITIALIZER(nbd_runtime_opts
.head
),
2171 .type
= QEMU_OPT_STRING
,
2172 .help
= "TCP host to connect to",
2176 .type
= QEMU_OPT_STRING
,
2177 .help
= "TCP port to connect to",
2181 .type
= QEMU_OPT_STRING
,
2182 .help
= "Unix socket path to connect to",
2186 .type
= QEMU_OPT_STRING
,
2187 .help
= "Name of the NBD export to open",
2190 .name
= "tls-creds",
2191 .type
= QEMU_OPT_STRING
,
2192 .help
= "ID of the TLS credentials to use",
2195 .name
= "x-dirty-bitmap",
2196 .type
= QEMU_OPT_STRING
,
2197 .help
= "experimental: expose named dirty bitmap in place of "
2201 .name
= "reconnect-delay",
2202 .type
= QEMU_OPT_NUMBER
,
2203 .help
= "On an unexpected disconnect, the nbd client tries to "
2204 "connect again until succeeding or encountering a serious "
2205 "error. During the first @reconnect-delay seconds, all "
2206 "requests are paused and will be rerun on a successful "
2207 "reconnect. After that time, any delayed requests and all "
2208 "future requests before a successful reconnect will "
2209 "immediately fail. Default 0",
2211 { /* end of list */ }
2215 static int nbd_process_options(BlockDriverState
*bs
, QDict
*options
,
2218 BDRVNBDState
*s
= bs
->opaque
;
2222 opts
= qemu_opts_create(&nbd_runtime_opts
, NULL
, 0, &error_abort
);
2223 if (!qemu_opts_absorb_qdict(opts
, options
, errp
)) {
2227 /* Translate @host, @port, and @path to a SocketAddress */
2228 if (!nbd_process_legacy_socket_options(options
, opts
, errp
)) {
2232 /* Pop the config into our state object. Exit if invalid. */
2233 s
->saddr
= nbd_config(s
, options
, errp
);
2238 s
->export
= g_strdup(qemu_opt_get(opts
, "export"));
2239 if (s
->export
&& strlen(s
->export
) > NBD_MAX_STRING_SIZE
) {
2240 error_setg(errp
, "export name too long to send to server");
2244 s
->tlscredsid
= g_strdup(qemu_opt_get(opts
, "tls-creds"));
2245 if (s
->tlscredsid
) {
2246 s
->tlscreds
= nbd_get_tls_creds(s
->tlscredsid
, errp
);
2251 /* TODO SOCKET_ADDRESS_KIND_FD where fd has AF_INET or AF_INET6 */
2252 if (s
->saddr
->type
!= SOCKET_ADDRESS_TYPE_INET
) {
2253 error_setg(errp
, "TLS only supported over IP sockets");
2256 s
->hostname
= s
->saddr
->u
.inet
.host
;
2259 s
->x_dirty_bitmap
= g_strdup(qemu_opt_get(opts
, "x-dirty-bitmap"));
2260 if (s
->x_dirty_bitmap
&& strlen(s
->x_dirty_bitmap
) > NBD_MAX_STRING_SIZE
) {
2261 error_setg(errp
, "x-dirty-bitmap query too long to send to server");
2265 s
->reconnect_delay
= qemu_opt_get_number(opts
, "reconnect-delay", 0);
2271 nbd_clear_bdrvstate(s
);
2273 qemu_opts_del(opts
);
2277 static int nbd_open(BlockDriverState
*bs
, QDict
*options
, int flags
,
2281 BDRVNBDState
*s
= (BDRVNBDState
*)bs
->opaque
;
2283 ret
= nbd_process_options(bs
, options
, errp
);
2289 qemu_co_mutex_init(&s
->send_mutex
);
2290 qemu_co_queue_init(&s
->free_sema
);
2292 if (!yank_register_instance(BLOCKDEV_YANK_INSTANCE(bs
->node_name
), errp
)) {
2297 * establish TCP connection, return error if it fails
2298 * TODO: Configurable retry-until-timeout behaviour.
2300 if (nbd_establish_connection(bs
, s
->saddr
, errp
) < 0) {
2301 yank_unregister_instance(BLOCKDEV_YANK_INSTANCE(bs
->node_name
));
2302 return -ECONNREFUSED
;
2305 ret
= nbd_client_handshake(bs
, errp
);
2307 yank_unregister_instance(BLOCKDEV_YANK_INSTANCE(bs
->node_name
));
2308 nbd_clear_bdrvstate(s
);
2311 /* successfully connected */
2312 s
->state
= NBD_CLIENT_CONNECTED
;
2314 nbd_init_connect_thread(s
);
2316 s
->connection_co
= qemu_coroutine_create(nbd_connection_entry
, s
);
2317 bdrv_inc_in_flight(bs
);
2318 aio_co_schedule(bdrv_get_aio_context(bs
), s
->connection_co
);
2323 static int nbd_co_flush(BlockDriverState
*bs
)
2325 return nbd_client_co_flush(bs
);
2328 static void nbd_refresh_limits(BlockDriverState
*bs
, Error
**errp
)
2330 BDRVNBDState
*s
= (BDRVNBDState
*)bs
->opaque
;
2331 uint32_t min
= s
->info
.min_block
;
2332 uint32_t max
= MIN_NON_ZERO(NBD_MAX_BUFFER_SIZE
, s
->info
.max_block
);
2335 * If the server did not advertise an alignment:
2336 * - a size that is not sector-aligned implies that an alignment
2337 * of 1 can be used to access those tail bytes
2338 * - advertisement of block status requires an alignment of 1, so
2339 * that we don't violate block layer constraints that block
2340 * status is always aligned (as we can't control whether the
2341 * server will report sub-sector extents, such as a hole at EOF
2342 * on an unaligned POSIX file)
2343 * - otherwise, assume the server is so old that we are safer avoiding
2344 * sub-sector requests
2347 min
= (!QEMU_IS_ALIGNED(s
->info
.size
, BDRV_SECTOR_SIZE
) ||
2348 s
->info
.base_allocation
) ? 1 : BDRV_SECTOR_SIZE
;
2351 bs
->bl
.request_alignment
= min
;
2352 bs
->bl
.max_pdiscard
= QEMU_ALIGN_DOWN(INT_MAX
, min
);
2353 bs
->bl
.max_pwrite_zeroes
= max
;
2354 bs
->bl
.max_transfer
= max
;
2356 if (s
->info
.opt_block
&&
2357 s
->info
.opt_block
> bs
->bl
.opt_transfer
) {
2358 bs
->bl
.opt_transfer
= s
->info
.opt_block
;
2362 static void nbd_close(BlockDriverState
*bs
)
2364 BDRVNBDState
*s
= bs
->opaque
;
2366 nbd_client_close(bs
);
2367 yank_unregister_instance(BLOCKDEV_YANK_INSTANCE(bs
->node_name
));
2368 nbd_clear_bdrvstate(s
);
2372 * NBD cannot truncate, but if the caller asks to truncate to the same size, or
2373 * to a smaller size with exact=false, there is no reason to fail the
2376 * Preallocation mode is ignored since it does not seems useful to fail when
2377 * we never change anything.
2379 static int coroutine_fn
nbd_co_truncate(BlockDriverState
*bs
, int64_t offset
,
2380 bool exact
, PreallocMode prealloc
,
2381 BdrvRequestFlags flags
, Error
**errp
)
2383 BDRVNBDState
*s
= bs
->opaque
;
2385 if (offset
!= s
->info
.size
&& exact
) {
2386 error_setg(errp
, "Cannot resize NBD nodes");
2390 if (offset
> s
->info
.size
) {
2391 error_setg(errp
, "Cannot grow NBD nodes");
2398 static int64_t nbd_getlength(BlockDriverState
*bs
)
2400 BDRVNBDState
*s
= bs
->opaque
;
2402 return s
->info
.size
;
2405 static void nbd_refresh_filename(BlockDriverState
*bs
)
2407 BDRVNBDState
*s
= bs
->opaque
;
2408 const char *host
= NULL
, *port
= NULL
, *path
= NULL
;
2411 if (s
->saddr
->type
== SOCKET_ADDRESS_TYPE_INET
) {
2412 const InetSocketAddress
*inet
= &s
->saddr
->u
.inet
;
2413 if (!inet
->has_ipv4
&& !inet
->has_ipv6
&& !inet
->has_to
) {
2417 } else if (s
->saddr
->type
== SOCKET_ADDRESS_TYPE_UNIX
) {
2418 path
= s
->saddr
->u
.q_unix
.path
;
2419 } /* else can't represent as pseudo-filename */
2421 if (path
&& s
->export
) {
2422 len
= snprintf(bs
->exact_filename
, sizeof(bs
->exact_filename
),
2423 "nbd+unix:///%s?socket=%s", s
->export
, path
);
2424 } else if (path
&& !s
->export
) {
2425 len
= snprintf(bs
->exact_filename
, sizeof(bs
->exact_filename
),
2426 "nbd+unix://?socket=%s", path
);
2427 } else if (host
&& s
->export
) {
2428 len
= snprintf(bs
->exact_filename
, sizeof(bs
->exact_filename
),
2429 "nbd://%s:%s/%s", host
, port
, s
->export
);
2430 } else if (host
&& !s
->export
) {
2431 len
= snprintf(bs
->exact_filename
, sizeof(bs
->exact_filename
),
2432 "nbd://%s:%s", host
, port
);
2434 if (len
>= sizeof(bs
->exact_filename
)) {
2435 /* Name is too long to represent exactly, so leave it empty. */
2436 bs
->exact_filename
[0] = '\0';
2440 static char *nbd_dirname(BlockDriverState
*bs
, Error
**errp
)
2442 /* The generic bdrv_dirname() implementation is able to work out some
2443 * directory name for NBD nodes, but that would be wrong. So far there is no
2444 * specification for how "export paths" would work, so NBD does not have
2445 * directory names. */
2446 error_setg(errp
, "Cannot generate a base directory for NBD nodes");
2450 static const char *const nbd_strong_runtime_opts
[] = {
2461 static void nbd_cancel_in_flight(BlockDriverState
*bs
)
2463 BDRVNBDState
*s
= (BDRVNBDState
*)bs
->opaque
;
2465 reconnect_delay_timer_del(s
);
2467 if (s
->state
== NBD_CLIENT_CONNECTING_WAIT
) {
2468 s
->state
= NBD_CLIENT_CONNECTING_NOWAIT
;
2469 qemu_co_queue_restart_all(&s
->free_sema
);
2473 static BlockDriver bdrv_nbd
= {
2474 .format_name
= "nbd",
2475 .protocol_name
= "nbd",
2476 .instance_size
= sizeof(BDRVNBDState
),
2477 .bdrv_parse_filename
= nbd_parse_filename
,
2478 .bdrv_co_create_opts
= bdrv_co_create_opts_simple
,
2479 .create_opts
= &bdrv_create_opts_simple
,
2480 .bdrv_file_open
= nbd_open
,
2481 .bdrv_reopen_prepare
= nbd_client_reopen_prepare
,
2482 .bdrv_co_preadv
= nbd_client_co_preadv
,
2483 .bdrv_co_pwritev
= nbd_client_co_pwritev
,
2484 .bdrv_co_pwrite_zeroes
= nbd_client_co_pwrite_zeroes
,
2485 .bdrv_close
= nbd_close
,
2486 .bdrv_co_flush_to_os
= nbd_co_flush
,
2487 .bdrv_co_pdiscard
= nbd_client_co_pdiscard
,
2488 .bdrv_refresh_limits
= nbd_refresh_limits
,
2489 .bdrv_co_truncate
= nbd_co_truncate
,
2490 .bdrv_getlength
= nbd_getlength
,
2491 .bdrv_detach_aio_context
= nbd_client_detach_aio_context
,
2492 .bdrv_attach_aio_context
= nbd_client_attach_aio_context
,
2493 .bdrv_co_drain_begin
= nbd_client_co_drain_begin
,
2494 .bdrv_co_drain_end
= nbd_client_co_drain_end
,
2495 .bdrv_refresh_filename
= nbd_refresh_filename
,
2496 .bdrv_co_block_status
= nbd_client_co_block_status
,
2497 .bdrv_dirname
= nbd_dirname
,
2498 .strong_runtime_opts
= nbd_strong_runtime_opts
,
2499 .bdrv_cancel_in_flight
= nbd_cancel_in_flight
,
2502 static BlockDriver bdrv_nbd_tcp
= {
2503 .format_name
= "nbd",
2504 .protocol_name
= "nbd+tcp",
2505 .instance_size
= sizeof(BDRVNBDState
),
2506 .bdrv_parse_filename
= nbd_parse_filename
,
2507 .bdrv_co_create_opts
= bdrv_co_create_opts_simple
,
2508 .create_opts
= &bdrv_create_opts_simple
,
2509 .bdrv_file_open
= nbd_open
,
2510 .bdrv_reopen_prepare
= nbd_client_reopen_prepare
,
2511 .bdrv_co_preadv
= nbd_client_co_preadv
,
2512 .bdrv_co_pwritev
= nbd_client_co_pwritev
,
2513 .bdrv_co_pwrite_zeroes
= nbd_client_co_pwrite_zeroes
,
2514 .bdrv_close
= nbd_close
,
2515 .bdrv_co_flush_to_os
= nbd_co_flush
,
2516 .bdrv_co_pdiscard
= nbd_client_co_pdiscard
,
2517 .bdrv_refresh_limits
= nbd_refresh_limits
,
2518 .bdrv_co_truncate
= nbd_co_truncate
,
2519 .bdrv_getlength
= nbd_getlength
,
2520 .bdrv_detach_aio_context
= nbd_client_detach_aio_context
,
2521 .bdrv_attach_aio_context
= nbd_client_attach_aio_context
,
2522 .bdrv_co_drain_begin
= nbd_client_co_drain_begin
,
2523 .bdrv_co_drain_end
= nbd_client_co_drain_end
,
2524 .bdrv_refresh_filename
= nbd_refresh_filename
,
2525 .bdrv_co_block_status
= nbd_client_co_block_status
,
2526 .bdrv_dirname
= nbd_dirname
,
2527 .strong_runtime_opts
= nbd_strong_runtime_opts
,
2528 .bdrv_cancel_in_flight
= nbd_cancel_in_flight
,
2531 static BlockDriver bdrv_nbd_unix
= {
2532 .format_name
= "nbd",
2533 .protocol_name
= "nbd+unix",
2534 .instance_size
= sizeof(BDRVNBDState
),
2535 .bdrv_parse_filename
= nbd_parse_filename
,
2536 .bdrv_co_create_opts
= bdrv_co_create_opts_simple
,
2537 .create_opts
= &bdrv_create_opts_simple
,
2538 .bdrv_file_open
= nbd_open
,
2539 .bdrv_reopen_prepare
= nbd_client_reopen_prepare
,
2540 .bdrv_co_preadv
= nbd_client_co_preadv
,
2541 .bdrv_co_pwritev
= nbd_client_co_pwritev
,
2542 .bdrv_co_pwrite_zeroes
= nbd_client_co_pwrite_zeroes
,
2543 .bdrv_close
= nbd_close
,
2544 .bdrv_co_flush_to_os
= nbd_co_flush
,
2545 .bdrv_co_pdiscard
= nbd_client_co_pdiscard
,
2546 .bdrv_refresh_limits
= nbd_refresh_limits
,
2547 .bdrv_co_truncate
= nbd_co_truncate
,
2548 .bdrv_getlength
= nbd_getlength
,
2549 .bdrv_detach_aio_context
= nbd_client_detach_aio_context
,
2550 .bdrv_attach_aio_context
= nbd_client_attach_aio_context
,
2551 .bdrv_co_drain_begin
= nbd_client_co_drain_begin
,
2552 .bdrv_co_drain_end
= nbd_client_co_drain_end
,
2553 .bdrv_refresh_filename
= nbd_refresh_filename
,
2554 .bdrv_co_block_status
= nbd_client_co_block_status
,
2555 .bdrv_dirname
= nbd_dirname
,
2556 .strong_runtime_opts
= nbd_strong_runtime_opts
,
2557 .bdrv_cancel_in_flight
= nbd_cancel_in_flight
,
2560 static void bdrv_nbd_init(void)
2562 bdrv_register(&bdrv_nbd
);
2563 bdrv_register(&bdrv_nbd_tcp
);
2564 bdrv_register(&bdrv_nbd_unix
);
2567 block_init(bdrv_nbd_init
);