xref: /openbmc/qemu/block/nbd.c (revision cb116da7)
1019d6b8fSAnthony Liguori /*
2019d6b8fSAnthony Liguori  * QEMU Block driver for  NBD
3019d6b8fSAnthony Liguori  *
4f7651539SVladimir Sementsov-Ogievskiy  * Copyright (c) 2019 Virtuozzo International GmbH.
586f8cdf3SVladimir Sementsov-Ogievskiy  * Copyright (C) 2016 Red Hat, Inc.
6019d6b8fSAnthony Liguori  * Copyright (C) 2008 Bull S.A.S.
7019d6b8fSAnthony Liguori  *     Author: Laurent Vivier <Laurent.Vivier@bull.net>
8019d6b8fSAnthony Liguori  *
9019d6b8fSAnthony Liguori  * Some parts:
10019d6b8fSAnthony Liguori  *    Copyright (C) 2007 Anthony Liguori <anthony@codemonkey.ws>
11019d6b8fSAnthony Liguori  *
12019d6b8fSAnthony Liguori  * Permission is hereby granted, free of charge, to any person obtaining a copy
13019d6b8fSAnthony Liguori  * of this software and associated documentation files (the "Software"), to deal
14019d6b8fSAnthony Liguori  * in the Software without restriction, including without limitation the rights
15019d6b8fSAnthony Liguori  * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
16019d6b8fSAnthony Liguori  * copies of the Software, and to permit persons to whom the Software is
17019d6b8fSAnthony Liguori  * furnished to do so, subject to the following conditions:
18019d6b8fSAnthony Liguori  *
19019d6b8fSAnthony Liguori  * The above copyright notice and this permission notice shall be included in
20019d6b8fSAnthony Liguori  * all copies or substantial portions of the Software.
21019d6b8fSAnthony Liguori  *
22019d6b8fSAnthony Liguori  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
23019d6b8fSAnthony Liguori  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
24019d6b8fSAnthony Liguori  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
25019d6b8fSAnthony Liguori  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
26019d6b8fSAnthony Liguori  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
27019d6b8fSAnthony Liguori  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
28019d6b8fSAnthony Liguori  * THE SOFTWARE.
29019d6b8fSAnthony Liguori  */
30019d6b8fSAnthony Liguori 
3180c71a24SPeter Maydell #include "qemu/osdep.h"
3286f8cdf3SVladimir Sementsov-Ogievskiy 
3386f8cdf3SVladimir Sementsov-Ogievskiy #include "trace.h"
341de7afc9SPaolo Bonzini #include "qemu/uri.h"
35922a01a0SMarkus Armbruster #include "qemu/option.h"
36f348b6d1SVeronia Bahaa #include "qemu/cutils.h"
37db725815SMarkus Armbruster #include "qemu/main-loop.h"
38fee091cdSLukas Straub #include "qemu/atomic.h"
39019d6b8fSAnthony Liguori 
4086f8cdf3SVladimir Sementsov-Ogievskiy #include "qapi/qapi-visit-sockets.h"
4186f8cdf3SVladimir Sementsov-Ogievskiy #include "qapi/qmp/qstring.h"
421dc4718dSVladimir Sementsov-Ogievskiy #include "qapi/clone-visitor.h"
4386f8cdf3SVladimir Sementsov-Ogievskiy 
4486f8cdf3SVladimir Sementsov-Ogievskiy #include "block/qdict.h"
4586f8cdf3SVladimir Sementsov-Ogievskiy #include "block/nbd.h"
4686f8cdf3SVladimir Sementsov-Ogievskiy #include "block/block_int.h"
47a71d597bSVladimir Sementsov-Ogievskiy #include "block/coroutines.h"
4886f8cdf3SVladimir Sementsov-Ogievskiy 
49fee091cdSLukas Straub #include "qemu/yank.h"
50fee091cdSLukas Straub 
511d45f8b5SLaurent Vivier #define EN_OPTSTR ":exportname="
5286f8cdf3SVladimir Sementsov-Ogievskiy #define MAX_NBD_REQUESTS    16
5386f8cdf3SVladimir Sementsov-Ogievskiy 
5486f8cdf3SVladimir Sementsov-Ogievskiy #define HANDLE_TO_INDEX(bs, handle) ((handle) ^ (uint64_t)(intptr_t)(bs))
5586f8cdf3SVladimir Sementsov-Ogievskiy #define INDEX_TO_HANDLE(bs, index)  ((index)  ^ (uint64_t)(intptr_t)(bs))
5686f8cdf3SVladimir Sementsov-Ogievskiy 
5786f8cdf3SVladimir Sementsov-Ogievskiy typedef struct {
5886f8cdf3SVladimir Sementsov-Ogievskiy     Coroutine *coroutine;
5986f8cdf3SVladimir Sementsov-Ogievskiy     uint64_t offset;        /* original offset of the request */
6086f8cdf3SVladimir Sementsov-Ogievskiy     bool receiving;         /* waiting for connection_co? */
6186f8cdf3SVladimir Sementsov-Ogievskiy } NBDClientRequest;
6286f8cdf3SVladimir Sementsov-Ogievskiy 
63a34b1e5eSVladimir Sementsov-Ogievskiy typedef enum NBDClientState {
64f7651539SVladimir Sementsov-Ogievskiy     NBD_CLIENT_CONNECTING_WAIT,
65f7651539SVladimir Sementsov-Ogievskiy     NBD_CLIENT_CONNECTING_NOWAIT,
66a34b1e5eSVladimir Sementsov-Ogievskiy     NBD_CLIENT_CONNECTED,
67a34b1e5eSVladimir Sementsov-Ogievskiy     NBD_CLIENT_QUIT
68a34b1e5eSVladimir Sementsov-Ogievskiy } NBDClientState;
69a34b1e5eSVladimir Sementsov-Ogievskiy 
70611ae1d7SVladimir Sementsov-Ogievskiy typedef struct BDRVNBDState {
7195a078eaSVladimir Sementsov-Ogievskiy     QIOChannel *ioc; /* The current I/O channel */
7286f8cdf3SVladimir Sementsov-Ogievskiy     NBDExportInfo info;
7386f8cdf3SVladimir Sementsov-Ogievskiy 
7486f8cdf3SVladimir Sementsov-Ogievskiy     CoMutex send_mutex;
7586f8cdf3SVladimir Sementsov-Ogievskiy     CoQueue free_sema;
7686f8cdf3SVladimir Sementsov-Ogievskiy     Coroutine *connection_co;
7778c81a3fSMax Reitz     Coroutine *teardown_co;
7829a6ea24SPaolo Bonzini     QemuCoSleep reconnect_sleep;
79f7651539SVladimir Sementsov-Ogievskiy     bool drained;
80f7651539SVladimir Sementsov-Ogievskiy     bool wait_drained_end;
8186f8cdf3SVladimir Sementsov-Ogievskiy     int in_flight;
82a34b1e5eSVladimir Sementsov-Ogievskiy     NBDClientState state;
83f7651539SVladimir Sementsov-Ogievskiy     bool wait_in_flight;
8486f8cdf3SVladimir Sementsov-Ogievskiy 
8546f56631SVladimir Sementsov-Ogievskiy     QEMUTimer *reconnect_delay_timer;
8646f56631SVladimir Sementsov-Ogievskiy 
8786f8cdf3SVladimir Sementsov-Ogievskiy     NBDClientRequest requests[MAX_NBD_REQUESTS];
8886f8cdf3SVladimir Sementsov-Ogievskiy     NBDReply reply;
8986f8cdf3SVladimir Sementsov-Ogievskiy     BlockDriverState *bs;
9003504d05SMax Reitz 
918f071c9dSVladimir Sementsov-Ogievskiy     /* Connection parameters */
928f071c9dSVladimir Sementsov-Ogievskiy     uint32_t reconnect_delay;
9362cf396bSMarkus Armbruster     SocketAddress *saddr;
94491d6c7cSMax Reitz     char *export, *tlscredsid;
958f071c9dSVladimir Sementsov-Ogievskiy     QCryptoTLSCreds *tlscreds;
968f071c9dSVladimir Sementsov-Ogievskiy     const char *hostname;
978f071c9dSVladimir Sementsov-Ogievskiy     char *x_dirty_bitmap;
98dbc7b014SEric Blake     bool alloc_depth;
991dc4718dSVladimir Sementsov-Ogievskiy 
10090ddc64fSVladimir Sementsov-Ogievskiy     NBDClientConnection *conn;
101019d6b8fSAnthony Liguori } BDRVNBDState;
102019d6b8fSAnthony Liguori 
103fee091cdSLukas Straub static void nbd_yank(void *opaque);
104f7651539SVladimir Sementsov-Ogievskiy 
105bbba1c37SVladimir Sementsov-Ogievskiy static void nbd_clear_bdrvstate(BlockDriverState *bs)
1067f493662SPan Nengyuan {
107bbba1c37SVladimir Sementsov-Ogievskiy     BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
108e8b35bf5SRoman Kagan 
109248d4701SVladimir Sementsov-Ogievskiy     nbd_client_connection_release(s->conn);
110248d4701SVladimir Sementsov-Ogievskiy     s->conn = NULL;
111bbba1c37SVladimir Sementsov-Ogievskiy 
112bbba1c37SVladimir Sementsov-Ogievskiy     yank_unregister_instance(BLOCKDEV_YANK_INSTANCE(bs->node_name));
113bbba1c37SVladimir Sementsov-Ogievskiy 
1147f493662SPan Nengyuan     object_unref(OBJECT(s->tlscreds));
1157f493662SPan Nengyuan     qapi_free_SocketAddress(s->saddr);
1167f493662SPan Nengyuan     s->saddr = NULL;
1177f493662SPan Nengyuan     g_free(s->export);
1187f493662SPan Nengyuan     s->export = NULL;
1197f493662SPan Nengyuan     g_free(s->tlscredsid);
1207f493662SPan Nengyuan     s->tlscredsid = NULL;
1217f493662SPan Nengyuan     g_free(s->x_dirty_bitmap);
1227f493662SPan Nengyuan     s->x_dirty_bitmap = NULL;
1237f493662SPan Nengyuan }
1247f493662SPan Nengyuan 
12591e0998fSVladimir Sementsov-Ogievskiy static bool nbd_client_connected(BDRVNBDState *s)
12691e0998fSVladimir Sementsov-Ogievskiy {
12791e0998fSVladimir Sementsov-Ogievskiy     return qatomic_load_acquire(&s->state) == NBD_CLIENT_CONNECTED;
12891e0998fSVladimir Sementsov-Ogievskiy }
12991e0998fSVladimir Sementsov-Ogievskiy 
130a34b1e5eSVladimir Sementsov-Ogievskiy static void nbd_channel_error(BDRVNBDState *s, int ret)
131a34b1e5eSVladimir Sementsov-Ogievskiy {
132*cb116da7SVladimir Sementsov-Ogievskiy     if (nbd_client_connected(s)) {
133*cb116da7SVladimir Sementsov-Ogievskiy         qio_channel_shutdown(s->ioc, QIO_CHANNEL_SHUTDOWN_BOTH, NULL);
134*cb116da7SVladimir Sementsov-Ogievskiy     }
135*cb116da7SVladimir Sementsov-Ogievskiy 
136f7651539SVladimir Sementsov-Ogievskiy     if (ret == -EIO) {
13791e0998fSVladimir Sementsov-Ogievskiy         if (nbd_client_connected(s)) {
138f7651539SVladimir Sementsov-Ogievskiy             s->state = s->reconnect_delay ? NBD_CLIENT_CONNECTING_WAIT :
139f7651539SVladimir Sementsov-Ogievskiy                                             NBD_CLIENT_CONNECTING_NOWAIT;
140f7651539SVladimir Sementsov-Ogievskiy         }
141f7651539SVladimir Sementsov-Ogievskiy     } else {
142a34b1e5eSVladimir Sementsov-Ogievskiy         s->state = NBD_CLIENT_QUIT;
143a34b1e5eSVladimir Sementsov-Ogievskiy     }
144f7651539SVladimir Sementsov-Ogievskiy }
145a34b1e5eSVladimir Sementsov-Ogievskiy 
146611ae1d7SVladimir Sementsov-Ogievskiy static void nbd_recv_coroutines_wake_all(BDRVNBDState *s)
14786f8cdf3SVladimir Sementsov-Ogievskiy {
14886f8cdf3SVladimir Sementsov-Ogievskiy     int i;
14986f8cdf3SVladimir Sementsov-Ogievskiy 
15086f8cdf3SVladimir Sementsov-Ogievskiy     for (i = 0; i < MAX_NBD_REQUESTS; i++) {
15186f8cdf3SVladimir Sementsov-Ogievskiy         NBDClientRequest *req = &s->requests[i];
15286f8cdf3SVladimir Sementsov-Ogievskiy 
15386f8cdf3SVladimir Sementsov-Ogievskiy         if (req->coroutine && req->receiving) {
154bbfb7c2fSVladimir Sementsov-Ogievskiy             req->receiving = false;
15586f8cdf3SVladimir Sementsov-Ogievskiy             aio_co_wake(req->coroutine);
15686f8cdf3SVladimir Sementsov-Ogievskiy         }
15786f8cdf3SVladimir Sementsov-Ogievskiy     }
15886f8cdf3SVladimir Sementsov-Ogievskiy }
15986f8cdf3SVladimir Sementsov-Ogievskiy 
16046f56631SVladimir Sementsov-Ogievskiy static void reconnect_delay_timer_del(BDRVNBDState *s)
16146f56631SVladimir Sementsov-Ogievskiy {
16246f56631SVladimir Sementsov-Ogievskiy     if (s->reconnect_delay_timer) {
16346f56631SVladimir Sementsov-Ogievskiy         timer_free(s->reconnect_delay_timer);
16446f56631SVladimir Sementsov-Ogievskiy         s->reconnect_delay_timer = NULL;
16546f56631SVladimir Sementsov-Ogievskiy     }
16646f56631SVladimir Sementsov-Ogievskiy }
16746f56631SVladimir Sementsov-Ogievskiy 
16846f56631SVladimir Sementsov-Ogievskiy static void reconnect_delay_timer_cb(void *opaque)
16946f56631SVladimir Sementsov-Ogievskiy {
17046f56631SVladimir Sementsov-Ogievskiy     BDRVNBDState *s = opaque;
17146f56631SVladimir Sementsov-Ogievskiy 
172fee091cdSLukas Straub     if (qatomic_load_acquire(&s->state) == NBD_CLIENT_CONNECTING_WAIT) {
17346f56631SVladimir Sementsov-Ogievskiy         s->state = NBD_CLIENT_CONNECTING_NOWAIT;
17446f56631SVladimir Sementsov-Ogievskiy         while (qemu_co_enter_next(&s->free_sema, NULL)) {
17546f56631SVladimir Sementsov-Ogievskiy             /* Resume all queued requests */
17646f56631SVladimir Sementsov-Ogievskiy         }
17746f56631SVladimir Sementsov-Ogievskiy     }
17846f56631SVladimir Sementsov-Ogievskiy 
17946f56631SVladimir Sementsov-Ogievskiy     reconnect_delay_timer_del(s);
18046f56631SVladimir Sementsov-Ogievskiy }
18146f56631SVladimir Sementsov-Ogievskiy 
18246f56631SVladimir Sementsov-Ogievskiy static void reconnect_delay_timer_init(BDRVNBDState *s, uint64_t expire_time_ns)
18346f56631SVladimir Sementsov-Ogievskiy {
184fee091cdSLukas Straub     if (qatomic_load_acquire(&s->state) != NBD_CLIENT_CONNECTING_WAIT) {
18546f56631SVladimir Sementsov-Ogievskiy         return;
18646f56631SVladimir Sementsov-Ogievskiy     }
18746f56631SVladimir Sementsov-Ogievskiy 
18846f56631SVladimir Sementsov-Ogievskiy     assert(!s->reconnect_delay_timer);
18946f56631SVladimir Sementsov-Ogievskiy     s->reconnect_delay_timer = aio_timer_new(bdrv_get_aio_context(s->bs),
19046f56631SVladimir Sementsov-Ogievskiy                                              QEMU_CLOCK_REALTIME,
19146f56631SVladimir Sementsov-Ogievskiy                                              SCALE_NS,
19246f56631SVladimir Sementsov-Ogievskiy                                              reconnect_delay_timer_cb, s);
19346f56631SVladimir Sementsov-Ogievskiy     timer_mod(s->reconnect_delay_timer, expire_time_ns);
19446f56631SVladimir Sementsov-Ogievskiy }
19546f56631SVladimir Sementsov-Ogievskiy 
19686f8cdf3SVladimir Sementsov-Ogievskiy static void nbd_client_detach_aio_context(BlockDriverState *bs)
19786f8cdf3SVladimir Sementsov-Ogievskiy {
198611ae1d7SVladimir Sementsov-Ogievskiy     BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
199611ae1d7SVladimir Sementsov-Ogievskiy 
20046f56631SVladimir Sementsov-Ogievskiy     /* Timer is deleted in nbd_client_co_drain_begin() */
20146f56631SVladimir Sementsov-Ogievskiy     assert(!s->reconnect_delay_timer);
2023b5e4db6SRoman Kagan     /*
2033b5e4db6SRoman Kagan      * If reconnect is in progress we may have no ->ioc.  It will be
2043b5e4db6SRoman Kagan      * re-instantiated in the proper aio context once the connection is
2053b5e4db6SRoman Kagan      * reestablished.
2063b5e4db6SRoman Kagan      */
2073b5e4db6SRoman Kagan     if (s->ioc) {
208611ae1d7SVladimir Sementsov-Ogievskiy         qio_channel_detach_aio_context(QIO_CHANNEL(s->ioc));
20986f8cdf3SVladimir Sementsov-Ogievskiy     }
2103b5e4db6SRoman Kagan }
21186f8cdf3SVladimir Sementsov-Ogievskiy 
21286f8cdf3SVladimir Sementsov-Ogievskiy static void nbd_client_attach_aio_context_bh(void *opaque)
21386f8cdf3SVladimir Sementsov-Ogievskiy {
21486f8cdf3SVladimir Sementsov-Ogievskiy     BlockDriverState *bs = opaque;
215611ae1d7SVladimir Sementsov-Ogievskiy     BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
21686f8cdf3SVladimir Sementsov-Ogievskiy 
217ddde5ee7SRoman Kagan     if (s->connection_co) {
21886f8cdf3SVladimir Sementsov-Ogievskiy         /*
21986f8cdf3SVladimir Sementsov-Ogievskiy          * The node is still drained, so we know the coroutine has yielded in
220ddde5ee7SRoman Kagan          * nbd_read_eof(), the only place where bs->in_flight can reach 0, or
221ddde5ee7SRoman Kagan          * it is entered for the first time. Both places are safe for entering
222ddde5ee7SRoman Kagan          * the coroutine.
22386f8cdf3SVladimir Sementsov-Ogievskiy          */
224611ae1d7SVladimir Sementsov-Ogievskiy         qemu_aio_coroutine_enter(bs->aio_context, s->connection_co);
225ddde5ee7SRoman Kagan     }
22686f8cdf3SVladimir Sementsov-Ogievskiy     bdrv_dec_in_flight(bs);
22786f8cdf3SVladimir Sementsov-Ogievskiy }
22886f8cdf3SVladimir Sementsov-Ogievskiy 
22986f8cdf3SVladimir Sementsov-Ogievskiy static void nbd_client_attach_aio_context(BlockDriverState *bs,
23086f8cdf3SVladimir Sementsov-Ogievskiy                                           AioContext *new_context)
23186f8cdf3SVladimir Sementsov-Ogievskiy {
232611ae1d7SVladimir Sementsov-Ogievskiy     BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
233611ae1d7SVladimir Sementsov-Ogievskiy 
234f7651539SVladimir Sementsov-Ogievskiy     /*
235f7651539SVladimir Sementsov-Ogievskiy      * s->connection_co is either yielded from nbd_receive_reply or from
236f7651539SVladimir Sementsov-Ogievskiy      * nbd_co_reconnect_loop()
237f7651539SVladimir Sementsov-Ogievskiy      */
23891e0998fSVladimir Sementsov-Ogievskiy     if (nbd_client_connected(s)) {
239611ae1d7SVladimir Sementsov-Ogievskiy         qio_channel_attach_aio_context(QIO_CHANNEL(s->ioc), new_context);
240f7651539SVladimir Sementsov-Ogievskiy     }
24186f8cdf3SVladimir Sementsov-Ogievskiy 
24286f8cdf3SVladimir Sementsov-Ogievskiy     bdrv_inc_in_flight(bs);
24386f8cdf3SVladimir Sementsov-Ogievskiy 
24486f8cdf3SVladimir Sementsov-Ogievskiy     /*
24586f8cdf3SVladimir Sementsov-Ogievskiy      * Need to wait here for the BH to run because the BH must run while the
24686f8cdf3SVladimir Sementsov-Ogievskiy      * node is still drained.
24786f8cdf3SVladimir Sementsov-Ogievskiy      */
24886f8cdf3SVladimir Sementsov-Ogievskiy     aio_wait_bh_oneshot(new_context, nbd_client_attach_aio_context_bh, bs);
24986f8cdf3SVladimir Sementsov-Ogievskiy }
25086f8cdf3SVladimir Sementsov-Ogievskiy 
251f7651539SVladimir Sementsov-Ogievskiy static void coroutine_fn nbd_client_co_drain_begin(BlockDriverState *bs)
252f7651539SVladimir Sementsov-Ogievskiy {
253f7651539SVladimir Sementsov-Ogievskiy     BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
254f7651539SVladimir Sementsov-Ogievskiy 
255f7651539SVladimir Sementsov-Ogievskiy     s->drained = true;
25629a6ea24SPaolo Bonzini     qemu_co_sleep_wake(&s->reconnect_sleep);
2571dc4718dSVladimir Sementsov-Ogievskiy 
25890ddc64fSVladimir Sementsov-Ogievskiy     nbd_co_establish_connection_cancel(s->conn);
2598c517de2SVladimir Sementsov-Ogievskiy 
26046f56631SVladimir Sementsov-Ogievskiy     reconnect_delay_timer_del(s);
26146f56631SVladimir Sementsov-Ogievskiy 
262fee091cdSLukas Straub     if (qatomic_load_acquire(&s->state) == NBD_CLIENT_CONNECTING_WAIT) {
2638c517de2SVladimir Sementsov-Ogievskiy         s->state = NBD_CLIENT_CONNECTING_NOWAIT;
2648c517de2SVladimir Sementsov-Ogievskiy         qemu_co_queue_restart_all(&s->free_sema);
2658c517de2SVladimir Sementsov-Ogievskiy     }
266f7651539SVladimir Sementsov-Ogievskiy }
267f7651539SVladimir Sementsov-Ogievskiy 
268f7651539SVladimir Sementsov-Ogievskiy static void coroutine_fn nbd_client_co_drain_end(BlockDriverState *bs)
269f7651539SVladimir Sementsov-Ogievskiy {
270f7651539SVladimir Sementsov-Ogievskiy     BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
271f7651539SVladimir Sementsov-Ogievskiy 
272f7651539SVladimir Sementsov-Ogievskiy     s->drained = false;
273f7651539SVladimir Sementsov-Ogievskiy     if (s->wait_drained_end) {
274f7651539SVladimir Sementsov-Ogievskiy         s->wait_drained_end = false;
275f7651539SVladimir Sementsov-Ogievskiy         aio_co_wake(s->connection_co);
276f7651539SVladimir Sementsov-Ogievskiy     }
277f7651539SVladimir Sementsov-Ogievskiy }
278f7651539SVladimir Sementsov-Ogievskiy 
27986f8cdf3SVladimir Sementsov-Ogievskiy 
28086f8cdf3SVladimir Sementsov-Ogievskiy static void nbd_teardown_connection(BlockDriverState *bs)
28186f8cdf3SVladimir Sementsov-Ogievskiy {
282611ae1d7SVladimir Sementsov-Ogievskiy     BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
28386f8cdf3SVladimir Sementsov-Ogievskiy 
284fbeb3e63SVladimir Sementsov-Ogievskiy     if (s->ioc) {
28586f8cdf3SVladimir Sementsov-Ogievskiy         /* finish any pending coroutines */
286f7651539SVladimir Sementsov-Ogievskiy         qio_channel_shutdown(s->ioc, QIO_CHANNEL_SHUTDOWN_BOTH, NULL);
287f7651539SVladimir Sementsov-Ogievskiy     }
288fbeb3e63SVladimir Sementsov-Ogievskiy 
289f7651539SVladimir Sementsov-Ogievskiy     s->state = NBD_CLIENT_QUIT;
290f7651539SVladimir Sementsov-Ogievskiy     if (s->connection_co) {
29129a6ea24SPaolo Bonzini         qemu_co_sleep_wake(&s->reconnect_sleep);
29290ddc64fSVladimir Sementsov-Ogievskiy         nbd_co_establish_connection_cancel(s->conn);
293f7651539SVladimir Sementsov-Ogievskiy     }
29478c81a3fSMax Reitz     if (qemu_in_coroutine()) {
29578c81a3fSMax Reitz         s->teardown_co = qemu_coroutine_self();
29678c81a3fSMax Reitz         /* connection_co resumes us when it terminates */
29778c81a3fSMax Reitz         qemu_coroutine_yield();
29878c81a3fSMax Reitz         s->teardown_co = NULL;
29978c81a3fSMax Reitz     } else {
300611ae1d7SVladimir Sementsov-Ogievskiy         BDRV_POLL_WHILE(bs, s->connection_co);
301f7651539SVladimir Sementsov-Ogievskiy     }
30278c81a3fSMax Reitz     assert(!s->connection_co);
30378c81a3fSMax Reitz }
30486f8cdf3SVladimir Sementsov-Ogievskiy 
305f7651539SVladimir Sementsov-Ogievskiy static bool nbd_client_connecting(BDRVNBDState *s)
306f7651539SVladimir Sementsov-Ogievskiy {
307fee091cdSLukas Straub     NBDClientState state = qatomic_load_acquire(&s->state);
308fee091cdSLukas Straub     return state == NBD_CLIENT_CONNECTING_WAIT ||
309fee091cdSLukas Straub         state == NBD_CLIENT_CONNECTING_NOWAIT;
310f7651539SVladimir Sementsov-Ogievskiy }
311f7651539SVladimir Sementsov-Ogievskiy 
312f7651539SVladimir Sementsov-Ogievskiy static bool nbd_client_connecting_wait(BDRVNBDState *s)
313f7651539SVladimir Sementsov-Ogievskiy {
314fee091cdSLukas Straub     return qatomic_load_acquire(&s->state) == NBD_CLIENT_CONNECTING_WAIT;
315f7651539SVladimir Sementsov-Ogievskiy }
316f7651539SVladimir Sementsov-Ogievskiy 
317e9ba7788SVladimir Sementsov-Ogievskiy /*
318e9ba7788SVladimir Sementsov-Ogievskiy  * Update @bs with information learned during a completed negotiation process.
319e9ba7788SVladimir Sementsov-Ogievskiy  * Return failure if the server's advertised options are incompatible with the
320e9ba7788SVladimir Sementsov-Ogievskiy  * client's needs.
321e9ba7788SVladimir Sementsov-Ogievskiy  */
322e9ba7788SVladimir Sementsov-Ogievskiy static int nbd_handle_updated_info(BlockDriverState *bs, Error **errp)
323e9ba7788SVladimir Sementsov-Ogievskiy {
324e9ba7788SVladimir Sementsov-Ogievskiy     BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
325e9ba7788SVladimir Sementsov-Ogievskiy     int ret;
326e9ba7788SVladimir Sementsov-Ogievskiy 
327e9ba7788SVladimir Sementsov-Ogievskiy     if (s->x_dirty_bitmap) {
328e9ba7788SVladimir Sementsov-Ogievskiy         if (!s->info.base_allocation) {
329e9ba7788SVladimir Sementsov-Ogievskiy             error_setg(errp, "requested x-dirty-bitmap %s not found",
330e9ba7788SVladimir Sementsov-Ogievskiy                        s->x_dirty_bitmap);
331e9ba7788SVladimir Sementsov-Ogievskiy             return -EINVAL;
332e9ba7788SVladimir Sementsov-Ogievskiy         }
333e9ba7788SVladimir Sementsov-Ogievskiy         if (strcmp(s->x_dirty_bitmap, "qemu:allocation-depth") == 0) {
334e9ba7788SVladimir Sementsov-Ogievskiy             s->alloc_depth = true;
335e9ba7788SVladimir Sementsov-Ogievskiy         }
336e9ba7788SVladimir Sementsov-Ogievskiy     }
337e9ba7788SVladimir Sementsov-Ogievskiy 
338e9ba7788SVladimir Sementsov-Ogievskiy     if (s->info.flags & NBD_FLAG_READ_ONLY) {
339e9ba7788SVladimir Sementsov-Ogievskiy         ret = bdrv_apply_auto_read_only(bs, "NBD export is read-only", errp);
340e9ba7788SVladimir Sementsov-Ogievskiy         if (ret < 0) {
341e9ba7788SVladimir Sementsov-Ogievskiy             return ret;
342e9ba7788SVladimir Sementsov-Ogievskiy         }
343e9ba7788SVladimir Sementsov-Ogievskiy     }
344e9ba7788SVladimir Sementsov-Ogievskiy 
345e9ba7788SVladimir Sementsov-Ogievskiy     if (s->info.flags & NBD_FLAG_SEND_FUA) {
346e9ba7788SVladimir Sementsov-Ogievskiy         bs->supported_write_flags = BDRV_REQ_FUA;
347e9ba7788SVladimir Sementsov-Ogievskiy         bs->supported_zero_flags |= BDRV_REQ_FUA;
348e9ba7788SVladimir Sementsov-Ogievskiy     }
349e9ba7788SVladimir Sementsov-Ogievskiy 
350e9ba7788SVladimir Sementsov-Ogievskiy     if (s->info.flags & NBD_FLAG_SEND_WRITE_ZEROES) {
351e9ba7788SVladimir Sementsov-Ogievskiy         bs->supported_zero_flags |= BDRV_REQ_MAY_UNMAP;
352e9ba7788SVladimir Sementsov-Ogievskiy         if (s->info.flags & NBD_FLAG_SEND_FAST_ZERO) {
353e9ba7788SVladimir Sementsov-Ogievskiy             bs->supported_zero_flags |= BDRV_REQ_NO_FALLBACK;
354e9ba7788SVladimir Sementsov-Ogievskiy         }
355e9ba7788SVladimir Sementsov-Ogievskiy     }
356e9ba7788SVladimir Sementsov-Ogievskiy 
357e9ba7788SVladimir Sementsov-Ogievskiy     trace_nbd_client_handshake_success(s->export);
358e9ba7788SVladimir Sementsov-Ogievskiy 
359e9ba7788SVladimir Sementsov-Ogievskiy     return 0;
360e9ba7788SVladimir Sementsov-Ogievskiy }
361e9ba7788SVladimir Sementsov-Ogievskiy 
362a71d597bSVladimir Sementsov-Ogievskiy int coroutine_fn nbd_co_do_establish_connection(BlockDriverState *bs,
36351edbf53SVladimir Sementsov-Ogievskiy                                                 Error **errp)
36451edbf53SVladimir Sementsov-Ogievskiy {
36551edbf53SVladimir Sementsov-Ogievskiy     BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
36651edbf53SVladimir Sementsov-Ogievskiy     int ret;
36751edbf53SVladimir Sementsov-Ogievskiy 
36851edbf53SVladimir Sementsov-Ogievskiy     assert(!s->ioc);
36951edbf53SVladimir Sementsov-Ogievskiy 
37097cf8925SVladimir Sementsov-Ogievskiy     s->ioc = nbd_co_establish_connection(s->conn, &s->info, true, errp);
37151edbf53SVladimir Sementsov-Ogievskiy     if (!s->ioc) {
37251edbf53SVladimir Sementsov-Ogievskiy         return -ECONNREFUSED;
37351edbf53SVladimir Sementsov-Ogievskiy     }
37451edbf53SVladimir Sementsov-Ogievskiy 
3750b9cd6b9SLukas Straub     yank_register_function(BLOCKDEV_YANK_INSTANCE(s->bs->node_name), nbd_yank,
3760b9cd6b9SLukas Straub                            bs);
3770b9cd6b9SLukas Straub 
37851edbf53SVladimir Sementsov-Ogievskiy     ret = nbd_handle_updated_info(s->bs, NULL);
37951edbf53SVladimir Sementsov-Ogievskiy     if (ret < 0) {
38051edbf53SVladimir Sementsov-Ogievskiy         /*
38151edbf53SVladimir Sementsov-Ogievskiy          * We have connected, but must fail for other reasons.
38251edbf53SVladimir Sementsov-Ogievskiy          * Send NBD_CMD_DISC as a courtesy to the server.
38351edbf53SVladimir Sementsov-Ogievskiy          */
38451edbf53SVladimir Sementsov-Ogievskiy         NBDRequest request = { .type = NBD_CMD_DISC };
38551edbf53SVladimir Sementsov-Ogievskiy 
38651edbf53SVladimir Sementsov-Ogievskiy         nbd_send_request(s->ioc, &request);
38751edbf53SVladimir Sementsov-Ogievskiy 
3880b9cd6b9SLukas Straub         yank_unregister_function(BLOCKDEV_YANK_INSTANCE(s->bs->node_name),
3890b9cd6b9SLukas Straub                                  nbd_yank, bs);
39051edbf53SVladimir Sementsov-Ogievskiy         object_unref(OBJECT(s->ioc));
39151edbf53SVladimir Sementsov-Ogievskiy         s->ioc = NULL;
39251edbf53SVladimir Sementsov-Ogievskiy 
39351edbf53SVladimir Sementsov-Ogievskiy         return ret;
39451edbf53SVladimir Sementsov-Ogievskiy     }
39551edbf53SVladimir Sementsov-Ogievskiy 
39651edbf53SVladimir Sementsov-Ogievskiy     qio_channel_set_blocking(s->ioc, false, NULL);
39751edbf53SVladimir Sementsov-Ogievskiy     qio_channel_attach_aio_context(s->ioc, bdrv_get_aio_context(bs));
39851edbf53SVladimir Sementsov-Ogievskiy 
39951edbf53SVladimir Sementsov-Ogievskiy     /* successfully connected */
40051edbf53SVladimir Sementsov-Ogievskiy     s->state = NBD_CLIENT_CONNECTED;
40151edbf53SVladimir Sementsov-Ogievskiy     qemu_co_queue_restart_all(&s->free_sema);
40251edbf53SVladimir Sementsov-Ogievskiy 
40351edbf53SVladimir Sementsov-Ogievskiy     return 0;
40451edbf53SVladimir Sementsov-Ogievskiy }
40551edbf53SVladimir Sementsov-Ogievskiy 
406f7651539SVladimir Sementsov-Ogievskiy static coroutine_fn void nbd_reconnect_attempt(BDRVNBDState *s)
407f7651539SVladimir Sementsov-Ogievskiy {
408f7651539SVladimir Sementsov-Ogievskiy     if (!nbd_client_connecting(s)) {
409f7651539SVladimir Sementsov-Ogievskiy         return;
410f7651539SVladimir Sementsov-Ogievskiy     }
411f7651539SVladimir Sementsov-Ogievskiy 
412f7651539SVladimir Sementsov-Ogievskiy     /* Wait for completion of all in-flight requests */
413f7651539SVladimir Sementsov-Ogievskiy 
414f7651539SVladimir Sementsov-Ogievskiy     qemu_co_mutex_lock(&s->send_mutex);
415f7651539SVladimir Sementsov-Ogievskiy 
416f7651539SVladimir Sementsov-Ogievskiy     while (s->in_flight > 0) {
417f7651539SVladimir Sementsov-Ogievskiy         qemu_co_mutex_unlock(&s->send_mutex);
418f7651539SVladimir Sementsov-Ogievskiy         nbd_recv_coroutines_wake_all(s);
419f7651539SVladimir Sementsov-Ogievskiy         s->wait_in_flight = true;
420f7651539SVladimir Sementsov-Ogievskiy         qemu_coroutine_yield();
421f7651539SVladimir Sementsov-Ogievskiy         s->wait_in_flight = false;
422f7651539SVladimir Sementsov-Ogievskiy         qemu_co_mutex_lock(&s->send_mutex);
423f7651539SVladimir Sementsov-Ogievskiy     }
424f7651539SVladimir Sementsov-Ogievskiy 
425f7651539SVladimir Sementsov-Ogievskiy     qemu_co_mutex_unlock(&s->send_mutex);
426f7651539SVladimir Sementsov-Ogievskiy 
427f7651539SVladimir Sementsov-Ogievskiy     if (!nbd_client_connecting(s)) {
428f7651539SVladimir Sementsov-Ogievskiy         return;
429f7651539SVladimir Sementsov-Ogievskiy     }
430f7651539SVladimir Sementsov-Ogievskiy 
431f7651539SVladimir Sementsov-Ogievskiy     /*
432f7651539SVladimir Sementsov-Ogievskiy      * Now we are sure that nobody is accessing the channel, and no one will
433f7651539SVladimir Sementsov-Ogievskiy      * try until we set the state to CONNECTED.
434f7651539SVladimir Sementsov-Ogievskiy      */
435f7651539SVladimir Sementsov-Ogievskiy 
436f7651539SVladimir Sementsov-Ogievskiy     /* Finalize previous connection if any */
437f7651539SVladimir Sementsov-Ogievskiy     if (s->ioc) {
4388a509afdSVladimir Sementsov-Ogievskiy         qio_channel_detach_aio_context(QIO_CHANNEL(s->ioc));
439fee091cdSLukas Straub         yank_unregister_function(BLOCKDEV_YANK_INSTANCE(s->bs->node_name),
440fee091cdSLukas Straub                                  nbd_yank, s->bs);
441611ae1d7SVladimir Sementsov-Ogievskiy         object_unref(OBJECT(s->ioc));
442611ae1d7SVladimir Sementsov-Ogievskiy         s->ioc = NULL;
44386f8cdf3SVladimir Sementsov-Ogievskiy     }
44486f8cdf3SVladimir Sementsov-Ogievskiy 
44551edbf53SVladimir Sementsov-Ogievskiy     nbd_co_do_establish_connection(s->bs, NULL);
446fa35591bSVladimir Sementsov-Ogievskiy }
447f7651539SVladimir Sementsov-Ogievskiy 
448f7651539SVladimir Sementsov-Ogievskiy static coroutine_fn void nbd_co_reconnect_loop(BDRVNBDState *s)
449f7651539SVladimir Sementsov-Ogievskiy {
450f7651539SVladimir Sementsov-Ogievskiy     uint64_t timeout = 1 * NANOSECONDS_PER_SECOND;
451f7651539SVladimir Sementsov-Ogievskiy     uint64_t max_timeout = 16 * NANOSECONDS_PER_SECOND;
452f7651539SVladimir Sementsov-Ogievskiy 
453fee091cdSLukas Straub     if (qatomic_load_acquire(&s->state) == NBD_CLIENT_CONNECTING_WAIT) {
45446f56631SVladimir Sementsov-Ogievskiy         reconnect_delay_timer_init(s, qemu_clock_get_ns(QEMU_CLOCK_REALTIME) +
45546f56631SVladimir Sementsov-Ogievskiy                                    s->reconnect_delay * NANOSECONDS_PER_SECOND);
45646f56631SVladimir Sementsov-Ogievskiy     }
45746f56631SVladimir Sementsov-Ogievskiy 
458f7651539SVladimir Sementsov-Ogievskiy     nbd_reconnect_attempt(s);
459f7651539SVladimir Sementsov-Ogievskiy 
460f7651539SVladimir Sementsov-Ogievskiy     while (nbd_client_connecting(s)) {
461f7651539SVladimir Sementsov-Ogievskiy         if (s->drained) {
462f7651539SVladimir Sementsov-Ogievskiy             bdrv_dec_in_flight(s->bs);
463f7651539SVladimir Sementsov-Ogievskiy             s->wait_drained_end = true;
464f7651539SVladimir Sementsov-Ogievskiy             while (s->drained) {
465f7651539SVladimir Sementsov-Ogievskiy                 /*
466f7651539SVladimir Sementsov-Ogievskiy                  * We may be entered once from nbd_client_attach_aio_context_bh
467f7651539SVladimir Sementsov-Ogievskiy                  * and then from nbd_client_co_drain_end. So here is a loop.
468f7651539SVladimir Sementsov-Ogievskiy                  */
469f7651539SVladimir Sementsov-Ogievskiy                 qemu_coroutine_yield();
470f7651539SVladimir Sementsov-Ogievskiy             }
471f7651539SVladimir Sementsov-Ogievskiy             bdrv_inc_in_flight(s->bs);
47212c75e20SVladimir Sementsov-Ogievskiy         } else {
47329a6ea24SPaolo Bonzini             qemu_co_sleep_ns_wakeable(&s->reconnect_sleep,
47429a6ea24SPaolo Bonzini                                       QEMU_CLOCK_REALTIME, timeout);
47599d72dbaSVladimir Sementsov-Ogievskiy             if (s->drained) {
47699d72dbaSVladimir Sementsov-Ogievskiy                 continue;
47799d72dbaSVladimir Sementsov-Ogievskiy             }
478f7651539SVladimir Sementsov-Ogievskiy             if (timeout < max_timeout) {
479f7651539SVladimir Sementsov-Ogievskiy                 timeout *= 2;
480f7651539SVladimir Sementsov-Ogievskiy             }
48112c75e20SVladimir Sementsov-Ogievskiy         }
482f7651539SVladimir Sementsov-Ogievskiy 
483f7651539SVladimir Sementsov-Ogievskiy         nbd_reconnect_attempt(s);
484f7651539SVladimir Sementsov-Ogievskiy     }
48546f56631SVladimir Sementsov-Ogievskiy 
48646f56631SVladimir Sementsov-Ogievskiy     reconnect_delay_timer_del(s);
487f7651539SVladimir Sementsov-Ogievskiy }
488f7651539SVladimir Sementsov-Ogievskiy 
48986f8cdf3SVladimir Sementsov-Ogievskiy static coroutine_fn void nbd_connection_entry(void *opaque)
49086f8cdf3SVladimir Sementsov-Ogievskiy {
491611ae1d7SVladimir Sementsov-Ogievskiy     BDRVNBDState *s = opaque;
49286f8cdf3SVladimir Sementsov-Ogievskiy     uint64_t i;
49386f8cdf3SVladimir Sementsov-Ogievskiy     int ret = 0;
49486f8cdf3SVladimir Sementsov-Ogievskiy     Error *local_err = NULL;
49586f8cdf3SVladimir Sementsov-Ogievskiy 
496fee091cdSLukas Straub     while (qatomic_load_acquire(&s->state) != NBD_CLIENT_QUIT) {
49786f8cdf3SVladimir Sementsov-Ogievskiy         /*
49886f8cdf3SVladimir Sementsov-Ogievskiy          * The NBD client can only really be considered idle when it has
49986f8cdf3SVladimir Sementsov-Ogievskiy          * yielded from qio_channel_readv_all_eof(), waiting for data. This is
50086f8cdf3SVladimir Sementsov-Ogievskiy          * the point where the additional scheduled coroutine entry happens
50186f8cdf3SVladimir Sementsov-Ogievskiy          * after nbd_client_attach_aio_context().
50286f8cdf3SVladimir Sementsov-Ogievskiy          *
50386f8cdf3SVladimir Sementsov-Ogievskiy          * Therefore we keep an additional in_flight reference all the time and
50486f8cdf3SVladimir Sementsov-Ogievskiy          * only drop it temporarily here.
50586f8cdf3SVladimir Sementsov-Ogievskiy          */
506f7651539SVladimir Sementsov-Ogievskiy 
507f7651539SVladimir Sementsov-Ogievskiy         if (nbd_client_connecting(s)) {
508f7651539SVladimir Sementsov-Ogievskiy             nbd_co_reconnect_loop(s);
509f7651539SVladimir Sementsov-Ogievskiy         }
510f7651539SVladimir Sementsov-Ogievskiy 
51191e0998fSVladimir Sementsov-Ogievskiy         if (!nbd_client_connected(s)) {
512f7651539SVladimir Sementsov-Ogievskiy             continue;
513f7651539SVladimir Sementsov-Ogievskiy         }
514f7651539SVladimir Sementsov-Ogievskiy 
51586f8cdf3SVladimir Sementsov-Ogievskiy         assert(s->reply.handle == 0);
51686f8cdf3SVladimir Sementsov-Ogievskiy         ret = nbd_receive_reply(s->bs, s->ioc, &s->reply, &local_err);
51786f8cdf3SVladimir Sementsov-Ogievskiy 
51886f8cdf3SVladimir Sementsov-Ogievskiy         if (local_err) {
51986f8cdf3SVladimir Sementsov-Ogievskiy             trace_nbd_read_reply_entry_fail(ret, error_get_pretty(local_err));
52086f8cdf3SVladimir Sementsov-Ogievskiy             error_free(local_err);
521f7651539SVladimir Sementsov-Ogievskiy             local_err = NULL;
52286f8cdf3SVladimir Sementsov-Ogievskiy         }
52386f8cdf3SVladimir Sementsov-Ogievskiy         if (ret <= 0) {
524a34b1e5eSVladimir Sementsov-Ogievskiy             nbd_channel_error(s, ret ? ret : -EIO);
525f7651539SVladimir Sementsov-Ogievskiy             continue;
52686f8cdf3SVladimir Sementsov-Ogievskiy         }
52786f8cdf3SVladimir Sementsov-Ogievskiy 
52886f8cdf3SVladimir Sementsov-Ogievskiy         /*
52986f8cdf3SVladimir Sementsov-Ogievskiy          * There's no need for a mutex on the receive side, because the
53086f8cdf3SVladimir Sementsov-Ogievskiy          * handler acts as a synchronization point and ensures that only
53186f8cdf3SVladimir Sementsov-Ogievskiy          * one coroutine is called until the reply finishes.
53286f8cdf3SVladimir Sementsov-Ogievskiy          */
53386f8cdf3SVladimir Sementsov-Ogievskiy         i = HANDLE_TO_INDEX(s, s->reply.handle);
53486f8cdf3SVladimir Sementsov-Ogievskiy         if (i >= MAX_NBD_REQUESTS ||
53586f8cdf3SVladimir Sementsov-Ogievskiy             !s->requests[i].coroutine ||
53686f8cdf3SVladimir Sementsov-Ogievskiy             !s->requests[i].receiving ||
53786f8cdf3SVladimir Sementsov-Ogievskiy             (nbd_reply_is_structured(&s->reply) && !s->info.structured_reply))
53886f8cdf3SVladimir Sementsov-Ogievskiy         {
539a34b1e5eSVladimir Sementsov-Ogievskiy             nbd_channel_error(s, -EINVAL);
540f7651539SVladimir Sementsov-Ogievskiy             continue;
54186f8cdf3SVladimir Sementsov-Ogievskiy         }
54286f8cdf3SVladimir Sementsov-Ogievskiy 
54386f8cdf3SVladimir Sementsov-Ogievskiy         /*
54486f8cdf3SVladimir Sementsov-Ogievskiy          * We're woken up again by the request itself.  Note that there
54586f8cdf3SVladimir Sementsov-Ogievskiy          * is no race between yielding and reentering connection_co.  This
54686f8cdf3SVladimir Sementsov-Ogievskiy          * is because:
54786f8cdf3SVladimir Sementsov-Ogievskiy          *
54886f8cdf3SVladimir Sementsov-Ogievskiy          * - if the request runs on the same AioContext, it is only
54986f8cdf3SVladimir Sementsov-Ogievskiy          *   entered after we yield
55086f8cdf3SVladimir Sementsov-Ogievskiy          *
55186f8cdf3SVladimir Sementsov-Ogievskiy          * - if the request runs on a different AioContext, reentering
55286f8cdf3SVladimir Sementsov-Ogievskiy          *   connection_co happens through a bottom half, which can only
55386f8cdf3SVladimir Sementsov-Ogievskiy          *   run after we yield.
55486f8cdf3SVladimir Sementsov-Ogievskiy          */
555bbfb7c2fSVladimir Sementsov-Ogievskiy         s->requests[i].receiving = false;
55686f8cdf3SVladimir Sementsov-Ogievskiy         aio_co_wake(s->requests[i].coroutine);
55786f8cdf3SVladimir Sementsov-Ogievskiy         qemu_coroutine_yield();
55886f8cdf3SVladimir Sementsov-Ogievskiy     }
55986f8cdf3SVladimir Sementsov-Ogievskiy 
560f7651539SVladimir Sementsov-Ogievskiy     qemu_co_queue_restart_all(&s->free_sema);
56186f8cdf3SVladimir Sementsov-Ogievskiy     nbd_recv_coroutines_wake_all(s);
56286f8cdf3SVladimir Sementsov-Ogievskiy     bdrv_dec_in_flight(s->bs);
56386f8cdf3SVladimir Sementsov-Ogievskiy 
56486f8cdf3SVladimir Sementsov-Ogievskiy     s->connection_co = NULL;
565f7651539SVladimir Sementsov-Ogievskiy     if (s->ioc) {
5668a509afdSVladimir Sementsov-Ogievskiy         qio_channel_detach_aio_context(QIO_CHANNEL(s->ioc));
567fee091cdSLukas Straub         yank_unregister_function(BLOCKDEV_YANK_INSTANCE(s->bs->node_name),
568fee091cdSLukas Straub                                  nbd_yank, s->bs);
569f7651539SVladimir Sementsov-Ogievskiy         object_unref(OBJECT(s->ioc));
570f7651539SVladimir Sementsov-Ogievskiy         s->ioc = NULL;
571f7651539SVladimir Sementsov-Ogievskiy     }
572f7651539SVladimir Sementsov-Ogievskiy 
57378c81a3fSMax Reitz     if (s->teardown_co) {
57478c81a3fSMax Reitz         aio_co_wake(s->teardown_co);
57578c81a3fSMax Reitz     }
57686f8cdf3SVladimir Sementsov-Ogievskiy     aio_wait_kick();
57786f8cdf3SVladimir Sementsov-Ogievskiy }
57886f8cdf3SVladimir Sementsov-Ogievskiy 
57986f8cdf3SVladimir Sementsov-Ogievskiy static int nbd_co_send_request(BlockDriverState *bs,
58086f8cdf3SVladimir Sementsov-Ogievskiy                                NBDRequest *request,
58186f8cdf3SVladimir Sementsov-Ogievskiy                                QEMUIOVector *qiov)
58286f8cdf3SVladimir Sementsov-Ogievskiy {
583611ae1d7SVladimir Sementsov-Ogievskiy     BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
584a34b1e5eSVladimir Sementsov-Ogievskiy     int rc, i = -1;
58586f8cdf3SVladimir Sementsov-Ogievskiy 
58686f8cdf3SVladimir Sementsov-Ogievskiy     qemu_co_mutex_lock(&s->send_mutex);
587f7651539SVladimir Sementsov-Ogievskiy     while (s->in_flight == MAX_NBD_REQUESTS || nbd_client_connecting_wait(s)) {
58886f8cdf3SVladimir Sementsov-Ogievskiy         qemu_co_queue_wait(&s->free_sema, &s->send_mutex);
58986f8cdf3SVladimir Sementsov-Ogievskiy     }
590a34b1e5eSVladimir Sementsov-Ogievskiy 
59191e0998fSVladimir Sementsov-Ogievskiy     if (!nbd_client_connected(s)) {
592a34b1e5eSVladimir Sementsov-Ogievskiy         rc = -EIO;
593a34b1e5eSVladimir Sementsov-Ogievskiy         goto err;
594a34b1e5eSVladimir Sementsov-Ogievskiy     }
595a34b1e5eSVladimir Sementsov-Ogievskiy 
59686f8cdf3SVladimir Sementsov-Ogievskiy     s->in_flight++;
59786f8cdf3SVladimir Sementsov-Ogievskiy 
59886f8cdf3SVladimir Sementsov-Ogievskiy     for (i = 0; i < MAX_NBD_REQUESTS; i++) {
59986f8cdf3SVladimir Sementsov-Ogievskiy         if (s->requests[i].coroutine == NULL) {
60086f8cdf3SVladimir Sementsov-Ogievskiy             break;
60186f8cdf3SVladimir Sementsov-Ogievskiy         }
60286f8cdf3SVladimir Sementsov-Ogievskiy     }
60386f8cdf3SVladimir Sementsov-Ogievskiy 
60486f8cdf3SVladimir Sementsov-Ogievskiy     g_assert(qemu_in_coroutine());
60586f8cdf3SVladimir Sementsov-Ogievskiy     assert(i < MAX_NBD_REQUESTS);
60686f8cdf3SVladimir Sementsov-Ogievskiy 
60786f8cdf3SVladimir Sementsov-Ogievskiy     s->requests[i].coroutine = qemu_coroutine_self();
60886f8cdf3SVladimir Sementsov-Ogievskiy     s->requests[i].offset = request->from;
60986f8cdf3SVladimir Sementsov-Ogievskiy     s->requests[i].receiving = false;
61086f8cdf3SVladimir Sementsov-Ogievskiy 
61186f8cdf3SVladimir Sementsov-Ogievskiy     request->handle = INDEX_TO_HANDLE(s, i);
61286f8cdf3SVladimir Sementsov-Ogievskiy 
61386f8cdf3SVladimir Sementsov-Ogievskiy     assert(s->ioc);
61486f8cdf3SVladimir Sementsov-Ogievskiy 
61586f8cdf3SVladimir Sementsov-Ogievskiy     if (qiov) {
61686f8cdf3SVladimir Sementsov-Ogievskiy         qio_channel_set_cork(s->ioc, true);
61786f8cdf3SVladimir Sementsov-Ogievskiy         rc = nbd_send_request(s->ioc, request);
61891e0998fSVladimir Sementsov-Ogievskiy         if (nbd_client_connected(s) && rc >= 0) {
61986f8cdf3SVladimir Sementsov-Ogievskiy             if (qio_channel_writev_all(s->ioc, qiov->iov, qiov->niov,
62086f8cdf3SVladimir Sementsov-Ogievskiy                                        NULL) < 0) {
62186f8cdf3SVladimir Sementsov-Ogievskiy                 rc = -EIO;
62286f8cdf3SVladimir Sementsov-Ogievskiy             }
62386f8cdf3SVladimir Sementsov-Ogievskiy         } else if (rc >= 0) {
62486f8cdf3SVladimir Sementsov-Ogievskiy             rc = -EIO;
62586f8cdf3SVladimir Sementsov-Ogievskiy         }
62686f8cdf3SVladimir Sementsov-Ogievskiy         qio_channel_set_cork(s->ioc, false);
62786f8cdf3SVladimir Sementsov-Ogievskiy     } else {
62886f8cdf3SVladimir Sementsov-Ogievskiy         rc = nbd_send_request(s->ioc, request);
62986f8cdf3SVladimir Sementsov-Ogievskiy     }
63086f8cdf3SVladimir Sementsov-Ogievskiy 
63186f8cdf3SVladimir Sementsov-Ogievskiy err:
63286f8cdf3SVladimir Sementsov-Ogievskiy     if (rc < 0) {
633a34b1e5eSVladimir Sementsov-Ogievskiy         nbd_channel_error(s, rc);
634a34b1e5eSVladimir Sementsov-Ogievskiy         if (i != -1) {
63586f8cdf3SVladimir Sementsov-Ogievskiy             s->requests[i].coroutine = NULL;
63686f8cdf3SVladimir Sementsov-Ogievskiy             s->in_flight--;
637a34b1e5eSVladimir Sementsov-Ogievskiy         }
638f7651539SVladimir Sementsov-Ogievskiy         if (s->in_flight == 0 && s->wait_in_flight) {
639f7651539SVladimir Sementsov-Ogievskiy             aio_co_wake(s->connection_co);
640f7651539SVladimir Sementsov-Ogievskiy         } else {
64186f8cdf3SVladimir Sementsov-Ogievskiy             qemu_co_queue_next(&s->free_sema);
64286f8cdf3SVladimir Sementsov-Ogievskiy         }
643f7651539SVladimir Sementsov-Ogievskiy     }
64486f8cdf3SVladimir Sementsov-Ogievskiy     qemu_co_mutex_unlock(&s->send_mutex);
64586f8cdf3SVladimir Sementsov-Ogievskiy     return rc;
64686f8cdf3SVladimir Sementsov-Ogievskiy }
64786f8cdf3SVladimir Sementsov-Ogievskiy 
64886f8cdf3SVladimir Sementsov-Ogievskiy static inline uint16_t payload_advance16(uint8_t **payload)
64986f8cdf3SVladimir Sementsov-Ogievskiy {
65086f8cdf3SVladimir Sementsov-Ogievskiy     *payload += 2;
65186f8cdf3SVladimir Sementsov-Ogievskiy     return lduw_be_p(*payload - 2);
65286f8cdf3SVladimir Sementsov-Ogievskiy }
65386f8cdf3SVladimir Sementsov-Ogievskiy 
65486f8cdf3SVladimir Sementsov-Ogievskiy static inline uint32_t payload_advance32(uint8_t **payload)
65586f8cdf3SVladimir Sementsov-Ogievskiy {
65686f8cdf3SVladimir Sementsov-Ogievskiy     *payload += 4;
65786f8cdf3SVladimir Sementsov-Ogievskiy     return ldl_be_p(*payload - 4);
65886f8cdf3SVladimir Sementsov-Ogievskiy }
65986f8cdf3SVladimir Sementsov-Ogievskiy 
66086f8cdf3SVladimir Sementsov-Ogievskiy static inline uint64_t payload_advance64(uint8_t **payload)
66186f8cdf3SVladimir Sementsov-Ogievskiy {
66286f8cdf3SVladimir Sementsov-Ogievskiy     *payload += 8;
66386f8cdf3SVladimir Sementsov-Ogievskiy     return ldq_be_p(*payload - 8);
66486f8cdf3SVladimir Sementsov-Ogievskiy }
66586f8cdf3SVladimir Sementsov-Ogievskiy 
666611ae1d7SVladimir Sementsov-Ogievskiy static int nbd_parse_offset_hole_payload(BDRVNBDState *s,
66786f8cdf3SVladimir Sementsov-Ogievskiy                                          NBDStructuredReplyChunk *chunk,
66886f8cdf3SVladimir Sementsov-Ogievskiy                                          uint8_t *payload, uint64_t orig_offset,
66986f8cdf3SVladimir Sementsov-Ogievskiy                                          QEMUIOVector *qiov, Error **errp)
67086f8cdf3SVladimir Sementsov-Ogievskiy {
67186f8cdf3SVladimir Sementsov-Ogievskiy     uint64_t offset;
67286f8cdf3SVladimir Sementsov-Ogievskiy     uint32_t hole_size;
67386f8cdf3SVladimir Sementsov-Ogievskiy 
67486f8cdf3SVladimir Sementsov-Ogievskiy     if (chunk->length != sizeof(offset) + sizeof(hole_size)) {
67586f8cdf3SVladimir Sementsov-Ogievskiy         error_setg(errp, "Protocol error: invalid payload for "
67686f8cdf3SVladimir Sementsov-Ogievskiy                          "NBD_REPLY_TYPE_OFFSET_HOLE");
67786f8cdf3SVladimir Sementsov-Ogievskiy         return -EINVAL;
67886f8cdf3SVladimir Sementsov-Ogievskiy     }
67986f8cdf3SVladimir Sementsov-Ogievskiy 
68086f8cdf3SVladimir Sementsov-Ogievskiy     offset = payload_advance64(&payload);
68186f8cdf3SVladimir Sementsov-Ogievskiy     hole_size = payload_advance32(&payload);
68286f8cdf3SVladimir Sementsov-Ogievskiy 
68386f8cdf3SVladimir Sementsov-Ogievskiy     if (!hole_size || offset < orig_offset || hole_size > qiov->size ||
68486f8cdf3SVladimir Sementsov-Ogievskiy         offset > orig_offset + qiov->size - hole_size) {
68586f8cdf3SVladimir Sementsov-Ogievskiy         error_setg(errp, "Protocol error: server sent chunk exceeding requested"
68686f8cdf3SVladimir Sementsov-Ogievskiy                          " region");
68786f8cdf3SVladimir Sementsov-Ogievskiy         return -EINVAL;
68886f8cdf3SVladimir Sementsov-Ogievskiy     }
689611ae1d7SVladimir Sementsov-Ogievskiy     if (s->info.min_block &&
690611ae1d7SVladimir Sementsov-Ogievskiy         !QEMU_IS_ALIGNED(hole_size, s->info.min_block)) {
69186f8cdf3SVladimir Sementsov-Ogievskiy         trace_nbd_structured_read_compliance("hole");
69286f8cdf3SVladimir Sementsov-Ogievskiy     }
69386f8cdf3SVladimir Sementsov-Ogievskiy 
69486f8cdf3SVladimir Sementsov-Ogievskiy     qemu_iovec_memset(qiov, offset - orig_offset, 0, hole_size);
69586f8cdf3SVladimir Sementsov-Ogievskiy 
69686f8cdf3SVladimir Sementsov-Ogievskiy     return 0;
69786f8cdf3SVladimir Sementsov-Ogievskiy }
69886f8cdf3SVladimir Sementsov-Ogievskiy 
69986f8cdf3SVladimir Sementsov-Ogievskiy /*
70086f8cdf3SVladimir Sementsov-Ogievskiy  * nbd_parse_blockstatus_payload
70186f8cdf3SVladimir Sementsov-Ogievskiy  * Based on our request, we expect only one extent in reply, for the
70286f8cdf3SVladimir Sementsov-Ogievskiy  * base:allocation context.
70386f8cdf3SVladimir Sementsov-Ogievskiy  */
704611ae1d7SVladimir Sementsov-Ogievskiy static int nbd_parse_blockstatus_payload(BDRVNBDState *s,
70586f8cdf3SVladimir Sementsov-Ogievskiy                                          NBDStructuredReplyChunk *chunk,
70686f8cdf3SVladimir Sementsov-Ogievskiy                                          uint8_t *payload, uint64_t orig_length,
70786f8cdf3SVladimir Sementsov-Ogievskiy                                          NBDExtent *extent, Error **errp)
70886f8cdf3SVladimir Sementsov-Ogievskiy {
70986f8cdf3SVladimir Sementsov-Ogievskiy     uint32_t context_id;
71086f8cdf3SVladimir Sementsov-Ogievskiy 
71186f8cdf3SVladimir Sementsov-Ogievskiy     /* The server succeeded, so it must have sent [at least] one extent */
71286f8cdf3SVladimir Sementsov-Ogievskiy     if (chunk->length < sizeof(context_id) + sizeof(*extent)) {
71386f8cdf3SVladimir Sementsov-Ogievskiy         error_setg(errp, "Protocol error: invalid payload for "
71486f8cdf3SVladimir Sementsov-Ogievskiy                          "NBD_REPLY_TYPE_BLOCK_STATUS");
71586f8cdf3SVladimir Sementsov-Ogievskiy         return -EINVAL;
71686f8cdf3SVladimir Sementsov-Ogievskiy     }
71786f8cdf3SVladimir Sementsov-Ogievskiy 
71886f8cdf3SVladimir Sementsov-Ogievskiy     context_id = payload_advance32(&payload);
719611ae1d7SVladimir Sementsov-Ogievskiy     if (s->info.context_id != context_id) {
72086f8cdf3SVladimir Sementsov-Ogievskiy         error_setg(errp, "Protocol error: unexpected context id %d for "
72186f8cdf3SVladimir Sementsov-Ogievskiy                          "NBD_REPLY_TYPE_BLOCK_STATUS, when negotiated context "
72286f8cdf3SVladimir Sementsov-Ogievskiy                          "id is %d", context_id,
723611ae1d7SVladimir Sementsov-Ogievskiy                          s->info.context_id);
72486f8cdf3SVladimir Sementsov-Ogievskiy         return -EINVAL;
72586f8cdf3SVladimir Sementsov-Ogievskiy     }
72686f8cdf3SVladimir Sementsov-Ogievskiy 
72786f8cdf3SVladimir Sementsov-Ogievskiy     extent->length = payload_advance32(&payload);
72886f8cdf3SVladimir Sementsov-Ogievskiy     extent->flags = payload_advance32(&payload);
72986f8cdf3SVladimir Sementsov-Ogievskiy 
73086f8cdf3SVladimir Sementsov-Ogievskiy     if (extent->length == 0) {
73186f8cdf3SVladimir Sementsov-Ogievskiy         error_setg(errp, "Protocol error: server sent status chunk with "
73286f8cdf3SVladimir Sementsov-Ogievskiy                    "zero length");
73386f8cdf3SVladimir Sementsov-Ogievskiy         return -EINVAL;
73486f8cdf3SVladimir Sementsov-Ogievskiy     }
73586f8cdf3SVladimir Sementsov-Ogievskiy 
73686f8cdf3SVladimir Sementsov-Ogievskiy     /*
73786f8cdf3SVladimir Sementsov-Ogievskiy      * A server sending unaligned block status is in violation of the
73886f8cdf3SVladimir Sementsov-Ogievskiy      * protocol, but as qemu-nbd 3.1 is such a server (at least for
73986f8cdf3SVladimir Sementsov-Ogievskiy      * POSIX files that are not a multiple of 512 bytes, since qemu
74086f8cdf3SVladimir Sementsov-Ogievskiy      * rounds files up to 512-byte multiples but lseek(SEEK_HOLE)
74186f8cdf3SVladimir Sementsov-Ogievskiy      * still sees an implicit hole beyond the real EOF), it's nicer to
74286f8cdf3SVladimir Sementsov-Ogievskiy      * work around the misbehaving server. If the request included
74386f8cdf3SVladimir Sementsov-Ogievskiy      * more than the final unaligned block, truncate it back to an
74486f8cdf3SVladimir Sementsov-Ogievskiy      * aligned result; if the request was only the final block, round
74586f8cdf3SVladimir Sementsov-Ogievskiy      * up to the full block and change the status to fully-allocated
74686f8cdf3SVladimir Sementsov-Ogievskiy      * (always a safe status, even if it loses information).
74786f8cdf3SVladimir Sementsov-Ogievskiy      */
748611ae1d7SVladimir Sementsov-Ogievskiy     if (s->info.min_block && !QEMU_IS_ALIGNED(extent->length,
749611ae1d7SVladimir Sementsov-Ogievskiy                                                    s->info.min_block)) {
75086f8cdf3SVladimir Sementsov-Ogievskiy         trace_nbd_parse_blockstatus_compliance("extent length is unaligned");
751611ae1d7SVladimir Sementsov-Ogievskiy         if (extent->length > s->info.min_block) {
75286f8cdf3SVladimir Sementsov-Ogievskiy             extent->length = QEMU_ALIGN_DOWN(extent->length,
753611ae1d7SVladimir Sementsov-Ogievskiy                                              s->info.min_block);
75486f8cdf3SVladimir Sementsov-Ogievskiy         } else {
755611ae1d7SVladimir Sementsov-Ogievskiy             extent->length = s->info.min_block;
75686f8cdf3SVladimir Sementsov-Ogievskiy             extent->flags = 0;
75786f8cdf3SVladimir Sementsov-Ogievskiy         }
75886f8cdf3SVladimir Sementsov-Ogievskiy     }
75986f8cdf3SVladimir Sementsov-Ogievskiy 
76086f8cdf3SVladimir Sementsov-Ogievskiy     /*
76186f8cdf3SVladimir Sementsov-Ogievskiy      * We used NBD_CMD_FLAG_REQ_ONE, so the server should not have
76286f8cdf3SVladimir Sementsov-Ogievskiy      * sent us any more than one extent, nor should it have included
76386f8cdf3SVladimir Sementsov-Ogievskiy      * status beyond our request in that extent. However, it's easy
76486f8cdf3SVladimir Sementsov-Ogievskiy      * enough to ignore the server's noncompliance without killing the
76586f8cdf3SVladimir Sementsov-Ogievskiy      * connection; just ignore trailing extents, and clamp things to
76686f8cdf3SVladimir Sementsov-Ogievskiy      * the length of our request.
76786f8cdf3SVladimir Sementsov-Ogievskiy      */
76886f8cdf3SVladimir Sementsov-Ogievskiy     if (chunk->length > sizeof(context_id) + sizeof(*extent)) {
76986f8cdf3SVladimir Sementsov-Ogievskiy         trace_nbd_parse_blockstatus_compliance("more than one extent");
77086f8cdf3SVladimir Sementsov-Ogievskiy     }
77186f8cdf3SVladimir Sementsov-Ogievskiy     if (extent->length > orig_length) {
77286f8cdf3SVladimir Sementsov-Ogievskiy         extent->length = orig_length;
77386f8cdf3SVladimir Sementsov-Ogievskiy         trace_nbd_parse_blockstatus_compliance("extent length too large");
77486f8cdf3SVladimir Sementsov-Ogievskiy     }
77586f8cdf3SVladimir Sementsov-Ogievskiy 
776dbc7b014SEric Blake     /*
777dbc7b014SEric Blake      * HACK: if we are using x-dirty-bitmaps to access
778dbc7b014SEric Blake      * qemu:allocation-depth, treat all depths > 2 the same as 2,
779dbc7b014SEric Blake      * since nbd_client_co_block_status is only expecting the low two
780dbc7b014SEric Blake      * bits to be set.
781dbc7b014SEric Blake      */
782dbc7b014SEric Blake     if (s->alloc_depth && extent->flags > 2) {
783dbc7b014SEric Blake         extent->flags = 2;
784dbc7b014SEric Blake     }
785dbc7b014SEric Blake 
78686f8cdf3SVladimir Sementsov-Ogievskiy     return 0;
78786f8cdf3SVladimir Sementsov-Ogievskiy }
78886f8cdf3SVladimir Sementsov-Ogievskiy 
78986f8cdf3SVladimir Sementsov-Ogievskiy /*
79086f8cdf3SVladimir Sementsov-Ogievskiy  * nbd_parse_error_payload
79186f8cdf3SVladimir Sementsov-Ogievskiy  * on success @errp contains message describing nbd error reply
79286f8cdf3SVladimir Sementsov-Ogievskiy  */
79386f8cdf3SVladimir Sementsov-Ogievskiy static int nbd_parse_error_payload(NBDStructuredReplyChunk *chunk,
79486f8cdf3SVladimir Sementsov-Ogievskiy                                    uint8_t *payload, int *request_ret,
79586f8cdf3SVladimir Sementsov-Ogievskiy                                    Error **errp)
79686f8cdf3SVladimir Sementsov-Ogievskiy {
79786f8cdf3SVladimir Sementsov-Ogievskiy     uint32_t error;
79886f8cdf3SVladimir Sementsov-Ogievskiy     uint16_t message_size;
79986f8cdf3SVladimir Sementsov-Ogievskiy 
80086f8cdf3SVladimir Sementsov-Ogievskiy     assert(chunk->type & (1 << 15));
80186f8cdf3SVladimir Sementsov-Ogievskiy 
80286f8cdf3SVladimir Sementsov-Ogievskiy     if (chunk->length < sizeof(error) + sizeof(message_size)) {
80386f8cdf3SVladimir Sementsov-Ogievskiy         error_setg(errp,
80486f8cdf3SVladimir Sementsov-Ogievskiy                    "Protocol error: invalid payload for structured error");
80586f8cdf3SVladimir Sementsov-Ogievskiy         return -EINVAL;
80686f8cdf3SVladimir Sementsov-Ogievskiy     }
80786f8cdf3SVladimir Sementsov-Ogievskiy 
80886f8cdf3SVladimir Sementsov-Ogievskiy     error = nbd_errno_to_system_errno(payload_advance32(&payload));
80986f8cdf3SVladimir Sementsov-Ogievskiy     if (error == 0) {
81086f8cdf3SVladimir Sementsov-Ogievskiy         error_setg(errp, "Protocol error: server sent structured error chunk "
81186f8cdf3SVladimir Sementsov-Ogievskiy                          "with error = 0");
81286f8cdf3SVladimir Sementsov-Ogievskiy         return -EINVAL;
81386f8cdf3SVladimir Sementsov-Ogievskiy     }
81486f8cdf3SVladimir Sementsov-Ogievskiy 
81586f8cdf3SVladimir Sementsov-Ogievskiy     *request_ret = -error;
81686f8cdf3SVladimir Sementsov-Ogievskiy     message_size = payload_advance16(&payload);
81786f8cdf3SVladimir Sementsov-Ogievskiy 
81886f8cdf3SVladimir Sementsov-Ogievskiy     if (message_size > chunk->length - sizeof(error) - sizeof(message_size)) {
81986f8cdf3SVladimir Sementsov-Ogievskiy         error_setg(errp, "Protocol error: server sent structured error chunk "
82086f8cdf3SVladimir Sementsov-Ogievskiy                          "with incorrect message size");
82186f8cdf3SVladimir Sementsov-Ogievskiy         return -EINVAL;
82286f8cdf3SVladimir Sementsov-Ogievskiy     }
82386f8cdf3SVladimir Sementsov-Ogievskiy 
82486f8cdf3SVladimir Sementsov-Ogievskiy     /* TODO: Add a trace point to mention the server complaint */
82586f8cdf3SVladimir Sementsov-Ogievskiy 
82686f8cdf3SVladimir Sementsov-Ogievskiy     /* TODO handle ERROR_OFFSET */
82786f8cdf3SVladimir Sementsov-Ogievskiy 
82886f8cdf3SVladimir Sementsov-Ogievskiy     return 0;
82986f8cdf3SVladimir Sementsov-Ogievskiy }
83086f8cdf3SVladimir Sementsov-Ogievskiy 
831611ae1d7SVladimir Sementsov-Ogievskiy static int nbd_co_receive_offset_data_payload(BDRVNBDState *s,
83286f8cdf3SVladimir Sementsov-Ogievskiy                                               uint64_t orig_offset,
83386f8cdf3SVladimir Sementsov-Ogievskiy                                               QEMUIOVector *qiov, Error **errp)
83486f8cdf3SVladimir Sementsov-Ogievskiy {
83586f8cdf3SVladimir Sementsov-Ogievskiy     QEMUIOVector sub_qiov;
83686f8cdf3SVladimir Sementsov-Ogievskiy     uint64_t offset;
83786f8cdf3SVladimir Sementsov-Ogievskiy     size_t data_size;
83886f8cdf3SVladimir Sementsov-Ogievskiy     int ret;
83986f8cdf3SVladimir Sementsov-Ogievskiy     NBDStructuredReplyChunk *chunk = &s->reply.structured;
84086f8cdf3SVladimir Sementsov-Ogievskiy 
84186f8cdf3SVladimir Sementsov-Ogievskiy     assert(nbd_reply_is_structured(&s->reply));
84286f8cdf3SVladimir Sementsov-Ogievskiy 
84386f8cdf3SVladimir Sementsov-Ogievskiy     /* The NBD spec requires at least one byte of payload */
84486f8cdf3SVladimir Sementsov-Ogievskiy     if (chunk->length <= sizeof(offset)) {
84586f8cdf3SVladimir Sementsov-Ogievskiy         error_setg(errp, "Protocol error: invalid payload for "
84686f8cdf3SVladimir Sementsov-Ogievskiy                          "NBD_REPLY_TYPE_OFFSET_DATA");
84786f8cdf3SVladimir Sementsov-Ogievskiy         return -EINVAL;
84886f8cdf3SVladimir Sementsov-Ogievskiy     }
84986f8cdf3SVladimir Sementsov-Ogievskiy 
85086f8cdf3SVladimir Sementsov-Ogievskiy     if (nbd_read64(s->ioc, &offset, "OFFSET_DATA offset", errp) < 0) {
85186f8cdf3SVladimir Sementsov-Ogievskiy         return -EIO;
85286f8cdf3SVladimir Sementsov-Ogievskiy     }
85386f8cdf3SVladimir Sementsov-Ogievskiy 
85486f8cdf3SVladimir Sementsov-Ogievskiy     data_size = chunk->length - sizeof(offset);
85586f8cdf3SVladimir Sementsov-Ogievskiy     assert(data_size);
85686f8cdf3SVladimir Sementsov-Ogievskiy     if (offset < orig_offset || data_size > qiov->size ||
85786f8cdf3SVladimir Sementsov-Ogievskiy         offset > orig_offset + qiov->size - data_size) {
85886f8cdf3SVladimir Sementsov-Ogievskiy         error_setg(errp, "Protocol error: server sent chunk exceeding requested"
85986f8cdf3SVladimir Sementsov-Ogievskiy                          " region");
86086f8cdf3SVladimir Sementsov-Ogievskiy         return -EINVAL;
86186f8cdf3SVladimir Sementsov-Ogievskiy     }
86286f8cdf3SVladimir Sementsov-Ogievskiy     if (s->info.min_block && !QEMU_IS_ALIGNED(data_size, s->info.min_block)) {
86386f8cdf3SVladimir Sementsov-Ogievskiy         trace_nbd_structured_read_compliance("data");
86486f8cdf3SVladimir Sementsov-Ogievskiy     }
86586f8cdf3SVladimir Sementsov-Ogievskiy 
86686f8cdf3SVladimir Sementsov-Ogievskiy     qemu_iovec_init(&sub_qiov, qiov->niov);
86786f8cdf3SVladimir Sementsov-Ogievskiy     qemu_iovec_concat(&sub_qiov, qiov, offset - orig_offset, data_size);
86886f8cdf3SVladimir Sementsov-Ogievskiy     ret = qio_channel_readv_all(s->ioc, sub_qiov.iov, sub_qiov.niov, errp);
86986f8cdf3SVladimir Sementsov-Ogievskiy     qemu_iovec_destroy(&sub_qiov);
87086f8cdf3SVladimir Sementsov-Ogievskiy 
87186f8cdf3SVladimir Sementsov-Ogievskiy     return ret < 0 ? -EIO : 0;
87286f8cdf3SVladimir Sementsov-Ogievskiy }
87386f8cdf3SVladimir Sementsov-Ogievskiy 
87486f8cdf3SVladimir Sementsov-Ogievskiy #define NBD_MAX_MALLOC_PAYLOAD 1000
87586f8cdf3SVladimir Sementsov-Ogievskiy static coroutine_fn int nbd_co_receive_structured_payload(
876611ae1d7SVladimir Sementsov-Ogievskiy         BDRVNBDState *s, void **payload, Error **errp)
87786f8cdf3SVladimir Sementsov-Ogievskiy {
87886f8cdf3SVladimir Sementsov-Ogievskiy     int ret;
87986f8cdf3SVladimir Sementsov-Ogievskiy     uint32_t len;
88086f8cdf3SVladimir Sementsov-Ogievskiy 
88186f8cdf3SVladimir Sementsov-Ogievskiy     assert(nbd_reply_is_structured(&s->reply));
88286f8cdf3SVladimir Sementsov-Ogievskiy 
88386f8cdf3SVladimir Sementsov-Ogievskiy     len = s->reply.structured.length;
88486f8cdf3SVladimir Sementsov-Ogievskiy 
88586f8cdf3SVladimir Sementsov-Ogievskiy     if (len == 0) {
88686f8cdf3SVladimir Sementsov-Ogievskiy         return 0;
88786f8cdf3SVladimir Sementsov-Ogievskiy     }
88886f8cdf3SVladimir Sementsov-Ogievskiy 
88986f8cdf3SVladimir Sementsov-Ogievskiy     if (payload == NULL) {
89086f8cdf3SVladimir Sementsov-Ogievskiy         error_setg(errp, "Unexpected structured payload");
89186f8cdf3SVladimir Sementsov-Ogievskiy         return -EINVAL;
89286f8cdf3SVladimir Sementsov-Ogievskiy     }
89386f8cdf3SVladimir Sementsov-Ogievskiy 
89486f8cdf3SVladimir Sementsov-Ogievskiy     if (len > NBD_MAX_MALLOC_PAYLOAD) {
89586f8cdf3SVladimir Sementsov-Ogievskiy         error_setg(errp, "Payload too large");
89686f8cdf3SVladimir Sementsov-Ogievskiy         return -EINVAL;
89786f8cdf3SVladimir Sementsov-Ogievskiy     }
89886f8cdf3SVladimir Sementsov-Ogievskiy 
89986f8cdf3SVladimir Sementsov-Ogievskiy     *payload = g_new(char, len);
90086f8cdf3SVladimir Sementsov-Ogievskiy     ret = nbd_read(s->ioc, *payload, len, "structured payload", errp);
90186f8cdf3SVladimir Sementsov-Ogievskiy     if (ret < 0) {
90286f8cdf3SVladimir Sementsov-Ogievskiy         g_free(*payload);
90386f8cdf3SVladimir Sementsov-Ogievskiy         *payload = NULL;
90486f8cdf3SVladimir Sementsov-Ogievskiy         return ret;
90586f8cdf3SVladimir Sementsov-Ogievskiy     }
90686f8cdf3SVladimir Sementsov-Ogievskiy 
90786f8cdf3SVladimir Sementsov-Ogievskiy     return 0;
90886f8cdf3SVladimir Sementsov-Ogievskiy }
90986f8cdf3SVladimir Sementsov-Ogievskiy 
91086f8cdf3SVladimir Sementsov-Ogievskiy /*
91186f8cdf3SVladimir Sementsov-Ogievskiy  * nbd_co_do_receive_one_chunk
91286f8cdf3SVladimir Sementsov-Ogievskiy  * for simple reply:
91386f8cdf3SVladimir Sementsov-Ogievskiy  *   set request_ret to received reply error
91486f8cdf3SVladimir Sementsov-Ogievskiy  *   if qiov is not NULL: read payload to @qiov
91586f8cdf3SVladimir Sementsov-Ogievskiy  * for structured reply chunk:
91686f8cdf3SVladimir Sementsov-Ogievskiy  *   if error chunk: read payload, set @request_ret, do not set @payload
91786f8cdf3SVladimir Sementsov-Ogievskiy  *   else if offset_data chunk: read payload data to @qiov, do not set @payload
91886f8cdf3SVladimir Sementsov-Ogievskiy  *   else: read payload to @payload
91986f8cdf3SVladimir Sementsov-Ogievskiy  *
92086f8cdf3SVladimir Sementsov-Ogievskiy  * If function fails, @errp contains corresponding error message, and the
92186f8cdf3SVladimir Sementsov-Ogievskiy  * connection with the server is suspect.  If it returns 0, then the
92286f8cdf3SVladimir Sementsov-Ogievskiy  * transaction succeeded (although @request_ret may be a negative errno
92386f8cdf3SVladimir Sementsov-Ogievskiy  * corresponding to the server's error reply), and errp is unchanged.
92486f8cdf3SVladimir Sementsov-Ogievskiy  */
92586f8cdf3SVladimir Sementsov-Ogievskiy static coroutine_fn int nbd_co_do_receive_one_chunk(
926611ae1d7SVladimir Sementsov-Ogievskiy         BDRVNBDState *s, uint64_t handle, bool only_structured,
92786f8cdf3SVladimir Sementsov-Ogievskiy         int *request_ret, QEMUIOVector *qiov, void **payload, Error **errp)
92886f8cdf3SVladimir Sementsov-Ogievskiy {
92986f8cdf3SVladimir Sementsov-Ogievskiy     int ret;
93086f8cdf3SVladimir Sementsov-Ogievskiy     int i = HANDLE_TO_INDEX(s, handle);
93186f8cdf3SVladimir Sementsov-Ogievskiy     void *local_payload = NULL;
93286f8cdf3SVladimir Sementsov-Ogievskiy     NBDStructuredReplyChunk *chunk;
93386f8cdf3SVladimir Sementsov-Ogievskiy 
93486f8cdf3SVladimir Sementsov-Ogievskiy     if (payload) {
93586f8cdf3SVladimir Sementsov-Ogievskiy         *payload = NULL;
93686f8cdf3SVladimir Sementsov-Ogievskiy     }
93786f8cdf3SVladimir Sementsov-Ogievskiy     *request_ret = 0;
93886f8cdf3SVladimir Sementsov-Ogievskiy 
93986f8cdf3SVladimir Sementsov-Ogievskiy     /* Wait until we're woken up by nbd_connection_entry.  */
94086f8cdf3SVladimir Sementsov-Ogievskiy     s->requests[i].receiving = true;
94186f8cdf3SVladimir Sementsov-Ogievskiy     qemu_coroutine_yield();
942bbfb7c2fSVladimir Sementsov-Ogievskiy     assert(!s->requests[i].receiving);
94391e0998fSVladimir Sementsov-Ogievskiy     if (!nbd_client_connected(s)) {
94486f8cdf3SVladimir Sementsov-Ogievskiy         error_setg(errp, "Connection closed");
94586f8cdf3SVladimir Sementsov-Ogievskiy         return -EIO;
94686f8cdf3SVladimir Sementsov-Ogievskiy     }
94786f8cdf3SVladimir Sementsov-Ogievskiy     assert(s->ioc);
94886f8cdf3SVladimir Sementsov-Ogievskiy 
94986f8cdf3SVladimir Sementsov-Ogievskiy     assert(s->reply.handle == handle);
95086f8cdf3SVladimir Sementsov-Ogievskiy 
95186f8cdf3SVladimir Sementsov-Ogievskiy     if (nbd_reply_is_simple(&s->reply)) {
95286f8cdf3SVladimir Sementsov-Ogievskiy         if (only_structured) {
95386f8cdf3SVladimir Sementsov-Ogievskiy             error_setg(errp, "Protocol error: simple reply when structured "
95486f8cdf3SVladimir Sementsov-Ogievskiy                              "reply chunk was expected");
95586f8cdf3SVladimir Sementsov-Ogievskiy             return -EINVAL;
95686f8cdf3SVladimir Sementsov-Ogievskiy         }
95786f8cdf3SVladimir Sementsov-Ogievskiy 
95886f8cdf3SVladimir Sementsov-Ogievskiy         *request_ret = -nbd_errno_to_system_errno(s->reply.simple.error);
95986f8cdf3SVladimir Sementsov-Ogievskiy         if (*request_ret < 0 || !qiov) {
96086f8cdf3SVladimir Sementsov-Ogievskiy             return 0;
96186f8cdf3SVladimir Sementsov-Ogievskiy         }
96286f8cdf3SVladimir Sementsov-Ogievskiy 
96386f8cdf3SVladimir Sementsov-Ogievskiy         return qio_channel_readv_all(s->ioc, qiov->iov, qiov->niov,
96486f8cdf3SVladimir Sementsov-Ogievskiy                                      errp) < 0 ? -EIO : 0;
96586f8cdf3SVladimir Sementsov-Ogievskiy     }
96686f8cdf3SVladimir Sementsov-Ogievskiy 
96786f8cdf3SVladimir Sementsov-Ogievskiy     /* handle structured reply chunk */
96886f8cdf3SVladimir Sementsov-Ogievskiy     assert(s->info.structured_reply);
96986f8cdf3SVladimir Sementsov-Ogievskiy     chunk = &s->reply.structured;
97086f8cdf3SVladimir Sementsov-Ogievskiy 
97186f8cdf3SVladimir Sementsov-Ogievskiy     if (chunk->type == NBD_REPLY_TYPE_NONE) {
97286f8cdf3SVladimir Sementsov-Ogievskiy         if (!(chunk->flags & NBD_REPLY_FLAG_DONE)) {
97386f8cdf3SVladimir Sementsov-Ogievskiy             error_setg(errp, "Protocol error: NBD_REPLY_TYPE_NONE chunk without"
97486f8cdf3SVladimir Sementsov-Ogievskiy                        " NBD_REPLY_FLAG_DONE flag set");
97586f8cdf3SVladimir Sementsov-Ogievskiy             return -EINVAL;
97686f8cdf3SVladimir Sementsov-Ogievskiy         }
97786f8cdf3SVladimir Sementsov-Ogievskiy         if (chunk->length) {
97886f8cdf3SVladimir Sementsov-Ogievskiy             error_setg(errp, "Protocol error: NBD_REPLY_TYPE_NONE chunk with"
97986f8cdf3SVladimir Sementsov-Ogievskiy                        " nonzero length");
98086f8cdf3SVladimir Sementsov-Ogievskiy             return -EINVAL;
98186f8cdf3SVladimir Sementsov-Ogievskiy         }
98286f8cdf3SVladimir Sementsov-Ogievskiy         return 0;
98386f8cdf3SVladimir Sementsov-Ogievskiy     }
98486f8cdf3SVladimir Sementsov-Ogievskiy 
98586f8cdf3SVladimir Sementsov-Ogievskiy     if (chunk->type == NBD_REPLY_TYPE_OFFSET_DATA) {
98686f8cdf3SVladimir Sementsov-Ogievskiy         if (!qiov) {
98786f8cdf3SVladimir Sementsov-Ogievskiy             error_setg(errp, "Unexpected NBD_REPLY_TYPE_OFFSET_DATA chunk");
98886f8cdf3SVladimir Sementsov-Ogievskiy             return -EINVAL;
98986f8cdf3SVladimir Sementsov-Ogievskiy         }
99086f8cdf3SVladimir Sementsov-Ogievskiy 
99186f8cdf3SVladimir Sementsov-Ogievskiy         return nbd_co_receive_offset_data_payload(s, s->requests[i].offset,
99286f8cdf3SVladimir Sementsov-Ogievskiy                                                   qiov, errp);
99386f8cdf3SVladimir Sementsov-Ogievskiy     }
99486f8cdf3SVladimir Sementsov-Ogievskiy 
99586f8cdf3SVladimir Sementsov-Ogievskiy     if (nbd_reply_type_is_error(chunk->type)) {
99686f8cdf3SVladimir Sementsov-Ogievskiy         payload = &local_payload;
99786f8cdf3SVladimir Sementsov-Ogievskiy     }
99886f8cdf3SVladimir Sementsov-Ogievskiy 
99986f8cdf3SVladimir Sementsov-Ogievskiy     ret = nbd_co_receive_structured_payload(s, payload, errp);
100086f8cdf3SVladimir Sementsov-Ogievskiy     if (ret < 0) {
100186f8cdf3SVladimir Sementsov-Ogievskiy         return ret;
100286f8cdf3SVladimir Sementsov-Ogievskiy     }
100386f8cdf3SVladimir Sementsov-Ogievskiy 
100486f8cdf3SVladimir Sementsov-Ogievskiy     if (nbd_reply_type_is_error(chunk->type)) {
100586f8cdf3SVladimir Sementsov-Ogievskiy         ret = nbd_parse_error_payload(chunk, local_payload, request_ret, errp);
100686f8cdf3SVladimir Sementsov-Ogievskiy         g_free(local_payload);
100786f8cdf3SVladimir Sementsov-Ogievskiy         return ret;
100886f8cdf3SVladimir Sementsov-Ogievskiy     }
100986f8cdf3SVladimir Sementsov-Ogievskiy 
101086f8cdf3SVladimir Sementsov-Ogievskiy     return 0;
101186f8cdf3SVladimir Sementsov-Ogievskiy }
101286f8cdf3SVladimir Sementsov-Ogievskiy 
101386f8cdf3SVladimir Sementsov-Ogievskiy /*
101486f8cdf3SVladimir Sementsov-Ogievskiy  * nbd_co_receive_one_chunk
101586f8cdf3SVladimir Sementsov-Ogievskiy  * Read reply, wake up connection_co and set s->quit if needed.
101686f8cdf3SVladimir Sementsov-Ogievskiy  * Return value is a fatal error code or normal nbd reply error code
101786f8cdf3SVladimir Sementsov-Ogievskiy  */
101886f8cdf3SVladimir Sementsov-Ogievskiy static coroutine_fn int nbd_co_receive_one_chunk(
1019611ae1d7SVladimir Sementsov-Ogievskiy         BDRVNBDState *s, uint64_t handle, bool only_structured,
102086f8cdf3SVladimir Sementsov-Ogievskiy         int *request_ret, QEMUIOVector *qiov, NBDReply *reply, void **payload,
102186f8cdf3SVladimir Sementsov-Ogievskiy         Error **errp)
102286f8cdf3SVladimir Sementsov-Ogievskiy {
102386f8cdf3SVladimir Sementsov-Ogievskiy     int ret = nbd_co_do_receive_one_chunk(s, handle, only_structured,
102486f8cdf3SVladimir Sementsov-Ogievskiy                                           request_ret, qiov, payload, errp);
102586f8cdf3SVladimir Sementsov-Ogievskiy 
102686f8cdf3SVladimir Sementsov-Ogievskiy     if (ret < 0) {
10275cf42b1cSEric Blake         memset(reply, 0, sizeof(*reply));
1028a34b1e5eSVladimir Sementsov-Ogievskiy         nbd_channel_error(s, ret);
102986f8cdf3SVladimir Sementsov-Ogievskiy     } else {
103086f8cdf3SVladimir Sementsov-Ogievskiy         /* For assert at loop start in nbd_connection_entry */
103186f8cdf3SVladimir Sementsov-Ogievskiy         *reply = s->reply;
103286f8cdf3SVladimir Sementsov-Ogievskiy     }
1033f7651539SVladimir Sementsov-Ogievskiy     s->reply.handle = 0;
103486f8cdf3SVladimir Sementsov-Ogievskiy 
1035f7651539SVladimir Sementsov-Ogievskiy     if (s->connection_co && !s->wait_in_flight) {
1036f7651539SVladimir Sementsov-Ogievskiy         /*
1037f7651539SVladimir Sementsov-Ogievskiy          * We must check s->wait_in_flight, because we may entered by
1038f7651539SVladimir Sementsov-Ogievskiy          * nbd_recv_coroutines_wake_all(), in this case we should not
1039f7651539SVladimir Sementsov-Ogievskiy          * wake connection_co here, it will woken by last request.
1040f7651539SVladimir Sementsov-Ogievskiy          */
104186f8cdf3SVladimir Sementsov-Ogievskiy         aio_co_wake(s->connection_co);
104286f8cdf3SVladimir Sementsov-Ogievskiy     }
104386f8cdf3SVladimir Sementsov-Ogievskiy 
104486f8cdf3SVladimir Sementsov-Ogievskiy     return ret;
104586f8cdf3SVladimir Sementsov-Ogievskiy }
104686f8cdf3SVladimir Sementsov-Ogievskiy 
104786f8cdf3SVladimir Sementsov-Ogievskiy typedef struct NBDReplyChunkIter {
104886f8cdf3SVladimir Sementsov-Ogievskiy     int ret;
104986f8cdf3SVladimir Sementsov-Ogievskiy     int request_ret;
105086f8cdf3SVladimir Sementsov-Ogievskiy     Error *err;
105186f8cdf3SVladimir Sementsov-Ogievskiy     bool done, only_structured;
105286f8cdf3SVladimir Sementsov-Ogievskiy } NBDReplyChunkIter;
105386f8cdf3SVladimir Sementsov-Ogievskiy 
105486f8cdf3SVladimir Sementsov-Ogievskiy static void nbd_iter_channel_error(NBDReplyChunkIter *iter,
105586f8cdf3SVladimir Sementsov-Ogievskiy                                    int ret, Error **local_err)
105686f8cdf3SVladimir Sementsov-Ogievskiy {
1057d9366135SVladimir Sementsov-Ogievskiy     assert(local_err && *local_err);
105886f8cdf3SVladimir Sementsov-Ogievskiy     assert(ret < 0);
105986f8cdf3SVladimir Sementsov-Ogievskiy 
106086f8cdf3SVladimir Sementsov-Ogievskiy     if (!iter->ret) {
106186f8cdf3SVladimir Sementsov-Ogievskiy         iter->ret = ret;
106286f8cdf3SVladimir Sementsov-Ogievskiy         error_propagate(&iter->err, *local_err);
106386f8cdf3SVladimir Sementsov-Ogievskiy     } else {
106486f8cdf3SVladimir Sementsov-Ogievskiy         error_free(*local_err);
106586f8cdf3SVladimir Sementsov-Ogievskiy     }
106686f8cdf3SVladimir Sementsov-Ogievskiy 
106786f8cdf3SVladimir Sementsov-Ogievskiy     *local_err = NULL;
106886f8cdf3SVladimir Sementsov-Ogievskiy }
106986f8cdf3SVladimir Sementsov-Ogievskiy 
107086f8cdf3SVladimir Sementsov-Ogievskiy static void nbd_iter_request_error(NBDReplyChunkIter *iter, int ret)
107186f8cdf3SVladimir Sementsov-Ogievskiy {
107286f8cdf3SVladimir Sementsov-Ogievskiy     assert(ret < 0);
107386f8cdf3SVladimir Sementsov-Ogievskiy 
107486f8cdf3SVladimir Sementsov-Ogievskiy     if (!iter->request_ret) {
107586f8cdf3SVladimir Sementsov-Ogievskiy         iter->request_ret = ret;
107686f8cdf3SVladimir Sementsov-Ogievskiy     }
107786f8cdf3SVladimir Sementsov-Ogievskiy }
107886f8cdf3SVladimir Sementsov-Ogievskiy 
107986f8cdf3SVladimir Sementsov-Ogievskiy /*
108086f8cdf3SVladimir Sementsov-Ogievskiy  * NBD_FOREACH_REPLY_CHUNK
108186f8cdf3SVladimir Sementsov-Ogievskiy  * The pointer stored in @payload requires g_free() to free it.
108286f8cdf3SVladimir Sementsov-Ogievskiy  */
108386f8cdf3SVladimir Sementsov-Ogievskiy #define NBD_FOREACH_REPLY_CHUNK(s, iter, handle, structured, \
108486f8cdf3SVladimir Sementsov-Ogievskiy                                 qiov, reply, payload) \
108586f8cdf3SVladimir Sementsov-Ogievskiy     for (iter = (NBDReplyChunkIter) { .only_structured = structured }; \
108686f8cdf3SVladimir Sementsov-Ogievskiy          nbd_reply_chunk_iter_receive(s, &iter, handle, qiov, reply, payload);)
108786f8cdf3SVladimir Sementsov-Ogievskiy 
108886f8cdf3SVladimir Sementsov-Ogievskiy /*
108986f8cdf3SVladimir Sementsov-Ogievskiy  * nbd_reply_chunk_iter_receive
109086f8cdf3SVladimir Sementsov-Ogievskiy  * The pointer stored in @payload requires g_free() to free it.
109186f8cdf3SVladimir Sementsov-Ogievskiy  */
1092611ae1d7SVladimir Sementsov-Ogievskiy static bool nbd_reply_chunk_iter_receive(BDRVNBDState *s,
109386f8cdf3SVladimir Sementsov-Ogievskiy                                          NBDReplyChunkIter *iter,
109486f8cdf3SVladimir Sementsov-Ogievskiy                                          uint64_t handle,
109586f8cdf3SVladimir Sementsov-Ogievskiy                                          QEMUIOVector *qiov, NBDReply *reply,
109686f8cdf3SVladimir Sementsov-Ogievskiy                                          void **payload)
109786f8cdf3SVladimir Sementsov-Ogievskiy {
109886f8cdf3SVladimir Sementsov-Ogievskiy     int ret, request_ret;
109986f8cdf3SVladimir Sementsov-Ogievskiy     NBDReply local_reply;
110086f8cdf3SVladimir Sementsov-Ogievskiy     NBDStructuredReplyChunk *chunk;
110186f8cdf3SVladimir Sementsov-Ogievskiy     Error *local_err = NULL;
110291e0998fSVladimir Sementsov-Ogievskiy     if (!nbd_client_connected(s)) {
110386f8cdf3SVladimir Sementsov-Ogievskiy         error_setg(&local_err, "Connection closed");
110486f8cdf3SVladimir Sementsov-Ogievskiy         nbd_iter_channel_error(iter, -EIO, &local_err);
110586f8cdf3SVladimir Sementsov-Ogievskiy         goto break_loop;
110686f8cdf3SVladimir Sementsov-Ogievskiy     }
110786f8cdf3SVladimir Sementsov-Ogievskiy 
110886f8cdf3SVladimir Sementsov-Ogievskiy     if (iter->done) {
110986f8cdf3SVladimir Sementsov-Ogievskiy         /* Previous iteration was last. */
111086f8cdf3SVladimir Sementsov-Ogievskiy         goto break_loop;
111186f8cdf3SVladimir Sementsov-Ogievskiy     }
111286f8cdf3SVladimir Sementsov-Ogievskiy 
111386f8cdf3SVladimir Sementsov-Ogievskiy     if (reply == NULL) {
111486f8cdf3SVladimir Sementsov-Ogievskiy         reply = &local_reply;
111586f8cdf3SVladimir Sementsov-Ogievskiy     }
111686f8cdf3SVladimir Sementsov-Ogievskiy 
111786f8cdf3SVladimir Sementsov-Ogievskiy     ret = nbd_co_receive_one_chunk(s, handle, iter->only_structured,
111886f8cdf3SVladimir Sementsov-Ogievskiy                                    &request_ret, qiov, reply, payload,
111986f8cdf3SVladimir Sementsov-Ogievskiy                                    &local_err);
112086f8cdf3SVladimir Sementsov-Ogievskiy     if (ret < 0) {
112186f8cdf3SVladimir Sementsov-Ogievskiy         nbd_iter_channel_error(iter, ret, &local_err);
112286f8cdf3SVladimir Sementsov-Ogievskiy     } else if (request_ret < 0) {
112386f8cdf3SVladimir Sementsov-Ogievskiy         nbd_iter_request_error(iter, request_ret);
112486f8cdf3SVladimir Sementsov-Ogievskiy     }
112586f8cdf3SVladimir Sementsov-Ogievskiy 
112686f8cdf3SVladimir Sementsov-Ogievskiy     /* Do not execute the body of NBD_FOREACH_REPLY_CHUNK for simple reply. */
112791e0998fSVladimir Sementsov-Ogievskiy     if (nbd_reply_is_simple(reply) || !nbd_client_connected(s)) {
112886f8cdf3SVladimir Sementsov-Ogievskiy         goto break_loop;
112986f8cdf3SVladimir Sementsov-Ogievskiy     }
113086f8cdf3SVladimir Sementsov-Ogievskiy 
113186f8cdf3SVladimir Sementsov-Ogievskiy     chunk = &reply->structured;
113286f8cdf3SVladimir Sementsov-Ogievskiy     iter->only_structured = true;
113386f8cdf3SVladimir Sementsov-Ogievskiy 
113486f8cdf3SVladimir Sementsov-Ogievskiy     if (chunk->type == NBD_REPLY_TYPE_NONE) {
113586f8cdf3SVladimir Sementsov-Ogievskiy         /* NBD_REPLY_FLAG_DONE is already checked in nbd_co_receive_one_chunk */
113686f8cdf3SVladimir Sementsov-Ogievskiy         assert(chunk->flags & NBD_REPLY_FLAG_DONE);
113786f8cdf3SVladimir Sementsov-Ogievskiy         goto break_loop;
113886f8cdf3SVladimir Sementsov-Ogievskiy     }
113986f8cdf3SVladimir Sementsov-Ogievskiy 
114086f8cdf3SVladimir Sementsov-Ogievskiy     if (chunk->flags & NBD_REPLY_FLAG_DONE) {
114186f8cdf3SVladimir Sementsov-Ogievskiy         /* This iteration is last. */
114286f8cdf3SVladimir Sementsov-Ogievskiy         iter->done = true;
114386f8cdf3SVladimir Sementsov-Ogievskiy     }
114486f8cdf3SVladimir Sementsov-Ogievskiy 
114586f8cdf3SVladimir Sementsov-Ogievskiy     /* Execute the loop body */
114686f8cdf3SVladimir Sementsov-Ogievskiy     return true;
114786f8cdf3SVladimir Sementsov-Ogievskiy 
114886f8cdf3SVladimir Sementsov-Ogievskiy break_loop:
114986f8cdf3SVladimir Sementsov-Ogievskiy     s->requests[HANDLE_TO_INDEX(s, handle)].coroutine = NULL;
115086f8cdf3SVladimir Sementsov-Ogievskiy 
115186f8cdf3SVladimir Sementsov-Ogievskiy     qemu_co_mutex_lock(&s->send_mutex);
115286f8cdf3SVladimir Sementsov-Ogievskiy     s->in_flight--;
1153f7651539SVladimir Sementsov-Ogievskiy     if (s->in_flight == 0 && s->wait_in_flight) {
1154f7651539SVladimir Sementsov-Ogievskiy         aio_co_wake(s->connection_co);
1155f7651539SVladimir Sementsov-Ogievskiy     } else {
115686f8cdf3SVladimir Sementsov-Ogievskiy         qemu_co_queue_next(&s->free_sema);
1157f7651539SVladimir Sementsov-Ogievskiy     }
115886f8cdf3SVladimir Sementsov-Ogievskiy     qemu_co_mutex_unlock(&s->send_mutex);
115986f8cdf3SVladimir Sementsov-Ogievskiy 
116086f8cdf3SVladimir Sementsov-Ogievskiy     return false;
116186f8cdf3SVladimir Sementsov-Ogievskiy }
116286f8cdf3SVladimir Sementsov-Ogievskiy 
1163611ae1d7SVladimir Sementsov-Ogievskiy static int nbd_co_receive_return_code(BDRVNBDState *s, uint64_t handle,
116486f8cdf3SVladimir Sementsov-Ogievskiy                                       int *request_ret, Error **errp)
116586f8cdf3SVladimir Sementsov-Ogievskiy {
116686f8cdf3SVladimir Sementsov-Ogievskiy     NBDReplyChunkIter iter;
116786f8cdf3SVladimir Sementsov-Ogievskiy 
116886f8cdf3SVladimir Sementsov-Ogievskiy     NBD_FOREACH_REPLY_CHUNK(s, iter, handle, false, NULL, NULL, NULL) {
116986f8cdf3SVladimir Sementsov-Ogievskiy         /* nbd_reply_chunk_iter_receive does all the work */
117086f8cdf3SVladimir Sementsov-Ogievskiy     }
117186f8cdf3SVladimir Sementsov-Ogievskiy 
117286f8cdf3SVladimir Sementsov-Ogievskiy     error_propagate(errp, iter.err);
117386f8cdf3SVladimir Sementsov-Ogievskiy     *request_ret = iter.request_ret;
117486f8cdf3SVladimir Sementsov-Ogievskiy     return iter.ret;
117586f8cdf3SVladimir Sementsov-Ogievskiy }
117686f8cdf3SVladimir Sementsov-Ogievskiy 
1177611ae1d7SVladimir Sementsov-Ogievskiy static int nbd_co_receive_cmdread_reply(BDRVNBDState *s, uint64_t handle,
117886f8cdf3SVladimir Sementsov-Ogievskiy                                         uint64_t offset, QEMUIOVector *qiov,
117986f8cdf3SVladimir Sementsov-Ogievskiy                                         int *request_ret, Error **errp)
118086f8cdf3SVladimir Sementsov-Ogievskiy {
118186f8cdf3SVladimir Sementsov-Ogievskiy     NBDReplyChunkIter iter;
118286f8cdf3SVladimir Sementsov-Ogievskiy     NBDReply reply;
118386f8cdf3SVladimir Sementsov-Ogievskiy     void *payload = NULL;
118486f8cdf3SVladimir Sementsov-Ogievskiy     Error *local_err = NULL;
118586f8cdf3SVladimir Sementsov-Ogievskiy 
118686f8cdf3SVladimir Sementsov-Ogievskiy     NBD_FOREACH_REPLY_CHUNK(s, iter, handle, s->info.structured_reply,
118786f8cdf3SVladimir Sementsov-Ogievskiy                             qiov, &reply, &payload)
118886f8cdf3SVladimir Sementsov-Ogievskiy     {
118986f8cdf3SVladimir Sementsov-Ogievskiy         int ret;
119086f8cdf3SVladimir Sementsov-Ogievskiy         NBDStructuredReplyChunk *chunk = &reply.structured;
119186f8cdf3SVladimir Sementsov-Ogievskiy 
119286f8cdf3SVladimir Sementsov-Ogievskiy         assert(nbd_reply_is_structured(&reply));
119386f8cdf3SVladimir Sementsov-Ogievskiy 
119486f8cdf3SVladimir Sementsov-Ogievskiy         switch (chunk->type) {
119586f8cdf3SVladimir Sementsov-Ogievskiy         case NBD_REPLY_TYPE_OFFSET_DATA:
119686f8cdf3SVladimir Sementsov-Ogievskiy             /*
119786f8cdf3SVladimir Sementsov-Ogievskiy              * special cased in nbd_co_receive_one_chunk, data is already
119886f8cdf3SVladimir Sementsov-Ogievskiy              * in qiov
119986f8cdf3SVladimir Sementsov-Ogievskiy              */
120086f8cdf3SVladimir Sementsov-Ogievskiy             break;
120186f8cdf3SVladimir Sementsov-Ogievskiy         case NBD_REPLY_TYPE_OFFSET_HOLE:
120286f8cdf3SVladimir Sementsov-Ogievskiy             ret = nbd_parse_offset_hole_payload(s, &reply.structured, payload,
120386f8cdf3SVladimir Sementsov-Ogievskiy                                                 offset, qiov, &local_err);
120486f8cdf3SVladimir Sementsov-Ogievskiy             if (ret < 0) {
1205a34b1e5eSVladimir Sementsov-Ogievskiy                 nbd_channel_error(s, ret);
120686f8cdf3SVladimir Sementsov-Ogievskiy                 nbd_iter_channel_error(&iter, ret, &local_err);
120786f8cdf3SVladimir Sementsov-Ogievskiy             }
120886f8cdf3SVladimir Sementsov-Ogievskiy             break;
120986f8cdf3SVladimir Sementsov-Ogievskiy         default:
121086f8cdf3SVladimir Sementsov-Ogievskiy             if (!nbd_reply_type_is_error(chunk->type)) {
121186f8cdf3SVladimir Sementsov-Ogievskiy                 /* not allowed reply type */
1212a34b1e5eSVladimir Sementsov-Ogievskiy                 nbd_channel_error(s, -EINVAL);
121386f8cdf3SVladimir Sementsov-Ogievskiy                 error_setg(&local_err,
121486f8cdf3SVladimir Sementsov-Ogievskiy                            "Unexpected reply type: %d (%s) for CMD_READ",
121586f8cdf3SVladimir Sementsov-Ogievskiy                            chunk->type, nbd_reply_type_lookup(chunk->type));
121686f8cdf3SVladimir Sementsov-Ogievskiy                 nbd_iter_channel_error(&iter, -EINVAL, &local_err);
121786f8cdf3SVladimir Sementsov-Ogievskiy             }
121886f8cdf3SVladimir Sementsov-Ogievskiy         }
121986f8cdf3SVladimir Sementsov-Ogievskiy 
122086f8cdf3SVladimir Sementsov-Ogievskiy         g_free(payload);
122186f8cdf3SVladimir Sementsov-Ogievskiy         payload = NULL;
122286f8cdf3SVladimir Sementsov-Ogievskiy     }
122386f8cdf3SVladimir Sementsov-Ogievskiy 
122486f8cdf3SVladimir Sementsov-Ogievskiy     error_propagate(errp, iter.err);
122586f8cdf3SVladimir Sementsov-Ogievskiy     *request_ret = iter.request_ret;
122686f8cdf3SVladimir Sementsov-Ogievskiy     return iter.ret;
122786f8cdf3SVladimir Sementsov-Ogievskiy }
122886f8cdf3SVladimir Sementsov-Ogievskiy 
1229611ae1d7SVladimir Sementsov-Ogievskiy static int nbd_co_receive_blockstatus_reply(BDRVNBDState *s,
123086f8cdf3SVladimir Sementsov-Ogievskiy                                             uint64_t handle, uint64_t length,
123186f8cdf3SVladimir Sementsov-Ogievskiy                                             NBDExtent *extent,
123286f8cdf3SVladimir Sementsov-Ogievskiy                                             int *request_ret, Error **errp)
123386f8cdf3SVladimir Sementsov-Ogievskiy {
123486f8cdf3SVladimir Sementsov-Ogievskiy     NBDReplyChunkIter iter;
123586f8cdf3SVladimir Sementsov-Ogievskiy     NBDReply reply;
123686f8cdf3SVladimir Sementsov-Ogievskiy     void *payload = NULL;
123786f8cdf3SVladimir Sementsov-Ogievskiy     Error *local_err = NULL;
123886f8cdf3SVladimir Sementsov-Ogievskiy     bool received = false;
123986f8cdf3SVladimir Sementsov-Ogievskiy 
124086f8cdf3SVladimir Sementsov-Ogievskiy     assert(!extent->length);
124186f8cdf3SVladimir Sementsov-Ogievskiy     NBD_FOREACH_REPLY_CHUNK(s, iter, handle, false, NULL, &reply, &payload) {
124286f8cdf3SVladimir Sementsov-Ogievskiy         int ret;
124386f8cdf3SVladimir Sementsov-Ogievskiy         NBDStructuredReplyChunk *chunk = &reply.structured;
124486f8cdf3SVladimir Sementsov-Ogievskiy 
124586f8cdf3SVladimir Sementsov-Ogievskiy         assert(nbd_reply_is_structured(&reply));
124686f8cdf3SVladimir Sementsov-Ogievskiy 
124786f8cdf3SVladimir Sementsov-Ogievskiy         switch (chunk->type) {
124886f8cdf3SVladimir Sementsov-Ogievskiy         case NBD_REPLY_TYPE_BLOCK_STATUS:
124986f8cdf3SVladimir Sementsov-Ogievskiy             if (received) {
1250a34b1e5eSVladimir Sementsov-Ogievskiy                 nbd_channel_error(s, -EINVAL);
125186f8cdf3SVladimir Sementsov-Ogievskiy                 error_setg(&local_err, "Several BLOCK_STATUS chunks in reply");
125286f8cdf3SVladimir Sementsov-Ogievskiy                 nbd_iter_channel_error(&iter, -EINVAL, &local_err);
125386f8cdf3SVladimir Sementsov-Ogievskiy             }
125486f8cdf3SVladimir Sementsov-Ogievskiy             received = true;
125586f8cdf3SVladimir Sementsov-Ogievskiy 
125686f8cdf3SVladimir Sementsov-Ogievskiy             ret = nbd_parse_blockstatus_payload(s, &reply.structured,
125786f8cdf3SVladimir Sementsov-Ogievskiy                                                 payload, length, extent,
125886f8cdf3SVladimir Sementsov-Ogievskiy                                                 &local_err);
125986f8cdf3SVladimir Sementsov-Ogievskiy             if (ret < 0) {
1260a34b1e5eSVladimir Sementsov-Ogievskiy                 nbd_channel_error(s, ret);
126186f8cdf3SVladimir Sementsov-Ogievskiy                 nbd_iter_channel_error(&iter, ret, &local_err);
126286f8cdf3SVladimir Sementsov-Ogievskiy             }
126386f8cdf3SVladimir Sementsov-Ogievskiy             break;
126486f8cdf3SVladimir Sementsov-Ogievskiy         default:
126586f8cdf3SVladimir Sementsov-Ogievskiy             if (!nbd_reply_type_is_error(chunk->type)) {
1266a34b1e5eSVladimir Sementsov-Ogievskiy                 nbd_channel_error(s, -EINVAL);
126786f8cdf3SVladimir Sementsov-Ogievskiy                 error_setg(&local_err,
126886f8cdf3SVladimir Sementsov-Ogievskiy                            "Unexpected reply type: %d (%s) "
126986f8cdf3SVladimir Sementsov-Ogievskiy                            "for CMD_BLOCK_STATUS",
127086f8cdf3SVladimir Sementsov-Ogievskiy                            chunk->type, nbd_reply_type_lookup(chunk->type));
127186f8cdf3SVladimir Sementsov-Ogievskiy                 nbd_iter_channel_error(&iter, -EINVAL, &local_err);
127286f8cdf3SVladimir Sementsov-Ogievskiy             }
127386f8cdf3SVladimir Sementsov-Ogievskiy         }
127486f8cdf3SVladimir Sementsov-Ogievskiy 
127586f8cdf3SVladimir Sementsov-Ogievskiy         g_free(payload);
127686f8cdf3SVladimir Sementsov-Ogievskiy         payload = NULL;
127786f8cdf3SVladimir Sementsov-Ogievskiy     }
127886f8cdf3SVladimir Sementsov-Ogievskiy 
127986f8cdf3SVladimir Sementsov-Ogievskiy     if (!extent->length && !iter.request_ret) {
128086f8cdf3SVladimir Sementsov-Ogievskiy         error_setg(&local_err, "Server did not reply with any status extents");
128186f8cdf3SVladimir Sementsov-Ogievskiy         nbd_iter_channel_error(&iter, -EIO, &local_err);
128286f8cdf3SVladimir Sementsov-Ogievskiy     }
128386f8cdf3SVladimir Sementsov-Ogievskiy 
128486f8cdf3SVladimir Sementsov-Ogievskiy     error_propagate(errp, iter.err);
128586f8cdf3SVladimir Sementsov-Ogievskiy     *request_ret = iter.request_ret;
128686f8cdf3SVladimir Sementsov-Ogievskiy     return iter.ret;
128786f8cdf3SVladimir Sementsov-Ogievskiy }
128886f8cdf3SVladimir Sementsov-Ogievskiy 
128986f8cdf3SVladimir Sementsov-Ogievskiy static int nbd_co_request(BlockDriverState *bs, NBDRequest *request,
129086f8cdf3SVladimir Sementsov-Ogievskiy                           QEMUIOVector *write_qiov)
129186f8cdf3SVladimir Sementsov-Ogievskiy {
129286f8cdf3SVladimir Sementsov-Ogievskiy     int ret, request_ret;
129386f8cdf3SVladimir Sementsov-Ogievskiy     Error *local_err = NULL;
1294611ae1d7SVladimir Sementsov-Ogievskiy     BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
129586f8cdf3SVladimir Sementsov-Ogievskiy 
129686f8cdf3SVladimir Sementsov-Ogievskiy     assert(request->type != NBD_CMD_READ);
129786f8cdf3SVladimir Sementsov-Ogievskiy     if (write_qiov) {
129886f8cdf3SVladimir Sementsov-Ogievskiy         assert(request->type == NBD_CMD_WRITE);
129986f8cdf3SVladimir Sementsov-Ogievskiy         assert(request->len == iov_size(write_qiov->iov, write_qiov->niov));
130086f8cdf3SVladimir Sementsov-Ogievskiy     } else {
130186f8cdf3SVladimir Sementsov-Ogievskiy         assert(request->type != NBD_CMD_WRITE);
130286f8cdf3SVladimir Sementsov-Ogievskiy     }
1303f7651539SVladimir Sementsov-Ogievskiy 
1304f7651539SVladimir Sementsov-Ogievskiy     do {
130586f8cdf3SVladimir Sementsov-Ogievskiy         ret = nbd_co_send_request(bs, request, write_qiov);
130686f8cdf3SVladimir Sementsov-Ogievskiy         if (ret < 0) {
1307f7651539SVladimir Sementsov-Ogievskiy             continue;
130886f8cdf3SVladimir Sementsov-Ogievskiy         }
130986f8cdf3SVladimir Sementsov-Ogievskiy 
1310611ae1d7SVladimir Sementsov-Ogievskiy         ret = nbd_co_receive_return_code(s, request->handle,
131186f8cdf3SVladimir Sementsov-Ogievskiy                                          &request_ret, &local_err);
131286f8cdf3SVladimir Sementsov-Ogievskiy         if (local_err) {
1313f7651539SVladimir Sementsov-Ogievskiy             trace_nbd_co_request_fail(request->from, request->len,
1314f7651539SVladimir Sementsov-Ogievskiy                                       request->handle, request->flags,
1315f7651539SVladimir Sementsov-Ogievskiy                                       request->type,
131686f8cdf3SVladimir Sementsov-Ogievskiy                                       nbd_cmd_lookup(request->type),
131786f8cdf3SVladimir Sementsov-Ogievskiy                                       ret, error_get_pretty(local_err));
131886f8cdf3SVladimir Sementsov-Ogievskiy             error_free(local_err);
1319f7651539SVladimir Sementsov-Ogievskiy             local_err = NULL;
132086f8cdf3SVladimir Sementsov-Ogievskiy         }
1321f7651539SVladimir Sementsov-Ogievskiy     } while (ret < 0 && nbd_client_connecting_wait(s));
1322f7651539SVladimir Sementsov-Ogievskiy 
132386f8cdf3SVladimir Sementsov-Ogievskiy     return ret ? ret : request_ret;
132486f8cdf3SVladimir Sementsov-Ogievskiy }
132586f8cdf3SVladimir Sementsov-Ogievskiy 
1326f7ef38ddSVladimir Sementsov-Ogievskiy static int nbd_client_co_preadv(BlockDriverState *bs, int64_t offset,
1327f7ef38ddSVladimir Sementsov-Ogievskiy                                 int64_t bytes, QEMUIOVector *qiov,
1328f7ef38ddSVladimir Sementsov-Ogievskiy                                 BdrvRequestFlags flags)
132986f8cdf3SVladimir Sementsov-Ogievskiy {
133086f8cdf3SVladimir Sementsov-Ogievskiy     int ret, request_ret;
133186f8cdf3SVladimir Sementsov-Ogievskiy     Error *local_err = NULL;
1332611ae1d7SVladimir Sementsov-Ogievskiy     BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
133386f8cdf3SVladimir Sementsov-Ogievskiy     NBDRequest request = {
133486f8cdf3SVladimir Sementsov-Ogievskiy         .type = NBD_CMD_READ,
133586f8cdf3SVladimir Sementsov-Ogievskiy         .from = offset,
133686f8cdf3SVladimir Sementsov-Ogievskiy         .len = bytes,
133786f8cdf3SVladimir Sementsov-Ogievskiy     };
133886f8cdf3SVladimir Sementsov-Ogievskiy 
133986f8cdf3SVladimir Sementsov-Ogievskiy     assert(bytes <= NBD_MAX_BUFFER_SIZE);
134086f8cdf3SVladimir Sementsov-Ogievskiy     assert(!flags);
134186f8cdf3SVladimir Sementsov-Ogievskiy 
134286f8cdf3SVladimir Sementsov-Ogievskiy     if (!bytes) {
134386f8cdf3SVladimir Sementsov-Ogievskiy         return 0;
134486f8cdf3SVladimir Sementsov-Ogievskiy     }
134586f8cdf3SVladimir Sementsov-Ogievskiy     /*
134686f8cdf3SVladimir Sementsov-Ogievskiy      * Work around the fact that the block layer doesn't do
134786f8cdf3SVladimir Sementsov-Ogievskiy      * byte-accurate sizing yet - if the read exceeds the server's
134886f8cdf3SVladimir Sementsov-Ogievskiy      * advertised size because the block layer rounded size up, then
134986f8cdf3SVladimir Sementsov-Ogievskiy      * truncate the request to the server and tail-pad with zero.
135086f8cdf3SVladimir Sementsov-Ogievskiy      */
1351611ae1d7SVladimir Sementsov-Ogievskiy     if (offset >= s->info.size) {
135286f8cdf3SVladimir Sementsov-Ogievskiy         assert(bytes < BDRV_SECTOR_SIZE);
135386f8cdf3SVladimir Sementsov-Ogievskiy         qemu_iovec_memset(qiov, 0, 0, bytes);
135486f8cdf3SVladimir Sementsov-Ogievskiy         return 0;
135586f8cdf3SVladimir Sementsov-Ogievskiy     }
1356611ae1d7SVladimir Sementsov-Ogievskiy     if (offset + bytes > s->info.size) {
1357611ae1d7SVladimir Sementsov-Ogievskiy         uint64_t slop = offset + bytes - s->info.size;
135886f8cdf3SVladimir Sementsov-Ogievskiy 
135986f8cdf3SVladimir Sementsov-Ogievskiy         assert(slop < BDRV_SECTOR_SIZE);
136086f8cdf3SVladimir Sementsov-Ogievskiy         qemu_iovec_memset(qiov, bytes - slop, 0, slop);
136186f8cdf3SVladimir Sementsov-Ogievskiy         request.len -= slop;
136286f8cdf3SVladimir Sementsov-Ogievskiy     }
136386f8cdf3SVladimir Sementsov-Ogievskiy 
1364f7651539SVladimir Sementsov-Ogievskiy     do {
136586f8cdf3SVladimir Sementsov-Ogievskiy         ret = nbd_co_send_request(bs, &request, NULL);
136686f8cdf3SVladimir Sementsov-Ogievskiy         if (ret < 0) {
1367f7651539SVladimir Sementsov-Ogievskiy             continue;
136886f8cdf3SVladimir Sementsov-Ogievskiy         }
136986f8cdf3SVladimir Sementsov-Ogievskiy 
1370611ae1d7SVladimir Sementsov-Ogievskiy         ret = nbd_co_receive_cmdread_reply(s, request.handle, offset, qiov,
137186f8cdf3SVladimir Sementsov-Ogievskiy                                            &request_ret, &local_err);
137286f8cdf3SVladimir Sementsov-Ogievskiy         if (local_err) {
137386f8cdf3SVladimir Sementsov-Ogievskiy             trace_nbd_co_request_fail(request.from, request.len, request.handle,
137486f8cdf3SVladimir Sementsov-Ogievskiy                                       request.flags, request.type,
137586f8cdf3SVladimir Sementsov-Ogievskiy                                       nbd_cmd_lookup(request.type),
137686f8cdf3SVladimir Sementsov-Ogievskiy                                       ret, error_get_pretty(local_err));
137786f8cdf3SVladimir Sementsov-Ogievskiy             error_free(local_err);
1378f7651539SVladimir Sementsov-Ogievskiy             local_err = NULL;
137986f8cdf3SVladimir Sementsov-Ogievskiy         }
1380f7651539SVladimir Sementsov-Ogievskiy     } while (ret < 0 && nbd_client_connecting_wait(s));
1381f7651539SVladimir Sementsov-Ogievskiy 
138286f8cdf3SVladimir Sementsov-Ogievskiy     return ret ? ret : request_ret;
138386f8cdf3SVladimir Sementsov-Ogievskiy }
138486f8cdf3SVladimir Sementsov-Ogievskiy 
1385e75abedaSVladimir Sementsov-Ogievskiy static int nbd_client_co_pwritev(BlockDriverState *bs, int64_t offset,
1386e75abedaSVladimir Sementsov-Ogievskiy                                  int64_t bytes, QEMUIOVector *qiov,
1387e75abedaSVladimir Sementsov-Ogievskiy                                  BdrvRequestFlags flags)
138886f8cdf3SVladimir Sementsov-Ogievskiy {
1389611ae1d7SVladimir Sementsov-Ogievskiy     BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
139086f8cdf3SVladimir Sementsov-Ogievskiy     NBDRequest request = {
139186f8cdf3SVladimir Sementsov-Ogievskiy         .type = NBD_CMD_WRITE,
139286f8cdf3SVladimir Sementsov-Ogievskiy         .from = offset,
139386f8cdf3SVladimir Sementsov-Ogievskiy         .len = bytes,
139486f8cdf3SVladimir Sementsov-Ogievskiy     };
139586f8cdf3SVladimir Sementsov-Ogievskiy 
1396611ae1d7SVladimir Sementsov-Ogievskiy     assert(!(s->info.flags & NBD_FLAG_READ_ONLY));
139786f8cdf3SVladimir Sementsov-Ogievskiy     if (flags & BDRV_REQ_FUA) {
1398611ae1d7SVladimir Sementsov-Ogievskiy         assert(s->info.flags & NBD_FLAG_SEND_FUA);
139986f8cdf3SVladimir Sementsov-Ogievskiy         request.flags |= NBD_CMD_FLAG_FUA;
140086f8cdf3SVladimir Sementsov-Ogievskiy     }
140186f8cdf3SVladimir Sementsov-Ogievskiy 
140286f8cdf3SVladimir Sementsov-Ogievskiy     assert(bytes <= NBD_MAX_BUFFER_SIZE);
140386f8cdf3SVladimir Sementsov-Ogievskiy 
140486f8cdf3SVladimir Sementsov-Ogievskiy     if (!bytes) {
140586f8cdf3SVladimir Sementsov-Ogievskiy         return 0;
140686f8cdf3SVladimir Sementsov-Ogievskiy     }
140786f8cdf3SVladimir Sementsov-Ogievskiy     return nbd_co_request(bs, &request, qiov);
140886f8cdf3SVladimir Sementsov-Ogievskiy }
140986f8cdf3SVladimir Sementsov-Ogievskiy 
141086f8cdf3SVladimir Sementsov-Ogievskiy static int nbd_client_co_pwrite_zeroes(BlockDriverState *bs, int64_t offset,
1411f34b2bcfSVladimir Sementsov-Ogievskiy                                        int64_t bytes, BdrvRequestFlags flags)
141286f8cdf3SVladimir Sementsov-Ogievskiy {
1413611ae1d7SVladimir Sementsov-Ogievskiy     BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
141486f8cdf3SVladimir Sementsov-Ogievskiy     NBDRequest request = {
141586f8cdf3SVladimir Sementsov-Ogievskiy         .type = NBD_CMD_WRITE_ZEROES,
141686f8cdf3SVladimir Sementsov-Ogievskiy         .from = offset,
1417f34b2bcfSVladimir Sementsov-Ogievskiy         .len = bytes,  /* .len is uint32_t actually */
141886f8cdf3SVladimir Sementsov-Ogievskiy     };
141986f8cdf3SVladimir Sementsov-Ogievskiy 
1420f34b2bcfSVladimir Sementsov-Ogievskiy     assert(bytes <= UINT32_MAX); /* rely on max_pwrite_zeroes */
1421f34b2bcfSVladimir Sementsov-Ogievskiy 
1422611ae1d7SVladimir Sementsov-Ogievskiy     assert(!(s->info.flags & NBD_FLAG_READ_ONLY));
1423611ae1d7SVladimir Sementsov-Ogievskiy     if (!(s->info.flags & NBD_FLAG_SEND_WRITE_ZEROES)) {
142486f8cdf3SVladimir Sementsov-Ogievskiy         return -ENOTSUP;
142586f8cdf3SVladimir Sementsov-Ogievskiy     }
142686f8cdf3SVladimir Sementsov-Ogievskiy 
142786f8cdf3SVladimir Sementsov-Ogievskiy     if (flags & BDRV_REQ_FUA) {
1428611ae1d7SVladimir Sementsov-Ogievskiy         assert(s->info.flags & NBD_FLAG_SEND_FUA);
142986f8cdf3SVladimir Sementsov-Ogievskiy         request.flags |= NBD_CMD_FLAG_FUA;
143086f8cdf3SVladimir Sementsov-Ogievskiy     }
143186f8cdf3SVladimir Sementsov-Ogievskiy     if (!(flags & BDRV_REQ_MAY_UNMAP)) {
143286f8cdf3SVladimir Sementsov-Ogievskiy         request.flags |= NBD_CMD_FLAG_NO_HOLE;
143386f8cdf3SVladimir Sementsov-Ogievskiy     }
1434f061656cSEric Blake     if (flags & BDRV_REQ_NO_FALLBACK) {
1435f061656cSEric Blake         assert(s->info.flags & NBD_FLAG_SEND_FAST_ZERO);
1436f061656cSEric Blake         request.flags |= NBD_CMD_FLAG_FAST_ZERO;
1437f061656cSEric Blake     }
143886f8cdf3SVladimir Sementsov-Ogievskiy 
143986f8cdf3SVladimir Sementsov-Ogievskiy     if (!bytes) {
144086f8cdf3SVladimir Sementsov-Ogievskiy         return 0;
144186f8cdf3SVladimir Sementsov-Ogievskiy     }
144286f8cdf3SVladimir Sementsov-Ogievskiy     return nbd_co_request(bs, &request, NULL);
144386f8cdf3SVladimir Sementsov-Ogievskiy }
144486f8cdf3SVladimir Sementsov-Ogievskiy 
144586f8cdf3SVladimir Sementsov-Ogievskiy static int nbd_client_co_flush(BlockDriverState *bs)
144686f8cdf3SVladimir Sementsov-Ogievskiy {
1447611ae1d7SVladimir Sementsov-Ogievskiy     BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
144886f8cdf3SVladimir Sementsov-Ogievskiy     NBDRequest request = { .type = NBD_CMD_FLUSH };
144986f8cdf3SVladimir Sementsov-Ogievskiy 
1450611ae1d7SVladimir Sementsov-Ogievskiy     if (!(s->info.flags & NBD_FLAG_SEND_FLUSH)) {
145186f8cdf3SVladimir Sementsov-Ogievskiy         return 0;
145286f8cdf3SVladimir Sementsov-Ogievskiy     }
145386f8cdf3SVladimir Sementsov-Ogievskiy 
145486f8cdf3SVladimir Sementsov-Ogievskiy     request.from = 0;
145586f8cdf3SVladimir Sementsov-Ogievskiy     request.len = 0;
145686f8cdf3SVladimir Sementsov-Ogievskiy 
145786f8cdf3SVladimir Sementsov-Ogievskiy     return nbd_co_request(bs, &request, NULL);
145886f8cdf3SVladimir Sementsov-Ogievskiy }
145986f8cdf3SVladimir Sementsov-Ogievskiy 
146086f8cdf3SVladimir Sementsov-Ogievskiy static int nbd_client_co_pdiscard(BlockDriverState *bs, int64_t offset,
14610c802287SVladimir Sementsov-Ogievskiy                                   int64_t bytes)
146286f8cdf3SVladimir Sementsov-Ogievskiy {
1463611ae1d7SVladimir Sementsov-Ogievskiy     BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
146486f8cdf3SVladimir Sementsov-Ogievskiy     NBDRequest request = {
146586f8cdf3SVladimir Sementsov-Ogievskiy         .type = NBD_CMD_TRIM,
146686f8cdf3SVladimir Sementsov-Ogievskiy         .from = offset,
14670c802287SVladimir Sementsov-Ogievskiy         .len = bytes, /* len is uint32_t */
146886f8cdf3SVladimir Sementsov-Ogievskiy     };
146986f8cdf3SVladimir Sementsov-Ogievskiy 
14700c802287SVladimir Sementsov-Ogievskiy     assert(bytes <= UINT32_MAX); /* rely on max_pdiscard */
14710c802287SVladimir Sementsov-Ogievskiy 
1472611ae1d7SVladimir Sementsov-Ogievskiy     assert(!(s->info.flags & NBD_FLAG_READ_ONLY));
1473611ae1d7SVladimir Sementsov-Ogievskiy     if (!(s->info.flags & NBD_FLAG_SEND_TRIM) || !bytes) {
147486f8cdf3SVladimir Sementsov-Ogievskiy         return 0;
147586f8cdf3SVladimir Sementsov-Ogievskiy     }
147686f8cdf3SVladimir Sementsov-Ogievskiy 
147786f8cdf3SVladimir Sementsov-Ogievskiy     return nbd_co_request(bs, &request, NULL);
147886f8cdf3SVladimir Sementsov-Ogievskiy }
147986f8cdf3SVladimir Sementsov-Ogievskiy 
148086f8cdf3SVladimir Sementsov-Ogievskiy static int coroutine_fn nbd_client_co_block_status(
148186f8cdf3SVladimir Sementsov-Ogievskiy         BlockDriverState *bs, bool want_zero, int64_t offset, int64_t bytes,
148286f8cdf3SVladimir Sementsov-Ogievskiy         int64_t *pnum, int64_t *map, BlockDriverState **file)
148386f8cdf3SVladimir Sementsov-Ogievskiy {
148486f8cdf3SVladimir Sementsov-Ogievskiy     int ret, request_ret;
148586f8cdf3SVladimir Sementsov-Ogievskiy     NBDExtent extent = { 0 };
1486611ae1d7SVladimir Sementsov-Ogievskiy     BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
148786f8cdf3SVladimir Sementsov-Ogievskiy     Error *local_err = NULL;
148886f8cdf3SVladimir Sementsov-Ogievskiy 
148986f8cdf3SVladimir Sementsov-Ogievskiy     NBDRequest request = {
149086f8cdf3SVladimir Sementsov-Ogievskiy         .type = NBD_CMD_BLOCK_STATUS,
149186f8cdf3SVladimir Sementsov-Ogievskiy         .from = offset,
14926bf792b4SVladimir Sementsov-Ogievskiy         .len = MIN(QEMU_ALIGN_DOWN(INT_MAX, bs->bl.request_alignment),
1493611ae1d7SVladimir Sementsov-Ogievskiy                    MIN(bytes, s->info.size - offset)),
149486f8cdf3SVladimir Sementsov-Ogievskiy         .flags = NBD_CMD_FLAG_REQ_ONE,
149586f8cdf3SVladimir Sementsov-Ogievskiy     };
149686f8cdf3SVladimir Sementsov-Ogievskiy 
1497611ae1d7SVladimir Sementsov-Ogievskiy     if (!s->info.base_allocation) {
149886f8cdf3SVladimir Sementsov-Ogievskiy         *pnum = bytes;
149986f8cdf3SVladimir Sementsov-Ogievskiy         *map = offset;
150086f8cdf3SVladimir Sementsov-Ogievskiy         *file = bs;
150186f8cdf3SVladimir Sementsov-Ogievskiy         return BDRV_BLOCK_DATA | BDRV_BLOCK_OFFSET_VALID;
150286f8cdf3SVladimir Sementsov-Ogievskiy     }
150386f8cdf3SVladimir Sementsov-Ogievskiy 
150486f8cdf3SVladimir Sementsov-Ogievskiy     /*
150586f8cdf3SVladimir Sementsov-Ogievskiy      * Work around the fact that the block layer doesn't do
150686f8cdf3SVladimir Sementsov-Ogievskiy      * byte-accurate sizing yet - if the status request exceeds the
150786f8cdf3SVladimir Sementsov-Ogievskiy      * server's advertised size because the block layer rounded size
150886f8cdf3SVladimir Sementsov-Ogievskiy      * up, we truncated the request to the server (above), or are
150986f8cdf3SVladimir Sementsov-Ogievskiy      * called on just the hole.
151086f8cdf3SVladimir Sementsov-Ogievskiy      */
1511611ae1d7SVladimir Sementsov-Ogievskiy     if (offset >= s->info.size) {
151286f8cdf3SVladimir Sementsov-Ogievskiy         *pnum = bytes;
151386f8cdf3SVladimir Sementsov-Ogievskiy         assert(bytes < BDRV_SECTOR_SIZE);
151486f8cdf3SVladimir Sementsov-Ogievskiy         /* Intentionally don't report offset_valid for the hole */
151586f8cdf3SVladimir Sementsov-Ogievskiy         return BDRV_BLOCK_ZERO;
151686f8cdf3SVladimir Sementsov-Ogievskiy     }
151786f8cdf3SVladimir Sementsov-Ogievskiy 
1518611ae1d7SVladimir Sementsov-Ogievskiy     if (s->info.min_block) {
1519611ae1d7SVladimir Sementsov-Ogievskiy         assert(QEMU_IS_ALIGNED(request.len, s->info.min_block));
152086f8cdf3SVladimir Sementsov-Ogievskiy     }
1521f7651539SVladimir Sementsov-Ogievskiy     do {
152286f8cdf3SVladimir Sementsov-Ogievskiy         ret = nbd_co_send_request(bs, &request, NULL);
152386f8cdf3SVladimir Sementsov-Ogievskiy         if (ret < 0) {
1524f7651539SVladimir Sementsov-Ogievskiy             continue;
152586f8cdf3SVladimir Sementsov-Ogievskiy         }
152686f8cdf3SVladimir Sementsov-Ogievskiy 
1527611ae1d7SVladimir Sementsov-Ogievskiy         ret = nbd_co_receive_blockstatus_reply(s, request.handle, bytes,
1528f7651539SVladimir Sementsov-Ogievskiy                                                &extent, &request_ret,
1529f7651539SVladimir Sementsov-Ogievskiy                                                &local_err);
153086f8cdf3SVladimir Sementsov-Ogievskiy         if (local_err) {
153186f8cdf3SVladimir Sementsov-Ogievskiy             trace_nbd_co_request_fail(request.from, request.len, request.handle,
153286f8cdf3SVladimir Sementsov-Ogievskiy                                       request.flags, request.type,
153386f8cdf3SVladimir Sementsov-Ogievskiy                                       nbd_cmd_lookup(request.type),
153486f8cdf3SVladimir Sementsov-Ogievskiy                                       ret, error_get_pretty(local_err));
153586f8cdf3SVladimir Sementsov-Ogievskiy             error_free(local_err);
1536f7651539SVladimir Sementsov-Ogievskiy             local_err = NULL;
153786f8cdf3SVladimir Sementsov-Ogievskiy         }
1538f7651539SVladimir Sementsov-Ogievskiy     } while (ret < 0 && nbd_client_connecting_wait(s));
1539f7651539SVladimir Sementsov-Ogievskiy 
154086f8cdf3SVladimir Sementsov-Ogievskiy     if (ret < 0 || request_ret < 0) {
154186f8cdf3SVladimir Sementsov-Ogievskiy         return ret ? ret : request_ret;
154286f8cdf3SVladimir Sementsov-Ogievskiy     }
154386f8cdf3SVladimir Sementsov-Ogievskiy 
154486f8cdf3SVladimir Sementsov-Ogievskiy     assert(extent.length);
154586f8cdf3SVladimir Sementsov-Ogievskiy     *pnum = extent.length;
154686f8cdf3SVladimir Sementsov-Ogievskiy     *map = offset;
154786f8cdf3SVladimir Sementsov-Ogievskiy     *file = bs;
154886f8cdf3SVladimir Sementsov-Ogievskiy     return (extent.flags & NBD_STATE_HOLE ? 0 : BDRV_BLOCK_DATA) |
154986f8cdf3SVladimir Sementsov-Ogievskiy         (extent.flags & NBD_STATE_ZERO ? BDRV_BLOCK_ZERO : 0) |
155086f8cdf3SVladimir Sementsov-Ogievskiy         BDRV_BLOCK_OFFSET_VALID;
155186f8cdf3SVladimir Sementsov-Ogievskiy }
155286f8cdf3SVladimir Sementsov-Ogievskiy 
1553e99754b4SMaxim Levitsky static int nbd_client_reopen_prepare(BDRVReopenState *state,
1554e99754b4SMaxim Levitsky                                      BlockReopenQueue *queue, Error **errp)
1555e99754b4SMaxim Levitsky {
1556e99754b4SMaxim Levitsky     BDRVNBDState *s = (BDRVNBDState *)state->bs->opaque;
1557e99754b4SMaxim Levitsky 
1558e99754b4SMaxim Levitsky     if ((state->flags & BDRV_O_RDWR) && (s->info.flags & NBD_FLAG_READ_ONLY)) {
1559e99754b4SMaxim Levitsky         error_setg(errp, "Can't reopen read-only NBD mount as read/write");
1560e99754b4SMaxim Levitsky         return -EACCES;
1561e99754b4SMaxim Levitsky     }
1562e99754b4SMaxim Levitsky     return 0;
1563e99754b4SMaxim Levitsky }
1564e99754b4SMaxim Levitsky 
1565fee091cdSLukas Straub static void nbd_yank(void *opaque)
1566fee091cdSLukas Straub {
1567fee091cdSLukas Straub     BlockDriverState *bs = opaque;
1568fee091cdSLukas Straub     BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
1569fee091cdSLukas Straub 
1570fee091cdSLukas Straub     qatomic_store_release(&s->state, NBD_CLIENT_QUIT);
157195a078eaSVladimir Sementsov-Ogievskiy     qio_channel_shutdown(QIO_CHANNEL(s->ioc), QIO_CHANNEL_SHUTDOWN_BOTH, NULL);
1572fee091cdSLukas Straub }
1573fee091cdSLukas Straub 
157486f8cdf3SVladimir Sementsov-Ogievskiy static void nbd_client_close(BlockDriverState *bs)
157586f8cdf3SVladimir Sementsov-Ogievskiy {
1576611ae1d7SVladimir Sementsov-Ogievskiy     BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
157786f8cdf3SVladimir Sementsov-Ogievskiy     NBDRequest request = { .type = NBD_CMD_DISC };
157886f8cdf3SVladimir Sementsov-Ogievskiy 
1579f7651539SVladimir Sementsov-Ogievskiy     if (s->ioc) {
1580611ae1d7SVladimir Sementsov-Ogievskiy         nbd_send_request(s->ioc, &request);
1581f7651539SVladimir Sementsov-Ogievskiy     }
158286f8cdf3SVladimir Sementsov-Ogievskiy 
158386f8cdf3SVladimir Sementsov-Ogievskiy     nbd_teardown_connection(bs);
158486f8cdf3SVladimir Sementsov-Ogievskiy }
158586f8cdf3SVladimir Sementsov-Ogievskiy 
158686f8cdf3SVladimir Sementsov-Ogievskiy 
15878f071c9dSVladimir Sementsov-Ogievskiy /*
15888f071c9dSVladimir Sementsov-Ogievskiy  * Parse nbd_open options
15898f071c9dSVladimir Sementsov-Ogievskiy  */
159086f8cdf3SVladimir Sementsov-Ogievskiy 
1591f53a1febSKevin Wolf static int nbd_parse_uri(const char *filename, QDict *options)
15921d7d2a9dSPaolo Bonzini {
15931d7d2a9dSPaolo Bonzini     URI *uri;
15941d7d2a9dSPaolo Bonzini     const char *p;
15951d7d2a9dSPaolo Bonzini     QueryParams *qp = NULL;
15961d7d2a9dSPaolo Bonzini     int ret = 0;
1597f53a1febSKevin Wolf     bool is_unix;
15981d7d2a9dSPaolo Bonzini 
15991d7d2a9dSPaolo Bonzini     uri = uri_parse(filename);
16001d7d2a9dSPaolo Bonzini     if (!uri) {
16011d7d2a9dSPaolo Bonzini         return -EINVAL;
16021d7d2a9dSPaolo Bonzini     }
16031d7d2a9dSPaolo Bonzini 
16041d7d2a9dSPaolo Bonzini     /* transport */
1605f69165a8SMax Reitz     if (!g_strcmp0(uri->scheme, "nbd")) {
1606f53a1febSKevin Wolf         is_unix = false;
1607f69165a8SMax Reitz     } else if (!g_strcmp0(uri->scheme, "nbd+tcp")) {
1608f53a1febSKevin Wolf         is_unix = false;
1609f69165a8SMax Reitz     } else if (!g_strcmp0(uri->scheme, "nbd+unix")) {
1610f53a1febSKevin Wolf         is_unix = true;
16111d7d2a9dSPaolo Bonzini     } else {
16121d7d2a9dSPaolo Bonzini         ret = -EINVAL;
16131d7d2a9dSPaolo Bonzini         goto out;
16141d7d2a9dSPaolo Bonzini     }
16151d7d2a9dSPaolo Bonzini 
16162485f22fSEric Blake     p = uri->path ? uri->path : "";
16172485f22fSEric Blake     if (p[0] == '/') {
16182485f22fSEric Blake         p++;
16192485f22fSEric Blake     }
16201d7d2a9dSPaolo Bonzini     if (p[0]) {
162146f5ac20SEric Blake         qdict_put_str(options, "export", p);
16221d7d2a9dSPaolo Bonzini     }
16231d7d2a9dSPaolo Bonzini 
16241d7d2a9dSPaolo Bonzini     qp = query_params_parse(uri->query);
1625f53a1febSKevin Wolf     if (qp->n > 1 || (is_unix && !qp->n) || (!is_unix && qp->n)) {
16261d7d2a9dSPaolo Bonzini         ret = -EINVAL;
16271d7d2a9dSPaolo Bonzini         goto out;
16281d7d2a9dSPaolo Bonzini     }
16291d7d2a9dSPaolo Bonzini 
1630f53a1febSKevin Wolf     if (is_unix) {
16311d7d2a9dSPaolo Bonzini         /* nbd+unix:///export?socket=path */
16321d7d2a9dSPaolo Bonzini         if (uri->server || uri->port || strcmp(qp->p[0].name, "socket")) {
16331d7d2a9dSPaolo Bonzini             ret = -EINVAL;
16341d7d2a9dSPaolo Bonzini             goto out;
16351d7d2a9dSPaolo Bonzini         }
163646f5ac20SEric Blake         qdict_put_str(options, "server.type", "unix");
163746f5ac20SEric Blake         qdict_put_str(options, "server.path", qp->p[0].value);
16381d7d2a9dSPaolo Bonzini     } else {
163923307908SJán Tomko         QString *host;
1640f84d431bSMax Reitz         char *port_str;
1641f84d431bSMax Reitz 
1642bebbf7faSKevin Wolf         /* nbd[+tcp]://host[:port]/export */
16431d7d2a9dSPaolo Bonzini         if (!uri->server) {
16441d7d2a9dSPaolo Bonzini             ret = -EINVAL;
16451d7d2a9dSPaolo Bonzini             goto out;
16461d7d2a9dSPaolo Bonzini         }
1647f17c90beSKevin Wolf 
164823307908SJán Tomko         /* strip braces from literal IPv6 address */
164923307908SJán Tomko         if (uri->server[0] == '[') {
165023307908SJán Tomko             host = qstring_from_substr(uri->server, 1,
1651ba891d68SMarkus Armbruster                                        strlen(uri->server) - 1);
165223307908SJán Tomko         } else {
165323307908SJán Tomko             host = qstring_from_str(uri->server);
165423307908SJán Tomko         }
165523307908SJán Tomko 
165646f5ac20SEric Blake         qdict_put_str(options, "server.type", "inet");
16579445673eSMarkus Armbruster         qdict_put(options, "server.host", host);
1658f84d431bSMax Reitz 
1659f84d431bSMax Reitz         port_str = g_strdup_printf("%d", uri->port ?: NBD_DEFAULT_PORT);
166046f5ac20SEric Blake         qdict_put_str(options, "server.port", port_str);
1661f53a1febSKevin Wolf         g_free(port_str);
16621d7d2a9dSPaolo Bonzini     }
16631d7d2a9dSPaolo Bonzini 
16641d7d2a9dSPaolo Bonzini out:
16651d7d2a9dSPaolo Bonzini     if (qp) {
16661d7d2a9dSPaolo Bonzini         query_params_free(qp);
16671d7d2a9dSPaolo Bonzini     }
16681d7d2a9dSPaolo Bonzini     uri_free(uri);
16691d7d2a9dSPaolo Bonzini     return ret;
16701d7d2a9dSPaolo Bonzini }
16711d7d2a9dSPaolo Bonzini 
167248c38e0bSMax Reitz static bool nbd_has_filename_options_conflict(QDict *options, Error **errp)
167348c38e0bSMax Reitz {
167448c38e0bSMax Reitz     const QDictEntry *e;
167548c38e0bSMax Reitz 
167648c38e0bSMax Reitz     for (e = qdict_first(options); e; e = qdict_next(options, e)) {
167748c38e0bSMax Reitz         if (!strcmp(e->key, "host") ||
167848c38e0bSMax Reitz             !strcmp(e->key, "port") ||
167948c38e0bSMax Reitz             !strcmp(e->key, "path") ||
1680491d6c7cSMax Reitz             !strcmp(e->key, "export") ||
1681491d6c7cSMax Reitz             strstart(e->key, "server.", NULL))
168248c38e0bSMax Reitz         {
168348c38e0bSMax Reitz             error_setg(errp, "Option '%s' cannot be used with a file name",
168448c38e0bSMax Reitz                        e->key);
168548c38e0bSMax Reitz             return true;
168648c38e0bSMax Reitz         }
168748c38e0bSMax Reitz     }
168848c38e0bSMax Reitz 
168948c38e0bSMax Reitz     return false;
169048c38e0bSMax Reitz }
169148c38e0bSMax Reitz 
16926963a30dSKevin Wolf static void nbd_parse_filename(const char *filename, QDict *options,
16936963a30dSKevin Wolf                                Error **errp)
1694019d6b8fSAnthony Liguori {
1695df18c04eSEric Blake     g_autofree char *file = NULL;
169633897dc7SNick Thomas     char *export_name;
169733897dc7SNick Thomas     const char *host_spec;
1698019d6b8fSAnthony Liguori     const char *unixpath;
1699019d6b8fSAnthony Liguori 
170048c38e0bSMax Reitz     if (nbd_has_filename_options_conflict(options, errp)) {
1701681e7ad0SKevin Wolf         return;
1702681e7ad0SKevin Wolf     }
1703681e7ad0SKevin Wolf 
17041d7d2a9dSPaolo Bonzini     if (strstr(filename, "://")) {
17056963a30dSKevin Wolf         int ret = nbd_parse_uri(filename, options);
17066963a30dSKevin Wolf         if (ret < 0) {
17076963a30dSKevin Wolf             error_setg(errp, "No valid URL specified");
17086963a30dSKevin Wolf         }
17096963a30dSKevin Wolf         return;
17101d7d2a9dSPaolo Bonzini     }
17111d7d2a9dSPaolo Bonzini 
17127267c094SAnthony Liguori     file = g_strdup(filename);
17131d45f8b5SLaurent Vivier 
171433897dc7SNick Thomas     export_name = strstr(file, EN_OPTSTR);
171533897dc7SNick Thomas     if (export_name) {
171633897dc7SNick Thomas         if (export_name[strlen(EN_OPTSTR)] == 0) {
1717df18c04eSEric Blake             return;
17181d45f8b5SLaurent Vivier         }
171933897dc7SNick Thomas         export_name[0] = 0; /* truncate 'file' */
172033897dc7SNick Thomas         export_name += strlen(EN_OPTSTR);
1721f53a1febSKevin Wolf 
172246f5ac20SEric Blake         qdict_put_str(options, "export", export_name);
17231d45f8b5SLaurent Vivier     }
17241d45f8b5SLaurent Vivier 
172533897dc7SNick Thomas     /* extract the host_spec - fail if it's not nbd:... */
172633897dc7SNick Thomas     if (!strstart(file, "nbd:", &host_spec)) {
17276963a30dSKevin Wolf         error_setg(errp, "File name string for NBD must start with 'nbd:'");
1728df18c04eSEric Blake         return;
17291d45f8b5SLaurent Vivier     }
1730019d6b8fSAnthony Liguori 
1731f53a1febSKevin Wolf     if (!*host_spec) {
1732df18c04eSEric Blake         return;
1733f53a1febSKevin Wolf     }
1734f53a1febSKevin Wolf 
173533897dc7SNick Thomas     /* are we a UNIX or TCP socket? */
173633897dc7SNick Thomas     if (strstart(host_spec, "unix:", &unixpath)) {
173746f5ac20SEric Blake         qdict_put_str(options, "server.type", "unix");
173846f5ac20SEric Blake         qdict_put_str(options, "server.path", unixpath);
1739019d6b8fSAnthony Liguori     } else {
17400785bd7aSMarkus Armbruster         InetSocketAddress *addr = g_new(InetSocketAddress, 1);
1741f53a1febSKevin Wolf 
17420785bd7aSMarkus Armbruster         if (inet_parse(addr, host_spec, errp)) {
17430785bd7aSMarkus Armbruster             goto out_inet;
1744f17c90beSKevin Wolf         }
1745f53a1febSKevin Wolf 
174646f5ac20SEric Blake         qdict_put_str(options, "server.type", "inet");
174746f5ac20SEric Blake         qdict_put_str(options, "server.host", addr->host);
174846f5ac20SEric Blake         qdict_put_str(options, "server.port", addr->port);
17490785bd7aSMarkus Armbruster     out_inet:
1750f53a1febSKevin Wolf         qapi_free_InetSocketAddress(addr);
17511d45f8b5SLaurent Vivier     }
175233897dc7SNick Thomas }
1753f53a1febSKevin Wolf 
1754491d6c7cSMax Reitz static bool nbd_process_legacy_socket_options(QDict *output_options,
1755491d6c7cSMax Reitz                                               QemuOpts *legacy_opts,
1756491d6c7cSMax Reitz                                               Error **errp)
1757f53a1febSKevin Wolf {
1758491d6c7cSMax Reitz     const char *path = qemu_opt_get(legacy_opts, "path");
1759491d6c7cSMax Reitz     const char *host = qemu_opt_get(legacy_opts, "host");
1760491d6c7cSMax Reitz     const char *port = qemu_opt_get(legacy_opts, "port");
1761491d6c7cSMax Reitz     const QDictEntry *e;
1762f53a1febSKevin Wolf 
1763491d6c7cSMax Reitz     if (!path && !host && !port) {
1764491d6c7cSMax Reitz         return true;
1765491d6c7cSMax Reitz     }
176603504d05SMax Reitz 
1767491d6c7cSMax Reitz     for (e = qdict_first(output_options); e; e = qdict_next(output_options, e))
1768491d6c7cSMax Reitz     {
1769491d6c7cSMax Reitz         if (strstart(e->key, "server.", NULL)) {
1770491d6c7cSMax Reitz             error_setg(errp, "Cannot use 'server' and path/host/port at the "
1771491d6c7cSMax Reitz                        "same time");
1772491d6c7cSMax Reitz             return false;
1773491d6c7cSMax Reitz         }
1774491d6c7cSMax Reitz     }
1775491d6c7cSMax Reitz 
1776491d6c7cSMax Reitz     if (path && host) {
177782d73014SMax Reitz         error_setg(errp, "path and host may not be used at the same time");
1778491d6c7cSMax Reitz         return false;
1779491d6c7cSMax Reitz     } else if (path) {
1780491d6c7cSMax Reitz         if (port) {
1781442045cbSMax Reitz             error_setg(errp, "port may not be used without host");
1782491d6c7cSMax Reitz             return false;
1783442045cbSMax Reitz         }
1784019d6b8fSAnthony Liguori 
178546f5ac20SEric Blake         qdict_put_str(output_options, "server.type", "unix");
178646f5ac20SEric Blake         qdict_put_str(output_options, "server.path", path);
1787491d6c7cSMax Reitz     } else if (host) {
178846f5ac20SEric Blake         qdict_put_str(output_options, "server.type", "inet");
178946f5ac20SEric Blake         qdict_put_str(output_options, "server.host", host);
179046f5ac20SEric Blake         qdict_put_str(output_options, "server.port",
179146f5ac20SEric Blake                       port ?: stringify(NBD_DEFAULT_PORT));
17927a5ed437SDaniel P. Berrange     }
1793491d6c7cSMax Reitz 
1794491d6c7cSMax Reitz     return true;
1795491d6c7cSMax Reitz }
1796491d6c7cSMax Reitz 
179762cf396bSMarkus Armbruster static SocketAddress *nbd_config(BDRVNBDState *s, QDict *options,
17989445673eSMarkus Armbruster                                  Error **errp)
1799491d6c7cSMax Reitz {
180062cf396bSMarkus Armbruster     SocketAddress *saddr = NULL;
1801491d6c7cSMax Reitz     QDict *addr = NULL;
1802491d6c7cSMax Reitz     Visitor *iv = NULL;
1803491d6c7cSMax Reitz 
1804491d6c7cSMax Reitz     qdict_extract_subqdict(options, &addr, "server.");
1805491d6c7cSMax Reitz     if (!qdict_size(addr)) {
1806491d6c7cSMax Reitz         error_setg(errp, "NBD server address missing");
1807491d6c7cSMax Reitz         goto done;
1808491d6c7cSMax Reitz     }
1809491d6c7cSMax Reitz 
1810af91062eSMarkus Armbruster     iv = qobject_input_visitor_new_flat_confused(addr, errp);
1811af91062eSMarkus Armbruster     if (!iv) {
1812491d6c7cSMax Reitz         goto done;
1813491d6c7cSMax Reitz     }
1814491d6c7cSMax Reitz 
1815af175e85SMarkus Armbruster     if (!visit_type_SocketAddress(iv, NULL, &saddr, errp)) {
1816491d6c7cSMax Reitz         goto done;
1817f53a1febSKevin Wolf     }
1818f53a1febSKevin Wolf 
18196cc702beSVladimir Sementsov-Ogievskiy     if (socket_address_parse_named_fd(saddr, errp) < 0) {
18206cc702beSVladimir Sementsov-Ogievskiy         qapi_free_SocketAddress(saddr);
18216cc702beSVladimir Sementsov-Ogievskiy         saddr = NULL;
18226cc702beSVladimir Sementsov-Ogievskiy         goto done;
18236cc702beSVladimir Sementsov-Ogievskiy     }
18246cc702beSVladimir Sementsov-Ogievskiy 
1825491d6c7cSMax Reitz done:
1826cb3e7f08SMarc-André Lureau     qobject_unref(addr);
1827491d6c7cSMax Reitz     visit_free(iv);
18287a5ed437SDaniel P. Berrange     return saddr;
1829f53a1febSKevin Wolf }
1830f53a1febSKevin Wolf 
183175822a12SDaniel P. Berrange static QCryptoTLSCreds *nbd_get_tls_creds(const char *id, Error **errp)
183275822a12SDaniel P. Berrange {
183375822a12SDaniel P. Berrange     Object *obj;
183475822a12SDaniel P. Berrange     QCryptoTLSCreds *creds;
183575822a12SDaniel P. Berrange 
183675822a12SDaniel P. Berrange     obj = object_resolve_path_component(
183775822a12SDaniel P. Berrange         object_get_objects_root(), id);
183875822a12SDaniel P. Berrange     if (!obj) {
183975822a12SDaniel P. Berrange         error_setg(errp, "No TLS credentials with id '%s'",
184075822a12SDaniel P. Berrange                    id);
184175822a12SDaniel P. Berrange         return NULL;
184275822a12SDaniel P. Berrange     }
184375822a12SDaniel P. Berrange     creds = (QCryptoTLSCreds *)
184475822a12SDaniel P. Berrange         object_dynamic_cast(obj, TYPE_QCRYPTO_TLS_CREDS);
184575822a12SDaniel P. Berrange     if (!creds) {
184675822a12SDaniel P. Berrange         error_setg(errp, "Object with id '%s' is not TLS credentials",
184775822a12SDaniel P. Berrange                    id);
184875822a12SDaniel P. Berrange         return NULL;
184975822a12SDaniel P. Berrange     }
185075822a12SDaniel P. Berrange 
18517b3b6168SPhilippe Mathieu-Daudé     if (!qcrypto_tls_creds_check_endpoint(creds,
18527b3b6168SPhilippe Mathieu-Daudé                                           QCRYPTO_TLS_CREDS_ENDPOINT_CLIENT,
18537b3b6168SPhilippe Mathieu-Daudé                                           errp)) {
185475822a12SDaniel P. Berrange         return NULL;
185575822a12SDaniel P. Berrange     }
185675822a12SDaniel P. Berrange     object_ref(obj);
185775822a12SDaniel P. Berrange     return creds;
185875822a12SDaniel P. Berrange }
185975822a12SDaniel P. Berrange 
186075822a12SDaniel P. Berrange 
18617ccc44fdSMax Reitz static QemuOptsList nbd_runtime_opts = {
18627ccc44fdSMax Reitz     .name = "nbd",
18637ccc44fdSMax Reitz     .head = QTAILQ_HEAD_INITIALIZER(nbd_runtime_opts.head),
18647ccc44fdSMax Reitz     .desc = {
18657ccc44fdSMax Reitz         {
18667ccc44fdSMax Reitz             .name = "host",
18677ccc44fdSMax Reitz             .type = QEMU_OPT_STRING,
18687ccc44fdSMax Reitz             .help = "TCP host to connect to",
18697ccc44fdSMax Reitz         },
18707ccc44fdSMax Reitz         {
18717ccc44fdSMax Reitz             .name = "port",
18727ccc44fdSMax Reitz             .type = QEMU_OPT_STRING,
18737ccc44fdSMax Reitz             .help = "TCP port to connect to",
18747ccc44fdSMax Reitz         },
18757ccc44fdSMax Reitz         {
18767ccc44fdSMax Reitz             .name = "path",
18777ccc44fdSMax Reitz             .type = QEMU_OPT_STRING,
18787ccc44fdSMax Reitz             .help = "Unix socket path to connect to",
18797ccc44fdSMax Reitz         },
18807ccc44fdSMax Reitz         {
18817ccc44fdSMax Reitz             .name = "export",
18827ccc44fdSMax Reitz             .type = QEMU_OPT_STRING,
18837ccc44fdSMax Reitz             .help = "Name of the NBD export to open",
18847ccc44fdSMax Reitz         },
18857ccc44fdSMax Reitz         {
18867ccc44fdSMax Reitz             .name = "tls-creds",
18877ccc44fdSMax Reitz             .type = QEMU_OPT_STRING,
18887ccc44fdSMax Reitz             .help = "ID of the TLS credentials to use",
18897ccc44fdSMax Reitz         },
1890216ee365SEric Blake         {
1891216ee365SEric Blake             .name = "x-dirty-bitmap",
1892216ee365SEric Blake             .type = QEMU_OPT_STRING,
1893216ee365SEric Blake             .help = "experimental: expose named dirty bitmap in place of "
1894216ee365SEric Blake                     "block status",
1895216ee365SEric Blake         },
1896b172ae2eSVladimir Sementsov-Ogievskiy         {
1897b172ae2eSVladimir Sementsov-Ogievskiy             .name = "reconnect-delay",
1898b172ae2eSVladimir Sementsov-Ogievskiy             .type = QEMU_OPT_NUMBER,
1899b172ae2eSVladimir Sementsov-Ogievskiy             .help = "On an unexpected disconnect, the nbd client tries to "
1900b172ae2eSVladimir Sementsov-Ogievskiy                     "connect again until succeeding or encountering a serious "
1901b172ae2eSVladimir Sementsov-Ogievskiy                     "error.  During the first @reconnect-delay seconds, all "
1902b172ae2eSVladimir Sementsov-Ogievskiy                     "requests are paused and will be rerun on a successful "
1903b172ae2eSVladimir Sementsov-Ogievskiy                     "reconnect. After that time, any delayed requests and all "
1904b172ae2eSVladimir Sementsov-Ogievskiy                     "future requests before a successful reconnect will "
1905b172ae2eSVladimir Sementsov-Ogievskiy                     "immediately fail. Default 0",
1906b172ae2eSVladimir Sementsov-Ogievskiy         },
1907c4365735SMurilo Opsfelder Araujo         { /* end of list */ }
19087ccc44fdSMax Reitz     },
19097ccc44fdSMax Reitz };
19107ccc44fdSMax Reitz 
19118f071c9dSVladimir Sementsov-Ogievskiy static int nbd_process_options(BlockDriverState *bs, QDict *options,
1912015a1036SMax Reitz                                Error **errp)
191333897dc7SNick Thomas {
191433897dc7SNick Thomas     BDRVNBDState *s = bs->opaque;
19158f071c9dSVladimir Sementsov-Ogievskiy     QemuOpts *opts;
191675822a12SDaniel P. Berrange     int ret = -EINVAL;
1917ae255e52SPaolo Bonzini 
19187ccc44fdSMax Reitz     opts = qemu_opts_create(&nbd_runtime_opts, NULL, 0, &error_abort);
1919af175e85SMarkus Armbruster     if (!qemu_opts_absorb_qdict(opts, options, errp)) {
19207ccc44fdSMax Reitz         goto error;
19217ccc44fdSMax Reitz     }
19227ccc44fdSMax Reitz 
192362cf396bSMarkus Armbruster     /* Translate @host, @port, and @path to a SocketAddress */
1924491d6c7cSMax Reitz     if (!nbd_process_legacy_socket_options(options, opts, errp)) {
192575822a12SDaniel P. Berrange         goto error;
192675822a12SDaniel P. Berrange     }
192775822a12SDaniel P. Berrange 
1928491d6c7cSMax Reitz     /* Pop the config into our state object. Exit if invalid. */
1929491d6c7cSMax Reitz     s->saddr = nbd_config(s, options, errp);
1930491d6c7cSMax Reitz     if (!s->saddr) {
1931491d6c7cSMax Reitz         goto error;
1932491d6c7cSMax Reitz     }
1933491d6c7cSMax Reitz 
1934491d6c7cSMax Reitz     s->export = g_strdup(qemu_opt_get(opts, "export"));
193593676c88SEric Blake     if (s->export && strlen(s->export) > NBD_MAX_STRING_SIZE) {
193693676c88SEric Blake         error_setg(errp, "export name too long to send to server");
193793676c88SEric Blake         goto error;
193893676c88SEric Blake     }
1939491d6c7cSMax Reitz 
194003504d05SMax Reitz     s->tlscredsid = g_strdup(qemu_opt_get(opts, "tls-creds"));
194103504d05SMax Reitz     if (s->tlscredsid) {
19428f071c9dSVladimir Sementsov-Ogievskiy         s->tlscreds = nbd_get_tls_creds(s->tlscredsid, errp);
19438f071c9dSVladimir Sementsov-Ogievskiy         if (!s->tlscreds) {
194475822a12SDaniel P. Berrange             goto error;
194575822a12SDaniel P. Berrange         }
194675822a12SDaniel P. Berrange 
1947ca0b64e5SMarkus Armbruster         /* TODO SOCKET_ADDRESS_KIND_FD where fd has AF_INET or AF_INET6 */
194862cf396bSMarkus Armbruster         if (s->saddr->type != SOCKET_ADDRESS_TYPE_INET) {
194975822a12SDaniel P. Berrange             error_setg(errp, "TLS only supported over IP sockets");
195075822a12SDaniel P. Berrange             goto error;
195175822a12SDaniel P. Berrange         }
19528f071c9dSVladimir Sementsov-Ogievskiy         s->hostname = s->saddr->u.inet.host;
195333897dc7SNick Thomas     }
195433897dc7SNick Thomas 
19558f071c9dSVladimir Sementsov-Ogievskiy     s->x_dirty_bitmap = g_strdup(qemu_opt_get(opts, "x-dirty-bitmap"));
195693676c88SEric Blake     if (s->x_dirty_bitmap && strlen(s->x_dirty_bitmap) > NBD_MAX_STRING_SIZE) {
195793676c88SEric Blake         error_setg(errp, "x-dirty-bitmap query too long to send to server");
195893676c88SEric Blake         goto error;
195993676c88SEric Blake     }
196093676c88SEric Blake 
19618f071c9dSVladimir Sementsov-Ogievskiy     s->reconnect_delay = qemu_opt_get_number(opts, "reconnect-delay", 0);
19628f071c9dSVladimir Sementsov-Ogievskiy 
19638f071c9dSVladimir Sementsov-Ogievskiy     ret = 0;
1964d42f78e9SVladimir Sementsov-Ogievskiy 
196575822a12SDaniel P. Berrange  error:
19667ccc44fdSMax Reitz     qemu_opts_del(opts);
196775822a12SDaniel P. Berrange     return ret;
1968ae255e52SPaolo Bonzini }
1969d9b09f13SPaolo Bonzini 
19708f071c9dSVladimir Sementsov-Ogievskiy static int nbd_open(BlockDriverState *bs, QDict *options, int flags,
19718f071c9dSVladimir Sementsov-Ogievskiy                     Error **errp)
19728f071c9dSVladimir Sementsov-Ogievskiy {
19738f071c9dSVladimir Sementsov-Ogievskiy     int ret;
19748f071c9dSVladimir Sementsov-Ogievskiy     BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
19758f071c9dSVladimir Sementsov-Ogievskiy 
19768f071c9dSVladimir Sementsov-Ogievskiy     s->bs = bs;
19778f071c9dSVladimir Sementsov-Ogievskiy     qemu_co_mutex_init(&s->send_mutex);
19788f071c9dSVladimir Sementsov-Ogievskiy     qemu_co_queue_init(&s->free_sema);
19798f071c9dSVladimir Sementsov-Ogievskiy 
1980fee091cdSLukas Straub     if (!yank_register_instance(BLOCKDEV_YANK_INSTANCE(bs->node_name), errp)) {
1981fee091cdSLukas Straub         return -EEXIST;
1982fee091cdSLukas Straub     }
1983fee091cdSLukas Straub 
1984bbba1c37SVladimir Sementsov-Ogievskiy     ret = nbd_process_options(bs, options, errp);
1985bbba1c37SVladimir Sementsov-Ogievskiy     if (ret < 0) {
1986bbba1c37SVladimir Sementsov-Ogievskiy         goto fail;
1987bbba1c37SVladimir Sementsov-Ogievskiy     }
1988bbba1c37SVladimir Sementsov-Ogievskiy 
19896d2b0332SVladimir Sementsov-Ogievskiy     s->conn = nbd_client_connection_new(s->saddr, true, s->export,
19906d2b0332SVladimir Sementsov-Ogievskiy                                         s->x_dirty_bitmap, s->tlscreds);
1991e8b35bf5SRoman Kagan 
1992a71d597bSVladimir Sementsov-Ogievskiy     /* TODO: Configurable retry-until-timeout behaviour. */
1993a71d597bSVladimir Sementsov-Ogievskiy     ret = nbd_do_establish_connection(bs, errp);
19948f071c9dSVladimir Sementsov-Ogievskiy     if (ret < 0) {
1995bbba1c37SVladimir Sementsov-Ogievskiy         goto fail;
19968f071c9dSVladimir Sementsov-Ogievskiy     }
19978f071c9dSVladimir Sementsov-Ogievskiy 
19988f071c9dSVladimir Sementsov-Ogievskiy     s->connection_co = qemu_coroutine_create(nbd_connection_entry, s);
19998f071c9dSVladimir Sementsov-Ogievskiy     bdrv_inc_in_flight(bs);
20008f071c9dSVladimir Sementsov-Ogievskiy     aio_co_schedule(bdrv_get_aio_context(bs), s->connection_co);
20018f071c9dSVladimir Sementsov-Ogievskiy 
20028f071c9dSVladimir Sementsov-Ogievskiy     return 0;
2003bbba1c37SVladimir Sementsov-Ogievskiy 
2004bbba1c37SVladimir Sementsov-Ogievskiy fail:
2005bbba1c37SVladimir Sementsov-Ogievskiy     nbd_clear_bdrvstate(bs);
2006bbba1c37SVladimir Sementsov-Ogievskiy     return ret;
20078f071c9dSVladimir Sementsov-Ogievskiy }
20088f071c9dSVladimir Sementsov-Ogievskiy 
20091486d04aSPaolo Bonzini static int nbd_co_flush(BlockDriverState *bs)
20101486d04aSPaolo Bonzini {
2011f53a829bSMax Reitz     return nbd_client_co_flush(bs);
20121486d04aSPaolo Bonzini }
20131486d04aSPaolo Bonzini 
2014fa21e6faSDenis V. Lunev static void nbd_refresh_limits(BlockDriverState *bs, Error **errp)
2015fa21e6faSDenis V. Lunev {
2016611ae1d7SVladimir Sementsov-Ogievskiy     BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
2017fd8d372dSEric Blake     uint32_t min = s->info.min_block;
2018081dd1feSEric Blake     uint32_t max = MIN_NON_ZERO(NBD_MAX_BUFFER_SIZE, s->info.max_block);
2019081dd1feSEric Blake 
20207da537f7SEric Blake     /*
20217da537f7SEric Blake      * If the server did not advertise an alignment:
20227da537f7SEric Blake      * - a size that is not sector-aligned implies that an alignment
20237da537f7SEric Blake      *   of 1 can be used to access those tail bytes
20247da537f7SEric Blake      * - advertisement of block status requires an alignment of 1, so
20257da537f7SEric Blake      *   that we don't violate block layer constraints that block
20267da537f7SEric Blake      *   status is always aligned (as we can't control whether the
20277da537f7SEric Blake      *   server will report sub-sector extents, such as a hole at EOF
20287da537f7SEric Blake      *   on an unaligned POSIX file)
20297da537f7SEric Blake      * - otherwise, assume the server is so old that we are safer avoiding
20307da537f7SEric Blake      *   sub-sector requests
20317da537f7SEric Blake      */
20327da537f7SEric Blake     if (!min) {
20337da537f7SEric Blake         min = (!QEMU_IS_ALIGNED(s->info.size, BDRV_SECTOR_SIZE) ||
20347da537f7SEric Blake                s->info.base_allocation) ? 1 : BDRV_SECTOR_SIZE;
20357da537f7SEric Blake     }
20367da537f7SEric Blake 
20377da537f7SEric Blake     bs->bl.request_alignment = min;
2038714eb0dbSVladimir Sementsov-Ogievskiy     bs->bl.max_pdiscard = QEMU_ALIGN_DOWN(INT_MAX, min);
2039081dd1feSEric Blake     bs->bl.max_pwrite_zeroes = max;
2040081dd1feSEric Blake     bs->bl.max_transfer = max;
2041081dd1feSEric Blake 
2042081dd1feSEric Blake     if (s->info.opt_block &&
2043081dd1feSEric Blake         s->info.opt_block > bs->bl.opt_transfer) {
2044081dd1feSEric Blake         bs->bl.opt_transfer = s->info.opt_block;
2045081dd1feSEric Blake     }
2046fa21e6faSDenis V. Lunev }
2047fa21e6faSDenis V. Lunev 
2048019d6b8fSAnthony Liguori static void nbd_close(BlockDriverState *bs)
2049019d6b8fSAnthony Liguori {
2050f53a829bSMax Reitz     nbd_client_close(bs);
2051bbba1c37SVladimir Sementsov-Ogievskiy     nbd_clear_bdrvstate(bs);
2052019d6b8fSAnthony Liguori }
2053019d6b8fSAnthony Liguori 
2054a2b333c0SNir Soffer /*
2055a2b333c0SNir Soffer  * NBD cannot truncate, but if the caller asks to truncate to the same size, or
2056a2b333c0SNir Soffer  * to a smaller size with exact=false, there is no reason to fail the
2057a2b333c0SNir Soffer  * operation.
2058a2b333c0SNir Soffer  *
2059a2b333c0SNir Soffer  * Preallocation mode is ignored since it does not seems useful to fail when
2060a2b333c0SNir Soffer  * we never change anything.
2061a2b333c0SNir Soffer  */
2062a2b333c0SNir Soffer static int coroutine_fn nbd_co_truncate(BlockDriverState *bs, int64_t offset,
2063a2b333c0SNir Soffer                                         bool exact, PreallocMode prealloc,
2064a2b333c0SNir Soffer                                         BdrvRequestFlags flags, Error **errp)
2065a2b333c0SNir Soffer {
2066a2b333c0SNir Soffer     BDRVNBDState *s = bs->opaque;
2067a2b333c0SNir Soffer 
2068a2b333c0SNir Soffer     if (offset != s->info.size && exact) {
2069a2b333c0SNir Soffer         error_setg(errp, "Cannot resize NBD nodes");
2070a2b333c0SNir Soffer         return -ENOTSUP;
2071a2b333c0SNir Soffer     }
2072a2b333c0SNir Soffer 
2073a2b333c0SNir Soffer     if (offset > s->info.size) {
2074a2b333c0SNir Soffer         error_setg(errp, "Cannot grow NBD nodes");
2075a2b333c0SNir Soffer         return -EINVAL;
2076a2b333c0SNir Soffer     }
2077a2b333c0SNir Soffer 
2078a2b333c0SNir Soffer     return 0;
2079a2b333c0SNir Soffer }
2080a2b333c0SNir Soffer 
2081019d6b8fSAnthony Liguori static int64_t nbd_getlength(BlockDriverState *bs)
2082019d6b8fSAnthony Liguori {
2083019d6b8fSAnthony Liguori     BDRVNBDState *s = bs->opaque;
2084019d6b8fSAnthony Liguori 
2085611ae1d7SVladimir Sementsov-Ogievskiy     return s->info.size;
2086019d6b8fSAnthony Liguori }
2087019d6b8fSAnthony Liguori 
2088998b3a1eSMax Reitz static void nbd_refresh_filename(BlockDriverState *bs)
20892019d68bSMax Reitz {
209003504d05SMax Reitz     BDRVNBDState *s = bs->opaque;
2091491d6c7cSMax Reitz     const char *host = NULL, *port = NULL, *path = NULL;
20925c86bdf1SEric Blake     size_t len = 0;
2093491d6c7cSMax Reitz 
209462cf396bSMarkus Armbruster     if (s->saddr->type == SOCKET_ADDRESS_TYPE_INET) {
20959445673eSMarkus Armbruster         const InetSocketAddress *inet = &s->saddr->u.inet;
2096491d6c7cSMax Reitz         if (!inet->has_ipv4 && !inet->has_ipv6 && !inet->has_to) {
2097491d6c7cSMax Reitz             host = inet->host;
2098491d6c7cSMax Reitz             port = inet->port;
2099491d6c7cSMax Reitz         }
210062cf396bSMarkus Armbruster     } else if (s->saddr->type == SOCKET_ADDRESS_TYPE_UNIX) {
21019445673eSMarkus Armbruster         path = s->saddr->u.q_unix.path;
21029445673eSMarkus Armbruster     } /* else can't represent as pseudo-filename */
21032019d68bSMax Reitz 
2104491d6c7cSMax Reitz     if (path && s->export) {
21055c86bdf1SEric Blake         len = snprintf(bs->exact_filename, sizeof(bs->exact_filename),
2106491d6c7cSMax Reitz                        "nbd+unix:///%s?socket=%s", s->export, path);
2107491d6c7cSMax Reitz     } else if (path && !s->export) {
21085c86bdf1SEric Blake         len = snprintf(bs->exact_filename, sizeof(bs->exact_filename),
2109491d6c7cSMax Reitz                        "nbd+unix://?socket=%s", path);
2110491d6c7cSMax Reitz     } else if (host && s->export) {
21115c86bdf1SEric Blake         len = snprintf(bs->exact_filename, sizeof(bs->exact_filename),
2112491d6c7cSMax Reitz                        "nbd://%s:%s/%s", host, port, s->export);
2113491d6c7cSMax Reitz     } else if (host && !s->export) {
21145c86bdf1SEric Blake         len = snprintf(bs->exact_filename, sizeof(bs->exact_filename),
2115491d6c7cSMax Reitz                        "nbd://%s:%s", host, port);
2116ec0de768SMax Reitz     }
211700d69986SEric Blake     if (len >= sizeof(bs->exact_filename)) {
21185c86bdf1SEric Blake         /* Name is too long to represent exactly, so leave it empty. */
21195c86bdf1SEric Blake         bs->exact_filename[0] = '\0';
21205c86bdf1SEric Blake     }
21212019d68bSMax Reitz }
21222019d68bSMax Reitz 
21238a6239c0SMax Reitz static char *nbd_dirname(BlockDriverState *bs, Error **errp)
21248a6239c0SMax Reitz {
21258a6239c0SMax Reitz     /* The generic bdrv_dirname() implementation is able to work out some
21268a6239c0SMax Reitz      * directory name for NBD nodes, but that would be wrong. So far there is no
21278a6239c0SMax Reitz      * specification for how "export paths" would work, so NBD does not have
21288a6239c0SMax Reitz      * directory names. */
21298a6239c0SMax Reitz     error_setg(errp, "Cannot generate a base directory for NBD nodes");
21308a6239c0SMax Reitz     return NULL;
21318a6239c0SMax Reitz }
21328a6239c0SMax Reitz 
21332654267cSMax Reitz static const char *const nbd_strong_runtime_opts[] = {
21342654267cSMax Reitz     "path",
21352654267cSMax Reitz     "host",
21362654267cSMax Reitz     "port",
21372654267cSMax Reitz     "export",
21382654267cSMax Reitz     "tls-creds",
21392654267cSMax Reitz     "server.",
21402654267cSMax Reitz 
21412654267cSMax Reitz     NULL
21422654267cSMax Reitz };
21432654267cSMax Reitz 
2144c4f7f24eSVladimir Sementsov-Ogievskiy static void nbd_cancel_in_flight(BlockDriverState *bs)
2145c4f7f24eSVladimir Sementsov-Ogievskiy {
2146c4f7f24eSVladimir Sementsov-Ogievskiy     BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
2147c4f7f24eSVladimir Sementsov-Ogievskiy 
2148c4f7f24eSVladimir Sementsov-Ogievskiy     reconnect_delay_timer_del(s);
2149c4f7f24eSVladimir Sementsov-Ogievskiy 
2150c4f7f24eSVladimir Sementsov-Ogievskiy     if (s->state == NBD_CLIENT_CONNECTING_WAIT) {
2151c4f7f24eSVladimir Sementsov-Ogievskiy         s->state = NBD_CLIENT_CONNECTING_NOWAIT;
2152c4f7f24eSVladimir Sementsov-Ogievskiy         qemu_co_queue_restart_all(&s->free_sema);
2153c4f7f24eSVladimir Sementsov-Ogievskiy     }
2154c4f7f24eSVladimir Sementsov-Ogievskiy }
2155c4f7f24eSVladimir Sementsov-Ogievskiy 
2156019d6b8fSAnthony Liguori static BlockDriver bdrv_nbd = {
2157019d6b8fSAnthony Liguori     .format_name                = "nbd",
21581d7d2a9dSPaolo Bonzini     .protocol_name              = "nbd",
2159019d6b8fSAnthony Liguori     .instance_size              = sizeof(BDRVNBDState),
21606963a30dSKevin Wolf     .bdrv_parse_filename        = nbd_parse_filename,
21615a5e7f8cSMaxim Levitsky     .bdrv_co_create_opts        = bdrv_co_create_opts_simple,
21625a5e7f8cSMaxim Levitsky     .create_opts                = &bdrv_create_opts_simple,
216366f82ceeSKevin Wolf     .bdrv_file_open             = nbd_open,
2164e99754b4SMaxim Levitsky     .bdrv_reopen_prepare        = nbd_client_reopen_prepare,
216570c4fb26SEric Blake     .bdrv_co_preadv             = nbd_client_co_preadv,
216670c4fb26SEric Blake     .bdrv_co_pwritev            = nbd_client_co_pwritev,
2167fa778fffSEric Blake     .bdrv_co_pwrite_zeroes      = nbd_client_co_pwrite_zeroes,
2168019d6b8fSAnthony Liguori     .bdrv_close                 = nbd_close,
21691486d04aSPaolo Bonzini     .bdrv_co_flush_to_os        = nbd_co_flush,
2170447e57c3SEric Blake     .bdrv_co_pdiscard           = nbd_client_co_pdiscard,
2171fa21e6faSDenis V. Lunev     .bdrv_refresh_limits        = nbd_refresh_limits,
2172a2b333c0SNir Soffer     .bdrv_co_truncate           = nbd_co_truncate,
2173019d6b8fSAnthony Liguori     .bdrv_getlength             = nbd_getlength,
217486f8cdf3SVladimir Sementsov-Ogievskiy     .bdrv_detach_aio_context    = nbd_client_detach_aio_context,
217586f8cdf3SVladimir Sementsov-Ogievskiy     .bdrv_attach_aio_context    = nbd_client_attach_aio_context,
2176f7651539SVladimir Sementsov-Ogievskiy     .bdrv_co_drain_begin        = nbd_client_co_drain_begin,
2177f7651539SVladimir Sementsov-Ogievskiy     .bdrv_co_drain_end          = nbd_client_co_drain_end,
21782019d68bSMax Reitz     .bdrv_refresh_filename      = nbd_refresh_filename,
217978a33ab5SVladimir Sementsov-Ogievskiy     .bdrv_co_block_status       = nbd_client_co_block_status,
21808a6239c0SMax Reitz     .bdrv_dirname               = nbd_dirname,
21812654267cSMax Reitz     .strong_runtime_opts        = nbd_strong_runtime_opts,
2182c4f7f24eSVladimir Sementsov-Ogievskiy     .bdrv_cancel_in_flight      = nbd_cancel_in_flight,
21831d7d2a9dSPaolo Bonzini };
21841d7d2a9dSPaolo Bonzini 
21851d7d2a9dSPaolo Bonzini static BlockDriver bdrv_nbd_tcp = {
21861d7d2a9dSPaolo Bonzini     .format_name                = "nbd",
21871d7d2a9dSPaolo Bonzini     .protocol_name              = "nbd+tcp",
21881d7d2a9dSPaolo Bonzini     .instance_size              = sizeof(BDRVNBDState),
21896963a30dSKevin Wolf     .bdrv_parse_filename        = nbd_parse_filename,
21905a5e7f8cSMaxim Levitsky     .bdrv_co_create_opts        = bdrv_co_create_opts_simple,
21915a5e7f8cSMaxim Levitsky     .create_opts                = &bdrv_create_opts_simple,
21921d7d2a9dSPaolo Bonzini     .bdrv_file_open             = nbd_open,
2193e99754b4SMaxim Levitsky     .bdrv_reopen_prepare        = nbd_client_reopen_prepare,
219470c4fb26SEric Blake     .bdrv_co_preadv             = nbd_client_co_preadv,
219570c4fb26SEric Blake     .bdrv_co_pwritev            = nbd_client_co_pwritev,
2196fa778fffSEric Blake     .bdrv_co_pwrite_zeroes      = nbd_client_co_pwrite_zeroes,
21971d7d2a9dSPaolo Bonzini     .bdrv_close                 = nbd_close,
21981d7d2a9dSPaolo Bonzini     .bdrv_co_flush_to_os        = nbd_co_flush,
2199447e57c3SEric Blake     .bdrv_co_pdiscard           = nbd_client_co_pdiscard,
2200fa21e6faSDenis V. Lunev     .bdrv_refresh_limits        = nbd_refresh_limits,
2201a2b333c0SNir Soffer     .bdrv_co_truncate           = nbd_co_truncate,
22021d7d2a9dSPaolo Bonzini     .bdrv_getlength             = nbd_getlength,
220386f8cdf3SVladimir Sementsov-Ogievskiy     .bdrv_detach_aio_context    = nbd_client_detach_aio_context,
220486f8cdf3SVladimir Sementsov-Ogievskiy     .bdrv_attach_aio_context    = nbd_client_attach_aio_context,
2205f7651539SVladimir Sementsov-Ogievskiy     .bdrv_co_drain_begin        = nbd_client_co_drain_begin,
2206f7651539SVladimir Sementsov-Ogievskiy     .bdrv_co_drain_end          = nbd_client_co_drain_end,
22072019d68bSMax Reitz     .bdrv_refresh_filename      = nbd_refresh_filename,
220878a33ab5SVladimir Sementsov-Ogievskiy     .bdrv_co_block_status       = nbd_client_co_block_status,
22098a6239c0SMax Reitz     .bdrv_dirname               = nbd_dirname,
22102654267cSMax Reitz     .strong_runtime_opts        = nbd_strong_runtime_opts,
2211c4f7f24eSVladimir Sementsov-Ogievskiy     .bdrv_cancel_in_flight      = nbd_cancel_in_flight,
22121d7d2a9dSPaolo Bonzini };
22131d7d2a9dSPaolo Bonzini 
22141d7d2a9dSPaolo Bonzini static BlockDriver bdrv_nbd_unix = {
22151d7d2a9dSPaolo Bonzini     .format_name                = "nbd",
22161d7d2a9dSPaolo Bonzini     .protocol_name              = "nbd+unix",
22171d7d2a9dSPaolo Bonzini     .instance_size              = sizeof(BDRVNBDState),
22186963a30dSKevin Wolf     .bdrv_parse_filename        = nbd_parse_filename,
22195a5e7f8cSMaxim Levitsky     .bdrv_co_create_opts        = bdrv_co_create_opts_simple,
22205a5e7f8cSMaxim Levitsky     .create_opts                = &bdrv_create_opts_simple,
22211d7d2a9dSPaolo Bonzini     .bdrv_file_open             = nbd_open,
2222e99754b4SMaxim Levitsky     .bdrv_reopen_prepare        = nbd_client_reopen_prepare,
222370c4fb26SEric Blake     .bdrv_co_preadv             = nbd_client_co_preadv,
222470c4fb26SEric Blake     .bdrv_co_pwritev            = nbd_client_co_pwritev,
2225fa778fffSEric Blake     .bdrv_co_pwrite_zeroes      = nbd_client_co_pwrite_zeroes,
22261d7d2a9dSPaolo Bonzini     .bdrv_close                 = nbd_close,
22271d7d2a9dSPaolo Bonzini     .bdrv_co_flush_to_os        = nbd_co_flush,
2228447e57c3SEric Blake     .bdrv_co_pdiscard           = nbd_client_co_pdiscard,
2229fa21e6faSDenis V. Lunev     .bdrv_refresh_limits        = nbd_refresh_limits,
2230a2b333c0SNir Soffer     .bdrv_co_truncate           = nbd_co_truncate,
22311d7d2a9dSPaolo Bonzini     .bdrv_getlength             = nbd_getlength,
223286f8cdf3SVladimir Sementsov-Ogievskiy     .bdrv_detach_aio_context    = nbd_client_detach_aio_context,
223386f8cdf3SVladimir Sementsov-Ogievskiy     .bdrv_attach_aio_context    = nbd_client_attach_aio_context,
2234f7651539SVladimir Sementsov-Ogievskiy     .bdrv_co_drain_begin        = nbd_client_co_drain_begin,
2235f7651539SVladimir Sementsov-Ogievskiy     .bdrv_co_drain_end          = nbd_client_co_drain_end,
22362019d68bSMax Reitz     .bdrv_refresh_filename      = nbd_refresh_filename,
223778a33ab5SVladimir Sementsov-Ogievskiy     .bdrv_co_block_status       = nbd_client_co_block_status,
22388a6239c0SMax Reitz     .bdrv_dirname               = nbd_dirname,
22392654267cSMax Reitz     .strong_runtime_opts        = nbd_strong_runtime_opts,
2240c4f7f24eSVladimir Sementsov-Ogievskiy     .bdrv_cancel_in_flight      = nbd_cancel_in_flight,
2241019d6b8fSAnthony Liguori };
2242019d6b8fSAnthony Liguori 
2243019d6b8fSAnthony Liguori static void bdrv_nbd_init(void)
2244019d6b8fSAnthony Liguori {
2245019d6b8fSAnthony Liguori     bdrv_register(&bdrv_nbd);
22461d7d2a9dSPaolo Bonzini     bdrv_register(&bdrv_nbd_tcp);
22471d7d2a9dSPaolo Bonzini     bdrv_register(&bdrv_nbd_unix);
2248019d6b8fSAnthony Liguori }
2249019d6b8fSAnthony Liguori 
2250019d6b8fSAnthony Liguori block_init(bdrv_nbd_init);
2251