2 * QEMU Block driver for NBD
4 * Copyright (c) 2021 Virtuozzo International GmbH.
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
25 #include "qemu/osdep.h"
27 #include "block/nbd.h"
29 #include "qapi/qapi-visit-sockets.h"
30 #include "qapi/clone-visitor.h"
32 struct NBDClientConnection
{
33 /* Initialization constants, never change */
34 SocketAddress
*saddr
; /* address to connect to */
35 QCryptoTLSCreds
*tlscreds
;
36 NBDExportInfo initial_info
;
42 NBDExportInfo updated_info
;
44 * @sioc represents a successful result. While thread is running, @sioc is
45 * used only by thread and not protected by mutex. When thread is not
46 * running, @sioc is stolen by nbd_co_establish_connection() under mutex.
48 QIOChannelSocket
*sioc
;
51 * @err represents previous attempt. It may be copied by
52 * nbd_co_establish_connection() when it reports failure.
56 /* All further fields are accessed only under mutex */
57 bool running
; /* thread is running now */
58 bool detached
; /* thread is detached and should cleanup the state */
61 * wait_co: if non-NULL, which coroutine to wake in
62 * nbd_co_establish_connection() after yield()
68 * The function isn't protected by any mutex, only call it when the client
69 * connection attempt has not yet started.
71 void nbd_client_connection_enable_retry(NBDClientConnection
*conn
)
73 conn
->do_retry
= true;
76 NBDClientConnection
*nbd_client_connection_new(const SocketAddress
*saddr
,
78 const char *export_name
,
79 const char *x_dirty_bitmap
,
80 QCryptoTLSCreds
*tlscreds
)
82 NBDClientConnection
*conn
= g_new(NBDClientConnection
, 1);
84 object_ref(OBJECT(tlscreds
));
85 *conn
= (NBDClientConnection
) {
86 .saddr
= QAPI_CLONE(SocketAddress
, saddr
),
88 .do_negotiation
= do_negotiation
,
90 .initial_info
.request_sizes
= true,
91 .initial_info
.structured_reply
= true,
92 .initial_info
.base_allocation
= true,
93 .initial_info
.x_dirty_bitmap
= g_strdup(x_dirty_bitmap
),
94 .initial_info
.name
= g_strdup(export_name
?: "")
97 qemu_mutex_init(&conn
->mutex
);
102 static void nbd_client_connection_do_free(NBDClientConnection
*conn
)
105 qio_channel_close(QIO_CHANNEL(conn
->sioc
), NULL
);
106 object_unref(OBJECT(conn
->sioc
));
108 error_free(conn
->err
);
109 qapi_free_SocketAddress(conn
->saddr
);
110 object_unref(OBJECT(conn
->tlscreds
));
111 g_free(conn
->initial_info
.x_dirty_bitmap
);
112 g_free(conn
->initial_info
.name
);
117 * Connect to @addr and do NBD negotiation if @info is not null. If @tlscreds
118 * are given @outioc is returned. @outioc is provided only on success. The call
119 * may be cancelled from other thread by simply qio_channel_shutdown(sioc).
121 static int nbd_connect(QIOChannelSocket
*sioc
, SocketAddress
*addr
,
122 NBDExportInfo
*info
, QCryptoTLSCreds
*tlscreds
,
123 QIOChannel
**outioc
, Error
**errp
)
131 ret
= qio_channel_socket_connect_sync(sioc
, addr
, errp
);
136 qio_channel_set_delay(QIO_CHANNEL(sioc
), false);
142 ret
= nbd_receive_negotiate(NULL
, QIO_CHANNEL(sioc
), tlscreds
,
143 tlscreds
? addr
->u
.inet
.host
: NULL
,
147 * nbd_receive_negotiate() may setup tls ioc and return it even on
148 * failure path. In this case we should use it instead of original
151 if (outioc
&& *outioc
) {
152 qio_channel_close(QIO_CHANNEL(*outioc
), NULL
);
153 object_unref(OBJECT(*outioc
));
156 qio_channel_close(QIO_CHANNEL(sioc
), NULL
);
165 static void *connect_thread_func(void *opaque
)
167 NBDClientConnection
*conn
= opaque
;
170 uint64_t timeout
= 1;
171 uint64_t max_timeout
= 16;
173 qemu_mutex_lock(&conn
->mutex
);
174 while (!conn
->detached
) {
175 Error
*local_err
= NULL
;
178 conn
->sioc
= qio_channel_socket_new();
180 qemu_mutex_unlock(&conn
->mutex
);
182 conn
->updated_info
= conn
->initial_info
;
184 ret
= nbd_connect(conn
->sioc
, conn
->saddr
,
185 conn
->do_negotiation
? &conn
->updated_info
: NULL
,
186 conn
->tlscreds
, &conn
->ioc
, &local_err
);
189 * conn->updated_info will finally be returned to the user. Clear the
190 * pointers to our internally allocated strings, which are IN parameters
191 * of nbd_receive_negotiate() and therefore nbd_connect(). Caller
192 * shoudn't be interested in these fields.
194 conn
->updated_info
.x_dirty_bitmap
= NULL
;
195 conn
->updated_info
.name
= NULL
;
197 qemu_mutex_lock(&conn
->mutex
);
199 error_free(conn
->err
);
201 error_propagate(&conn
->err
, local_err
);
204 object_unref(OBJECT(conn
->sioc
));
206 if (conn
->do_retry
&& !conn
->detached
) {
207 qemu_mutex_unlock(&conn
->mutex
);
210 if (timeout
< max_timeout
) {
214 qemu_mutex_lock(&conn
->mutex
);
222 /* mutex is locked */
224 assert(conn
->running
);
225 conn
->running
= false;
227 aio_co_wake(conn
->wait_co
);
228 conn
->wait_co
= NULL
;
230 do_free
= conn
->detached
;
232 qemu_mutex_unlock(&conn
->mutex
);
235 nbd_client_connection_do_free(conn
);
241 void nbd_client_connection_release(NBDClientConnection
*conn
)
243 bool do_free
= false;
249 WITH_QEMU_LOCK_GUARD(&conn
->mutex
) {
250 assert(!conn
->detached
);
252 conn
->detached
= true;
257 qio_channel_shutdown(QIO_CHANNEL(conn
->sioc
),
258 QIO_CHANNEL_SHUTDOWN_BOTH
, NULL
);
263 nbd_client_connection_do_free(conn
);
268 * Get a new connection in context of @conn:
269 * if the thread is running, wait for completion
270 * if the thread already succeeded in the background, and user didn't get the
271 * result, just return it now
272 * otherwise the thread is not running, so start a thread and wait for
275 * If @blocking is false, don't wait for the thread, return immediately.
277 * If @info is not NULL, also do nbd-negotiation after successful connection.
278 * In this case info is used only as out parameter, and is fully initialized by
279 * nbd_co_establish_connection(). "IN" fields of info as well as related only to
280 * nbd_receive_export_list() would be zero (see description of NBDExportInfo in
281 * include/block/nbd.h).
283 QIOChannel
*coroutine_fn
284 nbd_co_establish_connection(NBDClientConnection
*conn
, NBDExportInfo
*info
,
285 bool blocking
, Error
**errp
)
289 if (conn
->do_negotiation
) {
293 WITH_QEMU_LOCK_GUARD(&conn
->mutex
) {
295 * Don't call nbd_co_establish_connection() in several coroutines in
296 * parallel. Only one call at once is supported.
298 assert(!conn
->wait_co
);
300 if (!conn
->running
) {
302 /* Previous attempt finally succeeded in background */
303 if (conn
->do_negotiation
) {
304 memcpy(info
, &conn
->updated_info
, sizeof(*info
));
306 /* TLS channel now has own reference to parent */
307 object_unref(OBJECT(conn
->sioc
));
310 return g_steal_pointer(&conn
->ioc
);
316 return QIO_CHANNEL(g_steal_pointer(&conn
->sioc
));
319 conn
->running
= true;
320 qemu_thread_create(&thread
, "nbd-connect",
321 connect_thread_func
, conn
, QEMU_THREAD_DETACHED
);
326 error_propagate(errp
, error_copy(conn
->err
));
328 error_setg(errp
, "No connection at the moment");
334 conn
->wait_co
= qemu_coroutine_self();
338 * We are going to wait for connect-thread finish, but
339 * nbd_co_establish_connection_cancel() can interrupt.
341 qemu_coroutine_yield();
343 WITH_QEMU_LOCK_GUARD(&conn
->mutex
) {
346 * The connection attempt was canceled and the coroutine resumed
347 * before the connection thread finished its job. Report the
348 * attempt as failed, but leave the connection thread running,
349 * to reuse it for the next connection attempt.
352 error_propagate(errp
, error_copy(conn
->err
));
355 * The only possible case here is cancelling by open_timer
356 * during nbd_open(). So, the error message is for that case.
357 * If we have more use cases, we can refactor
358 * nbd_co_establish_connection_cancel() to take an additional
359 * parameter cancel_reason, that would be passed than to the
360 * caller of cancelled nbd_co_establish_connection().
362 error_setg(errp
, "Connection attempt cancelled by timeout");
367 /* Thread finished. There must be either error or sioc */
368 assert(!conn
->err
!= !conn
->sioc
);
371 error_propagate(errp
, error_copy(conn
->err
));
375 if (conn
->do_negotiation
) {
376 memcpy(info
, &conn
->updated_info
, sizeof(*info
));
378 /* TLS channel now has own reference to parent */
379 object_unref(OBJECT(conn
->sioc
));
382 return g_steal_pointer(&conn
->ioc
);
388 return QIO_CHANNEL(g_steal_pointer(&conn
->sioc
));
392 abort(); /* unreachable */
396 * nbd_co_establish_connection_cancel
397 * Cancel nbd_co_establish_connection() asynchronously.
399 * Note that this function neither directly stops the thread nor closes the
400 * socket, but rather safely wakes nbd_co_establish_connection() which is
401 * sleeping in yield()
403 void nbd_co_establish_connection_cancel(NBDClientConnection
*conn
)
407 WITH_QEMU_LOCK_GUARD(&conn
->mutex
) {
408 wait_co
= g_steal_pointer(&conn
->wait_co
);
412 aio_co_wake(wait_co
);