xref: /openbmc/qemu/block/nbd.c (revision 46f56631)
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"
38019d6b8fSAnthony Liguori 
3986f8cdf3SVladimir Sementsov-Ogievskiy #include "qapi/qapi-visit-sockets.h"
4086f8cdf3SVladimir Sementsov-Ogievskiy #include "qapi/qmp/qstring.h"
411dc4718dSVladimir Sementsov-Ogievskiy #include "qapi/clone-visitor.h"
4286f8cdf3SVladimir Sementsov-Ogievskiy 
4386f8cdf3SVladimir Sementsov-Ogievskiy #include "block/qdict.h"
4486f8cdf3SVladimir Sementsov-Ogievskiy #include "block/nbd.h"
4586f8cdf3SVladimir Sementsov-Ogievskiy #include "block/block_int.h"
4686f8cdf3SVladimir Sementsov-Ogievskiy 
471d45f8b5SLaurent Vivier #define EN_OPTSTR ":exportname="
4886f8cdf3SVladimir Sementsov-Ogievskiy #define MAX_NBD_REQUESTS    16
4986f8cdf3SVladimir Sementsov-Ogievskiy 
5086f8cdf3SVladimir Sementsov-Ogievskiy #define HANDLE_TO_INDEX(bs, handle) ((handle) ^ (uint64_t)(intptr_t)(bs))
5186f8cdf3SVladimir Sementsov-Ogievskiy #define INDEX_TO_HANDLE(bs, index)  ((index)  ^ (uint64_t)(intptr_t)(bs))
5286f8cdf3SVladimir Sementsov-Ogievskiy 
5386f8cdf3SVladimir Sementsov-Ogievskiy typedef struct {
5486f8cdf3SVladimir Sementsov-Ogievskiy     Coroutine *coroutine;
5586f8cdf3SVladimir Sementsov-Ogievskiy     uint64_t offset;        /* original offset of the request */
5686f8cdf3SVladimir Sementsov-Ogievskiy     bool receiving;         /* waiting for connection_co? */
5786f8cdf3SVladimir Sementsov-Ogievskiy } NBDClientRequest;
5886f8cdf3SVladimir Sementsov-Ogievskiy 
59a34b1e5eSVladimir Sementsov-Ogievskiy typedef enum NBDClientState {
60f7651539SVladimir Sementsov-Ogievskiy     NBD_CLIENT_CONNECTING_WAIT,
61f7651539SVladimir Sementsov-Ogievskiy     NBD_CLIENT_CONNECTING_NOWAIT,
62a34b1e5eSVladimir Sementsov-Ogievskiy     NBD_CLIENT_CONNECTED,
63a34b1e5eSVladimir Sementsov-Ogievskiy     NBD_CLIENT_QUIT
64a34b1e5eSVladimir Sementsov-Ogievskiy } NBDClientState;
65a34b1e5eSVladimir Sementsov-Ogievskiy 
661dc4718dSVladimir Sementsov-Ogievskiy typedef enum NBDConnectThreadState {
671dc4718dSVladimir Sementsov-Ogievskiy     /* No thread, no pending results */
681dc4718dSVladimir Sementsov-Ogievskiy     CONNECT_THREAD_NONE,
691dc4718dSVladimir Sementsov-Ogievskiy 
701dc4718dSVladimir Sementsov-Ogievskiy     /* Thread is running, no results for now */
711dc4718dSVladimir Sementsov-Ogievskiy     CONNECT_THREAD_RUNNING,
721dc4718dSVladimir Sementsov-Ogievskiy 
731dc4718dSVladimir Sementsov-Ogievskiy     /*
741dc4718dSVladimir Sementsov-Ogievskiy      * Thread is running, but requestor exited. Thread should close
751dc4718dSVladimir Sementsov-Ogievskiy      * the new socket and free the connect state on exit.
761dc4718dSVladimir Sementsov-Ogievskiy      */
771dc4718dSVladimir Sementsov-Ogievskiy     CONNECT_THREAD_RUNNING_DETACHED,
781dc4718dSVladimir Sementsov-Ogievskiy 
791dc4718dSVladimir Sementsov-Ogievskiy     /* Thread finished, results are stored in a state */
801dc4718dSVladimir Sementsov-Ogievskiy     CONNECT_THREAD_FAIL,
811dc4718dSVladimir Sementsov-Ogievskiy     CONNECT_THREAD_SUCCESS
821dc4718dSVladimir Sementsov-Ogievskiy } NBDConnectThreadState;
831dc4718dSVladimir Sementsov-Ogievskiy 
841dc4718dSVladimir Sementsov-Ogievskiy typedef struct NBDConnectThread {
851dc4718dSVladimir Sementsov-Ogievskiy     /* Initialization constants */
861dc4718dSVladimir Sementsov-Ogievskiy     SocketAddress *saddr; /* address to connect to */
871dc4718dSVladimir Sementsov-Ogievskiy     /*
881dc4718dSVladimir Sementsov-Ogievskiy      * Bottom half to schedule on completion. Scheduled only if bh_ctx is not
891dc4718dSVladimir Sementsov-Ogievskiy      * NULL
901dc4718dSVladimir Sementsov-Ogievskiy      */
911dc4718dSVladimir Sementsov-Ogievskiy     QEMUBHFunc *bh_func;
921dc4718dSVladimir Sementsov-Ogievskiy     void *bh_opaque;
931dc4718dSVladimir Sementsov-Ogievskiy 
941dc4718dSVladimir Sementsov-Ogievskiy     /*
951dc4718dSVladimir Sementsov-Ogievskiy      * Result of last attempt. Valid in FAIL and SUCCESS states.
961dc4718dSVladimir Sementsov-Ogievskiy      * If you want to steal error, don't forget to set pointer to NULL.
971dc4718dSVladimir Sementsov-Ogievskiy      */
981dc4718dSVladimir Sementsov-Ogievskiy     QIOChannelSocket *sioc;
991dc4718dSVladimir Sementsov-Ogievskiy     Error *err;
1001dc4718dSVladimir Sementsov-Ogievskiy 
1011dc4718dSVladimir Sementsov-Ogievskiy     /* state and bh_ctx are protected by mutex */
1021dc4718dSVladimir Sementsov-Ogievskiy     QemuMutex mutex;
1031dc4718dSVladimir Sementsov-Ogievskiy     NBDConnectThreadState state; /* current state of the thread */
1041dc4718dSVladimir Sementsov-Ogievskiy     AioContext *bh_ctx; /* where to schedule bh (NULL means don't schedule) */
1051dc4718dSVladimir Sementsov-Ogievskiy } NBDConnectThread;
1061dc4718dSVladimir Sementsov-Ogievskiy 
107611ae1d7SVladimir Sementsov-Ogievskiy typedef struct BDRVNBDState {
10886f8cdf3SVladimir Sementsov-Ogievskiy     QIOChannelSocket *sioc; /* The master data channel */
10986f8cdf3SVladimir Sementsov-Ogievskiy     QIOChannel *ioc; /* The current I/O channel which may differ (eg TLS) */
11086f8cdf3SVladimir Sementsov-Ogievskiy     NBDExportInfo info;
11186f8cdf3SVladimir Sementsov-Ogievskiy 
11286f8cdf3SVladimir Sementsov-Ogievskiy     CoMutex send_mutex;
11386f8cdf3SVladimir Sementsov-Ogievskiy     CoQueue free_sema;
11486f8cdf3SVladimir Sementsov-Ogievskiy     Coroutine *connection_co;
11578c81a3fSMax Reitz     Coroutine *teardown_co;
116f7651539SVladimir Sementsov-Ogievskiy     QemuCoSleepState *connection_co_sleep_ns_state;
117f7651539SVladimir Sementsov-Ogievskiy     bool drained;
118f7651539SVladimir Sementsov-Ogievskiy     bool wait_drained_end;
11986f8cdf3SVladimir Sementsov-Ogievskiy     int in_flight;
120a34b1e5eSVladimir Sementsov-Ogievskiy     NBDClientState state;
121f7651539SVladimir Sementsov-Ogievskiy     int connect_status;
122f7651539SVladimir Sementsov-Ogievskiy     Error *connect_err;
123f7651539SVladimir Sementsov-Ogievskiy     bool wait_in_flight;
12486f8cdf3SVladimir Sementsov-Ogievskiy 
125*46f56631SVladimir Sementsov-Ogievskiy     QEMUTimer *reconnect_delay_timer;
126*46f56631SVladimir Sementsov-Ogievskiy 
12786f8cdf3SVladimir Sementsov-Ogievskiy     NBDClientRequest requests[MAX_NBD_REQUESTS];
12886f8cdf3SVladimir Sementsov-Ogievskiy     NBDReply reply;
12986f8cdf3SVladimir Sementsov-Ogievskiy     BlockDriverState *bs;
13003504d05SMax Reitz 
1318f071c9dSVladimir Sementsov-Ogievskiy     /* Connection parameters */
1328f071c9dSVladimir Sementsov-Ogievskiy     uint32_t reconnect_delay;
13362cf396bSMarkus Armbruster     SocketAddress *saddr;
134491d6c7cSMax Reitz     char *export, *tlscredsid;
1358f071c9dSVladimir Sementsov-Ogievskiy     QCryptoTLSCreds *tlscreds;
1368f071c9dSVladimir Sementsov-Ogievskiy     const char *hostname;
1378f071c9dSVladimir Sementsov-Ogievskiy     char *x_dirty_bitmap;
1381dc4718dSVladimir Sementsov-Ogievskiy 
1391dc4718dSVladimir Sementsov-Ogievskiy     bool wait_connect;
1401dc4718dSVladimir Sementsov-Ogievskiy     NBDConnectThread *connect_thread;
141019d6b8fSAnthony Liguori } BDRVNBDState;
142019d6b8fSAnthony Liguori 
143fa35591bSVladimir Sementsov-Ogievskiy static QIOChannelSocket *nbd_establish_connection(SocketAddress *saddr,
144fa35591bSVladimir Sementsov-Ogievskiy                                                   Error **errp);
1451dc4718dSVladimir Sementsov-Ogievskiy static QIOChannelSocket *nbd_co_establish_connection(BlockDriverState *bs,
1461dc4718dSVladimir Sementsov-Ogievskiy                                                      Error **errp);
1471dc4718dSVladimir Sementsov-Ogievskiy static void nbd_co_establish_connection_cancel(BlockDriverState *bs,
1481dc4718dSVladimir Sementsov-Ogievskiy                                                bool detach);
149fa35591bSVladimir Sementsov-Ogievskiy static int nbd_client_handshake(BlockDriverState *bs, QIOChannelSocket *sioc,
150fa35591bSVladimir Sementsov-Ogievskiy                                 Error **errp);
151f7651539SVladimir Sementsov-Ogievskiy 
1527f493662SPan Nengyuan static void nbd_clear_bdrvstate(BDRVNBDState *s)
1537f493662SPan Nengyuan {
1547f493662SPan Nengyuan     object_unref(OBJECT(s->tlscreds));
1557f493662SPan Nengyuan     qapi_free_SocketAddress(s->saddr);
1567f493662SPan Nengyuan     s->saddr = NULL;
1577f493662SPan Nengyuan     g_free(s->export);
1587f493662SPan Nengyuan     s->export = NULL;
1597f493662SPan Nengyuan     g_free(s->tlscredsid);
1607f493662SPan Nengyuan     s->tlscredsid = NULL;
1617f493662SPan Nengyuan     g_free(s->x_dirty_bitmap);
1627f493662SPan Nengyuan     s->x_dirty_bitmap = NULL;
1637f493662SPan Nengyuan }
1647f493662SPan Nengyuan 
165a34b1e5eSVladimir Sementsov-Ogievskiy static void nbd_channel_error(BDRVNBDState *s, int ret)
166a34b1e5eSVladimir Sementsov-Ogievskiy {
167f7651539SVladimir Sementsov-Ogievskiy     if (ret == -EIO) {
168f7651539SVladimir Sementsov-Ogievskiy         if (s->state == NBD_CLIENT_CONNECTED) {
169f7651539SVladimir Sementsov-Ogievskiy             s->state = s->reconnect_delay ? NBD_CLIENT_CONNECTING_WAIT :
170f7651539SVladimir Sementsov-Ogievskiy                                             NBD_CLIENT_CONNECTING_NOWAIT;
171f7651539SVladimir Sementsov-Ogievskiy         }
172f7651539SVladimir Sementsov-Ogievskiy     } else {
173f7651539SVladimir Sementsov-Ogievskiy         if (s->state == NBD_CLIENT_CONNECTED) {
174f7651539SVladimir Sementsov-Ogievskiy             qio_channel_shutdown(s->ioc, QIO_CHANNEL_SHUTDOWN_BOTH, NULL);
175f7651539SVladimir Sementsov-Ogievskiy         }
176a34b1e5eSVladimir Sementsov-Ogievskiy         s->state = NBD_CLIENT_QUIT;
177a34b1e5eSVladimir Sementsov-Ogievskiy     }
178f7651539SVladimir Sementsov-Ogievskiy }
179a34b1e5eSVladimir Sementsov-Ogievskiy 
180611ae1d7SVladimir Sementsov-Ogievskiy static void nbd_recv_coroutines_wake_all(BDRVNBDState *s)
18186f8cdf3SVladimir Sementsov-Ogievskiy {
18286f8cdf3SVladimir Sementsov-Ogievskiy     int i;
18386f8cdf3SVladimir Sementsov-Ogievskiy 
18486f8cdf3SVladimir Sementsov-Ogievskiy     for (i = 0; i < MAX_NBD_REQUESTS; i++) {
18586f8cdf3SVladimir Sementsov-Ogievskiy         NBDClientRequest *req = &s->requests[i];
18686f8cdf3SVladimir Sementsov-Ogievskiy 
18786f8cdf3SVladimir Sementsov-Ogievskiy         if (req->coroutine && req->receiving) {
18886f8cdf3SVladimir Sementsov-Ogievskiy             aio_co_wake(req->coroutine);
18986f8cdf3SVladimir Sementsov-Ogievskiy         }
19086f8cdf3SVladimir Sementsov-Ogievskiy     }
19186f8cdf3SVladimir Sementsov-Ogievskiy }
19286f8cdf3SVladimir Sementsov-Ogievskiy 
193*46f56631SVladimir Sementsov-Ogievskiy static void reconnect_delay_timer_del(BDRVNBDState *s)
194*46f56631SVladimir Sementsov-Ogievskiy {
195*46f56631SVladimir Sementsov-Ogievskiy     if (s->reconnect_delay_timer) {
196*46f56631SVladimir Sementsov-Ogievskiy         timer_del(s->reconnect_delay_timer);
197*46f56631SVladimir Sementsov-Ogievskiy         timer_free(s->reconnect_delay_timer);
198*46f56631SVladimir Sementsov-Ogievskiy         s->reconnect_delay_timer = NULL;
199*46f56631SVladimir Sementsov-Ogievskiy     }
200*46f56631SVladimir Sementsov-Ogievskiy }
201*46f56631SVladimir Sementsov-Ogievskiy 
202*46f56631SVladimir Sementsov-Ogievskiy static void reconnect_delay_timer_cb(void *opaque)
203*46f56631SVladimir Sementsov-Ogievskiy {
204*46f56631SVladimir Sementsov-Ogievskiy     BDRVNBDState *s = opaque;
205*46f56631SVladimir Sementsov-Ogievskiy 
206*46f56631SVladimir Sementsov-Ogievskiy     if (s->state == NBD_CLIENT_CONNECTING_WAIT) {
207*46f56631SVladimir Sementsov-Ogievskiy         s->state = NBD_CLIENT_CONNECTING_NOWAIT;
208*46f56631SVladimir Sementsov-Ogievskiy         while (qemu_co_enter_next(&s->free_sema, NULL)) {
209*46f56631SVladimir Sementsov-Ogievskiy             /* Resume all queued requests */
210*46f56631SVladimir Sementsov-Ogievskiy         }
211*46f56631SVladimir Sementsov-Ogievskiy     }
212*46f56631SVladimir Sementsov-Ogievskiy 
213*46f56631SVladimir Sementsov-Ogievskiy     reconnect_delay_timer_del(s);
214*46f56631SVladimir Sementsov-Ogievskiy }
215*46f56631SVladimir Sementsov-Ogievskiy 
216*46f56631SVladimir Sementsov-Ogievskiy static void reconnect_delay_timer_init(BDRVNBDState *s, uint64_t expire_time_ns)
217*46f56631SVladimir Sementsov-Ogievskiy {
218*46f56631SVladimir Sementsov-Ogievskiy     if (s->state != NBD_CLIENT_CONNECTING_WAIT) {
219*46f56631SVladimir Sementsov-Ogievskiy         return;
220*46f56631SVladimir Sementsov-Ogievskiy     }
221*46f56631SVladimir Sementsov-Ogievskiy 
222*46f56631SVladimir Sementsov-Ogievskiy     assert(!s->reconnect_delay_timer);
223*46f56631SVladimir Sementsov-Ogievskiy     s->reconnect_delay_timer = aio_timer_new(bdrv_get_aio_context(s->bs),
224*46f56631SVladimir Sementsov-Ogievskiy                                              QEMU_CLOCK_REALTIME,
225*46f56631SVladimir Sementsov-Ogievskiy                                              SCALE_NS,
226*46f56631SVladimir Sementsov-Ogievskiy                                              reconnect_delay_timer_cb, s);
227*46f56631SVladimir Sementsov-Ogievskiy     timer_mod(s->reconnect_delay_timer, expire_time_ns);
228*46f56631SVladimir Sementsov-Ogievskiy }
229*46f56631SVladimir Sementsov-Ogievskiy 
23086f8cdf3SVladimir Sementsov-Ogievskiy static void nbd_client_detach_aio_context(BlockDriverState *bs)
23186f8cdf3SVladimir Sementsov-Ogievskiy {
232611ae1d7SVladimir Sementsov-Ogievskiy     BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
233611ae1d7SVladimir Sementsov-Ogievskiy 
234*46f56631SVladimir Sementsov-Ogievskiy     /* Timer is deleted in nbd_client_co_drain_begin() */
235*46f56631SVladimir Sementsov-Ogievskiy     assert(!s->reconnect_delay_timer);
236611ae1d7SVladimir Sementsov-Ogievskiy     qio_channel_detach_aio_context(QIO_CHANNEL(s->ioc));
23786f8cdf3SVladimir Sementsov-Ogievskiy }
23886f8cdf3SVladimir Sementsov-Ogievskiy 
23986f8cdf3SVladimir Sementsov-Ogievskiy static void nbd_client_attach_aio_context_bh(void *opaque)
24086f8cdf3SVladimir Sementsov-Ogievskiy {
24186f8cdf3SVladimir Sementsov-Ogievskiy     BlockDriverState *bs = opaque;
242611ae1d7SVladimir Sementsov-Ogievskiy     BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
24386f8cdf3SVladimir Sementsov-Ogievskiy 
24486f8cdf3SVladimir Sementsov-Ogievskiy     /*
24586f8cdf3SVladimir Sementsov-Ogievskiy      * The node is still drained, so we know the coroutine has yielded in
24686f8cdf3SVladimir Sementsov-Ogievskiy      * nbd_read_eof(), the only place where bs->in_flight can reach 0, or it is
24786f8cdf3SVladimir Sementsov-Ogievskiy      * entered for the first time. Both places are safe for entering the
24886f8cdf3SVladimir Sementsov-Ogievskiy      * coroutine.
24986f8cdf3SVladimir Sementsov-Ogievskiy      */
250611ae1d7SVladimir Sementsov-Ogievskiy     qemu_aio_coroutine_enter(bs->aio_context, s->connection_co);
25186f8cdf3SVladimir Sementsov-Ogievskiy     bdrv_dec_in_flight(bs);
25286f8cdf3SVladimir Sementsov-Ogievskiy }
25386f8cdf3SVladimir Sementsov-Ogievskiy 
25486f8cdf3SVladimir Sementsov-Ogievskiy static void nbd_client_attach_aio_context(BlockDriverState *bs,
25586f8cdf3SVladimir Sementsov-Ogievskiy                                           AioContext *new_context)
25686f8cdf3SVladimir Sementsov-Ogievskiy {
257611ae1d7SVladimir Sementsov-Ogievskiy     BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
258611ae1d7SVladimir Sementsov-Ogievskiy 
259f7651539SVladimir Sementsov-Ogievskiy     /*
260f7651539SVladimir Sementsov-Ogievskiy      * s->connection_co is either yielded from nbd_receive_reply or from
261f7651539SVladimir Sementsov-Ogievskiy      * nbd_co_reconnect_loop()
262f7651539SVladimir Sementsov-Ogievskiy      */
263f7651539SVladimir Sementsov-Ogievskiy     if (s->state == NBD_CLIENT_CONNECTED) {
264611ae1d7SVladimir Sementsov-Ogievskiy         qio_channel_attach_aio_context(QIO_CHANNEL(s->ioc), new_context);
265f7651539SVladimir Sementsov-Ogievskiy     }
26686f8cdf3SVladimir Sementsov-Ogievskiy 
26786f8cdf3SVladimir Sementsov-Ogievskiy     bdrv_inc_in_flight(bs);
26886f8cdf3SVladimir Sementsov-Ogievskiy 
26986f8cdf3SVladimir Sementsov-Ogievskiy     /*
27086f8cdf3SVladimir Sementsov-Ogievskiy      * Need to wait here for the BH to run because the BH must run while the
27186f8cdf3SVladimir Sementsov-Ogievskiy      * node is still drained.
27286f8cdf3SVladimir Sementsov-Ogievskiy      */
27386f8cdf3SVladimir Sementsov-Ogievskiy     aio_wait_bh_oneshot(new_context, nbd_client_attach_aio_context_bh, bs);
27486f8cdf3SVladimir Sementsov-Ogievskiy }
27586f8cdf3SVladimir Sementsov-Ogievskiy 
276f7651539SVladimir Sementsov-Ogievskiy static void coroutine_fn nbd_client_co_drain_begin(BlockDriverState *bs)
277f7651539SVladimir Sementsov-Ogievskiy {
278f7651539SVladimir Sementsov-Ogievskiy     BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
279f7651539SVladimir Sementsov-Ogievskiy 
280f7651539SVladimir Sementsov-Ogievskiy     s->drained = true;
281f7651539SVladimir Sementsov-Ogievskiy     if (s->connection_co_sleep_ns_state) {
282f7651539SVladimir Sementsov-Ogievskiy         qemu_co_sleep_wake(s->connection_co_sleep_ns_state);
283f7651539SVladimir Sementsov-Ogievskiy     }
2841dc4718dSVladimir Sementsov-Ogievskiy 
2851dc4718dSVladimir Sementsov-Ogievskiy     nbd_co_establish_connection_cancel(bs, false);
2868c517de2SVladimir Sementsov-Ogievskiy 
287*46f56631SVladimir Sementsov-Ogievskiy     reconnect_delay_timer_del(s);
288*46f56631SVladimir Sementsov-Ogievskiy 
2898c517de2SVladimir Sementsov-Ogievskiy     if (s->state == NBD_CLIENT_CONNECTING_WAIT) {
2908c517de2SVladimir Sementsov-Ogievskiy         s->state = NBD_CLIENT_CONNECTING_NOWAIT;
2918c517de2SVladimir Sementsov-Ogievskiy         qemu_co_queue_restart_all(&s->free_sema);
2928c517de2SVladimir Sementsov-Ogievskiy     }
293f7651539SVladimir Sementsov-Ogievskiy }
294f7651539SVladimir Sementsov-Ogievskiy 
295f7651539SVladimir Sementsov-Ogievskiy static void coroutine_fn nbd_client_co_drain_end(BlockDriverState *bs)
296f7651539SVladimir Sementsov-Ogievskiy {
297f7651539SVladimir Sementsov-Ogievskiy     BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
298f7651539SVladimir Sementsov-Ogievskiy 
299f7651539SVladimir Sementsov-Ogievskiy     s->drained = false;
300f7651539SVladimir Sementsov-Ogievskiy     if (s->wait_drained_end) {
301f7651539SVladimir Sementsov-Ogievskiy         s->wait_drained_end = false;
302f7651539SVladimir Sementsov-Ogievskiy         aio_co_wake(s->connection_co);
303f7651539SVladimir Sementsov-Ogievskiy     }
304f7651539SVladimir Sementsov-Ogievskiy }
305f7651539SVladimir Sementsov-Ogievskiy 
30686f8cdf3SVladimir Sementsov-Ogievskiy 
30786f8cdf3SVladimir Sementsov-Ogievskiy static void nbd_teardown_connection(BlockDriverState *bs)
30886f8cdf3SVladimir Sementsov-Ogievskiy {
309611ae1d7SVladimir Sementsov-Ogievskiy     BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
31086f8cdf3SVladimir Sementsov-Ogievskiy 
311fbeb3e63SVladimir Sementsov-Ogievskiy     if (s->ioc) {
31286f8cdf3SVladimir Sementsov-Ogievskiy         /* finish any pending coroutines */
313f7651539SVladimir Sementsov-Ogievskiy         qio_channel_shutdown(s->ioc, QIO_CHANNEL_SHUTDOWN_BOTH, NULL);
314fbeb3e63SVladimir Sementsov-Ogievskiy     } else if (s->sioc) {
315fbeb3e63SVladimir Sementsov-Ogievskiy         /* abort negotiation */
316fbeb3e63SVladimir Sementsov-Ogievskiy         qio_channel_shutdown(QIO_CHANNEL(s->sioc), QIO_CHANNEL_SHUTDOWN_BOTH,
317fbeb3e63SVladimir Sementsov-Ogievskiy                              NULL);
318f7651539SVladimir Sementsov-Ogievskiy     }
319fbeb3e63SVladimir Sementsov-Ogievskiy 
320f7651539SVladimir Sementsov-Ogievskiy     s->state = NBD_CLIENT_QUIT;
321f7651539SVladimir Sementsov-Ogievskiy     if (s->connection_co) {
322f7651539SVladimir Sementsov-Ogievskiy         if (s->connection_co_sleep_ns_state) {
323f7651539SVladimir Sementsov-Ogievskiy             qemu_co_sleep_wake(s->connection_co_sleep_ns_state);
324f7651539SVladimir Sementsov-Ogievskiy         }
3251dc4718dSVladimir Sementsov-Ogievskiy         nbd_co_establish_connection_cancel(bs, true);
326f7651539SVladimir Sementsov-Ogievskiy     }
32778c81a3fSMax Reitz     if (qemu_in_coroutine()) {
32878c81a3fSMax Reitz         s->teardown_co = qemu_coroutine_self();
32978c81a3fSMax Reitz         /* connection_co resumes us when it terminates */
33078c81a3fSMax Reitz         qemu_coroutine_yield();
33178c81a3fSMax Reitz         s->teardown_co = NULL;
33278c81a3fSMax Reitz     } else {
333611ae1d7SVladimir Sementsov-Ogievskiy         BDRV_POLL_WHILE(bs, s->connection_co);
334f7651539SVladimir Sementsov-Ogievskiy     }
33578c81a3fSMax Reitz     assert(!s->connection_co);
33678c81a3fSMax Reitz }
33786f8cdf3SVladimir Sementsov-Ogievskiy 
338f7651539SVladimir Sementsov-Ogievskiy static bool nbd_client_connecting(BDRVNBDState *s)
339f7651539SVladimir Sementsov-Ogievskiy {
340f7651539SVladimir Sementsov-Ogievskiy     return s->state == NBD_CLIENT_CONNECTING_WAIT ||
341f7651539SVladimir Sementsov-Ogievskiy         s->state == NBD_CLIENT_CONNECTING_NOWAIT;
342f7651539SVladimir Sementsov-Ogievskiy }
343f7651539SVladimir Sementsov-Ogievskiy 
344f7651539SVladimir Sementsov-Ogievskiy static bool nbd_client_connecting_wait(BDRVNBDState *s)
345f7651539SVladimir Sementsov-Ogievskiy {
346f7651539SVladimir Sementsov-Ogievskiy     return s->state == NBD_CLIENT_CONNECTING_WAIT;
347f7651539SVladimir Sementsov-Ogievskiy }
348f7651539SVladimir Sementsov-Ogievskiy 
3491dc4718dSVladimir Sementsov-Ogievskiy static void connect_bh(void *opaque)
3501dc4718dSVladimir Sementsov-Ogievskiy {
3511dc4718dSVladimir Sementsov-Ogievskiy     BDRVNBDState *state = opaque;
3521dc4718dSVladimir Sementsov-Ogievskiy 
3531dc4718dSVladimir Sementsov-Ogievskiy     assert(state->wait_connect);
3541dc4718dSVladimir Sementsov-Ogievskiy     state->wait_connect = false;
3551dc4718dSVladimir Sementsov-Ogievskiy     aio_co_wake(state->connection_co);
3561dc4718dSVladimir Sementsov-Ogievskiy }
3571dc4718dSVladimir Sementsov-Ogievskiy 
3581dc4718dSVladimir Sementsov-Ogievskiy static void nbd_init_connect_thread(BDRVNBDState *s)
3591dc4718dSVladimir Sementsov-Ogievskiy {
3601dc4718dSVladimir Sementsov-Ogievskiy     s->connect_thread = g_new(NBDConnectThread, 1);
3611dc4718dSVladimir Sementsov-Ogievskiy 
3621dc4718dSVladimir Sementsov-Ogievskiy     *s->connect_thread = (NBDConnectThread) {
3631dc4718dSVladimir Sementsov-Ogievskiy         .saddr = QAPI_CLONE(SocketAddress, s->saddr),
3641dc4718dSVladimir Sementsov-Ogievskiy         .state = CONNECT_THREAD_NONE,
3651dc4718dSVladimir Sementsov-Ogievskiy         .bh_func = connect_bh,
3661dc4718dSVladimir Sementsov-Ogievskiy         .bh_opaque = s,
3671dc4718dSVladimir Sementsov-Ogievskiy     };
3681dc4718dSVladimir Sementsov-Ogievskiy 
3691dc4718dSVladimir Sementsov-Ogievskiy     qemu_mutex_init(&s->connect_thread->mutex);
3701dc4718dSVladimir Sementsov-Ogievskiy }
3711dc4718dSVladimir Sementsov-Ogievskiy 
3721dc4718dSVladimir Sementsov-Ogievskiy static void nbd_free_connect_thread(NBDConnectThread *thr)
3731dc4718dSVladimir Sementsov-Ogievskiy {
3741dc4718dSVladimir Sementsov-Ogievskiy     if (thr->sioc) {
3751dc4718dSVladimir Sementsov-Ogievskiy         qio_channel_close(QIO_CHANNEL(thr->sioc), NULL);
3761dc4718dSVladimir Sementsov-Ogievskiy     }
3771dc4718dSVladimir Sementsov-Ogievskiy     error_free(thr->err);
3781dc4718dSVladimir Sementsov-Ogievskiy     qapi_free_SocketAddress(thr->saddr);
3791dc4718dSVladimir Sementsov-Ogievskiy     g_free(thr);
3801dc4718dSVladimir Sementsov-Ogievskiy }
3811dc4718dSVladimir Sementsov-Ogievskiy 
3821dc4718dSVladimir Sementsov-Ogievskiy static void *connect_thread_func(void *opaque)
3831dc4718dSVladimir Sementsov-Ogievskiy {
3841dc4718dSVladimir Sementsov-Ogievskiy     NBDConnectThread *thr = opaque;
3851dc4718dSVladimir Sementsov-Ogievskiy     int ret;
3861dc4718dSVladimir Sementsov-Ogievskiy     bool do_free = false;
3871dc4718dSVladimir Sementsov-Ogievskiy 
3881dc4718dSVladimir Sementsov-Ogievskiy     thr->sioc = qio_channel_socket_new();
3891dc4718dSVladimir Sementsov-Ogievskiy 
3901dc4718dSVladimir Sementsov-Ogievskiy     error_free(thr->err);
3911dc4718dSVladimir Sementsov-Ogievskiy     thr->err = NULL;
3921dc4718dSVladimir Sementsov-Ogievskiy     ret = qio_channel_socket_connect_sync(thr->sioc, thr->saddr, &thr->err);
3931dc4718dSVladimir Sementsov-Ogievskiy     if (ret < 0) {
3941dc4718dSVladimir Sementsov-Ogievskiy         object_unref(OBJECT(thr->sioc));
3951dc4718dSVladimir Sementsov-Ogievskiy         thr->sioc = NULL;
3961dc4718dSVladimir Sementsov-Ogievskiy     }
3971dc4718dSVladimir Sementsov-Ogievskiy 
3981dc4718dSVladimir Sementsov-Ogievskiy     qemu_mutex_lock(&thr->mutex);
3991dc4718dSVladimir Sementsov-Ogievskiy 
4001dc4718dSVladimir Sementsov-Ogievskiy     switch (thr->state) {
4011dc4718dSVladimir Sementsov-Ogievskiy     case CONNECT_THREAD_RUNNING:
4021dc4718dSVladimir Sementsov-Ogievskiy         thr->state = ret < 0 ? CONNECT_THREAD_FAIL : CONNECT_THREAD_SUCCESS;
4031dc4718dSVladimir Sementsov-Ogievskiy         if (thr->bh_ctx) {
4041dc4718dSVladimir Sementsov-Ogievskiy             aio_bh_schedule_oneshot(thr->bh_ctx, thr->bh_func, thr->bh_opaque);
4051dc4718dSVladimir Sementsov-Ogievskiy 
4061dc4718dSVladimir Sementsov-Ogievskiy             /* play safe, don't reuse bh_ctx on further connection attempts */
4071dc4718dSVladimir Sementsov-Ogievskiy             thr->bh_ctx = NULL;
4081dc4718dSVladimir Sementsov-Ogievskiy         }
4091dc4718dSVladimir Sementsov-Ogievskiy         break;
4101dc4718dSVladimir Sementsov-Ogievskiy     case CONNECT_THREAD_RUNNING_DETACHED:
4111dc4718dSVladimir Sementsov-Ogievskiy         do_free = true;
4121dc4718dSVladimir Sementsov-Ogievskiy         break;
4131dc4718dSVladimir Sementsov-Ogievskiy     default:
4141dc4718dSVladimir Sementsov-Ogievskiy         abort();
4151dc4718dSVladimir Sementsov-Ogievskiy     }
4161dc4718dSVladimir Sementsov-Ogievskiy 
4171dc4718dSVladimir Sementsov-Ogievskiy     qemu_mutex_unlock(&thr->mutex);
4181dc4718dSVladimir Sementsov-Ogievskiy 
4191dc4718dSVladimir Sementsov-Ogievskiy     if (do_free) {
4201dc4718dSVladimir Sementsov-Ogievskiy         nbd_free_connect_thread(thr);
4211dc4718dSVladimir Sementsov-Ogievskiy     }
4221dc4718dSVladimir Sementsov-Ogievskiy 
4231dc4718dSVladimir Sementsov-Ogievskiy     return NULL;
4241dc4718dSVladimir Sementsov-Ogievskiy }
4251dc4718dSVladimir Sementsov-Ogievskiy 
4261dc4718dSVladimir Sementsov-Ogievskiy static QIOChannelSocket *coroutine_fn
4271dc4718dSVladimir Sementsov-Ogievskiy nbd_co_establish_connection(BlockDriverState *bs, Error **errp)
4281dc4718dSVladimir Sementsov-Ogievskiy {
4291dc4718dSVladimir Sementsov-Ogievskiy     QemuThread thread;
4301dc4718dSVladimir Sementsov-Ogievskiy     BDRVNBDState *s = bs->opaque;
4311dc4718dSVladimir Sementsov-Ogievskiy     QIOChannelSocket *res;
4321dc4718dSVladimir Sementsov-Ogievskiy     NBDConnectThread *thr = s->connect_thread;
4331dc4718dSVladimir Sementsov-Ogievskiy 
4341dc4718dSVladimir Sementsov-Ogievskiy     qemu_mutex_lock(&thr->mutex);
4351dc4718dSVladimir Sementsov-Ogievskiy 
4361dc4718dSVladimir Sementsov-Ogievskiy     switch (thr->state) {
4371dc4718dSVladimir Sementsov-Ogievskiy     case CONNECT_THREAD_FAIL:
4381dc4718dSVladimir Sementsov-Ogievskiy     case CONNECT_THREAD_NONE:
4391dc4718dSVladimir Sementsov-Ogievskiy         error_free(thr->err);
4401dc4718dSVladimir Sementsov-Ogievskiy         thr->err = NULL;
4411dc4718dSVladimir Sementsov-Ogievskiy         thr->state = CONNECT_THREAD_RUNNING;
4421dc4718dSVladimir Sementsov-Ogievskiy         qemu_thread_create(&thread, "nbd-connect",
4431dc4718dSVladimir Sementsov-Ogievskiy                            connect_thread_func, thr, QEMU_THREAD_DETACHED);
4441dc4718dSVladimir Sementsov-Ogievskiy         break;
4451dc4718dSVladimir Sementsov-Ogievskiy     case CONNECT_THREAD_SUCCESS:
4461dc4718dSVladimir Sementsov-Ogievskiy         /* Previous attempt finally succeeded in background */
4471dc4718dSVladimir Sementsov-Ogievskiy         thr->state = CONNECT_THREAD_NONE;
4481dc4718dSVladimir Sementsov-Ogievskiy         res = thr->sioc;
4491dc4718dSVladimir Sementsov-Ogievskiy         thr->sioc = NULL;
4501dc4718dSVladimir Sementsov-Ogievskiy         qemu_mutex_unlock(&thr->mutex);
4511dc4718dSVladimir Sementsov-Ogievskiy         return res;
4521dc4718dSVladimir Sementsov-Ogievskiy     case CONNECT_THREAD_RUNNING:
4531dc4718dSVladimir Sementsov-Ogievskiy         /* Already running, will wait */
4541dc4718dSVladimir Sementsov-Ogievskiy         break;
4551dc4718dSVladimir Sementsov-Ogievskiy     default:
4561dc4718dSVladimir Sementsov-Ogievskiy         abort();
4571dc4718dSVladimir Sementsov-Ogievskiy     }
4581dc4718dSVladimir Sementsov-Ogievskiy 
4591dc4718dSVladimir Sementsov-Ogievskiy     thr->bh_ctx = qemu_get_current_aio_context();
4601dc4718dSVladimir Sementsov-Ogievskiy 
4611dc4718dSVladimir Sementsov-Ogievskiy     qemu_mutex_unlock(&thr->mutex);
4621dc4718dSVladimir Sementsov-Ogievskiy 
4631dc4718dSVladimir Sementsov-Ogievskiy 
4641dc4718dSVladimir Sementsov-Ogievskiy     /*
4651dc4718dSVladimir Sementsov-Ogievskiy      * We are going to wait for connect-thread finish, but
4661dc4718dSVladimir Sementsov-Ogievskiy      * nbd_client_co_drain_begin() can interrupt.
4671dc4718dSVladimir Sementsov-Ogievskiy      *
4681dc4718dSVladimir Sementsov-Ogievskiy      * Note that wait_connect variable is not visible for connect-thread. It
4691dc4718dSVladimir Sementsov-Ogievskiy      * doesn't need mutex protection, it used only inside home aio context of
4701dc4718dSVladimir Sementsov-Ogievskiy      * bs.
4711dc4718dSVladimir Sementsov-Ogievskiy      */
4721dc4718dSVladimir Sementsov-Ogievskiy     s->wait_connect = true;
4731dc4718dSVladimir Sementsov-Ogievskiy     qemu_coroutine_yield();
4741dc4718dSVladimir Sementsov-Ogievskiy 
4751dc4718dSVladimir Sementsov-Ogievskiy     qemu_mutex_lock(&thr->mutex);
4761dc4718dSVladimir Sementsov-Ogievskiy 
4771dc4718dSVladimir Sementsov-Ogievskiy     switch (thr->state) {
4781dc4718dSVladimir Sementsov-Ogievskiy     case CONNECT_THREAD_SUCCESS:
4791dc4718dSVladimir Sementsov-Ogievskiy     case CONNECT_THREAD_FAIL:
4801dc4718dSVladimir Sementsov-Ogievskiy         thr->state = CONNECT_THREAD_NONE;
4811dc4718dSVladimir Sementsov-Ogievskiy         error_propagate(errp, thr->err);
4821dc4718dSVladimir Sementsov-Ogievskiy         thr->err = NULL;
4831dc4718dSVladimir Sementsov-Ogievskiy         res = thr->sioc;
4841dc4718dSVladimir Sementsov-Ogievskiy         thr->sioc = NULL;
4851dc4718dSVladimir Sementsov-Ogievskiy         break;
4861dc4718dSVladimir Sementsov-Ogievskiy     case CONNECT_THREAD_RUNNING:
4871dc4718dSVladimir Sementsov-Ogievskiy     case CONNECT_THREAD_RUNNING_DETACHED:
4881dc4718dSVladimir Sementsov-Ogievskiy         /*
4891dc4718dSVladimir Sementsov-Ogievskiy          * Obviously, drained section wants to start. Report the attempt as
4901dc4718dSVladimir Sementsov-Ogievskiy          * failed. Still connect thread is executing in background, and its
4911dc4718dSVladimir Sementsov-Ogievskiy          * result may be used for next connection attempt.
4921dc4718dSVladimir Sementsov-Ogievskiy          */
4931dc4718dSVladimir Sementsov-Ogievskiy         res = NULL;
4941dc4718dSVladimir Sementsov-Ogievskiy         error_setg(errp, "Connection attempt cancelled by other operation");
4951dc4718dSVladimir Sementsov-Ogievskiy         break;
4961dc4718dSVladimir Sementsov-Ogievskiy 
4971dc4718dSVladimir Sementsov-Ogievskiy     case CONNECT_THREAD_NONE:
4981dc4718dSVladimir Sementsov-Ogievskiy         /*
4991dc4718dSVladimir Sementsov-Ogievskiy          * Impossible. We've seen this thread running. So it should be
5001dc4718dSVladimir Sementsov-Ogievskiy          * running or at least give some results.
5011dc4718dSVladimir Sementsov-Ogievskiy          */
5021dc4718dSVladimir Sementsov-Ogievskiy         abort();
5031dc4718dSVladimir Sementsov-Ogievskiy 
5041dc4718dSVladimir Sementsov-Ogievskiy     default:
5051dc4718dSVladimir Sementsov-Ogievskiy         abort();
5061dc4718dSVladimir Sementsov-Ogievskiy     }
5071dc4718dSVladimir Sementsov-Ogievskiy 
5081dc4718dSVladimir Sementsov-Ogievskiy     qemu_mutex_unlock(&thr->mutex);
5091dc4718dSVladimir Sementsov-Ogievskiy 
5101dc4718dSVladimir Sementsov-Ogievskiy     return res;
5111dc4718dSVladimir Sementsov-Ogievskiy }
5121dc4718dSVladimir Sementsov-Ogievskiy 
5131dc4718dSVladimir Sementsov-Ogievskiy /*
5141dc4718dSVladimir Sementsov-Ogievskiy  * nbd_co_establish_connection_cancel
5151dc4718dSVladimir Sementsov-Ogievskiy  * Cancel nbd_co_establish_connection asynchronously: it will finish soon, to
5161dc4718dSVladimir Sementsov-Ogievskiy  * allow drained section to begin.
5171dc4718dSVladimir Sementsov-Ogievskiy  *
5181dc4718dSVladimir Sementsov-Ogievskiy  * If detach is true, also cleanup the state (or if thread is running, move it
5191dc4718dSVladimir Sementsov-Ogievskiy  * to CONNECT_THREAD_RUNNING_DETACHED state). s->connect_thread becomes NULL if
5201dc4718dSVladimir Sementsov-Ogievskiy  * detach is true.
5211dc4718dSVladimir Sementsov-Ogievskiy  */
5221dc4718dSVladimir Sementsov-Ogievskiy static void nbd_co_establish_connection_cancel(BlockDriverState *bs,
5231dc4718dSVladimir Sementsov-Ogievskiy                                                bool detach)
5241dc4718dSVladimir Sementsov-Ogievskiy {
5251dc4718dSVladimir Sementsov-Ogievskiy     BDRVNBDState *s = bs->opaque;
5261dc4718dSVladimir Sementsov-Ogievskiy     NBDConnectThread *thr = s->connect_thread;
5271dc4718dSVladimir Sementsov-Ogievskiy     bool wake = false;
5281dc4718dSVladimir Sementsov-Ogievskiy     bool do_free = false;
5291dc4718dSVladimir Sementsov-Ogievskiy 
5301dc4718dSVladimir Sementsov-Ogievskiy     qemu_mutex_lock(&thr->mutex);
5311dc4718dSVladimir Sementsov-Ogievskiy 
5321dc4718dSVladimir Sementsov-Ogievskiy     if (thr->state == CONNECT_THREAD_RUNNING) {
5331dc4718dSVladimir Sementsov-Ogievskiy         /* We can cancel only in running state, when bh is not yet scheduled */
5341dc4718dSVladimir Sementsov-Ogievskiy         thr->bh_ctx = NULL;
5351dc4718dSVladimir Sementsov-Ogievskiy         if (s->wait_connect) {
5361dc4718dSVladimir Sementsov-Ogievskiy             s->wait_connect = false;
5371dc4718dSVladimir Sementsov-Ogievskiy             wake = true;
5381dc4718dSVladimir Sementsov-Ogievskiy         }
5391dc4718dSVladimir Sementsov-Ogievskiy         if (detach) {
5401dc4718dSVladimir Sementsov-Ogievskiy             thr->state = CONNECT_THREAD_RUNNING_DETACHED;
5411dc4718dSVladimir Sementsov-Ogievskiy             s->connect_thread = NULL;
5421dc4718dSVladimir Sementsov-Ogievskiy         }
5431dc4718dSVladimir Sementsov-Ogievskiy     } else if (detach) {
5441dc4718dSVladimir Sementsov-Ogievskiy         do_free = true;
5451dc4718dSVladimir Sementsov-Ogievskiy     }
5461dc4718dSVladimir Sementsov-Ogievskiy 
5471dc4718dSVladimir Sementsov-Ogievskiy     qemu_mutex_unlock(&thr->mutex);
5481dc4718dSVladimir Sementsov-Ogievskiy 
5491dc4718dSVladimir Sementsov-Ogievskiy     if (do_free) {
5501dc4718dSVladimir Sementsov-Ogievskiy         nbd_free_connect_thread(thr);
5511dc4718dSVladimir Sementsov-Ogievskiy         s->connect_thread = NULL;
5521dc4718dSVladimir Sementsov-Ogievskiy     }
5531dc4718dSVladimir Sementsov-Ogievskiy 
5541dc4718dSVladimir Sementsov-Ogievskiy     if (wake) {
5551dc4718dSVladimir Sementsov-Ogievskiy         aio_co_wake(s->connection_co);
5561dc4718dSVladimir Sementsov-Ogievskiy     }
5571dc4718dSVladimir Sementsov-Ogievskiy }
5581dc4718dSVladimir Sementsov-Ogievskiy 
559f7651539SVladimir Sementsov-Ogievskiy static coroutine_fn void nbd_reconnect_attempt(BDRVNBDState *s)
560f7651539SVladimir Sementsov-Ogievskiy {
561fa35591bSVladimir Sementsov-Ogievskiy     int ret;
562f7651539SVladimir Sementsov-Ogievskiy     Error *local_err = NULL;
563fa35591bSVladimir Sementsov-Ogievskiy     QIOChannelSocket *sioc;
564f7651539SVladimir Sementsov-Ogievskiy 
565f7651539SVladimir Sementsov-Ogievskiy     if (!nbd_client_connecting(s)) {
566f7651539SVladimir Sementsov-Ogievskiy         return;
567f7651539SVladimir Sementsov-Ogievskiy     }
568f7651539SVladimir Sementsov-Ogievskiy 
569f7651539SVladimir Sementsov-Ogievskiy     /* Wait for completion of all in-flight requests */
570f7651539SVladimir Sementsov-Ogievskiy 
571f7651539SVladimir Sementsov-Ogievskiy     qemu_co_mutex_lock(&s->send_mutex);
572f7651539SVladimir Sementsov-Ogievskiy 
573f7651539SVladimir Sementsov-Ogievskiy     while (s->in_flight > 0) {
574f7651539SVladimir Sementsov-Ogievskiy         qemu_co_mutex_unlock(&s->send_mutex);
575f7651539SVladimir Sementsov-Ogievskiy         nbd_recv_coroutines_wake_all(s);
576f7651539SVladimir Sementsov-Ogievskiy         s->wait_in_flight = true;
577f7651539SVladimir Sementsov-Ogievskiy         qemu_coroutine_yield();
578f7651539SVladimir Sementsov-Ogievskiy         s->wait_in_flight = false;
579f7651539SVladimir Sementsov-Ogievskiy         qemu_co_mutex_lock(&s->send_mutex);
580f7651539SVladimir Sementsov-Ogievskiy     }
581f7651539SVladimir Sementsov-Ogievskiy 
582f7651539SVladimir Sementsov-Ogievskiy     qemu_co_mutex_unlock(&s->send_mutex);
583f7651539SVladimir Sementsov-Ogievskiy 
584f7651539SVladimir Sementsov-Ogievskiy     if (!nbd_client_connecting(s)) {
585f7651539SVladimir Sementsov-Ogievskiy         return;
586f7651539SVladimir Sementsov-Ogievskiy     }
587f7651539SVladimir Sementsov-Ogievskiy 
588f7651539SVladimir Sementsov-Ogievskiy     /*
589f7651539SVladimir Sementsov-Ogievskiy      * Now we are sure that nobody is accessing the channel, and no one will
590f7651539SVladimir Sementsov-Ogievskiy      * try until we set the state to CONNECTED.
591f7651539SVladimir Sementsov-Ogievskiy      */
592f7651539SVladimir Sementsov-Ogievskiy 
593f7651539SVladimir Sementsov-Ogievskiy     /* Finalize previous connection if any */
594f7651539SVladimir Sementsov-Ogievskiy     if (s->ioc) {
5958a509afdSVladimir Sementsov-Ogievskiy         qio_channel_detach_aio_context(QIO_CHANNEL(s->ioc));
596611ae1d7SVladimir Sementsov-Ogievskiy         object_unref(OBJECT(s->sioc));
597611ae1d7SVladimir Sementsov-Ogievskiy         s->sioc = NULL;
598611ae1d7SVladimir Sementsov-Ogievskiy         object_unref(OBJECT(s->ioc));
599611ae1d7SVladimir Sementsov-Ogievskiy         s->ioc = NULL;
60086f8cdf3SVladimir Sementsov-Ogievskiy     }
60186f8cdf3SVladimir Sementsov-Ogievskiy 
6021dc4718dSVladimir Sementsov-Ogievskiy     sioc = nbd_co_establish_connection(s->bs, &local_err);
603fa35591bSVladimir Sementsov-Ogievskiy     if (!sioc) {
604fa35591bSVladimir Sementsov-Ogievskiy         ret = -ECONNREFUSED;
605fa35591bSVladimir Sementsov-Ogievskiy         goto out;
606fa35591bSVladimir Sementsov-Ogievskiy     }
607fa35591bSVladimir Sementsov-Ogievskiy 
608dd1ec1a4SVladimir Sementsov-Ogievskiy     bdrv_dec_in_flight(s->bs);
609dd1ec1a4SVladimir Sementsov-Ogievskiy 
610fa35591bSVladimir Sementsov-Ogievskiy     ret = nbd_client_handshake(s->bs, sioc, &local_err);
611fa35591bSVladimir Sementsov-Ogievskiy 
612dd1ec1a4SVladimir Sementsov-Ogievskiy     if (s->drained) {
613dd1ec1a4SVladimir Sementsov-Ogievskiy         s->wait_drained_end = true;
614dd1ec1a4SVladimir Sementsov-Ogievskiy         while (s->drained) {
615dd1ec1a4SVladimir Sementsov-Ogievskiy             /*
616dd1ec1a4SVladimir Sementsov-Ogievskiy              * We may be entered once from nbd_client_attach_aio_context_bh
617dd1ec1a4SVladimir Sementsov-Ogievskiy              * and then from nbd_client_co_drain_end. So here is a loop.
618dd1ec1a4SVladimir Sementsov-Ogievskiy              */
619dd1ec1a4SVladimir Sementsov-Ogievskiy             qemu_coroutine_yield();
620dd1ec1a4SVladimir Sementsov-Ogievskiy         }
621dd1ec1a4SVladimir Sementsov-Ogievskiy     }
622dd1ec1a4SVladimir Sementsov-Ogievskiy     bdrv_inc_in_flight(s->bs);
623dd1ec1a4SVladimir Sementsov-Ogievskiy 
624fa35591bSVladimir Sementsov-Ogievskiy out:
625fa35591bSVladimir Sementsov-Ogievskiy     s->connect_status = ret;
626f7651539SVladimir Sementsov-Ogievskiy     error_free(s->connect_err);
627f7651539SVladimir Sementsov-Ogievskiy     s->connect_err = NULL;
628f7651539SVladimir Sementsov-Ogievskiy     error_propagate(&s->connect_err, local_err);
629f7651539SVladimir Sementsov-Ogievskiy 
630fa35591bSVladimir Sementsov-Ogievskiy     if (ret >= 0) {
631f7651539SVladimir Sementsov-Ogievskiy         /* successfully connected */
632f7651539SVladimir Sementsov-Ogievskiy         s->state = NBD_CLIENT_CONNECTED;
633f7651539SVladimir Sementsov-Ogievskiy         qemu_co_queue_restart_all(&s->free_sema);
634f7651539SVladimir Sementsov-Ogievskiy     }
635fa35591bSVladimir Sementsov-Ogievskiy }
636f7651539SVladimir Sementsov-Ogievskiy 
637f7651539SVladimir Sementsov-Ogievskiy static coroutine_fn void nbd_co_reconnect_loop(BDRVNBDState *s)
638f7651539SVladimir Sementsov-Ogievskiy {
639f7651539SVladimir Sementsov-Ogievskiy     uint64_t timeout = 1 * NANOSECONDS_PER_SECOND;
640f7651539SVladimir Sementsov-Ogievskiy     uint64_t max_timeout = 16 * NANOSECONDS_PER_SECOND;
641f7651539SVladimir Sementsov-Ogievskiy 
642*46f56631SVladimir Sementsov-Ogievskiy     if (s->state == NBD_CLIENT_CONNECTING_WAIT) {
643*46f56631SVladimir Sementsov-Ogievskiy         reconnect_delay_timer_init(s, qemu_clock_get_ns(QEMU_CLOCK_REALTIME) +
644*46f56631SVladimir Sementsov-Ogievskiy                                    s->reconnect_delay * NANOSECONDS_PER_SECOND);
645*46f56631SVladimir Sementsov-Ogievskiy     }
646*46f56631SVladimir Sementsov-Ogievskiy 
647f7651539SVladimir Sementsov-Ogievskiy     nbd_reconnect_attempt(s);
648f7651539SVladimir Sementsov-Ogievskiy 
649f7651539SVladimir Sementsov-Ogievskiy     while (nbd_client_connecting(s)) {
650f7651539SVladimir Sementsov-Ogievskiy         if (s->drained) {
651f7651539SVladimir Sementsov-Ogievskiy             bdrv_dec_in_flight(s->bs);
652f7651539SVladimir Sementsov-Ogievskiy             s->wait_drained_end = true;
653f7651539SVladimir Sementsov-Ogievskiy             while (s->drained) {
654f7651539SVladimir Sementsov-Ogievskiy                 /*
655f7651539SVladimir Sementsov-Ogievskiy                  * We may be entered once from nbd_client_attach_aio_context_bh
656f7651539SVladimir Sementsov-Ogievskiy                  * and then from nbd_client_co_drain_end. So here is a loop.
657f7651539SVladimir Sementsov-Ogievskiy                  */
658f7651539SVladimir Sementsov-Ogievskiy                 qemu_coroutine_yield();
659f7651539SVladimir Sementsov-Ogievskiy             }
660f7651539SVladimir Sementsov-Ogievskiy             bdrv_inc_in_flight(s->bs);
66112c75e20SVladimir Sementsov-Ogievskiy         } else {
66212c75e20SVladimir Sementsov-Ogievskiy             qemu_co_sleep_ns_wakeable(QEMU_CLOCK_REALTIME, timeout,
66312c75e20SVladimir Sementsov-Ogievskiy                                       &s->connection_co_sleep_ns_state);
664f7651539SVladimir Sementsov-Ogievskiy             if (timeout < max_timeout) {
665f7651539SVladimir Sementsov-Ogievskiy                 timeout *= 2;
666f7651539SVladimir Sementsov-Ogievskiy             }
66712c75e20SVladimir Sementsov-Ogievskiy         }
668f7651539SVladimir Sementsov-Ogievskiy 
669f7651539SVladimir Sementsov-Ogievskiy         nbd_reconnect_attempt(s);
670f7651539SVladimir Sementsov-Ogievskiy     }
671*46f56631SVladimir Sementsov-Ogievskiy 
672*46f56631SVladimir Sementsov-Ogievskiy     reconnect_delay_timer_del(s);
673f7651539SVladimir Sementsov-Ogievskiy }
674f7651539SVladimir Sementsov-Ogievskiy 
67586f8cdf3SVladimir Sementsov-Ogievskiy static coroutine_fn void nbd_connection_entry(void *opaque)
67686f8cdf3SVladimir Sementsov-Ogievskiy {
677611ae1d7SVladimir Sementsov-Ogievskiy     BDRVNBDState *s = opaque;
67886f8cdf3SVladimir Sementsov-Ogievskiy     uint64_t i;
67986f8cdf3SVladimir Sementsov-Ogievskiy     int ret = 0;
68086f8cdf3SVladimir Sementsov-Ogievskiy     Error *local_err = NULL;
68186f8cdf3SVladimir Sementsov-Ogievskiy 
682a34b1e5eSVladimir Sementsov-Ogievskiy     while (s->state != NBD_CLIENT_QUIT) {
68386f8cdf3SVladimir Sementsov-Ogievskiy         /*
68486f8cdf3SVladimir Sementsov-Ogievskiy          * The NBD client can only really be considered idle when it has
68586f8cdf3SVladimir Sementsov-Ogievskiy          * yielded from qio_channel_readv_all_eof(), waiting for data. This is
68686f8cdf3SVladimir Sementsov-Ogievskiy          * the point where the additional scheduled coroutine entry happens
68786f8cdf3SVladimir Sementsov-Ogievskiy          * after nbd_client_attach_aio_context().
68886f8cdf3SVladimir Sementsov-Ogievskiy          *
68986f8cdf3SVladimir Sementsov-Ogievskiy          * Therefore we keep an additional in_flight reference all the time and
69086f8cdf3SVladimir Sementsov-Ogievskiy          * only drop it temporarily here.
69186f8cdf3SVladimir Sementsov-Ogievskiy          */
692f7651539SVladimir Sementsov-Ogievskiy 
693f7651539SVladimir Sementsov-Ogievskiy         if (nbd_client_connecting(s)) {
694f7651539SVladimir Sementsov-Ogievskiy             nbd_co_reconnect_loop(s);
695f7651539SVladimir Sementsov-Ogievskiy         }
696f7651539SVladimir Sementsov-Ogievskiy 
697f7651539SVladimir Sementsov-Ogievskiy         if (s->state != NBD_CLIENT_CONNECTED) {
698f7651539SVladimir Sementsov-Ogievskiy             continue;
699f7651539SVladimir Sementsov-Ogievskiy         }
700f7651539SVladimir Sementsov-Ogievskiy 
70186f8cdf3SVladimir Sementsov-Ogievskiy         assert(s->reply.handle == 0);
70286f8cdf3SVladimir Sementsov-Ogievskiy         ret = nbd_receive_reply(s->bs, s->ioc, &s->reply, &local_err);
70386f8cdf3SVladimir Sementsov-Ogievskiy 
70486f8cdf3SVladimir Sementsov-Ogievskiy         if (local_err) {
70586f8cdf3SVladimir Sementsov-Ogievskiy             trace_nbd_read_reply_entry_fail(ret, error_get_pretty(local_err));
70686f8cdf3SVladimir Sementsov-Ogievskiy             error_free(local_err);
707f7651539SVladimir Sementsov-Ogievskiy             local_err = NULL;
70886f8cdf3SVladimir Sementsov-Ogievskiy         }
70986f8cdf3SVladimir Sementsov-Ogievskiy         if (ret <= 0) {
710a34b1e5eSVladimir Sementsov-Ogievskiy             nbd_channel_error(s, ret ? ret : -EIO);
711f7651539SVladimir Sementsov-Ogievskiy             continue;
71286f8cdf3SVladimir Sementsov-Ogievskiy         }
71386f8cdf3SVladimir Sementsov-Ogievskiy 
71486f8cdf3SVladimir Sementsov-Ogievskiy         /*
71586f8cdf3SVladimir Sementsov-Ogievskiy          * There's no need for a mutex on the receive side, because the
71686f8cdf3SVladimir Sementsov-Ogievskiy          * handler acts as a synchronization point and ensures that only
71786f8cdf3SVladimir Sementsov-Ogievskiy          * one coroutine is called until the reply finishes.
71886f8cdf3SVladimir Sementsov-Ogievskiy          */
71986f8cdf3SVladimir Sementsov-Ogievskiy         i = HANDLE_TO_INDEX(s, s->reply.handle);
72086f8cdf3SVladimir Sementsov-Ogievskiy         if (i >= MAX_NBD_REQUESTS ||
72186f8cdf3SVladimir Sementsov-Ogievskiy             !s->requests[i].coroutine ||
72286f8cdf3SVladimir Sementsov-Ogievskiy             !s->requests[i].receiving ||
72386f8cdf3SVladimir Sementsov-Ogievskiy             (nbd_reply_is_structured(&s->reply) && !s->info.structured_reply))
72486f8cdf3SVladimir Sementsov-Ogievskiy         {
725a34b1e5eSVladimir Sementsov-Ogievskiy             nbd_channel_error(s, -EINVAL);
726f7651539SVladimir Sementsov-Ogievskiy             continue;
72786f8cdf3SVladimir Sementsov-Ogievskiy         }
72886f8cdf3SVladimir Sementsov-Ogievskiy 
72986f8cdf3SVladimir Sementsov-Ogievskiy         /*
73086f8cdf3SVladimir Sementsov-Ogievskiy          * We're woken up again by the request itself.  Note that there
73186f8cdf3SVladimir Sementsov-Ogievskiy          * is no race between yielding and reentering connection_co.  This
73286f8cdf3SVladimir Sementsov-Ogievskiy          * is because:
73386f8cdf3SVladimir Sementsov-Ogievskiy          *
73486f8cdf3SVladimir Sementsov-Ogievskiy          * - if the request runs on the same AioContext, it is only
73586f8cdf3SVladimir Sementsov-Ogievskiy          *   entered after we yield
73686f8cdf3SVladimir Sementsov-Ogievskiy          *
73786f8cdf3SVladimir Sementsov-Ogievskiy          * - if the request runs on a different AioContext, reentering
73886f8cdf3SVladimir Sementsov-Ogievskiy          *   connection_co happens through a bottom half, which can only
73986f8cdf3SVladimir Sementsov-Ogievskiy          *   run after we yield.
74086f8cdf3SVladimir Sementsov-Ogievskiy          */
74186f8cdf3SVladimir Sementsov-Ogievskiy         aio_co_wake(s->requests[i].coroutine);
74286f8cdf3SVladimir Sementsov-Ogievskiy         qemu_coroutine_yield();
74386f8cdf3SVladimir Sementsov-Ogievskiy     }
74486f8cdf3SVladimir Sementsov-Ogievskiy 
745f7651539SVladimir Sementsov-Ogievskiy     qemu_co_queue_restart_all(&s->free_sema);
74686f8cdf3SVladimir Sementsov-Ogievskiy     nbd_recv_coroutines_wake_all(s);
74786f8cdf3SVladimir Sementsov-Ogievskiy     bdrv_dec_in_flight(s->bs);
74886f8cdf3SVladimir Sementsov-Ogievskiy 
74986f8cdf3SVladimir Sementsov-Ogievskiy     s->connection_co = NULL;
750f7651539SVladimir Sementsov-Ogievskiy     if (s->ioc) {
7518a509afdSVladimir Sementsov-Ogievskiy         qio_channel_detach_aio_context(QIO_CHANNEL(s->ioc));
752f7651539SVladimir Sementsov-Ogievskiy         object_unref(OBJECT(s->sioc));
753f7651539SVladimir Sementsov-Ogievskiy         s->sioc = NULL;
754f7651539SVladimir Sementsov-Ogievskiy         object_unref(OBJECT(s->ioc));
755f7651539SVladimir Sementsov-Ogievskiy         s->ioc = NULL;
756f7651539SVladimir Sementsov-Ogievskiy     }
757f7651539SVladimir Sementsov-Ogievskiy 
75878c81a3fSMax Reitz     if (s->teardown_co) {
75978c81a3fSMax Reitz         aio_co_wake(s->teardown_co);
76078c81a3fSMax Reitz     }
76186f8cdf3SVladimir Sementsov-Ogievskiy     aio_wait_kick();
76286f8cdf3SVladimir Sementsov-Ogievskiy }
76386f8cdf3SVladimir Sementsov-Ogievskiy 
76486f8cdf3SVladimir Sementsov-Ogievskiy static int nbd_co_send_request(BlockDriverState *bs,
76586f8cdf3SVladimir Sementsov-Ogievskiy                                NBDRequest *request,
76686f8cdf3SVladimir Sementsov-Ogievskiy                                QEMUIOVector *qiov)
76786f8cdf3SVladimir Sementsov-Ogievskiy {
768611ae1d7SVladimir Sementsov-Ogievskiy     BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
769a34b1e5eSVladimir Sementsov-Ogievskiy     int rc, i = -1;
77086f8cdf3SVladimir Sementsov-Ogievskiy 
77186f8cdf3SVladimir Sementsov-Ogievskiy     qemu_co_mutex_lock(&s->send_mutex);
772f7651539SVladimir Sementsov-Ogievskiy     while (s->in_flight == MAX_NBD_REQUESTS || nbd_client_connecting_wait(s)) {
77386f8cdf3SVladimir Sementsov-Ogievskiy         qemu_co_queue_wait(&s->free_sema, &s->send_mutex);
77486f8cdf3SVladimir Sementsov-Ogievskiy     }
775a34b1e5eSVladimir Sementsov-Ogievskiy 
776a34b1e5eSVladimir Sementsov-Ogievskiy     if (s->state != NBD_CLIENT_CONNECTED) {
777a34b1e5eSVladimir Sementsov-Ogievskiy         rc = -EIO;
778a34b1e5eSVladimir Sementsov-Ogievskiy         goto err;
779a34b1e5eSVladimir Sementsov-Ogievskiy     }
780a34b1e5eSVladimir Sementsov-Ogievskiy 
78186f8cdf3SVladimir Sementsov-Ogievskiy     s->in_flight++;
78286f8cdf3SVladimir Sementsov-Ogievskiy 
78386f8cdf3SVladimir Sementsov-Ogievskiy     for (i = 0; i < MAX_NBD_REQUESTS; i++) {
78486f8cdf3SVladimir Sementsov-Ogievskiy         if (s->requests[i].coroutine == NULL) {
78586f8cdf3SVladimir Sementsov-Ogievskiy             break;
78686f8cdf3SVladimir Sementsov-Ogievskiy         }
78786f8cdf3SVladimir Sementsov-Ogievskiy     }
78886f8cdf3SVladimir Sementsov-Ogievskiy 
78986f8cdf3SVladimir Sementsov-Ogievskiy     g_assert(qemu_in_coroutine());
79086f8cdf3SVladimir Sementsov-Ogievskiy     assert(i < MAX_NBD_REQUESTS);
79186f8cdf3SVladimir Sementsov-Ogievskiy 
79286f8cdf3SVladimir Sementsov-Ogievskiy     s->requests[i].coroutine = qemu_coroutine_self();
79386f8cdf3SVladimir Sementsov-Ogievskiy     s->requests[i].offset = request->from;
79486f8cdf3SVladimir Sementsov-Ogievskiy     s->requests[i].receiving = false;
79586f8cdf3SVladimir Sementsov-Ogievskiy 
79686f8cdf3SVladimir Sementsov-Ogievskiy     request->handle = INDEX_TO_HANDLE(s, i);
79786f8cdf3SVladimir Sementsov-Ogievskiy 
79886f8cdf3SVladimir Sementsov-Ogievskiy     assert(s->ioc);
79986f8cdf3SVladimir Sementsov-Ogievskiy 
80086f8cdf3SVladimir Sementsov-Ogievskiy     if (qiov) {
80186f8cdf3SVladimir Sementsov-Ogievskiy         qio_channel_set_cork(s->ioc, true);
80286f8cdf3SVladimir Sementsov-Ogievskiy         rc = nbd_send_request(s->ioc, request);
803a34b1e5eSVladimir Sementsov-Ogievskiy         if (rc >= 0 && s->state == NBD_CLIENT_CONNECTED) {
80486f8cdf3SVladimir Sementsov-Ogievskiy             if (qio_channel_writev_all(s->ioc, qiov->iov, qiov->niov,
80586f8cdf3SVladimir Sementsov-Ogievskiy                                        NULL) < 0) {
80686f8cdf3SVladimir Sementsov-Ogievskiy                 rc = -EIO;
80786f8cdf3SVladimir Sementsov-Ogievskiy             }
80886f8cdf3SVladimir Sementsov-Ogievskiy         } else if (rc >= 0) {
80986f8cdf3SVladimir Sementsov-Ogievskiy             rc = -EIO;
81086f8cdf3SVladimir Sementsov-Ogievskiy         }
81186f8cdf3SVladimir Sementsov-Ogievskiy         qio_channel_set_cork(s->ioc, false);
81286f8cdf3SVladimir Sementsov-Ogievskiy     } else {
81386f8cdf3SVladimir Sementsov-Ogievskiy         rc = nbd_send_request(s->ioc, request);
81486f8cdf3SVladimir Sementsov-Ogievskiy     }
81586f8cdf3SVladimir Sementsov-Ogievskiy 
81686f8cdf3SVladimir Sementsov-Ogievskiy err:
81786f8cdf3SVladimir Sementsov-Ogievskiy     if (rc < 0) {
818a34b1e5eSVladimir Sementsov-Ogievskiy         nbd_channel_error(s, rc);
819a34b1e5eSVladimir Sementsov-Ogievskiy         if (i != -1) {
82086f8cdf3SVladimir Sementsov-Ogievskiy             s->requests[i].coroutine = NULL;
82186f8cdf3SVladimir Sementsov-Ogievskiy             s->in_flight--;
822a34b1e5eSVladimir Sementsov-Ogievskiy         }
823f7651539SVladimir Sementsov-Ogievskiy         if (s->in_flight == 0 && s->wait_in_flight) {
824f7651539SVladimir Sementsov-Ogievskiy             aio_co_wake(s->connection_co);
825f7651539SVladimir Sementsov-Ogievskiy         } else {
82686f8cdf3SVladimir Sementsov-Ogievskiy             qemu_co_queue_next(&s->free_sema);
82786f8cdf3SVladimir Sementsov-Ogievskiy         }
828f7651539SVladimir Sementsov-Ogievskiy     }
82986f8cdf3SVladimir Sementsov-Ogievskiy     qemu_co_mutex_unlock(&s->send_mutex);
83086f8cdf3SVladimir Sementsov-Ogievskiy     return rc;
83186f8cdf3SVladimir Sementsov-Ogievskiy }
83286f8cdf3SVladimir Sementsov-Ogievskiy 
83386f8cdf3SVladimir Sementsov-Ogievskiy static inline uint16_t payload_advance16(uint8_t **payload)
83486f8cdf3SVladimir Sementsov-Ogievskiy {
83586f8cdf3SVladimir Sementsov-Ogievskiy     *payload += 2;
83686f8cdf3SVladimir Sementsov-Ogievskiy     return lduw_be_p(*payload - 2);
83786f8cdf3SVladimir Sementsov-Ogievskiy }
83886f8cdf3SVladimir Sementsov-Ogievskiy 
83986f8cdf3SVladimir Sementsov-Ogievskiy static inline uint32_t payload_advance32(uint8_t **payload)
84086f8cdf3SVladimir Sementsov-Ogievskiy {
84186f8cdf3SVladimir Sementsov-Ogievskiy     *payload += 4;
84286f8cdf3SVladimir Sementsov-Ogievskiy     return ldl_be_p(*payload - 4);
84386f8cdf3SVladimir Sementsov-Ogievskiy }
84486f8cdf3SVladimir Sementsov-Ogievskiy 
84586f8cdf3SVladimir Sementsov-Ogievskiy static inline uint64_t payload_advance64(uint8_t **payload)
84686f8cdf3SVladimir Sementsov-Ogievskiy {
84786f8cdf3SVladimir Sementsov-Ogievskiy     *payload += 8;
84886f8cdf3SVladimir Sementsov-Ogievskiy     return ldq_be_p(*payload - 8);
84986f8cdf3SVladimir Sementsov-Ogievskiy }
85086f8cdf3SVladimir Sementsov-Ogievskiy 
851611ae1d7SVladimir Sementsov-Ogievskiy static int nbd_parse_offset_hole_payload(BDRVNBDState *s,
85286f8cdf3SVladimir Sementsov-Ogievskiy                                          NBDStructuredReplyChunk *chunk,
85386f8cdf3SVladimir Sementsov-Ogievskiy                                          uint8_t *payload, uint64_t orig_offset,
85486f8cdf3SVladimir Sementsov-Ogievskiy                                          QEMUIOVector *qiov, Error **errp)
85586f8cdf3SVladimir Sementsov-Ogievskiy {
85686f8cdf3SVladimir Sementsov-Ogievskiy     uint64_t offset;
85786f8cdf3SVladimir Sementsov-Ogievskiy     uint32_t hole_size;
85886f8cdf3SVladimir Sementsov-Ogievskiy 
85986f8cdf3SVladimir Sementsov-Ogievskiy     if (chunk->length != sizeof(offset) + sizeof(hole_size)) {
86086f8cdf3SVladimir Sementsov-Ogievskiy         error_setg(errp, "Protocol error: invalid payload for "
86186f8cdf3SVladimir Sementsov-Ogievskiy                          "NBD_REPLY_TYPE_OFFSET_HOLE");
86286f8cdf3SVladimir Sementsov-Ogievskiy         return -EINVAL;
86386f8cdf3SVladimir Sementsov-Ogievskiy     }
86486f8cdf3SVladimir Sementsov-Ogievskiy 
86586f8cdf3SVladimir Sementsov-Ogievskiy     offset = payload_advance64(&payload);
86686f8cdf3SVladimir Sementsov-Ogievskiy     hole_size = payload_advance32(&payload);
86786f8cdf3SVladimir Sementsov-Ogievskiy 
86886f8cdf3SVladimir Sementsov-Ogievskiy     if (!hole_size || offset < orig_offset || hole_size > qiov->size ||
86986f8cdf3SVladimir Sementsov-Ogievskiy         offset > orig_offset + qiov->size - hole_size) {
87086f8cdf3SVladimir Sementsov-Ogievskiy         error_setg(errp, "Protocol error: server sent chunk exceeding requested"
87186f8cdf3SVladimir Sementsov-Ogievskiy                          " region");
87286f8cdf3SVladimir Sementsov-Ogievskiy         return -EINVAL;
87386f8cdf3SVladimir Sementsov-Ogievskiy     }
874611ae1d7SVladimir Sementsov-Ogievskiy     if (s->info.min_block &&
875611ae1d7SVladimir Sementsov-Ogievskiy         !QEMU_IS_ALIGNED(hole_size, s->info.min_block)) {
87686f8cdf3SVladimir Sementsov-Ogievskiy         trace_nbd_structured_read_compliance("hole");
87786f8cdf3SVladimir Sementsov-Ogievskiy     }
87886f8cdf3SVladimir Sementsov-Ogievskiy 
87986f8cdf3SVladimir Sementsov-Ogievskiy     qemu_iovec_memset(qiov, offset - orig_offset, 0, hole_size);
88086f8cdf3SVladimir Sementsov-Ogievskiy 
88186f8cdf3SVladimir Sementsov-Ogievskiy     return 0;
88286f8cdf3SVladimir Sementsov-Ogievskiy }
88386f8cdf3SVladimir Sementsov-Ogievskiy 
88486f8cdf3SVladimir Sementsov-Ogievskiy /*
88586f8cdf3SVladimir Sementsov-Ogievskiy  * nbd_parse_blockstatus_payload
88686f8cdf3SVladimir Sementsov-Ogievskiy  * Based on our request, we expect only one extent in reply, for the
88786f8cdf3SVladimir Sementsov-Ogievskiy  * base:allocation context.
88886f8cdf3SVladimir Sementsov-Ogievskiy  */
889611ae1d7SVladimir Sementsov-Ogievskiy static int nbd_parse_blockstatus_payload(BDRVNBDState *s,
89086f8cdf3SVladimir Sementsov-Ogievskiy                                          NBDStructuredReplyChunk *chunk,
89186f8cdf3SVladimir Sementsov-Ogievskiy                                          uint8_t *payload, uint64_t orig_length,
89286f8cdf3SVladimir Sementsov-Ogievskiy                                          NBDExtent *extent, Error **errp)
89386f8cdf3SVladimir Sementsov-Ogievskiy {
89486f8cdf3SVladimir Sementsov-Ogievskiy     uint32_t context_id;
89586f8cdf3SVladimir Sementsov-Ogievskiy 
89686f8cdf3SVladimir Sementsov-Ogievskiy     /* The server succeeded, so it must have sent [at least] one extent */
89786f8cdf3SVladimir Sementsov-Ogievskiy     if (chunk->length < sizeof(context_id) + sizeof(*extent)) {
89886f8cdf3SVladimir Sementsov-Ogievskiy         error_setg(errp, "Protocol error: invalid payload for "
89986f8cdf3SVladimir Sementsov-Ogievskiy                          "NBD_REPLY_TYPE_BLOCK_STATUS");
90086f8cdf3SVladimir Sementsov-Ogievskiy         return -EINVAL;
90186f8cdf3SVladimir Sementsov-Ogievskiy     }
90286f8cdf3SVladimir Sementsov-Ogievskiy 
90386f8cdf3SVladimir Sementsov-Ogievskiy     context_id = payload_advance32(&payload);
904611ae1d7SVladimir Sementsov-Ogievskiy     if (s->info.context_id != context_id) {
90586f8cdf3SVladimir Sementsov-Ogievskiy         error_setg(errp, "Protocol error: unexpected context id %d for "
90686f8cdf3SVladimir Sementsov-Ogievskiy                          "NBD_REPLY_TYPE_BLOCK_STATUS, when negotiated context "
90786f8cdf3SVladimir Sementsov-Ogievskiy                          "id is %d", context_id,
908611ae1d7SVladimir Sementsov-Ogievskiy                          s->info.context_id);
90986f8cdf3SVladimir Sementsov-Ogievskiy         return -EINVAL;
91086f8cdf3SVladimir Sementsov-Ogievskiy     }
91186f8cdf3SVladimir Sementsov-Ogievskiy 
91286f8cdf3SVladimir Sementsov-Ogievskiy     extent->length = payload_advance32(&payload);
91386f8cdf3SVladimir Sementsov-Ogievskiy     extent->flags = payload_advance32(&payload);
91486f8cdf3SVladimir Sementsov-Ogievskiy 
91586f8cdf3SVladimir Sementsov-Ogievskiy     if (extent->length == 0) {
91686f8cdf3SVladimir Sementsov-Ogievskiy         error_setg(errp, "Protocol error: server sent status chunk with "
91786f8cdf3SVladimir Sementsov-Ogievskiy                    "zero length");
91886f8cdf3SVladimir Sementsov-Ogievskiy         return -EINVAL;
91986f8cdf3SVladimir Sementsov-Ogievskiy     }
92086f8cdf3SVladimir Sementsov-Ogievskiy 
92186f8cdf3SVladimir Sementsov-Ogievskiy     /*
92286f8cdf3SVladimir Sementsov-Ogievskiy      * A server sending unaligned block status is in violation of the
92386f8cdf3SVladimir Sementsov-Ogievskiy      * protocol, but as qemu-nbd 3.1 is such a server (at least for
92486f8cdf3SVladimir Sementsov-Ogievskiy      * POSIX files that are not a multiple of 512 bytes, since qemu
92586f8cdf3SVladimir Sementsov-Ogievskiy      * rounds files up to 512-byte multiples but lseek(SEEK_HOLE)
92686f8cdf3SVladimir Sementsov-Ogievskiy      * still sees an implicit hole beyond the real EOF), it's nicer to
92786f8cdf3SVladimir Sementsov-Ogievskiy      * work around the misbehaving server. If the request included
92886f8cdf3SVladimir Sementsov-Ogievskiy      * more than the final unaligned block, truncate it back to an
92986f8cdf3SVladimir Sementsov-Ogievskiy      * aligned result; if the request was only the final block, round
93086f8cdf3SVladimir Sementsov-Ogievskiy      * up to the full block and change the status to fully-allocated
93186f8cdf3SVladimir Sementsov-Ogievskiy      * (always a safe status, even if it loses information).
93286f8cdf3SVladimir Sementsov-Ogievskiy      */
933611ae1d7SVladimir Sementsov-Ogievskiy     if (s->info.min_block && !QEMU_IS_ALIGNED(extent->length,
934611ae1d7SVladimir Sementsov-Ogievskiy                                                    s->info.min_block)) {
93586f8cdf3SVladimir Sementsov-Ogievskiy         trace_nbd_parse_blockstatus_compliance("extent length is unaligned");
936611ae1d7SVladimir Sementsov-Ogievskiy         if (extent->length > s->info.min_block) {
93786f8cdf3SVladimir Sementsov-Ogievskiy             extent->length = QEMU_ALIGN_DOWN(extent->length,
938611ae1d7SVladimir Sementsov-Ogievskiy                                              s->info.min_block);
93986f8cdf3SVladimir Sementsov-Ogievskiy         } else {
940611ae1d7SVladimir Sementsov-Ogievskiy             extent->length = s->info.min_block;
94186f8cdf3SVladimir Sementsov-Ogievskiy             extent->flags = 0;
94286f8cdf3SVladimir Sementsov-Ogievskiy         }
94386f8cdf3SVladimir Sementsov-Ogievskiy     }
94486f8cdf3SVladimir Sementsov-Ogievskiy 
94586f8cdf3SVladimir Sementsov-Ogievskiy     /*
94686f8cdf3SVladimir Sementsov-Ogievskiy      * We used NBD_CMD_FLAG_REQ_ONE, so the server should not have
94786f8cdf3SVladimir Sementsov-Ogievskiy      * sent us any more than one extent, nor should it have included
94886f8cdf3SVladimir Sementsov-Ogievskiy      * status beyond our request in that extent. However, it's easy
94986f8cdf3SVladimir Sementsov-Ogievskiy      * enough to ignore the server's noncompliance without killing the
95086f8cdf3SVladimir Sementsov-Ogievskiy      * connection; just ignore trailing extents, and clamp things to
95186f8cdf3SVladimir Sementsov-Ogievskiy      * the length of our request.
95286f8cdf3SVladimir Sementsov-Ogievskiy      */
95386f8cdf3SVladimir Sementsov-Ogievskiy     if (chunk->length > sizeof(context_id) + sizeof(*extent)) {
95486f8cdf3SVladimir Sementsov-Ogievskiy         trace_nbd_parse_blockstatus_compliance("more than one extent");
95586f8cdf3SVladimir Sementsov-Ogievskiy     }
95686f8cdf3SVladimir Sementsov-Ogievskiy     if (extent->length > orig_length) {
95786f8cdf3SVladimir Sementsov-Ogievskiy         extent->length = orig_length;
95886f8cdf3SVladimir Sementsov-Ogievskiy         trace_nbd_parse_blockstatus_compliance("extent length too large");
95986f8cdf3SVladimir Sementsov-Ogievskiy     }
96086f8cdf3SVladimir Sementsov-Ogievskiy 
96186f8cdf3SVladimir Sementsov-Ogievskiy     return 0;
96286f8cdf3SVladimir Sementsov-Ogievskiy }
96386f8cdf3SVladimir Sementsov-Ogievskiy 
96486f8cdf3SVladimir Sementsov-Ogievskiy /*
96586f8cdf3SVladimir Sementsov-Ogievskiy  * nbd_parse_error_payload
96686f8cdf3SVladimir Sementsov-Ogievskiy  * on success @errp contains message describing nbd error reply
96786f8cdf3SVladimir Sementsov-Ogievskiy  */
96886f8cdf3SVladimir Sementsov-Ogievskiy static int nbd_parse_error_payload(NBDStructuredReplyChunk *chunk,
96986f8cdf3SVladimir Sementsov-Ogievskiy                                    uint8_t *payload, int *request_ret,
97086f8cdf3SVladimir Sementsov-Ogievskiy                                    Error **errp)
97186f8cdf3SVladimir Sementsov-Ogievskiy {
97286f8cdf3SVladimir Sementsov-Ogievskiy     uint32_t error;
97386f8cdf3SVladimir Sementsov-Ogievskiy     uint16_t message_size;
97486f8cdf3SVladimir Sementsov-Ogievskiy 
97586f8cdf3SVladimir Sementsov-Ogievskiy     assert(chunk->type & (1 << 15));
97686f8cdf3SVladimir Sementsov-Ogievskiy 
97786f8cdf3SVladimir Sementsov-Ogievskiy     if (chunk->length < sizeof(error) + sizeof(message_size)) {
97886f8cdf3SVladimir Sementsov-Ogievskiy         error_setg(errp,
97986f8cdf3SVladimir Sementsov-Ogievskiy                    "Protocol error: invalid payload for structured error");
98086f8cdf3SVladimir Sementsov-Ogievskiy         return -EINVAL;
98186f8cdf3SVladimir Sementsov-Ogievskiy     }
98286f8cdf3SVladimir Sementsov-Ogievskiy 
98386f8cdf3SVladimir Sementsov-Ogievskiy     error = nbd_errno_to_system_errno(payload_advance32(&payload));
98486f8cdf3SVladimir Sementsov-Ogievskiy     if (error == 0) {
98586f8cdf3SVladimir Sementsov-Ogievskiy         error_setg(errp, "Protocol error: server sent structured error chunk "
98686f8cdf3SVladimir Sementsov-Ogievskiy                          "with error = 0");
98786f8cdf3SVladimir Sementsov-Ogievskiy         return -EINVAL;
98886f8cdf3SVladimir Sementsov-Ogievskiy     }
98986f8cdf3SVladimir Sementsov-Ogievskiy 
99086f8cdf3SVladimir Sementsov-Ogievskiy     *request_ret = -error;
99186f8cdf3SVladimir Sementsov-Ogievskiy     message_size = payload_advance16(&payload);
99286f8cdf3SVladimir Sementsov-Ogievskiy 
99386f8cdf3SVladimir Sementsov-Ogievskiy     if (message_size > chunk->length - sizeof(error) - sizeof(message_size)) {
99486f8cdf3SVladimir Sementsov-Ogievskiy         error_setg(errp, "Protocol error: server sent structured error chunk "
99586f8cdf3SVladimir Sementsov-Ogievskiy                          "with incorrect message size");
99686f8cdf3SVladimir Sementsov-Ogievskiy         return -EINVAL;
99786f8cdf3SVladimir Sementsov-Ogievskiy     }
99886f8cdf3SVladimir Sementsov-Ogievskiy 
99986f8cdf3SVladimir Sementsov-Ogievskiy     /* TODO: Add a trace point to mention the server complaint */
100086f8cdf3SVladimir Sementsov-Ogievskiy 
100186f8cdf3SVladimir Sementsov-Ogievskiy     /* TODO handle ERROR_OFFSET */
100286f8cdf3SVladimir Sementsov-Ogievskiy 
100386f8cdf3SVladimir Sementsov-Ogievskiy     return 0;
100486f8cdf3SVladimir Sementsov-Ogievskiy }
100586f8cdf3SVladimir Sementsov-Ogievskiy 
1006611ae1d7SVladimir Sementsov-Ogievskiy static int nbd_co_receive_offset_data_payload(BDRVNBDState *s,
100786f8cdf3SVladimir Sementsov-Ogievskiy                                               uint64_t orig_offset,
100886f8cdf3SVladimir Sementsov-Ogievskiy                                               QEMUIOVector *qiov, Error **errp)
100986f8cdf3SVladimir Sementsov-Ogievskiy {
101086f8cdf3SVladimir Sementsov-Ogievskiy     QEMUIOVector sub_qiov;
101186f8cdf3SVladimir Sementsov-Ogievskiy     uint64_t offset;
101286f8cdf3SVladimir Sementsov-Ogievskiy     size_t data_size;
101386f8cdf3SVladimir Sementsov-Ogievskiy     int ret;
101486f8cdf3SVladimir Sementsov-Ogievskiy     NBDStructuredReplyChunk *chunk = &s->reply.structured;
101586f8cdf3SVladimir Sementsov-Ogievskiy 
101686f8cdf3SVladimir Sementsov-Ogievskiy     assert(nbd_reply_is_structured(&s->reply));
101786f8cdf3SVladimir Sementsov-Ogievskiy 
101886f8cdf3SVladimir Sementsov-Ogievskiy     /* The NBD spec requires at least one byte of payload */
101986f8cdf3SVladimir Sementsov-Ogievskiy     if (chunk->length <= sizeof(offset)) {
102086f8cdf3SVladimir Sementsov-Ogievskiy         error_setg(errp, "Protocol error: invalid payload for "
102186f8cdf3SVladimir Sementsov-Ogievskiy                          "NBD_REPLY_TYPE_OFFSET_DATA");
102286f8cdf3SVladimir Sementsov-Ogievskiy         return -EINVAL;
102386f8cdf3SVladimir Sementsov-Ogievskiy     }
102486f8cdf3SVladimir Sementsov-Ogievskiy 
102586f8cdf3SVladimir Sementsov-Ogievskiy     if (nbd_read64(s->ioc, &offset, "OFFSET_DATA offset", errp) < 0) {
102686f8cdf3SVladimir Sementsov-Ogievskiy         return -EIO;
102786f8cdf3SVladimir Sementsov-Ogievskiy     }
102886f8cdf3SVladimir Sementsov-Ogievskiy 
102986f8cdf3SVladimir Sementsov-Ogievskiy     data_size = chunk->length - sizeof(offset);
103086f8cdf3SVladimir Sementsov-Ogievskiy     assert(data_size);
103186f8cdf3SVladimir Sementsov-Ogievskiy     if (offset < orig_offset || data_size > qiov->size ||
103286f8cdf3SVladimir Sementsov-Ogievskiy         offset > orig_offset + qiov->size - data_size) {
103386f8cdf3SVladimir Sementsov-Ogievskiy         error_setg(errp, "Protocol error: server sent chunk exceeding requested"
103486f8cdf3SVladimir Sementsov-Ogievskiy                          " region");
103586f8cdf3SVladimir Sementsov-Ogievskiy         return -EINVAL;
103686f8cdf3SVladimir Sementsov-Ogievskiy     }
103786f8cdf3SVladimir Sementsov-Ogievskiy     if (s->info.min_block && !QEMU_IS_ALIGNED(data_size, s->info.min_block)) {
103886f8cdf3SVladimir Sementsov-Ogievskiy         trace_nbd_structured_read_compliance("data");
103986f8cdf3SVladimir Sementsov-Ogievskiy     }
104086f8cdf3SVladimir Sementsov-Ogievskiy 
104186f8cdf3SVladimir Sementsov-Ogievskiy     qemu_iovec_init(&sub_qiov, qiov->niov);
104286f8cdf3SVladimir Sementsov-Ogievskiy     qemu_iovec_concat(&sub_qiov, qiov, offset - orig_offset, data_size);
104386f8cdf3SVladimir Sementsov-Ogievskiy     ret = qio_channel_readv_all(s->ioc, sub_qiov.iov, sub_qiov.niov, errp);
104486f8cdf3SVladimir Sementsov-Ogievskiy     qemu_iovec_destroy(&sub_qiov);
104586f8cdf3SVladimir Sementsov-Ogievskiy 
104686f8cdf3SVladimir Sementsov-Ogievskiy     return ret < 0 ? -EIO : 0;
104786f8cdf3SVladimir Sementsov-Ogievskiy }
104886f8cdf3SVladimir Sementsov-Ogievskiy 
104986f8cdf3SVladimir Sementsov-Ogievskiy #define NBD_MAX_MALLOC_PAYLOAD 1000
105086f8cdf3SVladimir Sementsov-Ogievskiy static coroutine_fn int nbd_co_receive_structured_payload(
1051611ae1d7SVladimir Sementsov-Ogievskiy         BDRVNBDState *s, void **payload, Error **errp)
105286f8cdf3SVladimir Sementsov-Ogievskiy {
105386f8cdf3SVladimir Sementsov-Ogievskiy     int ret;
105486f8cdf3SVladimir Sementsov-Ogievskiy     uint32_t len;
105586f8cdf3SVladimir Sementsov-Ogievskiy 
105686f8cdf3SVladimir Sementsov-Ogievskiy     assert(nbd_reply_is_structured(&s->reply));
105786f8cdf3SVladimir Sementsov-Ogievskiy 
105886f8cdf3SVladimir Sementsov-Ogievskiy     len = s->reply.structured.length;
105986f8cdf3SVladimir Sementsov-Ogievskiy 
106086f8cdf3SVladimir Sementsov-Ogievskiy     if (len == 0) {
106186f8cdf3SVladimir Sementsov-Ogievskiy         return 0;
106286f8cdf3SVladimir Sementsov-Ogievskiy     }
106386f8cdf3SVladimir Sementsov-Ogievskiy 
106486f8cdf3SVladimir Sementsov-Ogievskiy     if (payload == NULL) {
106586f8cdf3SVladimir Sementsov-Ogievskiy         error_setg(errp, "Unexpected structured payload");
106686f8cdf3SVladimir Sementsov-Ogievskiy         return -EINVAL;
106786f8cdf3SVladimir Sementsov-Ogievskiy     }
106886f8cdf3SVladimir Sementsov-Ogievskiy 
106986f8cdf3SVladimir Sementsov-Ogievskiy     if (len > NBD_MAX_MALLOC_PAYLOAD) {
107086f8cdf3SVladimir Sementsov-Ogievskiy         error_setg(errp, "Payload too large");
107186f8cdf3SVladimir Sementsov-Ogievskiy         return -EINVAL;
107286f8cdf3SVladimir Sementsov-Ogievskiy     }
107386f8cdf3SVladimir Sementsov-Ogievskiy 
107486f8cdf3SVladimir Sementsov-Ogievskiy     *payload = g_new(char, len);
107586f8cdf3SVladimir Sementsov-Ogievskiy     ret = nbd_read(s->ioc, *payload, len, "structured payload", errp);
107686f8cdf3SVladimir Sementsov-Ogievskiy     if (ret < 0) {
107786f8cdf3SVladimir Sementsov-Ogievskiy         g_free(*payload);
107886f8cdf3SVladimir Sementsov-Ogievskiy         *payload = NULL;
107986f8cdf3SVladimir Sementsov-Ogievskiy         return ret;
108086f8cdf3SVladimir Sementsov-Ogievskiy     }
108186f8cdf3SVladimir Sementsov-Ogievskiy 
108286f8cdf3SVladimir Sementsov-Ogievskiy     return 0;
108386f8cdf3SVladimir Sementsov-Ogievskiy }
108486f8cdf3SVladimir Sementsov-Ogievskiy 
108586f8cdf3SVladimir Sementsov-Ogievskiy /*
108686f8cdf3SVladimir Sementsov-Ogievskiy  * nbd_co_do_receive_one_chunk
108786f8cdf3SVladimir Sementsov-Ogievskiy  * for simple reply:
108886f8cdf3SVladimir Sementsov-Ogievskiy  *   set request_ret to received reply error
108986f8cdf3SVladimir Sementsov-Ogievskiy  *   if qiov is not NULL: read payload to @qiov
109086f8cdf3SVladimir Sementsov-Ogievskiy  * for structured reply chunk:
109186f8cdf3SVladimir Sementsov-Ogievskiy  *   if error chunk: read payload, set @request_ret, do not set @payload
109286f8cdf3SVladimir Sementsov-Ogievskiy  *   else if offset_data chunk: read payload data to @qiov, do not set @payload
109386f8cdf3SVladimir Sementsov-Ogievskiy  *   else: read payload to @payload
109486f8cdf3SVladimir Sementsov-Ogievskiy  *
109586f8cdf3SVladimir Sementsov-Ogievskiy  * If function fails, @errp contains corresponding error message, and the
109686f8cdf3SVladimir Sementsov-Ogievskiy  * connection with the server is suspect.  If it returns 0, then the
109786f8cdf3SVladimir Sementsov-Ogievskiy  * transaction succeeded (although @request_ret may be a negative errno
109886f8cdf3SVladimir Sementsov-Ogievskiy  * corresponding to the server's error reply), and errp is unchanged.
109986f8cdf3SVladimir Sementsov-Ogievskiy  */
110086f8cdf3SVladimir Sementsov-Ogievskiy static coroutine_fn int nbd_co_do_receive_one_chunk(
1101611ae1d7SVladimir Sementsov-Ogievskiy         BDRVNBDState *s, uint64_t handle, bool only_structured,
110286f8cdf3SVladimir Sementsov-Ogievskiy         int *request_ret, QEMUIOVector *qiov, void **payload, Error **errp)
110386f8cdf3SVladimir Sementsov-Ogievskiy {
110486f8cdf3SVladimir Sementsov-Ogievskiy     int ret;
110586f8cdf3SVladimir Sementsov-Ogievskiy     int i = HANDLE_TO_INDEX(s, handle);
110686f8cdf3SVladimir Sementsov-Ogievskiy     void *local_payload = NULL;
110786f8cdf3SVladimir Sementsov-Ogievskiy     NBDStructuredReplyChunk *chunk;
110886f8cdf3SVladimir Sementsov-Ogievskiy 
110986f8cdf3SVladimir Sementsov-Ogievskiy     if (payload) {
111086f8cdf3SVladimir Sementsov-Ogievskiy         *payload = NULL;
111186f8cdf3SVladimir Sementsov-Ogievskiy     }
111286f8cdf3SVladimir Sementsov-Ogievskiy     *request_ret = 0;
111386f8cdf3SVladimir Sementsov-Ogievskiy 
111486f8cdf3SVladimir Sementsov-Ogievskiy     /* Wait until we're woken up by nbd_connection_entry.  */
111586f8cdf3SVladimir Sementsov-Ogievskiy     s->requests[i].receiving = true;
111686f8cdf3SVladimir Sementsov-Ogievskiy     qemu_coroutine_yield();
111786f8cdf3SVladimir Sementsov-Ogievskiy     s->requests[i].receiving = false;
1118a34b1e5eSVladimir Sementsov-Ogievskiy     if (s->state != NBD_CLIENT_CONNECTED) {
111986f8cdf3SVladimir Sementsov-Ogievskiy         error_setg(errp, "Connection closed");
112086f8cdf3SVladimir Sementsov-Ogievskiy         return -EIO;
112186f8cdf3SVladimir Sementsov-Ogievskiy     }
112286f8cdf3SVladimir Sementsov-Ogievskiy     assert(s->ioc);
112386f8cdf3SVladimir Sementsov-Ogievskiy 
112486f8cdf3SVladimir Sementsov-Ogievskiy     assert(s->reply.handle == handle);
112586f8cdf3SVladimir Sementsov-Ogievskiy 
112686f8cdf3SVladimir Sementsov-Ogievskiy     if (nbd_reply_is_simple(&s->reply)) {
112786f8cdf3SVladimir Sementsov-Ogievskiy         if (only_structured) {
112886f8cdf3SVladimir Sementsov-Ogievskiy             error_setg(errp, "Protocol error: simple reply when structured "
112986f8cdf3SVladimir Sementsov-Ogievskiy                              "reply chunk was expected");
113086f8cdf3SVladimir Sementsov-Ogievskiy             return -EINVAL;
113186f8cdf3SVladimir Sementsov-Ogievskiy         }
113286f8cdf3SVladimir Sementsov-Ogievskiy 
113386f8cdf3SVladimir Sementsov-Ogievskiy         *request_ret = -nbd_errno_to_system_errno(s->reply.simple.error);
113486f8cdf3SVladimir Sementsov-Ogievskiy         if (*request_ret < 0 || !qiov) {
113586f8cdf3SVladimir Sementsov-Ogievskiy             return 0;
113686f8cdf3SVladimir Sementsov-Ogievskiy         }
113786f8cdf3SVladimir Sementsov-Ogievskiy 
113886f8cdf3SVladimir Sementsov-Ogievskiy         return qio_channel_readv_all(s->ioc, qiov->iov, qiov->niov,
113986f8cdf3SVladimir Sementsov-Ogievskiy                                      errp) < 0 ? -EIO : 0;
114086f8cdf3SVladimir Sementsov-Ogievskiy     }
114186f8cdf3SVladimir Sementsov-Ogievskiy 
114286f8cdf3SVladimir Sementsov-Ogievskiy     /* handle structured reply chunk */
114386f8cdf3SVladimir Sementsov-Ogievskiy     assert(s->info.structured_reply);
114486f8cdf3SVladimir Sementsov-Ogievskiy     chunk = &s->reply.structured;
114586f8cdf3SVladimir Sementsov-Ogievskiy 
114686f8cdf3SVladimir Sementsov-Ogievskiy     if (chunk->type == NBD_REPLY_TYPE_NONE) {
114786f8cdf3SVladimir Sementsov-Ogievskiy         if (!(chunk->flags & NBD_REPLY_FLAG_DONE)) {
114886f8cdf3SVladimir Sementsov-Ogievskiy             error_setg(errp, "Protocol error: NBD_REPLY_TYPE_NONE chunk without"
114986f8cdf3SVladimir Sementsov-Ogievskiy                        " NBD_REPLY_FLAG_DONE flag set");
115086f8cdf3SVladimir Sementsov-Ogievskiy             return -EINVAL;
115186f8cdf3SVladimir Sementsov-Ogievskiy         }
115286f8cdf3SVladimir Sementsov-Ogievskiy         if (chunk->length) {
115386f8cdf3SVladimir Sementsov-Ogievskiy             error_setg(errp, "Protocol error: NBD_REPLY_TYPE_NONE chunk with"
115486f8cdf3SVladimir Sementsov-Ogievskiy                        " nonzero length");
115586f8cdf3SVladimir Sementsov-Ogievskiy             return -EINVAL;
115686f8cdf3SVladimir Sementsov-Ogievskiy         }
115786f8cdf3SVladimir Sementsov-Ogievskiy         return 0;
115886f8cdf3SVladimir Sementsov-Ogievskiy     }
115986f8cdf3SVladimir Sementsov-Ogievskiy 
116086f8cdf3SVladimir Sementsov-Ogievskiy     if (chunk->type == NBD_REPLY_TYPE_OFFSET_DATA) {
116186f8cdf3SVladimir Sementsov-Ogievskiy         if (!qiov) {
116286f8cdf3SVladimir Sementsov-Ogievskiy             error_setg(errp, "Unexpected NBD_REPLY_TYPE_OFFSET_DATA chunk");
116386f8cdf3SVladimir Sementsov-Ogievskiy             return -EINVAL;
116486f8cdf3SVladimir Sementsov-Ogievskiy         }
116586f8cdf3SVladimir Sementsov-Ogievskiy 
116686f8cdf3SVladimir Sementsov-Ogievskiy         return nbd_co_receive_offset_data_payload(s, s->requests[i].offset,
116786f8cdf3SVladimir Sementsov-Ogievskiy                                                   qiov, errp);
116886f8cdf3SVladimir Sementsov-Ogievskiy     }
116986f8cdf3SVladimir Sementsov-Ogievskiy 
117086f8cdf3SVladimir Sementsov-Ogievskiy     if (nbd_reply_type_is_error(chunk->type)) {
117186f8cdf3SVladimir Sementsov-Ogievskiy         payload = &local_payload;
117286f8cdf3SVladimir Sementsov-Ogievskiy     }
117386f8cdf3SVladimir Sementsov-Ogievskiy 
117486f8cdf3SVladimir Sementsov-Ogievskiy     ret = nbd_co_receive_structured_payload(s, payload, errp);
117586f8cdf3SVladimir Sementsov-Ogievskiy     if (ret < 0) {
117686f8cdf3SVladimir Sementsov-Ogievskiy         return ret;
117786f8cdf3SVladimir Sementsov-Ogievskiy     }
117886f8cdf3SVladimir Sementsov-Ogievskiy 
117986f8cdf3SVladimir Sementsov-Ogievskiy     if (nbd_reply_type_is_error(chunk->type)) {
118086f8cdf3SVladimir Sementsov-Ogievskiy         ret = nbd_parse_error_payload(chunk, local_payload, request_ret, errp);
118186f8cdf3SVladimir Sementsov-Ogievskiy         g_free(local_payload);
118286f8cdf3SVladimir Sementsov-Ogievskiy         return ret;
118386f8cdf3SVladimir Sementsov-Ogievskiy     }
118486f8cdf3SVladimir Sementsov-Ogievskiy 
118586f8cdf3SVladimir Sementsov-Ogievskiy     return 0;
118686f8cdf3SVladimir Sementsov-Ogievskiy }
118786f8cdf3SVladimir Sementsov-Ogievskiy 
118886f8cdf3SVladimir Sementsov-Ogievskiy /*
118986f8cdf3SVladimir Sementsov-Ogievskiy  * nbd_co_receive_one_chunk
119086f8cdf3SVladimir Sementsov-Ogievskiy  * Read reply, wake up connection_co and set s->quit if needed.
119186f8cdf3SVladimir Sementsov-Ogievskiy  * Return value is a fatal error code or normal nbd reply error code
119286f8cdf3SVladimir Sementsov-Ogievskiy  */
119386f8cdf3SVladimir Sementsov-Ogievskiy static coroutine_fn int nbd_co_receive_one_chunk(
1194611ae1d7SVladimir Sementsov-Ogievskiy         BDRVNBDState *s, uint64_t handle, bool only_structured,
119586f8cdf3SVladimir Sementsov-Ogievskiy         int *request_ret, QEMUIOVector *qiov, NBDReply *reply, void **payload,
119686f8cdf3SVladimir Sementsov-Ogievskiy         Error **errp)
119786f8cdf3SVladimir Sementsov-Ogievskiy {
119886f8cdf3SVladimir Sementsov-Ogievskiy     int ret = nbd_co_do_receive_one_chunk(s, handle, only_structured,
119986f8cdf3SVladimir Sementsov-Ogievskiy                                           request_ret, qiov, payload, errp);
120086f8cdf3SVladimir Sementsov-Ogievskiy 
120186f8cdf3SVladimir Sementsov-Ogievskiy     if (ret < 0) {
12025cf42b1cSEric Blake         memset(reply, 0, sizeof(*reply));
1203a34b1e5eSVladimir Sementsov-Ogievskiy         nbd_channel_error(s, ret);
120486f8cdf3SVladimir Sementsov-Ogievskiy     } else {
120586f8cdf3SVladimir Sementsov-Ogievskiy         /* For assert at loop start in nbd_connection_entry */
120686f8cdf3SVladimir Sementsov-Ogievskiy         *reply = s->reply;
120786f8cdf3SVladimir Sementsov-Ogievskiy     }
1208f7651539SVladimir Sementsov-Ogievskiy     s->reply.handle = 0;
120986f8cdf3SVladimir Sementsov-Ogievskiy 
1210f7651539SVladimir Sementsov-Ogievskiy     if (s->connection_co && !s->wait_in_flight) {
1211f7651539SVladimir Sementsov-Ogievskiy         /*
1212f7651539SVladimir Sementsov-Ogievskiy          * We must check s->wait_in_flight, because we may entered by
1213f7651539SVladimir Sementsov-Ogievskiy          * nbd_recv_coroutines_wake_all(), in this case we should not
1214f7651539SVladimir Sementsov-Ogievskiy          * wake connection_co here, it will woken by last request.
1215f7651539SVladimir Sementsov-Ogievskiy          */
121686f8cdf3SVladimir Sementsov-Ogievskiy         aio_co_wake(s->connection_co);
121786f8cdf3SVladimir Sementsov-Ogievskiy     }
121886f8cdf3SVladimir Sementsov-Ogievskiy 
121986f8cdf3SVladimir Sementsov-Ogievskiy     return ret;
122086f8cdf3SVladimir Sementsov-Ogievskiy }
122186f8cdf3SVladimir Sementsov-Ogievskiy 
122286f8cdf3SVladimir Sementsov-Ogievskiy typedef struct NBDReplyChunkIter {
122386f8cdf3SVladimir Sementsov-Ogievskiy     int ret;
122486f8cdf3SVladimir Sementsov-Ogievskiy     int request_ret;
122586f8cdf3SVladimir Sementsov-Ogievskiy     Error *err;
122686f8cdf3SVladimir Sementsov-Ogievskiy     bool done, only_structured;
122786f8cdf3SVladimir Sementsov-Ogievskiy } NBDReplyChunkIter;
122886f8cdf3SVladimir Sementsov-Ogievskiy 
122986f8cdf3SVladimir Sementsov-Ogievskiy static void nbd_iter_channel_error(NBDReplyChunkIter *iter,
123086f8cdf3SVladimir Sementsov-Ogievskiy                                    int ret, Error **local_err)
123186f8cdf3SVladimir Sementsov-Ogievskiy {
1232d9366135SVladimir Sementsov-Ogievskiy     assert(local_err && *local_err);
123386f8cdf3SVladimir Sementsov-Ogievskiy     assert(ret < 0);
123486f8cdf3SVladimir Sementsov-Ogievskiy 
123586f8cdf3SVladimir Sementsov-Ogievskiy     if (!iter->ret) {
123686f8cdf3SVladimir Sementsov-Ogievskiy         iter->ret = ret;
123786f8cdf3SVladimir Sementsov-Ogievskiy         error_propagate(&iter->err, *local_err);
123886f8cdf3SVladimir Sementsov-Ogievskiy     } else {
123986f8cdf3SVladimir Sementsov-Ogievskiy         error_free(*local_err);
124086f8cdf3SVladimir Sementsov-Ogievskiy     }
124186f8cdf3SVladimir Sementsov-Ogievskiy 
124286f8cdf3SVladimir Sementsov-Ogievskiy     *local_err = NULL;
124386f8cdf3SVladimir Sementsov-Ogievskiy }
124486f8cdf3SVladimir Sementsov-Ogievskiy 
124586f8cdf3SVladimir Sementsov-Ogievskiy static void nbd_iter_request_error(NBDReplyChunkIter *iter, int ret)
124686f8cdf3SVladimir Sementsov-Ogievskiy {
124786f8cdf3SVladimir Sementsov-Ogievskiy     assert(ret < 0);
124886f8cdf3SVladimir Sementsov-Ogievskiy 
124986f8cdf3SVladimir Sementsov-Ogievskiy     if (!iter->request_ret) {
125086f8cdf3SVladimir Sementsov-Ogievskiy         iter->request_ret = ret;
125186f8cdf3SVladimir Sementsov-Ogievskiy     }
125286f8cdf3SVladimir Sementsov-Ogievskiy }
125386f8cdf3SVladimir Sementsov-Ogievskiy 
125486f8cdf3SVladimir Sementsov-Ogievskiy /*
125586f8cdf3SVladimir Sementsov-Ogievskiy  * NBD_FOREACH_REPLY_CHUNK
125686f8cdf3SVladimir Sementsov-Ogievskiy  * The pointer stored in @payload requires g_free() to free it.
125786f8cdf3SVladimir Sementsov-Ogievskiy  */
125886f8cdf3SVladimir Sementsov-Ogievskiy #define NBD_FOREACH_REPLY_CHUNK(s, iter, handle, structured, \
125986f8cdf3SVladimir Sementsov-Ogievskiy                                 qiov, reply, payload) \
126086f8cdf3SVladimir Sementsov-Ogievskiy     for (iter = (NBDReplyChunkIter) { .only_structured = structured }; \
126186f8cdf3SVladimir Sementsov-Ogievskiy          nbd_reply_chunk_iter_receive(s, &iter, handle, qiov, reply, payload);)
126286f8cdf3SVladimir Sementsov-Ogievskiy 
126386f8cdf3SVladimir Sementsov-Ogievskiy /*
126486f8cdf3SVladimir Sementsov-Ogievskiy  * nbd_reply_chunk_iter_receive
126586f8cdf3SVladimir Sementsov-Ogievskiy  * The pointer stored in @payload requires g_free() to free it.
126686f8cdf3SVladimir Sementsov-Ogievskiy  */
1267611ae1d7SVladimir Sementsov-Ogievskiy static bool nbd_reply_chunk_iter_receive(BDRVNBDState *s,
126886f8cdf3SVladimir Sementsov-Ogievskiy                                          NBDReplyChunkIter *iter,
126986f8cdf3SVladimir Sementsov-Ogievskiy                                          uint64_t handle,
127086f8cdf3SVladimir Sementsov-Ogievskiy                                          QEMUIOVector *qiov, NBDReply *reply,
127186f8cdf3SVladimir Sementsov-Ogievskiy                                          void **payload)
127286f8cdf3SVladimir Sementsov-Ogievskiy {
127386f8cdf3SVladimir Sementsov-Ogievskiy     int ret, request_ret;
127486f8cdf3SVladimir Sementsov-Ogievskiy     NBDReply local_reply;
127586f8cdf3SVladimir Sementsov-Ogievskiy     NBDStructuredReplyChunk *chunk;
127686f8cdf3SVladimir Sementsov-Ogievskiy     Error *local_err = NULL;
1277a34b1e5eSVladimir Sementsov-Ogievskiy     if (s->state != NBD_CLIENT_CONNECTED) {
127886f8cdf3SVladimir Sementsov-Ogievskiy         error_setg(&local_err, "Connection closed");
127986f8cdf3SVladimir Sementsov-Ogievskiy         nbd_iter_channel_error(iter, -EIO, &local_err);
128086f8cdf3SVladimir Sementsov-Ogievskiy         goto break_loop;
128186f8cdf3SVladimir Sementsov-Ogievskiy     }
128286f8cdf3SVladimir Sementsov-Ogievskiy 
128386f8cdf3SVladimir Sementsov-Ogievskiy     if (iter->done) {
128486f8cdf3SVladimir Sementsov-Ogievskiy         /* Previous iteration was last. */
128586f8cdf3SVladimir Sementsov-Ogievskiy         goto break_loop;
128686f8cdf3SVladimir Sementsov-Ogievskiy     }
128786f8cdf3SVladimir Sementsov-Ogievskiy 
128886f8cdf3SVladimir Sementsov-Ogievskiy     if (reply == NULL) {
128986f8cdf3SVladimir Sementsov-Ogievskiy         reply = &local_reply;
129086f8cdf3SVladimir Sementsov-Ogievskiy     }
129186f8cdf3SVladimir Sementsov-Ogievskiy 
129286f8cdf3SVladimir Sementsov-Ogievskiy     ret = nbd_co_receive_one_chunk(s, handle, iter->only_structured,
129386f8cdf3SVladimir Sementsov-Ogievskiy                                    &request_ret, qiov, reply, payload,
129486f8cdf3SVladimir Sementsov-Ogievskiy                                    &local_err);
129586f8cdf3SVladimir Sementsov-Ogievskiy     if (ret < 0) {
129686f8cdf3SVladimir Sementsov-Ogievskiy         nbd_iter_channel_error(iter, ret, &local_err);
129786f8cdf3SVladimir Sementsov-Ogievskiy     } else if (request_ret < 0) {
129886f8cdf3SVladimir Sementsov-Ogievskiy         nbd_iter_request_error(iter, request_ret);
129986f8cdf3SVladimir Sementsov-Ogievskiy     }
130086f8cdf3SVladimir Sementsov-Ogievskiy 
130186f8cdf3SVladimir Sementsov-Ogievskiy     /* Do not execute the body of NBD_FOREACH_REPLY_CHUNK for simple reply. */
1302a34b1e5eSVladimir Sementsov-Ogievskiy     if (nbd_reply_is_simple(reply) || s->state != NBD_CLIENT_CONNECTED) {
130386f8cdf3SVladimir Sementsov-Ogievskiy         goto break_loop;
130486f8cdf3SVladimir Sementsov-Ogievskiy     }
130586f8cdf3SVladimir Sementsov-Ogievskiy 
130686f8cdf3SVladimir Sementsov-Ogievskiy     chunk = &reply->structured;
130786f8cdf3SVladimir Sementsov-Ogievskiy     iter->only_structured = true;
130886f8cdf3SVladimir Sementsov-Ogievskiy 
130986f8cdf3SVladimir Sementsov-Ogievskiy     if (chunk->type == NBD_REPLY_TYPE_NONE) {
131086f8cdf3SVladimir Sementsov-Ogievskiy         /* NBD_REPLY_FLAG_DONE is already checked in nbd_co_receive_one_chunk */
131186f8cdf3SVladimir Sementsov-Ogievskiy         assert(chunk->flags & NBD_REPLY_FLAG_DONE);
131286f8cdf3SVladimir Sementsov-Ogievskiy         goto break_loop;
131386f8cdf3SVladimir Sementsov-Ogievskiy     }
131486f8cdf3SVladimir Sementsov-Ogievskiy 
131586f8cdf3SVladimir Sementsov-Ogievskiy     if (chunk->flags & NBD_REPLY_FLAG_DONE) {
131686f8cdf3SVladimir Sementsov-Ogievskiy         /* This iteration is last. */
131786f8cdf3SVladimir Sementsov-Ogievskiy         iter->done = true;
131886f8cdf3SVladimir Sementsov-Ogievskiy     }
131986f8cdf3SVladimir Sementsov-Ogievskiy 
132086f8cdf3SVladimir Sementsov-Ogievskiy     /* Execute the loop body */
132186f8cdf3SVladimir Sementsov-Ogievskiy     return true;
132286f8cdf3SVladimir Sementsov-Ogievskiy 
132386f8cdf3SVladimir Sementsov-Ogievskiy break_loop:
132486f8cdf3SVladimir Sementsov-Ogievskiy     s->requests[HANDLE_TO_INDEX(s, handle)].coroutine = NULL;
132586f8cdf3SVladimir Sementsov-Ogievskiy 
132686f8cdf3SVladimir Sementsov-Ogievskiy     qemu_co_mutex_lock(&s->send_mutex);
132786f8cdf3SVladimir Sementsov-Ogievskiy     s->in_flight--;
1328f7651539SVladimir Sementsov-Ogievskiy     if (s->in_flight == 0 && s->wait_in_flight) {
1329f7651539SVladimir Sementsov-Ogievskiy         aio_co_wake(s->connection_co);
1330f7651539SVladimir Sementsov-Ogievskiy     } else {
133186f8cdf3SVladimir Sementsov-Ogievskiy         qemu_co_queue_next(&s->free_sema);
1332f7651539SVladimir Sementsov-Ogievskiy     }
133386f8cdf3SVladimir Sementsov-Ogievskiy     qemu_co_mutex_unlock(&s->send_mutex);
133486f8cdf3SVladimir Sementsov-Ogievskiy 
133586f8cdf3SVladimir Sementsov-Ogievskiy     return false;
133686f8cdf3SVladimir Sementsov-Ogievskiy }
133786f8cdf3SVladimir Sementsov-Ogievskiy 
1338611ae1d7SVladimir Sementsov-Ogievskiy static int nbd_co_receive_return_code(BDRVNBDState *s, uint64_t handle,
133986f8cdf3SVladimir Sementsov-Ogievskiy                                       int *request_ret, Error **errp)
134086f8cdf3SVladimir Sementsov-Ogievskiy {
134186f8cdf3SVladimir Sementsov-Ogievskiy     NBDReplyChunkIter iter;
134286f8cdf3SVladimir Sementsov-Ogievskiy 
134386f8cdf3SVladimir Sementsov-Ogievskiy     NBD_FOREACH_REPLY_CHUNK(s, iter, handle, false, NULL, NULL, NULL) {
134486f8cdf3SVladimir Sementsov-Ogievskiy         /* nbd_reply_chunk_iter_receive does all the work */
134586f8cdf3SVladimir Sementsov-Ogievskiy     }
134686f8cdf3SVladimir Sementsov-Ogievskiy 
134786f8cdf3SVladimir Sementsov-Ogievskiy     error_propagate(errp, iter.err);
134886f8cdf3SVladimir Sementsov-Ogievskiy     *request_ret = iter.request_ret;
134986f8cdf3SVladimir Sementsov-Ogievskiy     return iter.ret;
135086f8cdf3SVladimir Sementsov-Ogievskiy }
135186f8cdf3SVladimir Sementsov-Ogievskiy 
1352611ae1d7SVladimir Sementsov-Ogievskiy static int nbd_co_receive_cmdread_reply(BDRVNBDState *s, uint64_t handle,
135386f8cdf3SVladimir Sementsov-Ogievskiy                                         uint64_t offset, QEMUIOVector *qiov,
135486f8cdf3SVladimir Sementsov-Ogievskiy                                         int *request_ret, Error **errp)
135586f8cdf3SVladimir Sementsov-Ogievskiy {
135686f8cdf3SVladimir Sementsov-Ogievskiy     NBDReplyChunkIter iter;
135786f8cdf3SVladimir Sementsov-Ogievskiy     NBDReply reply;
135886f8cdf3SVladimir Sementsov-Ogievskiy     void *payload = NULL;
135986f8cdf3SVladimir Sementsov-Ogievskiy     Error *local_err = NULL;
136086f8cdf3SVladimir Sementsov-Ogievskiy 
136186f8cdf3SVladimir Sementsov-Ogievskiy     NBD_FOREACH_REPLY_CHUNK(s, iter, handle, s->info.structured_reply,
136286f8cdf3SVladimir Sementsov-Ogievskiy                             qiov, &reply, &payload)
136386f8cdf3SVladimir Sementsov-Ogievskiy     {
136486f8cdf3SVladimir Sementsov-Ogievskiy         int ret;
136586f8cdf3SVladimir Sementsov-Ogievskiy         NBDStructuredReplyChunk *chunk = &reply.structured;
136686f8cdf3SVladimir Sementsov-Ogievskiy 
136786f8cdf3SVladimir Sementsov-Ogievskiy         assert(nbd_reply_is_structured(&reply));
136886f8cdf3SVladimir Sementsov-Ogievskiy 
136986f8cdf3SVladimir Sementsov-Ogievskiy         switch (chunk->type) {
137086f8cdf3SVladimir Sementsov-Ogievskiy         case NBD_REPLY_TYPE_OFFSET_DATA:
137186f8cdf3SVladimir Sementsov-Ogievskiy             /*
137286f8cdf3SVladimir Sementsov-Ogievskiy              * special cased in nbd_co_receive_one_chunk, data is already
137386f8cdf3SVladimir Sementsov-Ogievskiy              * in qiov
137486f8cdf3SVladimir Sementsov-Ogievskiy              */
137586f8cdf3SVladimir Sementsov-Ogievskiy             break;
137686f8cdf3SVladimir Sementsov-Ogievskiy         case NBD_REPLY_TYPE_OFFSET_HOLE:
137786f8cdf3SVladimir Sementsov-Ogievskiy             ret = nbd_parse_offset_hole_payload(s, &reply.structured, payload,
137886f8cdf3SVladimir Sementsov-Ogievskiy                                                 offset, qiov, &local_err);
137986f8cdf3SVladimir Sementsov-Ogievskiy             if (ret < 0) {
1380a34b1e5eSVladimir Sementsov-Ogievskiy                 nbd_channel_error(s, ret);
138186f8cdf3SVladimir Sementsov-Ogievskiy                 nbd_iter_channel_error(&iter, ret, &local_err);
138286f8cdf3SVladimir Sementsov-Ogievskiy             }
138386f8cdf3SVladimir Sementsov-Ogievskiy             break;
138486f8cdf3SVladimir Sementsov-Ogievskiy         default:
138586f8cdf3SVladimir Sementsov-Ogievskiy             if (!nbd_reply_type_is_error(chunk->type)) {
138686f8cdf3SVladimir Sementsov-Ogievskiy                 /* not allowed reply type */
1387a34b1e5eSVladimir Sementsov-Ogievskiy                 nbd_channel_error(s, -EINVAL);
138886f8cdf3SVladimir Sementsov-Ogievskiy                 error_setg(&local_err,
138986f8cdf3SVladimir Sementsov-Ogievskiy                            "Unexpected reply type: %d (%s) for CMD_READ",
139086f8cdf3SVladimir Sementsov-Ogievskiy                            chunk->type, nbd_reply_type_lookup(chunk->type));
139186f8cdf3SVladimir Sementsov-Ogievskiy                 nbd_iter_channel_error(&iter, -EINVAL, &local_err);
139286f8cdf3SVladimir Sementsov-Ogievskiy             }
139386f8cdf3SVladimir Sementsov-Ogievskiy         }
139486f8cdf3SVladimir Sementsov-Ogievskiy 
139586f8cdf3SVladimir Sementsov-Ogievskiy         g_free(payload);
139686f8cdf3SVladimir Sementsov-Ogievskiy         payload = NULL;
139786f8cdf3SVladimir Sementsov-Ogievskiy     }
139886f8cdf3SVladimir Sementsov-Ogievskiy 
139986f8cdf3SVladimir Sementsov-Ogievskiy     error_propagate(errp, iter.err);
140086f8cdf3SVladimir Sementsov-Ogievskiy     *request_ret = iter.request_ret;
140186f8cdf3SVladimir Sementsov-Ogievskiy     return iter.ret;
140286f8cdf3SVladimir Sementsov-Ogievskiy }
140386f8cdf3SVladimir Sementsov-Ogievskiy 
1404611ae1d7SVladimir Sementsov-Ogievskiy static int nbd_co_receive_blockstatus_reply(BDRVNBDState *s,
140586f8cdf3SVladimir Sementsov-Ogievskiy                                             uint64_t handle, uint64_t length,
140686f8cdf3SVladimir Sementsov-Ogievskiy                                             NBDExtent *extent,
140786f8cdf3SVladimir Sementsov-Ogievskiy                                             int *request_ret, Error **errp)
140886f8cdf3SVladimir Sementsov-Ogievskiy {
140986f8cdf3SVladimir Sementsov-Ogievskiy     NBDReplyChunkIter iter;
141086f8cdf3SVladimir Sementsov-Ogievskiy     NBDReply reply;
141186f8cdf3SVladimir Sementsov-Ogievskiy     void *payload = NULL;
141286f8cdf3SVladimir Sementsov-Ogievskiy     Error *local_err = NULL;
141386f8cdf3SVladimir Sementsov-Ogievskiy     bool received = false;
141486f8cdf3SVladimir Sementsov-Ogievskiy 
141586f8cdf3SVladimir Sementsov-Ogievskiy     assert(!extent->length);
141686f8cdf3SVladimir Sementsov-Ogievskiy     NBD_FOREACH_REPLY_CHUNK(s, iter, handle, false, NULL, &reply, &payload) {
141786f8cdf3SVladimir Sementsov-Ogievskiy         int ret;
141886f8cdf3SVladimir Sementsov-Ogievskiy         NBDStructuredReplyChunk *chunk = &reply.structured;
141986f8cdf3SVladimir Sementsov-Ogievskiy 
142086f8cdf3SVladimir Sementsov-Ogievskiy         assert(nbd_reply_is_structured(&reply));
142186f8cdf3SVladimir Sementsov-Ogievskiy 
142286f8cdf3SVladimir Sementsov-Ogievskiy         switch (chunk->type) {
142386f8cdf3SVladimir Sementsov-Ogievskiy         case NBD_REPLY_TYPE_BLOCK_STATUS:
142486f8cdf3SVladimir Sementsov-Ogievskiy             if (received) {
1425a34b1e5eSVladimir Sementsov-Ogievskiy                 nbd_channel_error(s, -EINVAL);
142686f8cdf3SVladimir Sementsov-Ogievskiy                 error_setg(&local_err, "Several BLOCK_STATUS chunks in reply");
142786f8cdf3SVladimir Sementsov-Ogievskiy                 nbd_iter_channel_error(&iter, -EINVAL, &local_err);
142886f8cdf3SVladimir Sementsov-Ogievskiy             }
142986f8cdf3SVladimir Sementsov-Ogievskiy             received = true;
143086f8cdf3SVladimir Sementsov-Ogievskiy 
143186f8cdf3SVladimir Sementsov-Ogievskiy             ret = nbd_parse_blockstatus_payload(s, &reply.structured,
143286f8cdf3SVladimir Sementsov-Ogievskiy                                                 payload, length, extent,
143386f8cdf3SVladimir Sementsov-Ogievskiy                                                 &local_err);
143486f8cdf3SVladimir Sementsov-Ogievskiy             if (ret < 0) {
1435a34b1e5eSVladimir Sementsov-Ogievskiy                 nbd_channel_error(s, ret);
143686f8cdf3SVladimir Sementsov-Ogievskiy                 nbd_iter_channel_error(&iter, ret, &local_err);
143786f8cdf3SVladimir Sementsov-Ogievskiy             }
143886f8cdf3SVladimir Sementsov-Ogievskiy             break;
143986f8cdf3SVladimir Sementsov-Ogievskiy         default:
144086f8cdf3SVladimir Sementsov-Ogievskiy             if (!nbd_reply_type_is_error(chunk->type)) {
1441a34b1e5eSVladimir Sementsov-Ogievskiy                 nbd_channel_error(s, -EINVAL);
144286f8cdf3SVladimir Sementsov-Ogievskiy                 error_setg(&local_err,
144386f8cdf3SVladimir Sementsov-Ogievskiy                            "Unexpected reply type: %d (%s) "
144486f8cdf3SVladimir Sementsov-Ogievskiy                            "for CMD_BLOCK_STATUS",
144586f8cdf3SVladimir Sementsov-Ogievskiy                            chunk->type, nbd_reply_type_lookup(chunk->type));
144686f8cdf3SVladimir Sementsov-Ogievskiy                 nbd_iter_channel_error(&iter, -EINVAL, &local_err);
144786f8cdf3SVladimir Sementsov-Ogievskiy             }
144886f8cdf3SVladimir Sementsov-Ogievskiy         }
144986f8cdf3SVladimir Sementsov-Ogievskiy 
145086f8cdf3SVladimir Sementsov-Ogievskiy         g_free(payload);
145186f8cdf3SVladimir Sementsov-Ogievskiy         payload = NULL;
145286f8cdf3SVladimir Sementsov-Ogievskiy     }
145386f8cdf3SVladimir Sementsov-Ogievskiy 
145486f8cdf3SVladimir Sementsov-Ogievskiy     if (!extent->length && !iter.request_ret) {
145586f8cdf3SVladimir Sementsov-Ogievskiy         error_setg(&local_err, "Server did not reply with any status extents");
145686f8cdf3SVladimir Sementsov-Ogievskiy         nbd_iter_channel_error(&iter, -EIO, &local_err);
145786f8cdf3SVladimir Sementsov-Ogievskiy     }
145886f8cdf3SVladimir Sementsov-Ogievskiy 
145986f8cdf3SVladimir Sementsov-Ogievskiy     error_propagate(errp, iter.err);
146086f8cdf3SVladimir Sementsov-Ogievskiy     *request_ret = iter.request_ret;
146186f8cdf3SVladimir Sementsov-Ogievskiy     return iter.ret;
146286f8cdf3SVladimir Sementsov-Ogievskiy }
146386f8cdf3SVladimir Sementsov-Ogievskiy 
146486f8cdf3SVladimir Sementsov-Ogievskiy static int nbd_co_request(BlockDriverState *bs, NBDRequest *request,
146586f8cdf3SVladimir Sementsov-Ogievskiy                           QEMUIOVector *write_qiov)
146686f8cdf3SVladimir Sementsov-Ogievskiy {
146786f8cdf3SVladimir Sementsov-Ogievskiy     int ret, request_ret;
146886f8cdf3SVladimir Sementsov-Ogievskiy     Error *local_err = NULL;
1469611ae1d7SVladimir Sementsov-Ogievskiy     BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
147086f8cdf3SVladimir Sementsov-Ogievskiy 
147186f8cdf3SVladimir Sementsov-Ogievskiy     assert(request->type != NBD_CMD_READ);
147286f8cdf3SVladimir Sementsov-Ogievskiy     if (write_qiov) {
147386f8cdf3SVladimir Sementsov-Ogievskiy         assert(request->type == NBD_CMD_WRITE);
147486f8cdf3SVladimir Sementsov-Ogievskiy         assert(request->len == iov_size(write_qiov->iov, write_qiov->niov));
147586f8cdf3SVladimir Sementsov-Ogievskiy     } else {
147686f8cdf3SVladimir Sementsov-Ogievskiy         assert(request->type != NBD_CMD_WRITE);
147786f8cdf3SVladimir Sementsov-Ogievskiy     }
1478f7651539SVladimir Sementsov-Ogievskiy 
1479f7651539SVladimir Sementsov-Ogievskiy     do {
148086f8cdf3SVladimir Sementsov-Ogievskiy         ret = nbd_co_send_request(bs, request, write_qiov);
148186f8cdf3SVladimir Sementsov-Ogievskiy         if (ret < 0) {
1482f7651539SVladimir Sementsov-Ogievskiy             continue;
148386f8cdf3SVladimir Sementsov-Ogievskiy         }
148486f8cdf3SVladimir Sementsov-Ogievskiy 
1485611ae1d7SVladimir Sementsov-Ogievskiy         ret = nbd_co_receive_return_code(s, request->handle,
148686f8cdf3SVladimir Sementsov-Ogievskiy                                          &request_ret, &local_err);
148786f8cdf3SVladimir Sementsov-Ogievskiy         if (local_err) {
1488f7651539SVladimir Sementsov-Ogievskiy             trace_nbd_co_request_fail(request->from, request->len,
1489f7651539SVladimir Sementsov-Ogievskiy                                       request->handle, request->flags,
1490f7651539SVladimir Sementsov-Ogievskiy                                       request->type,
149186f8cdf3SVladimir Sementsov-Ogievskiy                                       nbd_cmd_lookup(request->type),
149286f8cdf3SVladimir Sementsov-Ogievskiy                                       ret, error_get_pretty(local_err));
149386f8cdf3SVladimir Sementsov-Ogievskiy             error_free(local_err);
1494f7651539SVladimir Sementsov-Ogievskiy             local_err = NULL;
149586f8cdf3SVladimir Sementsov-Ogievskiy         }
1496f7651539SVladimir Sementsov-Ogievskiy     } while (ret < 0 && nbd_client_connecting_wait(s));
1497f7651539SVladimir Sementsov-Ogievskiy 
149886f8cdf3SVladimir Sementsov-Ogievskiy     return ret ? ret : request_ret;
149986f8cdf3SVladimir Sementsov-Ogievskiy }
150086f8cdf3SVladimir Sementsov-Ogievskiy 
150186f8cdf3SVladimir Sementsov-Ogievskiy static int nbd_client_co_preadv(BlockDriverState *bs, uint64_t offset,
150286f8cdf3SVladimir Sementsov-Ogievskiy                                 uint64_t bytes, QEMUIOVector *qiov, int flags)
150386f8cdf3SVladimir Sementsov-Ogievskiy {
150486f8cdf3SVladimir Sementsov-Ogievskiy     int ret, request_ret;
150586f8cdf3SVladimir Sementsov-Ogievskiy     Error *local_err = NULL;
1506611ae1d7SVladimir Sementsov-Ogievskiy     BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
150786f8cdf3SVladimir Sementsov-Ogievskiy     NBDRequest request = {
150886f8cdf3SVladimir Sementsov-Ogievskiy         .type = NBD_CMD_READ,
150986f8cdf3SVladimir Sementsov-Ogievskiy         .from = offset,
151086f8cdf3SVladimir Sementsov-Ogievskiy         .len = bytes,
151186f8cdf3SVladimir Sementsov-Ogievskiy     };
151286f8cdf3SVladimir Sementsov-Ogievskiy 
151386f8cdf3SVladimir Sementsov-Ogievskiy     assert(bytes <= NBD_MAX_BUFFER_SIZE);
151486f8cdf3SVladimir Sementsov-Ogievskiy     assert(!flags);
151586f8cdf3SVladimir Sementsov-Ogievskiy 
151686f8cdf3SVladimir Sementsov-Ogievskiy     if (!bytes) {
151786f8cdf3SVladimir Sementsov-Ogievskiy         return 0;
151886f8cdf3SVladimir Sementsov-Ogievskiy     }
151986f8cdf3SVladimir Sementsov-Ogievskiy     /*
152086f8cdf3SVladimir Sementsov-Ogievskiy      * Work around the fact that the block layer doesn't do
152186f8cdf3SVladimir Sementsov-Ogievskiy      * byte-accurate sizing yet - if the read exceeds the server's
152286f8cdf3SVladimir Sementsov-Ogievskiy      * advertised size because the block layer rounded size up, then
152386f8cdf3SVladimir Sementsov-Ogievskiy      * truncate the request to the server and tail-pad with zero.
152486f8cdf3SVladimir Sementsov-Ogievskiy      */
1525611ae1d7SVladimir Sementsov-Ogievskiy     if (offset >= s->info.size) {
152686f8cdf3SVladimir Sementsov-Ogievskiy         assert(bytes < BDRV_SECTOR_SIZE);
152786f8cdf3SVladimir Sementsov-Ogievskiy         qemu_iovec_memset(qiov, 0, 0, bytes);
152886f8cdf3SVladimir Sementsov-Ogievskiy         return 0;
152986f8cdf3SVladimir Sementsov-Ogievskiy     }
1530611ae1d7SVladimir Sementsov-Ogievskiy     if (offset + bytes > s->info.size) {
1531611ae1d7SVladimir Sementsov-Ogievskiy         uint64_t slop = offset + bytes - s->info.size;
153286f8cdf3SVladimir Sementsov-Ogievskiy 
153386f8cdf3SVladimir Sementsov-Ogievskiy         assert(slop < BDRV_SECTOR_SIZE);
153486f8cdf3SVladimir Sementsov-Ogievskiy         qemu_iovec_memset(qiov, bytes - slop, 0, slop);
153586f8cdf3SVladimir Sementsov-Ogievskiy         request.len -= slop;
153686f8cdf3SVladimir Sementsov-Ogievskiy     }
153786f8cdf3SVladimir Sementsov-Ogievskiy 
1538f7651539SVladimir Sementsov-Ogievskiy     do {
153986f8cdf3SVladimir Sementsov-Ogievskiy         ret = nbd_co_send_request(bs, &request, NULL);
154086f8cdf3SVladimir Sementsov-Ogievskiy         if (ret < 0) {
1541f7651539SVladimir Sementsov-Ogievskiy             continue;
154286f8cdf3SVladimir Sementsov-Ogievskiy         }
154386f8cdf3SVladimir Sementsov-Ogievskiy 
1544611ae1d7SVladimir Sementsov-Ogievskiy         ret = nbd_co_receive_cmdread_reply(s, request.handle, offset, qiov,
154586f8cdf3SVladimir Sementsov-Ogievskiy                                            &request_ret, &local_err);
154686f8cdf3SVladimir Sementsov-Ogievskiy         if (local_err) {
154786f8cdf3SVladimir Sementsov-Ogievskiy             trace_nbd_co_request_fail(request.from, request.len, request.handle,
154886f8cdf3SVladimir Sementsov-Ogievskiy                                       request.flags, request.type,
154986f8cdf3SVladimir Sementsov-Ogievskiy                                       nbd_cmd_lookup(request.type),
155086f8cdf3SVladimir Sementsov-Ogievskiy                                       ret, error_get_pretty(local_err));
155186f8cdf3SVladimir Sementsov-Ogievskiy             error_free(local_err);
1552f7651539SVladimir Sementsov-Ogievskiy             local_err = NULL;
155386f8cdf3SVladimir Sementsov-Ogievskiy         }
1554f7651539SVladimir Sementsov-Ogievskiy     } while (ret < 0 && nbd_client_connecting_wait(s));
1555f7651539SVladimir Sementsov-Ogievskiy 
155686f8cdf3SVladimir Sementsov-Ogievskiy     return ret ? ret : request_ret;
155786f8cdf3SVladimir Sementsov-Ogievskiy }
155886f8cdf3SVladimir Sementsov-Ogievskiy 
155986f8cdf3SVladimir Sementsov-Ogievskiy static int nbd_client_co_pwritev(BlockDriverState *bs, uint64_t offset,
156086f8cdf3SVladimir Sementsov-Ogievskiy                                  uint64_t bytes, QEMUIOVector *qiov, int flags)
156186f8cdf3SVladimir Sementsov-Ogievskiy {
1562611ae1d7SVladimir Sementsov-Ogievskiy     BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
156386f8cdf3SVladimir Sementsov-Ogievskiy     NBDRequest request = {
156486f8cdf3SVladimir Sementsov-Ogievskiy         .type = NBD_CMD_WRITE,
156586f8cdf3SVladimir Sementsov-Ogievskiy         .from = offset,
156686f8cdf3SVladimir Sementsov-Ogievskiy         .len = bytes,
156786f8cdf3SVladimir Sementsov-Ogievskiy     };
156886f8cdf3SVladimir Sementsov-Ogievskiy 
1569611ae1d7SVladimir Sementsov-Ogievskiy     assert(!(s->info.flags & NBD_FLAG_READ_ONLY));
157086f8cdf3SVladimir Sementsov-Ogievskiy     if (flags & BDRV_REQ_FUA) {
1571611ae1d7SVladimir Sementsov-Ogievskiy         assert(s->info.flags & NBD_FLAG_SEND_FUA);
157286f8cdf3SVladimir Sementsov-Ogievskiy         request.flags |= NBD_CMD_FLAG_FUA;
157386f8cdf3SVladimir Sementsov-Ogievskiy     }
157486f8cdf3SVladimir Sementsov-Ogievskiy 
157586f8cdf3SVladimir Sementsov-Ogievskiy     assert(bytes <= NBD_MAX_BUFFER_SIZE);
157686f8cdf3SVladimir Sementsov-Ogievskiy 
157786f8cdf3SVladimir Sementsov-Ogievskiy     if (!bytes) {
157886f8cdf3SVladimir Sementsov-Ogievskiy         return 0;
157986f8cdf3SVladimir Sementsov-Ogievskiy     }
158086f8cdf3SVladimir Sementsov-Ogievskiy     return nbd_co_request(bs, &request, qiov);
158186f8cdf3SVladimir Sementsov-Ogievskiy }
158286f8cdf3SVladimir Sementsov-Ogievskiy 
158386f8cdf3SVladimir Sementsov-Ogievskiy static int nbd_client_co_pwrite_zeroes(BlockDriverState *bs, int64_t offset,
158486f8cdf3SVladimir Sementsov-Ogievskiy                                        int bytes, BdrvRequestFlags flags)
158586f8cdf3SVladimir Sementsov-Ogievskiy {
1586611ae1d7SVladimir Sementsov-Ogievskiy     BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
158786f8cdf3SVladimir Sementsov-Ogievskiy     NBDRequest request = {
158886f8cdf3SVladimir Sementsov-Ogievskiy         .type = NBD_CMD_WRITE_ZEROES,
158986f8cdf3SVladimir Sementsov-Ogievskiy         .from = offset,
159086f8cdf3SVladimir Sementsov-Ogievskiy         .len = bytes,
159186f8cdf3SVladimir Sementsov-Ogievskiy     };
159286f8cdf3SVladimir Sementsov-Ogievskiy 
1593611ae1d7SVladimir Sementsov-Ogievskiy     assert(!(s->info.flags & NBD_FLAG_READ_ONLY));
1594611ae1d7SVladimir Sementsov-Ogievskiy     if (!(s->info.flags & NBD_FLAG_SEND_WRITE_ZEROES)) {
159586f8cdf3SVladimir Sementsov-Ogievskiy         return -ENOTSUP;
159686f8cdf3SVladimir Sementsov-Ogievskiy     }
159786f8cdf3SVladimir Sementsov-Ogievskiy 
159886f8cdf3SVladimir Sementsov-Ogievskiy     if (flags & BDRV_REQ_FUA) {
1599611ae1d7SVladimir Sementsov-Ogievskiy         assert(s->info.flags & NBD_FLAG_SEND_FUA);
160086f8cdf3SVladimir Sementsov-Ogievskiy         request.flags |= NBD_CMD_FLAG_FUA;
160186f8cdf3SVladimir Sementsov-Ogievskiy     }
160286f8cdf3SVladimir Sementsov-Ogievskiy     if (!(flags & BDRV_REQ_MAY_UNMAP)) {
160386f8cdf3SVladimir Sementsov-Ogievskiy         request.flags |= NBD_CMD_FLAG_NO_HOLE;
160486f8cdf3SVladimir Sementsov-Ogievskiy     }
1605f061656cSEric Blake     if (flags & BDRV_REQ_NO_FALLBACK) {
1606f061656cSEric Blake         assert(s->info.flags & NBD_FLAG_SEND_FAST_ZERO);
1607f061656cSEric Blake         request.flags |= NBD_CMD_FLAG_FAST_ZERO;
1608f061656cSEric Blake     }
160986f8cdf3SVladimir Sementsov-Ogievskiy 
161086f8cdf3SVladimir Sementsov-Ogievskiy     if (!bytes) {
161186f8cdf3SVladimir Sementsov-Ogievskiy         return 0;
161286f8cdf3SVladimir Sementsov-Ogievskiy     }
161386f8cdf3SVladimir Sementsov-Ogievskiy     return nbd_co_request(bs, &request, NULL);
161486f8cdf3SVladimir Sementsov-Ogievskiy }
161586f8cdf3SVladimir Sementsov-Ogievskiy 
161686f8cdf3SVladimir Sementsov-Ogievskiy static int nbd_client_co_flush(BlockDriverState *bs)
161786f8cdf3SVladimir Sementsov-Ogievskiy {
1618611ae1d7SVladimir Sementsov-Ogievskiy     BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
161986f8cdf3SVladimir Sementsov-Ogievskiy     NBDRequest request = { .type = NBD_CMD_FLUSH };
162086f8cdf3SVladimir Sementsov-Ogievskiy 
1621611ae1d7SVladimir Sementsov-Ogievskiy     if (!(s->info.flags & NBD_FLAG_SEND_FLUSH)) {
162286f8cdf3SVladimir Sementsov-Ogievskiy         return 0;
162386f8cdf3SVladimir Sementsov-Ogievskiy     }
162486f8cdf3SVladimir Sementsov-Ogievskiy 
162586f8cdf3SVladimir Sementsov-Ogievskiy     request.from = 0;
162686f8cdf3SVladimir Sementsov-Ogievskiy     request.len = 0;
162786f8cdf3SVladimir Sementsov-Ogievskiy 
162886f8cdf3SVladimir Sementsov-Ogievskiy     return nbd_co_request(bs, &request, NULL);
162986f8cdf3SVladimir Sementsov-Ogievskiy }
163086f8cdf3SVladimir Sementsov-Ogievskiy 
163186f8cdf3SVladimir Sementsov-Ogievskiy static int nbd_client_co_pdiscard(BlockDriverState *bs, int64_t offset,
163286f8cdf3SVladimir Sementsov-Ogievskiy                                   int bytes)
163386f8cdf3SVladimir Sementsov-Ogievskiy {
1634611ae1d7SVladimir Sementsov-Ogievskiy     BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
163586f8cdf3SVladimir Sementsov-Ogievskiy     NBDRequest request = {
163686f8cdf3SVladimir Sementsov-Ogievskiy         .type = NBD_CMD_TRIM,
163786f8cdf3SVladimir Sementsov-Ogievskiy         .from = offset,
163886f8cdf3SVladimir Sementsov-Ogievskiy         .len = bytes,
163986f8cdf3SVladimir Sementsov-Ogievskiy     };
164086f8cdf3SVladimir Sementsov-Ogievskiy 
1641611ae1d7SVladimir Sementsov-Ogievskiy     assert(!(s->info.flags & NBD_FLAG_READ_ONLY));
1642611ae1d7SVladimir Sementsov-Ogievskiy     if (!(s->info.flags & NBD_FLAG_SEND_TRIM) || !bytes) {
164386f8cdf3SVladimir Sementsov-Ogievskiy         return 0;
164486f8cdf3SVladimir Sementsov-Ogievskiy     }
164586f8cdf3SVladimir Sementsov-Ogievskiy 
164686f8cdf3SVladimir Sementsov-Ogievskiy     return nbd_co_request(bs, &request, NULL);
164786f8cdf3SVladimir Sementsov-Ogievskiy }
164886f8cdf3SVladimir Sementsov-Ogievskiy 
164986f8cdf3SVladimir Sementsov-Ogievskiy static int coroutine_fn nbd_client_co_block_status(
165086f8cdf3SVladimir Sementsov-Ogievskiy         BlockDriverState *bs, bool want_zero, int64_t offset, int64_t bytes,
165186f8cdf3SVladimir Sementsov-Ogievskiy         int64_t *pnum, int64_t *map, BlockDriverState **file)
165286f8cdf3SVladimir Sementsov-Ogievskiy {
165386f8cdf3SVladimir Sementsov-Ogievskiy     int ret, request_ret;
165486f8cdf3SVladimir Sementsov-Ogievskiy     NBDExtent extent = { 0 };
1655611ae1d7SVladimir Sementsov-Ogievskiy     BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
165686f8cdf3SVladimir Sementsov-Ogievskiy     Error *local_err = NULL;
165786f8cdf3SVladimir Sementsov-Ogievskiy 
165886f8cdf3SVladimir Sementsov-Ogievskiy     NBDRequest request = {
165986f8cdf3SVladimir Sementsov-Ogievskiy         .type = NBD_CMD_BLOCK_STATUS,
166086f8cdf3SVladimir Sementsov-Ogievskiy         .from = offset,
16616bf792b4SVladimir Sementsov-Ogievskiy         .len = MIN(QEMU_ALIGN_DOWN(INT_MAX, bs->bl.request_alignment),
1662611ae1d7SVladimir Sementsov-Ogievskiy                    MIN(bytes, s->info.size - offset)),
166386f8cdf3SVladimir Sementsov-Ogievskiy         .flags = NBD_CMD_FLAG_REQ_ONE,
166486f8cdf3SVladimir Sementsov-Ogievskiy     };
166586f8cdf3SVladimir Sementsov-Ogievskiy 
1666611ae1d7SVladimir Sementsov-Ogievskiy     if (!s->info.base_allocation) {
166786f8cdf3SVladimir Sementsov-Ogievskiy         *pnum = bytes;
166886f8cdf3SVladimir Sementsov-Ogievskiy         *map = offset;
166986f8cdf3SVladimir Sementsov-Ogievskiy         *file = bs;
167086f8cdf3SVladimir Sementsov-Ogievskiy         return BDRV_BLOCK_DATA | BDRV_BLOCK_OFFSET_VALID;
167186f8cdf3SVladimir Sementsov-Ogievskiy     }
167286f8cdf3SVladimir Sementsov-Ogievskiy 
167386f8cdf3SVladimir Sementsov-Ogievskiy     /*
167486f8cdf3SVladimir Sementsov-Ogievskiy      * Work around the fact that the block layer doesn't do
167586f8cdf3SVladimir Sementsov-Ogievskiy      * byte-accurate sizing yet - if the status request exceeds the
167686f8cdf3SVladimir Sementsov-Ogievskiy      * server's advertised size because the block layer rounded size
167786f8cdf3SVladimir Sementsov-Ogievskiy      * up, we truncated the request to the server (above), or are
167886f8cdf3SVladimir Sementsov-Ogievskiy      * called on just the hole.
167986f8cdf3SVladimir Sementsov-Ogievskiy      */
1680611ae1d7SVladimir Sementsov-Ogievskiy     if (offset >= s->info.size) {
168186f8cdf3SVladimir Sementsov-Ogievskiy         *pnum = bytes;
168286f8cdf3SVladimir Sementsov-Ogievskiy         assert(bytes < BDRV_SECTOR_SIZE);
168386f8cdf3SVladimir Sementsov-Ogievskiy         /* Intentionally don't report offset_valid for the hole */
168486f8cdf3SVladimir Sementsov-Ogievskiy         return BDRV_BLOCK_ZERO;
168586f8cdf3SVladimir Sementsov-Ogievskiy     }
168686f8cdf3SVladimir Sementsov-Ogievskiy 
1687611ae1d7SVladimir Sementsov-Ogievskiy     if (s->info.min_block) {
1688611ae1d7SVladimir Sementsov-Ogievskiy         assert(QEMU_IS_ALIGNED(request.len, s->info.min_block));
168986f8cdf3SVladimir Sementsov-Ogievskiy     }
1690f7651539SVladimir Sementsov-Ogievskiy     do {
169186f8cdf3SVladimir Sementsov-Ogievskiy         ret = nbd_co_send_request(bs, &request, NULL);
169286f8cdf3SVladimir Sementsov-Ogievskiy         if (ret < 0) {
1693f7651539SVladimir Sementsov-Ogievskiy             continue;
169486f8cdf3SVladimir Sementsov-Ogievskiy         }
169586f8cdf3SVladimir Sementsov-Ogievskiy 
1696611ae1d7SVladimir Sementsov-Ogievskiy         ret = nbd_co_receive_blockstatus_reply(s, request.handle, bytes,
1697f7651539SVladimir Sementsov-Ogievskiy                                                &extent, &request_ret,
1698f7651539SVladimir Sementsov-Ogievskiy                                                &local_err);
169986f8cdf3SVladimir Sementsov-Ogievskiy         if (local_err) {
170086f8cdf3SVladimir Sementsov-Ogievskiy             trace_nbd_co_request_fail(request.from, request.len, request.handle,
170186f8cdf3SVladimir Sementsov-Ogievskiy                                       request.flags, request.type,
170286f8cdf3SVladimir Sementsov-Ogievskiy                                       nbd_cmd_lookup(request.type),
170386f8cdf3SVladimir Sementsov-Ogievskiy                                       ret, error_get_pretty(local_err));
170486f8cdf3SVladimir Sementsov-Ogievskiy             error_free(local_err);
1705f7651539SVladimir Sementsov-Ogievskiy             local_err = NULL;
170686f8cdf3SVladimir Sementsov-Ogievskiy         }
1707f7651539SVladimir Sementsov-Ogievskiy     } while (ret < 0 && nbd_client_connecting_wait(s));
1708f7651539SVladimir Sementsov-Ogievskiy 
170986f8cdf3SVladimir Sementsov-Ogievskiy     if (ret < 0 || request_ret < 0) {
171086f8cdf3SVladimir Sementsov-Ogievskiy         return ret ? ret : request_ret;
171186f8cdf3SVladimir Sementsov-Ogievskiy     }
171286f8cdf3SVladimir Sementsov-Ogievskiy 
171386f8cdf3SVladimir Sementsov-Ogievskiy     assert(extent.length);
171486f8cdf3SVladimir Sementsov-Ogievskiy     *pnum = extent.length;
171586f8cdf3SVladimir Sementsov-Ogievskiy     *map = offset;
171686f8cdf3SVladimir Sementsov-Ogievskiy     *file = bs;
171786f8cdf3SVladimir Sementsov-Ogievskiy     return (extent.flags & NBD_STATE_HOLE ? 0 : BDRV_BLOCK_DATA) |
171886f8cdf3SVladimir Sementsov-Ogievskiy         (extent.flags & NBD_STATE_ZERO ? BDRV_BLOCK_ZERO : 0) |
171986f8cdf3SVladimir Sementsov-Ogievskiy         BDRV_BLOCK_OFFSET_VALID;
172086f8cdf3SVladimir Sementsov-Ogievskiy }
172186f8cdf3SVladimir Sementsov-Ogievskiy 
1722e99754b4SMaxim Levitsky static int nbd_client_reopen_prepare(BDRVReopenState *state,
1723e99754b4SMaxim Levitsky                                      BlockReopenQueue *queue, Error **errp)
1724e99754b4SMaxim Levitsky {
1725e99754b4SMaxim Levitsky     BDRVNBDState *s = (BDRVNBDState *)state->bs->opaque;
1726e99754b4SMaxim Levitsky 
1727e99754b4SMaxim Levitsky     if ((state->flags & BDRV_O_RDWR) && (s->info.flags & NBD_FLAG_READ_ONLY)) {
1728e99754b4SMaxim Levitsky         error_setg(errp, "Can't reopen read-only NBD mount as read/write");
1729e99754b4SMaxim Levitsky         return -EACCES;
1730e99754b4SMaxim Levitsky     }
1731e99754b4SMaxim Levitsky     return 0;
1732e99754b4SMaxim Levitsky }
1733e99754b4SMaxim Levitsky 
173486f8cdf3SVladimir Sementsov-Ogievskiy static void nbd_client_close(BlockDriverState *bs)
173586f8cdf3SVladimir Sementsov-Ogievskiy {
1736611ae1d7SVladimir Sementsov-Ogievskiy     BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
173786f8cdf3SVladimir Sementsov-Ogievskiy     NBDRequest request = { .type = NBD_CMD_DISC };
173886f8cdf3SVladimir Sementsov-Ogievskiy 
1739f7651539SVladimir Sementsov-Ogievskiy     if (s->ioc) {
1740611ae1d7SVladimir Sementsov-Ogievskiy         nbd_send_request(s->ioc, &request);
1741f7651539SVladimir Sementsov-Ogievskiy     }
174286f8cdf3SVladimir Sementsov-Ogievskiy 
174386f8cdf3SVladimir Sementsov-Ogievskiy     nbd_teardown_connection(bs);
174486f8cdf3SVladimir Sementsov-Ogievskiy }
174586f8cdf3SVladimir Sementsov-Ogievskiy 
174686f8cdf3SVladimir Sementsov-Ogievskiy static QIOChannelSocket *nbd_establish_connection(SocketAddress *saddr,
174786f8cdf3SVladimir Sementsov-Ogievskiy                                                   Error **errp)
174886f8cdf3SVladimir Sementsov-Ogievskiy {
1749795d946dSVladimir Sementsov-Ogievskiy     ERRP_GUARD();
175086f8cdf3SVladimir Sementsov-Ogievskiy     QIOChannelSocket *sioc;
175186f8cdf3SVladimir Sementsov-Ogievskiy 
175286f8cdf3SVladimir Sementsov-Ogievskiy     sioc = qio_channel_socket_new();
175386f8cdf3SVladimir Sementsov-Ogievskiy     qio_channel_set_name(QIO_CHANNEL(sioc), "nbd-client");
175486f8cdf3SVladimir Sementsov-Ogievskiy 
1755795d946dSVladimir Sementsov-Ogievskiy     qio_channel_socket_connect_sync(sioc, saddr, errp);
1756795d946dSVladimir Sementsov-Ogievskiy     if (*errp) {
175786f8cdf3SVladimir Sementsov-Ogievskiy         object_unref(OBJECT(sioc));
175886f8cdf3SVladimir Sementsov-Ogievskiy         return NULL;
175986f8cdf3SVladimir Sementsov-Ogievskiy     }
176086f8cdf3SVladimir Sementsov-Ogievskiy 
176186f8cdf3SVladimir Sementsov-Ogievskiy     qio_channel_set_delay(QIO_CHANNEL(sioc), false);
176286f8cdf3SVladimir Sementsov-Ogievskiy 
176386f8cdf3SVladimir Sementsov-Ogievskiy     return sioc;
176486f8cdf3SVladimir Sementsov-Ogievskiy }
176586f8cdf3SVladimir Sementsov-Ogievskiy 
1766fa35591bSVladimir Sementsov-Ogievskiy /* nbd_client_handshake takes ownership on sioc. On failure it is unref'ed. */
1767fa35591bSVladimir Sementsov-Ogievskiy static int nbd_client_handshake(BlockDriverState *bs, QIOChannelSocket *sioc,
1768fa35591bSVladimir Sementsov-Ogievskiy                                 Error **errp)
176986f8cdf3SVladimir Sementsov-Ogievskiy {
1770611ae1d7SVladimir Sementsov-Ogievskiy     BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
1771a8e2bb6aSVladimir Sementsov-Ogievskiy     AioContext *aio_context = bdrv_get_aio_context(bs);
177286f8cdf3SVladimir Sementsov-Ogievskiy     int ret;
177386f8cdf3SVladimir Sementsov-Ogievskiy 
1774fa35591bSVladimir Sementsov-Ogievskiy     trace_nbd_client_handshake(s->export);
1775fbeb3e63SVladimir Sementsov-Ogievskiy 
1776fbeb3e63SVladimir Sementsov-Ogievskiy     s->sioc = sioc;
1777fbeb3e63SVladimir Sementsov-Ogievskiy 
1778a8e2bb6aSVladimir Sementsov-Ogievskiy     qio_channel_set_blocking(QIO_CHANNEL(sioc), false, NULL);
1779a8e2bb6aSVladimir Sementsov-Ogievskiy     qio_channel_attach_aio_context(QIO_CHANNEL(sioc), aio_context);
178086f8cdf3SVladimir Sementsov-Ogievskiy 
1781611ae1d7SVladimir Sementsov-Ogievskiy     s->info.request_sizes = true;
1782611ae1d7SVladimir Sementsov-Ogievskiy     s->info.structured_reply = true;
1783611ae1d7SVladimir Sementsov-Ogievskiy     s->info.base_allocation = true;
17848f071c9dSVladimir Sementsov-Ogievskiy     s->info.x_dirty_bitmap = g_strdup(s->x_dirty_bitmap);
17858f071c9dSVladimir Sementsov-Ogievskiy     s->info.name = g_strdup(s->export ?: "");
17868f071c9dSVladimir Sementsov-Ogievskiy     ret = nbd_receive_negotiate(aio_context, QIO_CHANNEL(sioc), s->tlscreds,
17878f071c9dSVladimir Sementsov-Ogievskiy                                 s->hostname, &s->ioc, &s->info, errp);
1788611ae1d7SVladimir Sementsov-Ogievskiy     g_free(s->info.x_dirty_bitmap);
1789611ae1d7SVladimir Sementsov-Ogievskiy     g_free(s->info.name);
179086f8cdf3SVladimir Sementsov-Ogievskiy     if (ret < 0) {
179186f8cdf3SVladimir Sementsov-Ogievskiy         object_unref(OBJECT(sioc));
1792fbeb3e63SVladimir Sementsov-Ogievskiy         s->sioc = NULL;
179386f8cdf3SVladimir Sementsov-Ogievskiy         return ret;
179486f8cdf3SVladimir Sementsov-Ogievskiy     }
17958f071c9dSVladimir Sementsov-Ogievskiy     if (s->x_dirty_bitmap && !s->info.base_allocation) {
179686f8cdf3SVladimir Sementsov-Ogievskiy         error_setg(errp, "requested x-dirty-bitmap %s not found",
17978f071c9dSVladimir Sementsov-Ogievskiy                    s->x_dirty_bitmap);
179886f8cdf3SVladimir Sementsov-Ogievskiy         ret = -EINVAL;
179986f8cdf3SVladimir Sementsov-Ogievskiy         goto fail;
180086f8cdf3SVladimir Sementsov-Ogievskiy     }
1801611ae1d7SVladimir Sementsov-Ogievskiy     if (s->info.flags & NBD_FLAG_READ_ONLY) {
180286f8cdf3SVladimir Sementsov-Ogievskiy         ret = bdrv_apply_auto_read_only(bs, "NBD export is read-only", errp);
180386f8cdf3SVladimir Sementsov-Ogievskiy         if (ret < 0) {
180486f8cdf3SVladimir Sementsov-Ogievskiy             goto fail;
180586f8cdf3SVladimir Sementsov-Ogievskiy         }
180686f8cdf3SVladimir Sementsov-Ogievskiy     }
1807611ae1d7SVladimir Sementsov-Ogievskiy     if (s->info.flags & NBD_FLAG_SEND_FUA) {
180886f8cdf3SVladimir Sementsov-Ogievskiy         bs->supported_write_flags = BDRV_REQ_FUA;
180986f8cdf3SVladimir Sementsov-Ogievskiy         bs->supported_zero_flags |= BDRV_REQ_FUA;
181086f8cdf3SVladimir Sementsov-Ogievskiy     }
1811611ae1d7SVladimir Sementsov-Ogievskiy     if (s->info.flags & NBD_FLAG_SEND_WRITE_ZEROES) {
181286f8cdf3SVladimir Sementsov-Ogievskiy         bs->supported_zero_flags |= BDRV_REQ_MAY_UNMAP;
1813f061656cSEric Blake         if (s->info.flags & NBD_FLAG_SEND_FAST_ZERO) {
1814f061656cSEric Blake             bs->supported_zero_flags |= BDRV_REQ_NO_FALLBACK;
1815f061656cSEric Blake         }
181686f8cdf3SVladimir Sementsov-Ogievskiy     }
181786f8cdf3SVladimir Sementsov-Ogievskiy 
1818611ae1d7SVladimir Sementsov-Ogievskiy     if (!s->ioc) {
1819611ae1d7SVladimir Sementsov-Ogievskiy         s->ioc = QIO_CHANNEL(sioc);
1820611ae1d7SVladimir Sementsov-Ogievskiy         object_ref(OBJECT(s->ioc));
182186f8cdf3SVladimir Sementsov-Ogievskiy     }
182286f8cdf3SVladimir Sementsov-Ogievskiy 
1823fa35591bSVladimir Sementsov-Ogievskiy     trace_nbd_client_handshake_success(s->export);
182486f8cdf3SVladimir Sementsov-Ogievskiy 
182586f8cdf3SVladimir Sementsov-Ogievskiy     return 0;
182686f8cdf3SVladimir Sementsov-Ogievskiy 
182786f8cdf3SVladimir Sementsov-Ogievskiy  fail:
182886f8cdf3SVladimir Sementsov-Ogievskiy     /*
1829a8e2bb6aSVladimir Sementsov-Ogievskiy      * We have connected, but must fail for other reasons.
1830a8e2bb6aSVladimir Sementsov-Ogievskiy      * Send NBD_CMD_DISC as a courtesy to the server.
183186f8cdf3SVladimir Sementsov-Ogievskiy      */
183286f8cdf3SVladimir Sementsov-Ogievskiy     {
183386f8cdf3SVladimir Sementsov-Ogievskiy         NBDRequest request = { .type = NBD_CMD_DISC };
183486f8cdf3SVladimir Sementsov-Ogievskiy 
1835611ae1d7SVladimir Sementsov-Ogievskiy         nbd_send_request(s->ioc ?: QIO_CHANNEL(sioc), &request);
183686f8cdf3SVladimir Sementsov-Ogievskiy 
183786f8cdf3SVladimir Sementsov-Ogievskiy         object_unref(OBJECT(sioc));
1838fbeb3e63SVladimir Sementsov-Ogievskiy         s->sioc = NULL;
183986f8cdf3SVladimir Sementsov-Ogievskiy 
184086f8cdf3SVladimir Sementsov-Ogievskiy         return ret;
184186f8cdf3SVladimir Sementsov-Ogievskiy     }
184286f8cdf3SVladimir Sementsov-Ogievskiy }
184386f8cdf3SVladimir Sementsov-Ogievskiy 
18448f071c9dSVladimir Sementsov-Ogievskiy /*
18458f071c9dSVladimir Sementsov-Ogievskiy  * Parse nbd_open options
18468f071c9dSVladimir Sementsov-Ogievskiy  */
184786f8cdf3SVladimir Sementsov-Ogievskiy 
1848f53a1febSKevin Wolf static int nbd_parse_uri(const char *filename, QDict *options)
18491d7d2a9dSPaolo Bonzini {
18501d7d2a9dSPaolo Bonzini     URI *uri;
18511d7d2a9dSPaolo Bonzini     const char *p;
18521d7d2a9dSPaolo Bonzini     QueryParams *qp = NULL;
18531d7d2a9dSPaolo Bonzini     int ret = 0;
1854f53a1febSKevin Wolf     bool is_unix;
18551d7d2a9dSPaolo Bonzini 
18561d7d2a9dSPaolo Bonzini     uri = uri_parse(filename);
18571d7d2a9dSPaolo Bonzini     if (!uri) {
18581d7d2a9dSPaolo Bonzini         return -EINVAL;
18591d7d2a9dSPaolo Bonzini     }
18601d7d2a9dSPaolo Bonzini 
18611d7d2a9dSPaolo Bonzini     /* transport */
1862f69165a8SMax Reitz     if (!g_strcmp0(uri->scheme, "nbd")) {
1863f53a1febSKevin Wolf         is_unix = false;
1864f69165a8SMax Reitz     } else if (!g_strcmp0(uri->scheme, "nbd+tcp")) {
1865f53a1febSKevin Wolf         is_unix = false;
1866f69165a8SMax Reitz     } else if (!g_strcmp0(uri->scheme, "nbd+unix")) {
1867f53a1febSKevin Wolf         is_unix = true;
18681d7d2a9dSPaolo Bonzini     } else {
18691d7d2a9dSPaolo Bonzini         ret = -EINVAL;
18701d7d2a9dSPaolo Bonzini         goto out;
18711d7d2a9dSPaolo Bonzini     }
18721d7d2a9dSPaolo Bonzini 
18732485f22fSEric Blake     p = uri->path ? uri->path : "";
18742485f22fSEric Blake     if (p[0] == '/') {
18752485f22fSEric Blake         p++;
18762485f22fSEric Blake     }
18771d7d2a9dSPaolo Bonzini     if (p[0]) {
187846f5ac20SEric Blake         qdict_put_str(options, "export", p);
18791d7d2a9dSPaolo Bonzini     }
18801d7d2a9dSPaolo Bonzini 
18811d7d2a9dSPaolo Bonzini     qp = query_params_parse(uri->query);
1882f53a1febSKevin Wolf     if (qp->n > 1 || (is_unix && !qp->n) || (!is_unix && qp->n)) {
18831d7d2a9dSPaolo Bonzini         ret = -EINVAL;
18841d7d2a9dSPaolo Bonzini         goto out;
18851d7d2a9dSPaolo Bonzini     }
18861d7d2a9dSPaolo Bonzini 
1887f53a1febSKevin Wolf     if (is_unix) {
18881d7d2a9dSPaolo Bonzini         /* nbd+unix:///export?socket=path */
18891d7d2a9dSPaolo Bonzini         if (uri->server || uri->port || strcmp(qp->p[0].name, "socket")) {
18901d7d2a9dSPaolo Bonzini             ret = -EINVAL;
18911d7d2a9dSPaolo Bonzini             goto out;
18921d7d2a9dSPaolo Bonzini         }
189346f5ac20SEric Blake         qdict_put_str(options, "server.type", "unix");
189446f5ac20SEric Blake         qdict_put_str(options, "server.path", qp->p[0].value);
18951d7d2a9dSPaolo Bonzini     } else {
189623307908SJán Tomko         QString *host;
1897f84d431bSMax Reitz         char *port_str;
1898f84d431bSMax Reitz 
1899bebbf7faSKevin Wolf         /* nbd[+tcp]://host[:port]/export */
19001d7d2a9dSPaolo Bonzini         if (!uri->server) {
19011d7d2a9dSPaolo Bonzini             ret = -EINVAL;
19021d7d2a9dSPaolo Bonzini             goto out;
19031d7d2a9dSPaolo Bonzini         }
1904f17c90beSKevin Wolf 
190523307908SJán Tomko         /* strip braces from literal IPv6 address */
190623307908SJán Tomko         if (uri->server[0] == '[') {
190723307908SJán Tomko             host = qstring_from_substr(uri->server, 1,
1908ba891d68SMarkus Armbruster                                        strlen(uri->server) - 1);
190923307908SJán Tomko         } else {
191023307908SJán Tomko             host = qstring_from_str(uri->server);
191123307908SJán Tomko         }
191223307908SJán Tomko 
191346f5ac20SEric Blake         qdict_put_str(options, "server.type", "inet");
19149445673eSMarkus Armbruster         qdict_put(options, "server.host", host);
1915f84d431bSMax Reitz 
1916f84d431bSMax Reitz         port_str = g_strdup_printf("%d", uri->port ?: NBD_DEFAULT_PORT);
191746f5ac20SEric Blake         qdict_put_str(options, "server.port", port_str);
1918f53a1febSKevin Wolf         g_free(port_str);
19191d7d2a9dSPaolo Bonzini     }
19201d7d2a9dSPaolo Bonzini 
19211d7d2a9dSPaolo Bonzini out:
19221d7d2a9dSPaolo Bonzini     if (qp) {
19231d7d2a9dSPaolo Bonzini         query_params_free(qp);
19241d7d2a9dSPaolo Bonzini     }
19251d7d2a9dSPaolo Bonzini     uri_free(uri);
19261d7d2a9dSPaolo Bonzini     return ret;
19271d7d2a9dSPaolo Bonzini }
19281d7d2a9dSPaolo Bonzini 
192948c38e0bSMax Reitz static bool nbd_has_filename_options_conflict(QDict *options, Error **errp)
193048c38e0bSMax Reitz {
193148c38e0bSMax Reitz     const QDictEntry *e;
193248c38e0bSMax Reitz 
193348c38e0bSMax Reitz     for (e = qdict_first(options); e; e = qdict_next(options, e)) {
193448c38e0bSMax Reitz         if (!strcmp(e->key, "host") ||
193548c38e0bSMax Reitz             !strcmp(e->key, "port") ||
193648c38e0bSMax Reitz             !strcmp(e->key, "path") ||
1937491d6c7cSMax Reitz             !strcmp(e->key, "export") ||
1938491d6c7cSMax Reitz             strstart(e->key, "server.", NULL))
193948c38e0bSMax Reitz         {
194048c38e0bSMax Reitz             error_setg(errp, "Option '%s' cannot be used with a file name",
194148c38e0bSMax Reitz                        e->key);
194248c38e0bSMax Reitz             return true;
194348c38e0bSMax Reitz         }
194448c38e0bSMax Reitz     }
194548c38e0bSMax Reitz 
194648c38e0bSMax Reitz     return false;
194748c38e0bSMax Reitz }
194848c38e0bSMax Reitz 
19496963a30dSKevin Wolf static void nbd_parse_filename(const char *filename, QDict *options,
19506963a30dSKevin Wolf                                Error **errp)
1951019d6b8fSAnthony Liguori {
1952df18c04eSEric Blake     g_autofree char *file = NULL;
195333897dc7SNick Thomas     char *export_name;
195433897dc7SNick Thomas     const char *host_spec;
1955019d6b8fSAnthony Liguori     const char *unixpath;
1956019d6b8fSAnthony Liguori 
195748c38e0bSMax Reitz     if (nbd_has_filename_options_conflict(options, errp)) {
1958681e7ad0SKevin Wolf         return;
1959681e7ad0SKevin Wolf     }
1960681e7ad0SKevin Wolf 
19611d7d2a9dSPaolo Bonzini     if (strstr(filename, "://")) {
19626963a30dSKevin Wolf         int ret = nbd_parse_uri(filename, options);
19636963a30dSKevin Wolf         if (ret < 0) {
19646963a30dSKevin Wolf             error_setg(errp, "No valid URL specified");
19656963a30dSKevin Wolf         }
19666963a30dSKevin Wolf         return;
19671d7d2a9dSPaolo Bonzini     }
19681d7d2a9dSPaolo Bonzini 
19697267c094SAnthony Liguori     file = g_strdup(filename);
19701d45f8b5SLaurent Vivier 
197133897dc7SNick Thomas     export_name = strstr(file, EN_OPTSTR);
197233897dc7SNick Thomas     if (export_name) {
197333897dc7SNick Thomas         if (export_name[strlen(EN_OPTSTR)] == 0) {
1974df18c04eSEric Blake             return;
19751d45f8b5SLaurent Vivier         }
197633897dc7SNick Thomas         export_name[0] = 0; /* truncate 'file' */
197733897dc7SNick Thomas         export_name += strlen(EN_OPTSTR);
1978f53a1febSKevin Wolf 
197946f5ac20SEric Blake         qdict_put_str(options, "export", export_name);
19801d45f8b5SLaurent Vivier     }
19811d45f8b5SLaurent Vivier 
198233897dc7SNick Thomas     /* extract the host_spec - fail if it's not nbd:... */
198333897dc7SNick Thomas     if (!strstart(file, "nbd:", &host_spec)) {
19846963a30dSKevin Wolf         error_setg(errp, "File name string for NBD must start with 'nbd:'");
1985df18c04eSEric Blake         return;
19861d45f8b5SLaurent Vivier     }
1987019d6b8fSAnthony Liguori 
1988f53a1febSKevin Wolf     if (!*host_spec) {
1989df18c04eSEric Blake         return;
1990f53a1febSKevin Wolf     }
1991f53a1febSKevin Wolf 
199233897dc7SNick Thomas     /* are we a UNIX or TCP socket? */
199333897dc7SNick Thomas     if (strstart(host_spec, "unix:", &unixpath)) {
199446f5ac20SEric Blake         qdict_put_str(options, "server.type", "unix");
199546f5ac20SEric Blake         qdict_put_str(options, "server.path", unixpath);
1996019d6b8fSAnthony Liguori     } else {
19970785bd7aSMarkus Armbruster         InetSocketAddress *addr = g_new(InetSocketAddress, 1);
1998f53a1febSKevin Wolf 
19990785bd7aSMarkus Armbruster         if (inet_parse(addr, host_spec, errp)) {
20000785bd7aSMarkus Armbruster             goto out_inet;
2001f17c90beSKevin Wolf         }
2002f53a1febSKevin Wolf 
200346f5ac20SEric Blake         qdict_put_str(options, "server.type", "inet");
200446f5ac20SEric Blake         qdict_put_str(options, "server.host", addr->host);
200546f5ac20SEric Blake         qdict_put_str(options, "server.port", addr->port);
20060785bd7aSMarkus Armbruster     out_inet:
2007f53a1febSKevin Wolf         qapi_free_InetSocketAddress(addr);
20081d45f8b5SLaurent Vivier     }
200933897dc7SNick Thomas }
2010f53a1febSKevin Wolf 
2011491d6c7cSMax Reitz static bool nbd_process_legacy_socket_options(QDict *output_options,
2012491d6c7cSMax Reitz                                               QemuOpts *legacy_opts,
2013491d6c7cSMax Reitz                                               Error **errp)
2014f53a1febSKevin Wolf {
2015491d6c7cSMax Reitz     const char *path = qemu_opt_get(legacy_opts, "path");
2016491d6c7cSMax Reitz     const char *host = qemu_opt_get(legacy_opts, "host");
2017491d6c7cSMax Reitz     const char *port = qemu_opt_get(legacy_opts, "port");
2018491d6c7cSMax Reitz     const QDictEntry *e;
2019f53a1febSKevin Wolf 
2020491d6c7cSMax Reitz     if (!path && !host && !port) {
2021491d6c7cSMax Reitz         return true;
2022491d6c7cSMax Reitz     }
202303504d05SMax Reitz 
2024491d6c7cSMax Reitz     for (e = qdict_first(output_options); e; e = qdict_next(output_options, e))
2025491d6c7cSMax Reitz     {
2026491d6c7cSMax Reitz         if (strstart(e->key, "server.", NULL)) {
2027491d6c7cSMax Reitz             error_setg(errp, "Cannot use 'server' and path/host/port at the "
2028491d6c7cSMax Reitz                        "same time");
2029491d6c7cSMax Reitz             return false;
2030491d6c7cSMax Reitz         }
2031491d6c7cSMax Reitz     }
2032491d6c7cSMax Reitz 
2033491d6c7cSMax Reitz     if (path && host) {
203482d73014SMax Reitz         error_setg(errp, "path and host may not be used at the same time");
2035491d6c7cSMax Reitz         return false;
2036491d6c7cSMax Reitz     } else if (path) {
2037491d6c7cSMax Reitz         if (port) {
2038442045cbSMax Reitz             error_setg(errp, "port may not be used without host");
2039491d6c7cSMax Reitz             return false;
2040442045cbSMax Reitz         }
2041019d6b8fSAnthony Liguori 
204246f5ac20SEric Blake         qdict_put_str(output_options, "server.type", "unix");
204346f5ac20SEric Blake         qdict_put_str(output_options, "server.path", path);
2044491d6c7cSMax Reitz     } else if (host) {
204546f5ac20SEric Blake         qdict_put_str(output_options, "server.type", "inet");
204646f5ac20SEric Blake         qdict_put_str(output_options, "server.host", host);
204746f5ac20SEric Blake         qdict_put_str(output_options, "server.port",
204846f5ac20SEric Blake                       port ?: stringify(NBD_DEFAULT_PORT));
20497a5ed437SDaniel P. Berrange     }
2050491d6c7cSMax Reitz 
2051491d6c7cSMax Reitz     return true;
2052491d6c7cSMax Reitz }
2053491d6c7cSMax Reitz 
205462cf396bSMarkus Armbruster static SocketAddress *nbd_config(BDRVNBDState *s, QDict *options,
20559445673eSMarkus Armbruster                                  Error **errp)
2056491d6c7cSMax Reitz {
205762cf396bSMarkus Armbruster     SocketAddress *saddr = NULL;
2058491d6c7cSMax Reitz     QDict *addr = NULL;
2059491d6c7cSMax Reitz     Visitor *iv = NULL;
2060491d6c7cSMax Reitz 
2061491d6c7cSMax Reitz     qdict_extract_subqdict(options, &addr, "server.");
2062491d6c7cSMax Reitz     if (!qdict_size(addr)) {
2063491d6c7cSMax Reitz         error_setg(errp, "NBD server address missing");
2064491d6c7cSMax Reitz         goto done;
2065491d6c7cSMax Reitz     }
2066491d6c7cSMax Reitz 
2067af91062eSMarkus Armbruster     iv = qobject_input_visitor_new_flat_confused(addr, errp);
2068af91062eSMarkus Armbruster     if (!iv) {
2069491d6c7cSMax Reitz         goto done;
2070491d6c7cSMax Reitz     }
2071491d6c7cSMax Reitz 
2072af175e85SMarkus Armbruster     if (!visit_type_SocketAddress(iv, NULL, &saddr, errp)) {
2073491d6c7cSMax Reitz         goto done;
2074f53a1febSKevin Wolf     }
2075f53a1febSKevin Wolf 
2076491d6c7cSMax Reitz done:
2077cb3e7f08SMarc-André Lureau     qobject_unref(addr);
2078491d6c7cSMax Reitz     visit_free(iv);
20797a5ed437SDaniel P. Berrange     return saddr;
2080f53a1febSKevin Wolf }
2081f53a1febSKevin Wolf 
208275822a12SDaniel P. Berrange static QCryptoTLSCreds *nbd_get_tls_creds(const char *id, Error **errp)
208375822a12SDaniel P. Berrange {
208475822a12SDaniel P. Berrange     Object *obj;
208575822a12SDaniel P. Berrange     QCryptoTLSCreds *creds;
208675822a12SDaniel P. Berrange 
208775822a12SDaniel P. Berrange     obj = object_resolve_path_component(
208875822a12SDaniel P. Berrange         object_get_objects_root(), id);
208975822a12SDaniel P. Berrange     if (!obj) {
209075822a12SDaniel P. Berrange         error_setg(errp, "No TLS credentials with id '%s'",
209175822a12SDaniel P. Berrange                    id);
209275822a12SDaniel P. Berrange         return NULL;
209375822a12SDaniel P. Berrange     }
209475822a12SDaniel P. Berrange     creds = (QCryptoTLSCreds *)
209575822a12SDaniel P. Berrange         object_dynamic_cast(obj, TYPE_QCRYPTO_TLS_CREDS);
209675822a12SDaniel P. Berrange     if (!creds) {
209775822a12SDaniel P. Berrange         error_setg(errp, "Object with id '%s' is not TLS credentials",
209875822a12SDaniel P. Berrange                    id);
209975822a12SDaniel P. Berrange         return NULL;
210075822a12SDaniel P. Berrange     }
210175822a12SDaniel P. Berrange 
210275822a12SDaniel P. Berrange     if (creds->endpoint != QCRYPTO_TLS_CREDS_ENDPOINT_CLIENT) {
210375822a12SDaniel P. Berrange         error_setg(errp,
210475822a12SDaniel P. Berrange                    "Expecting TLS credentials with a client endpoint");
210575822a12SDaniel P. Berrange         return NULL;
210675822a12SDaniel P. Berrange     }
210775822a12SDaniel P. Berrange     object_ref(obj);
210875822a12SDaniel P. Berrange     return creds;
210975822a12SDaniel P. Berrange }
211075822a12SDaniel P. Berrange 
211175822a12SDaniel P. Berrange 
21127ccc44fdSMax Reitz static QemuOptsList nbd_runtime_opts = {
21137ccc44fdSMax Reitz     .name = "nbd",
21147ccc44fdSMax Reitz     .head = QTAILQ_HEAD_INITIALIZER(nbd_runtime_opts.head),
21157ccc44fdSMax Reitz     .desc = {
21167ccc44fdSMax Reitz         {
21177ccc44fdSMax Reitz             .name = "host",
21187ccc44fdSMax Reitz             .type = QEMU_OPT_STRING,
21197ccc44fdSMax Reitz             .help = "TCP host to connect to",
21207ccc44fdSMax Reitz         },
21217ccc44fdSMax Reitz         {
21227ccc44fdSMax Reitz             .name = "port",
21237ccc44fdSMax Reitz             .type = QEMU_OPT_STRING,
21247ccc44fdSMax Reitz             .help = "TCP port to connect to",
21257ccc44fdSMax Reitz         },
21267ccc44fdSMax Reitz         {
21277ccc44fdSMax Reitz             .name = "path",
21287ccc44fdSMax Reitz             .type = QEMU_OPT_STRING,
21297ccc44fdSMax Reitz             .help = "Unix socket path to connect to",
21307ccc44fdSMax Reitz         },
21317ccc44fdSMax Reitz         {
21327ccc44fdSMax Reitz             .name = "export",
21337ccc44fdSMax Reitz             .type = QEMU_OPT_STRING,
21347ccc44fdSMax Reitz             .help = "Name of the NBD export to open",
21357ccc44fdSMax Reitz         },
21367ccc44fdSMax Reitz         {
21377ccc44fdSMax Reitz             .name = "tls-creds",
21387ccc44fdSMax Reitz             .type = QEMU_OPT_STRING,
21397ccc44fdSMax Reitz             .help = "ID of the TLS credentials to use",
21407ccc44fdSMax Reitz         },
2141216ee365SEric Blake         {
2142216ee365SEric Blake             .name = "x-dirty-bitmap",
2143216ee365SEric Blake             .type = QEMU_OPT_STRING,
2144216ee365SEric Blake             .help = "experimental: expose named dirty bitmap in place of "
2145216ee365SEric Blake                     "block status",
2146216ee365SEric Blake         },
2147b172ae2eSVladimir Sementsov-Ogievskiy         {
2148b172ae2eSVladimir Sementsov-Ogievskiy             .name = "reconnect-delay",
2149b172ae2eSVladimir Sementsov-Ogievskiy             .type = QEMU_OPT_NUMBER,
2150b172ae2eSVladimir Sementsov-Ogievskiy             .help = "On an unexpected disconnect, the nbd client tries to "
2151b172ae2eSVladimir Sementsov-Ogievskiy                     "connect again until succeeding or encountering a serious "
2152b172ae2eSVladimir Sementsov-Ogievskiy                     "error.  During the first @reconnect-delay seconds, all "
2153b172ae2eSVladimir Sementsov-Ogievskiy                     "requests are paused and will be rerun on a successful "
2154b172ae2eSVladimir Sementsov-Ogievskiy                     "reconnect. After that time, any delayed requests and all "
2155b172ae2eSVladimir Sementsov-Ogievskiy                     "future requests before a successful reconnect will "
2156b172ae2eSVladimir Sementsov-Ogievskiy                     "immediately fail. Default 0",
2157b172ae2eSVladimir Sementsov-Ogievskiy         },
2158c4365735SMurilo Opsfelder Araujo         { /* end of list */ }
21597ccc44fdSMax Reitz     },
21607ccc44fdSMax Reitz };
21617ccc44fdSMax Reitz 
21628f071c9dSVladimir Sementsov-Ogievskiy static int nbd_process_options(BlockDriverState *bs, QDict *options,
2163015a1036SMax Reitz                                Error **errp)
216433897dc7SNick Thomas {
216533897dc7SNick Thomas     BDRVNBDState *s = bs->opaque;
21668f071c9dSVladimir Sementsov-Ogievskiy     QemuOpts *opts;
216775822a12SDaniel P. Berrange     int ret = -EINVAL;
2168ae255e52SPaolo Bonzini 
21697ccc44fdSMax Reitz     opts = qemu_opts_create(&nbd_runtime_opts, NULL, 0, &error_abort);
2170af175e85SMarkus Armbruster     if (!qemu_opts_absorb_qdict(opts, options, errp)) {
21717ccc44fdSMax Reitz         goto error;
21727ccc44fdSMax Reitz     }
21737ccc44fdSMax Reitz 
217462cf396bSMarkus Armbruster     /* Translate @host, @port, and @path to a SocketAddress */
2175491d6c7cSMax Reitz     if (!nbd_process_legacy_socket_options(options, opts, errp)) {
217675822a12SDaniel P. Berrange         goto error;
217775822a12SDaniel P. Berrange     }
217875822a12SDaniel P. Berrange 
2179491d6c7cSMax Reitz     /* Pop the config into our state object. Exit if invalid. */
2180491d6c7cSMax Reitz     s->saddr = nbd_config(s, options, errp);
2181491d6c7cSMax Reitz     if (!s->saddr) {
2182491d6c7cSMax Reitz         goto error;
2183491d6c7cSMax Reitz     }
2184491d6c7cSMax Reitz 
2185491d6c7cSMax Reitz     s->export = g_strdup(qemu_opt_get(opts, "export"));
218693676c88SEric Blake     if (s->export && strlen(s->export) > NBD_MAX_STRING_SIZE) {
218793676c88SEric Blake         error_setg(errp, "export name too long to send to server");
218893676c88SEric Blake         goto error;
218993676c88SEric Blake     }
2190491d6c7cSMax Reitz 
219103504d05SMax Reitz     s->tlscredsid = g_strdup(qemu_opt_get(opts, "tls-creds"));
219203504d05SMax Reitz     if (s->tlscredsid) {
21938f071c9dSVladimir Sementsov-Ogievskiy         s->tlscreds = nbd_get_tls_creds(s->tlscredsid, errp);
21948f071c9dSVladimir Sementsov-Ogievskiy         if (!s->tlscreds) {
219575822a12SDaniel P. Berrange             goto error;
219675822a12SDaniel P. Berrange         }
219775822a12SDaniel P. Berrange 
2198ca0b64e5SMarkus Armbruster         /* TODO SOCKET_ADDRESS_KIND_FD where fd has AF_INET or AF_INET6 */
219962cf396bSMarkus Armbruster         if (s->saddr->type != SOCKET_ADDRESS_TYPE_INET) {
220075822a12SDaniel P. Berrange             error_setg(errp, "TLS only supported over IP sockets");
220175822a12SDaniel P. Berrange             goto error;
220275822a12SDaniel P. Berrange         }
22038f071c9dSVladimir Sementsov-Ogievskiy         s->hostname = s->saddr->u.inet.host;
220433897dc7SNick Thomas     }
220533897dc7SNick Thomas 
22068f071c9dSVladimir Sementsov-Ogievskiy     s->x_dirty_bitmap = g_strdup(qemu_opt_get(opts, "x-dirty-bitmap"));
220793676c88SEric Blake     if (s->x_dirty_bitmap && strlen(s->x_dirty_bitmap) > NBD_MAX_STRING_SIZE) {
220893676c88SEric Blake         error_setg(errp, "x-dirty-bitmap query too long to send to server");
220993676c88SEric Blake         goto error;
221093676c88SEric Blake     }
221193676c88SEric Blake 
22128f071c9dSVladimir Sementsov-Ogievskiy     s->reconnect_delay = qemu_opt_get_number(opts, "reconnect-delay", 0);
22138f071c9dSVladimir Sementsov-Ogievskiy 
22148f071c9dSVladimir Sementsov-Ogievskiy     ret = 0;
2215d42f78e9SVladimir Sementsov-Ogievskiy 
221675822a12SDaniel P. Berrange  error:
221703504d05SMax Reitz     if (ret < 0) {
22187f493662SPan Nengyuan         nbd_clear_bdrvstate(s);
221903504d05SMax Reitz     }
22207ccc44fdSMax Reitz     qemu_opts_del(opts);
222175822a12SDaniel P. Berrange     return ret;
2222ae255e52SPaolo Bonzini }
2223d9b09f13SPaolo Bonzini 
22248f071c9dSVladimir Sementsov-Ogievskiy static int nbd_open(BlockDriverState *bs, QDict *options, int flags,
22258f071c9dSVladimir Sementsov-Ogievskiy                     Error **errp)
22268f071c9dSVladimir Sementsov-Ogievskiy {
22278f071c9dSVladimir Sementsov-Ogievskiy     int ret;
22288f071c9dSVladimir Sementsov-Ogievskiy     BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
2229fa35591bSVladimir Sementsov-Ogievskiy     QIOChannelSocket *sioc;
22308f071c9dSVladimir Sementsov-Ogievskiy 
22318f071c9dSVladimir Sementsov-Ogievskiy     ret = nbd_process_options(bs, options, errp);
22328f071c9dSVladimir Sementsov-Ogievskiy     if (ret < 0) {
22338f071c9dSVladimir Sementsov-Ogievskiy         return ret;
22348f071c9dSVladimir Sementsov-Ogievskiy     }
22358f071c9dSVladimir Sementsov-Ogievskiy 
22368f071c9dSVladimir Sementsov-Ogievskiy     s->bs = bs;
22378f071c9dSVladimir Sementsov-Ogievskiy     qemu_co_mutex_init(&s->send_mutex);
22388f071c9dSVladimir Sementsov-Ogievskiy     qemu_co_queue_init(&s->free_sema);
22398f071c9dSVladimir Sementsov-Ogievskiy 
2240fa35591bSVladimir Sementsov-Ogievskiy     /*
2241fa35591bSVladimir Sementsov-Ogievskiy      * establish TCP connection, return error if it fails
2242fa35591bSVladimir Sementsov-Ogievskiy      * TODO: Configurable retry-until-timeout behaviour.
2243fa35591bSVladimir Sementsov-Ogievskiy      */
2244fa35591bSVladimir Sementsov-Ogievskiy     sioc = nbd_establish_connection(s->saddr, errp);
2245fa35591bSVladimir Sementsov-Ogievskiy     if (!sioc) {
2246fa35591bSVladimir Sementsov-Ogievskiy         return -ECONNREFUSED;
2247fa35591bSVladimir Sementsov-Ogievskiy     }
2248fa35591bSVladimir Sementsov-Ogievskiy 
2249fa35591bSVladimir Sementsov-Ogievskiy     ret = nbd_client_handshake(bs, sioc, errp);
22508f071c9dSVladimir Sementsov-Ogievskiy     if (ret < 0) {
22518198cf5eSPan Nengyuan         nbd_clear_bdrvstate(s);
22528f071c9dSVladimir Sementsov-Ogievskiy         return ret;
22538f071c9dSVladimir Sementsov-Ogievskiy     }
22548f071c9dSVladimir Sementsov-Ogievskiy     /* successfully connected */
22558f071c9dSVladimir Sementsov-Ogievskiy     s->state = NBD_CLIENT_CONNECTED;
22568f071c9dSVladimir Sementsov-Ogievskiy 
22571dc4718dSVladimir Sementsov-Ogievskiy     nbd_init_connect_thread(s);
22581dc4718dSVladimir Sementsov-Ogievskiy 
22598f071c9dSVladimir Sementsov-Ogievskiy     s->connection_co = qemu_coroutine_create(nbd_connection_entry, s);
22608f071c9dSVladimir Sementsov-Ogievskiy     bdrv_inc_in_flight(bs);
22618f071c9dSVladimir Sementsov-Ogievskiy     aio_co_schedule(bdrv_get_aio_context(bs), s->connection_co);
22628f071c9dSVladimir Sementsov-Ogievskiy 
22638f071c9dSVladimir Sementsov-Ogievskiy     return 0;
22648f071c9dSVladimir Sementsov-Ogievskiy }
22658f071c9dSVladimir Sementsov-Ogievskiy 
22661486d04aSPaolo Bonzini static int nbd_co_flush(BlockDriverState *bs)
22671486d04aSPaolo Bonzini {
2268f53a829bSMax Reitz     return nbd_client_co_flush(bs);
22691486d04aSPaolo Bonzini }
22701486d04aSPaolo Bonzini 
2271fa21e6faSDenis V. Lunev static void nbd_refresh_limits(BlockDriverState *bs, Error **errp)
2272fa21e6faSDenis V. Lunev {
2273611ae1d7SVladimir Sementsov-Ogievskiy     BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
2274fd8d372dSEric Blake     uint32_t min = s->info.min_block;
2275081dd1feSEric Blake     uint32_t max = MIN_NON_ZERO(NBD_MAX_BUFFER_SIZE, s->info.max_block);
2276081dd1feSEric Blake 
22777da537f7SEric Blake     /*
22787da537f7SEric Blake      * If the server did not advertise an alignment:
22797da537f7SEric Blake      * - a size that is not sector-aligned implies that an alignment
22807da537f7SEric Blake      *   of 1 can be used to access those tail bytes
22817da537f7SEric Blake      * - advertisement of block status requires an alignment of 1, so
22827da537f7SEric Blake      *   that we don't violate block layer constraints that block
22837da537f7SEric Blake      *   status is always aligned (as we can't control whether the
22847da537f7SEric Blake      *   server will report sub-sector extents, such as a hole at EOF
22857da537f7SEric Blake      *   on an unaligned POSIX file)
22867da537f7SEric Blake      * - otherwise, assume the server is so old that we are safer avoiding
22877da537f7SEric Blake      *   sub-sector requests
22887da537f7SEric Blake      */
22897da537f7SEric Blake     if (!min) {
22907da537f7SEric Blake         min = (!QEMU_IS_ALIGNED(s->info.size, BDRV_SECTOR_SIZE) ||
22917da537f7SEric Blake                s->info.base_allocation) ? 1 : BDRV_SECTOR_SIZE;
22927da537f7SEric Blake     }
22937da537f7SEric Blake 
22947da537f7SEric Blake     bs->bl.request_alignment = min;
2295714eb0dbSVladimir Sementsov-Ogievskiy     bs->bl.max_pdiscard = QEMU_ALIGN_DOWN(INT_MAX, min);
2296081dd1feSEric Blake     bs->bl.max_pwrite_zeroes = max;
2297081dd1feSEric Blake     bs->bl.max_transfer = max;
2298081dd1feSEric Blake 
2299081dd1feSEric Blake     if (s->info.opt_block &&
2300081dd1feSEric Blake         s->info.opt_block > bs->bl.opt_transfer) {
2301081dd1feSEric Blake         bs->bl.opt_transfer = s->info.opt_block;
2302081dd1feSEric Blake     }
2303fa21e6faSDenis V. Lunev }
2304fa21e6faSDenis V. Lunev 
2305019d6b8fSAnthony Liguori static void nbd_close(BlockDriverState *bs)
2306019d6b8fSAnthony Liguori {
230703504d05SMax Reitz     BDRVNBDState *s = bs->opaque;
230803504d05SMax Reitz 
2309f53a829bSMax Reitz     nbd_client_close(bs);
23107f493662SPan Nengyuan     nbd_clear_bdrvstate(s);
2311019d6b8fSAnthony Liguori }
2312019d6b8fSAnthony Liguori 
2313a2b333c0SNir Soffer /*
2314a2b333c0SNir Soffer  * NBD cannot truncate, but if the caller asks to truncate to the same size, or
2315a2b333c0SNir Soffer  * to a smaller size with exact=false, there is no reason to fail the
2316a2b333c0SNir Soffer  * operation.
2317a2b333c0SNir Soffer  *
2318a2b333c0SNir Soffer  * Preallocation mode is ignored since it does not seems useful to fail when
2319a2b333c0SNir Soffer  * we never change anything.
2320a2b333c0SNir Soffer  */
2321a2b333c0SNir Soffer static int coroutine_fn nbd_co_truncate(BlockDriverState *bs, int64_t offset,
2322a2b333c0SNir Soffer                                         bool exact, PreallocMode prealloc,
2323a2b333c0SNir Soffer                                         BdrvRequestFlags flags, Error **errp)
2324a2b333c0SNir Soffer {
2325a2b333c0SNir Soffer     BDRVNBDState *s = bs->opaque;
2326a2b333c0SNir Soffer 
2327a2b333c0SNir Soffer     if (offset != s->info.size && exact) {
2328a2b333c0SNir Soffer         error_setg(errp, "Cannot resize NBD nodes");
2329a2b333c0SNir Soffer         return -ENOTSUP;
2330a2b333c0SNir Soffer     }
2331a2b333c0SNir Soffer 
2332a2b333c0SNir Soffer     if (offset > s->info.size) {
2333a2b333c0SNir Soffer         error_setg(errp, "Cannot grow NBD nodes");
2334a2b333c0SNir Soffer         return -EINVAL;
2335a2b333c0SNir Soffer     }
2336a2b333c0SNir Soffer 
2337a2b333c0SNir Soffer     return 0;
2338a2b333c0SNir Soffer }
2339a2b333c0SNir Soffer 
2340019d6b8fSAnthony Liguori static int64_t nbd_getlength(BlockDriverState *bs)
2341019d6b8fSAnthony Liguori {
2342019d6b8fSAnthony Liguori     BDRVNBDState *s = bs->opaque;
2343019d6b8fSAnthony Liguori 
2344611ae1d7SVladimir Sementsov-Ogievskiy     return s->info.size;
2345019d6b8fSAnthony Liguori }
2346019d6b8fSAnthony Liguori 
2347998b3a1eSMax Reitz static void nbd_refresh_filename(BlockDriverState *bs)
23482019d68bSMax Reitz {
234903504d05SMax Reitz     BDRVNBDState *s = bs->opaque;
2350491d6c7cSMax Reitz     const char *host = NULL, *port = NULL, *path = NULL;
23515c86bdf1SEric Blake     size_t len = 0;
2352491d6c7cSMax Reitz 
235362cf396bSMarkus Armbruster     if (s->saddr->type == SOCKET_ADDRESS_TYPE_INET) {
23549445673eSMarkus Armbruster         const InetSocketAddress *inet = &s->saddr->u.inet;
2355491d6c7cSMax Reitz         if (!inet->has_ipv4 && !inet->has_ipv6 && !inet->has_to) {
2356491d6c7cSMax Reitz             host = inet->host;
2357491d6c7cSMax Reitz             port = inet->port;
2358491d6c7cSMax Reitz         }
235962cf396bSMarkus Armbruster     } else if (s->saddr->type == SOCKET_ADDRESS_TYPE_UNIX) {
23609445673eSMarkus Armbruster         path = s->saddr->u.q_unix.path;
23619445673eSMarkus Armbruster     } /* else can't represent as pseudo-filename */
23622019d68bSMax Reitz 
2363491d6c7cSMax Reitz     if (path && s->export) {
23645c86bdf1SEric Blake         len = snprintf(bs->exact_filename, sizeof(bs->exact_filename),
2365491d6c7cSMax Reitz                        "nbd+unix:///%s?socket=%s", s->export, path);
2366491d6c7cSMax Reitz     } else if (path && !s->export) {
23675c86bdf1SEric Blake         len = snprintf(bs->exact_filename, sizeof(bs->exact_filename),
2368491d6c7cSMax Reitz                        "nbd+unix://?socket=%s", path);
2369491d6c7cSMax Reitz     } else if (host && s->export) {
23705c86bdf1SEric Blake         len = snprintf(bs->exact_filename, sizeof(bs->exact_filename),
2371491d6c7cSMax Reitz                        "nbd://%s:%s/%s", host, port, s->export);
2372491d6c7cSMax Reitz     } else if (host && !s->export) {
23735c86bdf1SEric Blake         len = snprintf(bs->exact_filename, sizeof(bs->exact_filename),
2374491d6c7cSMax Reitz                        "nbd://%s:%s", host, port);
2375ec0de768SMax Reitz     }
237600d69986SEric Blake     if (len >= sizeof(bs->exact_filename)) {
23775c86bdf1SEric Blake         /* Name is too long to represent exactly, so leave it empty. */
23785c86bdf1SEric Blake         bs->exact_filename[0] = '\0';
23795c86bdf1SEric Blake     }
23802019d68bSMax Reitz }
23812019d68bSMax Reitz 
23828a6239c0SMax Reitz static char *nbd_dirname(BlockDriverState *bs, Error **errp)
23838a6239c0SMax Reitz {
23848a6239c0SMax Reitz     /* The generic bdrv_dirname() implementation is able to work out some
23858a6239c0SMax Reitz      * directory name for NBD nodes, but that would be wrong. So far there is no
23868a6239c0SMax Reitz      * specification for how "export paths" would work, so NBD does not have
23878a6239c0SMax Reitz      * directory names. */
23888a6239c0SMax Reitz     error_setg(errp, "Cannot generate a base directory for NBD nodes");
23898a6239c0SMax Reitz     return NULL;
23908a6239c0SMax Reitz }
23918a6239c0SMax Reitz 
23922654267cSMax Reitz static const char *const nbd_strong_runtime_opts[] = {
23932654267cSMax Reitz     "path",
23942654267cSMax Reitz     "host",
23952654267cSMax Reitz     "port",
23962654267cSMax Reitz     "export",
23972654267cSMax Reitz     "tls-creds",
23982654267cSMax Reitz     "server.",
23992654267cSMax Reitz 
24002654267cSMax Reitz     NULL
24012654267cSMax Reitz };
24022654267cSMax Reitz 
2403019d6b8fSAnthony Liguori static BlockDriver bdrv_nbd = {
2404019d6b8fSAnthony Liguori     .format_name                = "nbd",
24051d7d2a9dSPaolo Bonzini     .protocol_name              = "nbd",
2406019d6b8fSAnthony Liguori     .instance_size              = sizeof(BDRVNBDState),
24076963a30dSKevin Wolf     .bdrv_parse_filename        = nbd_parse_filename,
24085a5e7f8cSMaxim Levitsky     .bdrv_co_create_opts        = bdrv_co_create_opts_simple,
24095a5e7f8cSMaxim Levitsky     .create_opts                = &bdrv_create_opts_simple,
241066f82ceeSKevin Wolf     .bdrv_file_open             = nbd_open,
2411e99754b4SMaxim Levitsky     .bdrv_reopen_prepare        = nbd_client_reopen_prepare,
241270c4fb26SEric Blake     .bdrv_co_preadv             = nbd_client_co_preadv,
241370c4fb26SEric Blake     .bdrv_co_pwritev            = nbd_client_co_pwritev,
2414fa778fffSEric Blake     .bdrv_co_pwrite_zeroes      = nbd_client_co_pwrite_zeroes,
2415019d6b8fSAnthony Liguori     .bdrv_close                 = nbd_close,
24161486d04aSPaolo Bonzini     .bdrv_co_flush_to_os        = nbd_co_flush,
2417447e57c3SEric Blake     .bdrv_co_pdiscard           = nbd_client_co_pdiscard,
2418fa21e6faSDenis V. Lunev     .bdrv_refresh_limits        = nbd_refresh_limits,
2419a2b333c0SNir Soffer     .bdrv_co_truncate           = nbd_co_truncate,
2420019d6b8fSAnthony Liguori     .bdrv_getlength             = nbd_getlength,
242186f8cdf3SVladimir Sementsov-Ogievskiy     .bdrv_detach_aio_context    = nbd_client_detach_aio_context,
242286f8cdf3SVladimir Sementsov-Ogievskiy     .bdrv_attach_aio_context    = nbd_client_attach_aio_context,
2423f7651539SVladimir Sementsov-Ogievskiy     .bdrv_co_drain_begin        = nbd_client_co_drain_begin,
2424f7651539SVladimir Sementsov-Ogievskiy     .bdrv_co_drain_end          = nbd_client_co_drain_end,
24252019d68bSMax Reitz     .bdrv_refresh_filename      = nbd_refresh_filename,
242678a33ab5SVladimir Sementsov-Ogievskiy     .bdrv_co_block_status       = nbd_client_co_block_status,
24278a6239c0SMax Reitz     .bdrv_dirname               = nbd_dirname,
24282654267cSMax Reitz     .strong_runtime_opts        = nbd_strong_runtime_opts,
24291d7d2a9dSPaolo Bonzini };
24301d7d2a9dSPaolo Bonzini 
24311d7d2a9dSPaolo Bonzini static BlockDriver bdrv_nbd_tcp = {
24321d7d2a9dSPaolo Bonzini     .format_name                = "nbd",
24331d7d2a9dSPaolo Bonzini     .protocol_name              = "nbd+tcp",
24341d7d2a9dSPaolo Bonzini     .instance_size              = sizeof(BDRVNBDState),
24356963a30dSKevin Wolf     .bdrv_parse_filename        = nbd_parse_filename,
24365a5e7f8cSMaxim Levitsky     .bdrv_co_create_opts        = bdrv_co_create_opts_simple,
24375a5e7f8cSMaxim Levitsky     .create_opts                = &bdrv_create_opts_simple,
24381d7d2a9dSPaolo Bonzini     .bdrv_file_open             = nbd_open,
2439e99754b4SMaxim Levitsky     .bdrv_reopen_prepare        = nbd_client_reopen_prepare,
244070c4fb26SEric Blake     .bdrv_co_preadv             = nbd_client_co_preadv,
244170c4fb26SEric Blake     .bdrv_co_pwritev            = nbd_client_co_pwritev,
2442fa778fffSEric Blake     .bdrv_co_pwrite_zeroes      = nbd_client_co_pwrite_zeroes,
24431d7d2a9dSPaolo Bonzini     .bdrv_close                 = nbd_close,
24441d7d2a9dSPaolo Bonzini     .bdrv_co_flush_to_os        = nbd_co_flush,
2445447e57c3SEric Blake     .bdrv_co_pdiscard           = nbd_client_co_pdiscard,
2446fa21e6faSDenis V. Lunev     .bdrv_refresh_limits        = nbd_refresh_limits,
2447a2b333c0SNir Soffer     .bdrv_co_truncate           = nbd_co_truncate,
24481d7d2a9dSPaolo Bonzini     .bdrv_getlength             = nbd_getlength,
244986f8cdf3SVladimir Sementsov-Ogievskiy     .bdrv_detach_aio_context    = nbd_client_detach_aio_context,
245086f8cdf3SVladimir Sementsov-Ogievskiy     .bdrv_attach_aio_context    = nbd_client_attach_aio_context,
2451f7651539SVladimir Sementsov-Ogievskiy     .bdrv_co_drain_begin        = nbd_client_co_drain_begin,
2452f7651539SVladimir Sementsov-Ogievskiy     .bdrv_co_drain_end          = nbd_client_co_drain_end,
24532019d68bSMax Reitz     .bdrv_refresh_filename      = nbd_refresh_filename,
245478a33ab5SVladimir Sementsov-Ogievskiy     .bdrv_co_block_status       = nbd_client_co_block_status,
24558a6239c0SMax Reitz     .bdrv_dirname               = nbd_dirname,
24562654267cSMax Reitz     .strong_runtime_opts        = nbd_strong_runtime_opts,
24571d7d2a9dSPaolo Bonzini };
24581d7d2a9dSPaolo Bonzini 
24591d7d2a9dSPaolo Bonzini static BlockDriver bdrv_nbd_unix = {
24601d7d2a9dSPaolo Bonzini     .format_name                = "nbd",
24611d7d2a9dSPaolo Bonzini     .protocol_name              = "nbd+unix",
24621d7d2a9dSPaolo Bonzini     .instance_size              = sizeof(BDRVNBDState),
24636963a30dSKevin Wolf     .bdrv_parse_filename        = nbd_parse_filename,
24645a5e7f8cSMaxim Levitsky     .bdrv_co_create_opts        = bdrv_co_create_opts_simple,
24655a5e7f8cSMaxim Levitsky     .create_opts                = &bdrv_create_opts_simple,
24661d7d2a9dSPaolo Bonzini     .bdrv_file_open             = nbd_open,
2467e99754b4SMaxim Levitsky     .bdrv_reopen_prepare        = nbd_client_reopen_prepare,
246870c4fb26SEric Blake     .bdrv_co_preadv             = nbd_client_co_preadv,
246970c4fb26SEric Blake     .bdrv_co_pwritev            = nbd_client_co_pwritev,
2470fa778fffSEric Blake     .bdrv_co_pwrite_zeroes      = nbd_client_co_pwrite_zeroes,
24711d7d2a9dSPaolo Bonzini     .bdrv_close                 = nbd_close,
24721d7d2a9dSPaolo Bonzini     .bdrv_co_flush_to_os        = nbd_co_flush,
2473447e57c3SEric Blake     .bdrv_co_pdiscard           = nbd_client_co_pdiscard,
2474fa21e6faSDenis V. Lunev     .bdrv_refresh_limits        = nbd_refresh_limits,
2475a2b333c0SNir Soffer     .bdrv_co_truncate           = nbd_co_truncate,
24761d7d2a9dSPaolo Bonzini     .bdrv_getlength             = nbd_getlength,
247786f8cdf3SVladimir Sementsov-Ogievskiy     .bdrv_detach_aio_context    = nbd_client_detach_aio_context,
247886f8cdf3SVladimir Sementsov-Ogievskiy     .bdrv_attach_aio_context    = nbd_client_attach_aio_context,
2479f7651539SVladimir Sementsov-Ogievskiy     .bdrv_co_drain_begin        = nbd_client_co_drain_begin,
2480f7651539SVladimir Sementsov-Ogievskiy     .bdrv_co_drain_end          = nbd_client_co_drain_end,
24812019d68bSMax Reitz     .bdrv_refresh_filename      = nbd_refresh_filename,
248278a33ab5SVladimir Sementsov-Ogievskiy     .bdrv_co_block_status       = nbd_client_co_block_status,
24838a6239c0SMax Reitz     .bdrv_dirname               = nbd_dirname,
24842654267cSMax Reitz     .strong_runtime_opts        = nbd_strong_runtime_opts,
2485019d6b8fSAnthony Liguori };
2486019d6b8fSAnthony Liguori 
2487019d6b8fSAnthony Liguori static void bdrv_nbd_init(void)
2488019d6b8fSAnthony Liguori {
2489019d6b8fSAnthony Liguori     bdrv_register(&bdrv_nbd);
24901d7d2a9dSPaolo Bonzini     bdrv_register(&bdrv_nbd_tcp);
24911d7d2a9dSPaolo Bonzini     bdrv_register(&bdrv_nbd_unix);
2492019d6b8fSAnthony Liguori }
2493019d6b8fSAnthony Liguori 
2494019d6b8fSAnthony Liguori block_init(bdrv_nbd_init);
2495