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
;
37 NBDExportInfo initial_info
;
43 NBDExportInfo updated_info
;
45 * @sioc represents a successful result. While thread is running, @sioc is
46 * used only by thread and not protected by mutex. When thread is not
47 * running, @sioc is stolen by nbd_co_establish_connection() under mutex.
49 QIOChannelSocket
*sioc
;
52 * @err represents previous attempt. It may be copied by
53 * nbd_co_establish_connection() when it reports failure.
57 /* All further fields are accessed only under mutex */
58 bool running
; /* thread is running now */
59 bool detached
; /* thread is detached and should cleanup the state */
62 * wait_co: if non-NULL, which coroutine to wake in
63 * nbd_co_establish_connection() after yield()
69 * The function isn't protected by any mutex, only call it when the client
70 * connection attempt has not yet started.
72 void nbd_client_connection_enable_retry(NBDClientConnection
*conn
)
74 conn
->do_retry
= true;
77 NBDClientConnection
*nbd_client_connection_new(const SocketAddress
*saddr
,
79 const char *export_name
,
80 const char *x_dirty_bitmap
,
81 QCryptoTLSCreds
*tlscreds
,
82 const char *tlshostname
)
84 NBDClientConnection
*conn
= g_new(NBDClientConnection
, 1);
86 object_ref(OBJECT(tlscreds
));
87 *conn
= (NBDClientConnection
) {
88 .saddr
= QAPI_CLONE(SocketAddress
, saddr
),
90 .tlshostname
= g_strdup(tlshostname
),
91 .do_negotiation
= do_negotiation
,
93 .initial_info
.request_sizes
= true,
94 .initial_info
.structured_reply
= true,
95 .initial_info
.base_allocation
= true,
96 .initial_info
.x_dirty_bitmap
= g_strdup(x_dirty_bitmap
),
97 .initial_info
.name
= g_strdup(export_name
?: "")
100 qemu_mutex_init(&conn
->mutex
);
105 static void nbd_client_connection_do_free(NBDClientConnection
*conn
)
108 qio_channel_close(QIO_CHANNEL(conn
->sioc
), NULL
);
109 object_unref(OBJECT(conn
->sioc
));
111 error_free(conn
->err
);
112 qapi_free_SocketAddress(conn
->saddr
);
113 g_free(conn
->tlshostname
);
114 object_unref(OBJECT(conn
->tlscreds
));
115 g_free(conn
->initial_info
.x_dirty_bitmap
);
116 g_free(conn
->initial_info
.name
);
121 * Connect to @addr and do NBD negotiation if @info is not null. If @tlscreds
122 * are given @outioc is returned. @outioc is provided only on success. The call
123 * may be cancelled from other thread by simply qio_channel_shutdown(sioc).
125 static int nbd_connect(QIOChannelSocket
*sioc
, SocketAddress
*addr
,
126 NBDExportInfo
*info
, QCryptoTLSCreds
*tlscreds
,
127 const char *tlshostname
,
128 QIOChannel
**outioc
, Error
**errp
)
136 ret
= qio_channel_socket_connect_sync(sioc
, addr
, errp
);
141 qio_channel_set_delay(QIO_CHANNEL(sioc
), false);
147 ret
= nbd_receive_negotiate(NULL
, QIO_CHANNEL(sioc
), tlscreds
,
152 * nbd_receive_negotiate() may setup tls ioc and return it even on
153 * failure path. In this case we should use it instead of original
156 if (outioc
&& *outioc
) {
157 qio_channel_close(QIO_CHANNEL(*outioc
), NULL
);
158 object_unref(OBJECT(*outioc
));
161 qio_channel_close(QIO_CHANNEL(sioc
), NULL
);
170 static void *connect_thread_func(void *opaque
)
172 NBDClientConnection
*conn
= opaque
;
175 uint64_t timeout
= 1;
176 uint64_t max_timeout
= 16;
178 qemu_mutex_lock(&conn
->mutex
);
179 while (!conn
->detached
) {
180 Error
*local_err
= NULL
;
183 conn
->sioc
= qio_channel_socket_new();
185 qemu_mutex_unlock(&conn
->mutex
);
187 conn
->updated_info
= conn
->initial_info
;
189 ret
= nbd_connect(conn
->sioc
, conn
->saddr
,
190 conn
->do_negotiation
? &conn
->updated_info
: NULL
,
191 conn
->tlscreds
, conn
->tlshostname
,
192 &conn
->ioc
, &local_err
);
195 * conn->updated_info will finally be returned to the user. Clear the
196 * pointers to our internally allocated strings, which are IN parameters
197 * of nbd_receive_negotiate() and therefore nbd_connect(). Caller
198 * shoudn't be interested in these fields.
200 conn
->updated_info
.x_dirty_bitmap
= NULL
;
201 conn
->updated_info
.name
= NULL
;
203 qemu_mutex_lock(&conn
->mutex
);
205 error_free(conn
->err
);
207 error_propagate(&conn
->err
, local_err
);
210 object_unref(OBJECT(conn
->sioc
));
212 if (conn
->do_retry
&& !conn
->detached
) {
213 qemu_mutex_unlock(&conn
->mutex
);
216 if (timeout
< max_timeout
) {
220 qemu_mutex_lock(&conn
->mutex
);
228 /* mutex is locked */
230 assert(conn
->running
);
231 conn
->running
= false;
233 aio_co_wake(conn
->wait_co
);
234 conn
->wait_co
= NULL
;
236 do_free
= conn
->detached
;
238 qemu_mutex_unlock(&conn
->mutex
);
241 nbd_client_connection_do_free(conn
);
247 void nbd_client_connection_release(NBDClientConnection
*conn
)
249 bool do_free
= false;
255 WITH_QEMU_LOCK_GUARD(&conn
->mutex
) {
256 assert(!conn
->detached
);
258 conn
->detached
= true;
263 qio_channel_shutdown(QIO_CHANNEL(conn
->sioc
),
264 QIO_CHANNEL_SHUTDOWN_BOTH
, NULL
);
269 nbd_client_connection_do_free(conn
);
274 * Get a new connection in context of @conn:
275 * if the thread is running, wait for completion
276 * if the thread already succeeded in the background, and user didn't get the
277 * result, just return it now
278 * otherwise the thread is not running, so start a thread and wait for
281 * If @blocking is false, don't wait for the thread, return immediately.
283 * If @info is not NULL, also do nbd-negotiation after successful connection.
284 * In this case info is used only as out parameter, and is fully initialized by
285 * nbd_co_establish_connection(). "IN" fields of info as well as related only to
286 * nbd_receive_export_list() would be zero (see description of NBDExportInfo in
287 * include/block/nbd.h).
289 QIOChannel
*coroutine_fn
290 nbd_co_establish_connection(NBDClientConnection
*conn
, NBDExportInfo
*info
,
291 bool blocking
, Error
**errp
)
295 if (conn
->do_negotiation
) {
299 WITH_QEMU_LOCK_GUARD(&conn
->mutex
) {
301 * Don't call nbd_co_establish_connection() in several coroutines in
302 * parallel. Only one call at once is supported.
304 assert(!conn
->wait_co
);
306 if (!conn
->running
) {
308 /* Previous attempt finally succeeded in background */
309 if (conn
->do_negotiation
) {
310 memcpy(info
, &conn
->updated_info
, sizeof(*info
));
312 /* TLS channel now has own reference to parent */
313 object_unref(OBJECT(conn
->sioc
));
316 return g_steal_pointer(&conn
->ioc
);
322 return QIO_CHANNEL(g_steal_pointer(&conn
->sioc
));
325 conn
->running
= true;
326 qemu_thread_create(&thread
, "nbd-connect",
327 connect_thread_func
, conn
, QEMU_THREAD_DETACHED
);
332 error_propagate(errp
, error_copy(conn
->err
));
334 error_setg(errp
, "No connection at the moment");
340 conn
->wait_co
= qemu_coroutine_self();
344 * We are going to wait for connect-thread finish, but
345 * nbd_co_establish_connection_cancel() can interrupt.
347 qemu_coroutine_yield();
349 WITH_QEMU_LOCK_GUARD(&conn
->mutex
) {
352 * The connection attempt was canceled and the coroutine resumed
353 * before the connection thread finished its job. Report the
354 * attempt as failed, but leave the connection thread running,
355 * to reuse it for the next connection attempt.
358 error_propagate(errp
, error_copy(conn
->err
));
361 * The only possible case here is cancelling by open_timer
362 * during nbd_open(). So, the error message is for that case.
363 * If we have more use cases, we can refactor
364 * nbd_co_establish_connection_cancel() to take an additional
365 * parameter cancel_reason, that would be passed than to the
366 * caller of cancelled nbd_co_establish_connection().
368 error_setg(errp
, "Connection attempt cancelled by timeout");
373 /* Thread finished. There must be either error or sioc */
374 assert(!conn
->err
!= !conn
->sioc
);
377 error_propagate(errp
, error_copy(conn
->err
));
381 if (conn
->do_negotiation
) {
382 memcpy(info
, &conn
->updated_info
, sizeof(*info
));
384 /* TLS channel now has own reference to parent */
385 object_unref(OBJECT(conn
->sioc
));
388 return g_steal_pointer(&conn
->ioc
);
394 return QIO_CHANNEL(g_steal_pointer(&conn
->sioc
));
398 abort(); /* unreachable */
402 * nbd_co_establish_connection_cancel
403 * Cancel nbd_co_establish_connection() asynchronously.
405 * Note that this function neither directly stops the thread nor closes the
406 * socket, but rather safely wakes nbd_co_establish_connection() which is
407 * sleeping in yield()
409 void nbd_co_establish_connection_cancel(NBDClientConnection
*conn
)
413 WITH_QEMU_LOCK_GUARD(&conn
->mutex
) {
414 wait_co
= g_steal_pointer(&conn
->wait_co
);
418 aio_co_wake(wait_co
);