xref: /openbmc/qemu/block/nbd.c (revision 8d45185c)
1019d6b8fSAnthony Liguori /*
2019d6b8fSAnthony Liguori  * QEMU Block driver for  NBD
3019d6b8fSAnthony Liguori  *
4f7651539SVladimir Sementsov-Ogievskiy  * Copyright (c) 2019 Virtuozzo International GmbH.
586f8cdf3SVladimir Sementsov-Ogievskiy  * Copyright (C) 2016 Red Hat, Inc.
6019d6b8fSAnthony Liguori  * Copyright (C) 2008 Bull S.A.S.
7019d6b8fSAnthony Liguori  *     Author: Laurent Vivier <Laurent.Vivier@bull.net>
8019d6b8fSAnthony Liguori  *
9019d6b8fSAnthony Liguori  * Some parts:
10019d6b8fSAnthony Liguori  *    Copyright (C) 2007 Anthony Liguori <anthony@codemonkey.ws>
11019d6b8fSAnthony Liguori  *
12019d6b8fSAnthony Liguori  * Permission is hereby granted, free of charge, to any person obtaining a copy
13019d6b8fSAnthony Liguori  * of this software and associated documentation files (the "Software"), to deal
14019d6b8fSAnthony Liguori  * in the Software without restriction, including without limitation the rights
15019d6b8fSAnthony Liguori  * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
16019d6b8fSAnthony Liguori  * copies of the Software, and to permit persons to whom the Software is
17019d6b8fSAnthony Liguori  * furnished to do so, subject to the following conditions:
18019d6b8fSAnthony Liguori  *
19019d6b8fSAnthony Liguori  * The above copyright notice and this permission notice shall be included in
20019d6b8fSAnthony Liguori  * all copies or substantial portions of the Software.
21019d6b8fSAnthony Liguori  *
22019d6b8fSAnthony Liguori  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
23019d6b8fSAnthony Liguori  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
24019d6b8fSAnthony Liguori  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
25019d6b8fSAnthony Liguori  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
26019d6b8fSAnthony Liguori  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
27019d6b8fSAnthony Liguori  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
28019d6b8fSAnthony Liguori  * THE SOFTWARE.
29019d6b8fSAnthony Liguori  */
30019d6b8fSAnthony Liguori 
3180c71a24SPeter Maydell #include "qemu/osdep.h"
3286f8cdf3SVladimir Sementsov-Ogievskiy 
3386f8cdf3SVladimir Sementsov-Ogievskiy #include "trace.h"
341de7afc9SPaolo Bonzini #include "qemu/uri.h"
35922a01a0SMarkus Armbruster #include "qemu/option.h"
36f348b6d1SVeronia Bahaa #include "qemu/cutils.h"
37db725815SMarkus Armbruster #include "qemu/main-loop.h"
38fee091cdSLukas Straub #include "qemu/atomic.h"
39019d6b8fSAnthony Liguori 
4086f8cdf3SVladimir Sementsov-Ogievskiy #include "qapi/qapi-visit-sockets.h"
4186f8cdf3SVladimir Sementsov-Ogievskiy #include "qapi/qmp/qstring.h"
421dc4718dSVladimir Sementsov-Ogievskiy #include "qapi/clone-visitor.h"
4386f8cdf3SVladimir Sementsov-Ogievskiy 
4486f8cdf3SVladimir Sementsov-Ogievskiy #include "block/qdict.h"
4586f8cdf3SVladimir Sementsov-Ogievskiy #include "block/nbd.h"
4686f8cdf3SVladimir Sementsov-Ogievskiy #include "block/block_int.h"
47a71d597bSVladimir Sementsov-Ogievskiy #include "block/coroutines.h"
4886f8cdf3SVladimir Sementsov-Ogievskiy 
49fee091cdSLukas Straub #include "qemu/yank.h"
50fee091cdSLukas Straub 
511d45f8b5SLaurent Vivier #define EN_OPTSTR ":exportname="
5286f8cdf3SVladimir Sementsov-Ogievskiy #define MAX_NBD_REQUESTS    16
5386f8cdf3SVladimir Sementsov-Ogievskiy 
5486f8cdf3SVladimir Sementsov-Ogievskiy #define HANDLE_TO_INDEX(bs, handle) ((handle) ^ (uint64_t)(intptr_t)(bs))
5586f8cdf3SVladimir Sementsov-Ogievskiy #define INDEX_TO_HANDLE(bs, index)  ((index)  ^ (uint64_t)(intptr_t)(bs))
5686f8cdf3SVladimir Sementsov-Ogievskiy 
5786f8cdf3SVladimir Sementsov-Ogievskiy typedef struct {
5886f8cdf3SVladimir Sementsov-Ogievskiy     Coroutine *coroutine;
5986f8cdf3SVladimir Sementsov-Ogievskiy     uint64_t offset;        /* original offset of the request */
604ddb5d2fSVladimir Sementsov-Ogievskiy     bool receiving;         /* sleeping in the yield in nbd_receive_replies */
6186f8cdf3SVladimir Sementsov-Ogievskiy } NBDClientRequest;
6286f8cdf3SVladimir Sementsov-Ogievskiy 
63a34b1e5eSVladimir Sementsov-Ogievskiy typedef enum NBDClientState {
64f7651539SVladimir Sementsov-Ogievskiy     NBD_CLIENT_CONNECTING_WAIT,
65f7651539SVladimir Sementsov-Ogievskiy     NBD_CLIENT_CONNECTING_NOWAIT,
66a34b1e5eSVladimir Sementsov-Ogievskiy     NBD_CLIENT_CONNECTED,
67a34b1e5eSVladimir Sementsov-Ogievskiy     NBD_CLIENT_QUIT
68a34b1e5eSVladimir Sementsov-Ogievskiy } NBDClientState;
69a34b1e5eSVladimir Sementsov-Ogievskiy 
70611ae1d7SVladimir Sementsov-Ogievskiy typedef struct BDRVNBDState {
7195a078eaSVladimir Sementsov-Ogievskiy     QIOChannel *ioc; /* The current I/O channel */
7286f8cdf3SVladimir Sementsov-Ogievskiy     NBDExportInfo info;
7386f8cdf3SVladimir Sementsov-Ogievskiy 
74ee19d953SPaolo Bonzini     /*
75ee19d953SPaolo Bonzini      * Protects free_sema, in_flight, requests[].coroutine,
76ee19d953SPaolo Bonzini      * reconnect_delay_timer.
77ee19d953SPaolo Bonzini      */
78ee19d953SPaolo Bonzini     QemuMutex requests_lock;
7986f8cdf3SVladimir Sementsov-Ogievskiy     CoQueue free_sema;
8086f8cdf3SVladimir Sementsov-Ogievskiy     int in_flight;
81ee19d953SPaolo Bonzini     NBDClientRequest requests[MAX_NBD_REQUESTS];
82ee19d953SPaolo Bonzini     QEMUTimer *reconnect_delay_timer;
83ee19d953SPaolo Bonzini 
84ee19d953SPaolo Bonzini     CoMutex send_mutex;
85ee19d953SPaolo Bonzini     CoMutex receive_mutex;
86a34b1e5eSVladimir Sementsov-Ogievskiy     NBDClientState state;
8786f8cdf3SVladimir Sementsov-Ogievskiy 
88be16b8bfSVladimir Sementsov-Ogievskiy     QEMUTimer *open_timer;
8946f56631SVladimir Sementsov-Ogievskiy 
9086f8cdf3SVladimir Sementsov-Ogievskiy     NBDReply reply;
9186f8cdf3SVladimir Sementsov-Ogievskiy     BlockDriverState *bs;
9203504d05SMax Reitz 
938f071c9dSVladimir Sementsov-Ogievskiy     /* Connection parameters */
948f071c9dSVladimir Sementsov-Ogievskiy     uint32_t reconnect_delay;
95be16b8bfSVladimir Sementsov-Ogievskiy     uint32_t open_timeout;
9662cf396bSMarkus Armbruster     SocketAddress *saddr;
97a0cd6d29SDaniel P. Berrangé     char *export;
98a0cd6d29SDaniel P. Berrangé     char *tlscredsid;
998f071c9dSVladimir Sementsov-Ogievskiy     QCryptoTLSCreds *tlscreds;
100a0cd6d29SDaniel P. Berrangé     char *tlshostname;
1018f071c9dSVladimir Sementsov-Ogievskiy     char *x_dirty_bitmap;
102dbc7b014SEric Blake     bool alloc_depth;
1031dc4718dSVladimir Sementsov-Ogievskiy 
10490ddc64fSVladimir Sementsov-Ogievskiy     NBDClientConnection *conn;
105019d6b8fSAnthony Liguori } BDRVNBDState;
106019d6b8fSAnthony Liguori 
107fee091cdSLukas Straub static void nbd_yank(void *opaque);
108f7651539SVladimir Sementsov-Ogievskiy 
109bbba1c37SVladimir Sementsov-Ogievskiy static void nbd_clear_bdrvstate(BlockDriverState *bs)
1107f493662SPan Nengyuan {
111bbba1c37SVladimir Sementsov-Ogievskiy     BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
112e8b35bf5SRoman Kagan 
113248d4701SVladimir Sementsov-Ogievskiy     nbd_client_connection_release(s->conn);
114248d4701SVladimir Sementsov-Ogievskiy     s->conn = NULL;
115bbba1c37SVladimir Sementsov-Ogievskiy 
116bbba1c37SVladimir Sementsov-Ogievskiy     yank_unregister_instance(BLOCKDEV_YANK_INSTANCE(bs->node_name));
117bbba1c37SVladimir Sementsov-Ogievskiy 
1188a39c381SHanna Reitz     /* Must not leave timers behind that would access freed data */
1198a39c381SHanna Reitz     assert(!s->reconnect_delay_timer);
1208a39c381SHanna Reitz     assert(!s->open_timer);
1218a39c381SHanna Reitz 
1227f493662SPan Nengyuan     object_unref(OBJECT(s->tlscreds));
1237f493662SPan Nengyuan     qapi_free_SocketAddress(s->saddr);
1247f493662SPan Nengyuan     s->saddr = NULL;
1257f493662SPan Nengyuan     g_free(s->export);
1267f493662SPan Nengyuan     s->export = NULL;
1277f493662SPan Nengyuan     g_free(s->tlscredsid);
1287f493662SPan Nengyuan     s->tlscredsid = NULL;
129a0cd6d29SDaniel P. Berrangé     g_free(s->tlshostname);
130a0cd6d29SDaniel P. Berrangé     s->tlshostname = NULL;
1317f493662SPan Nengyuan     g_free(s->x_dirty_bitmap);
1327f493662SPan Nengyuan     s->x_dirty_bitmap = NULL;
1337f493662SPan Nengyuan }
1347f493662SPan Nengyuan 
13591e0998fSVladimir Sementsov-Ogievskiy static bool nbd_client_connected(BDRVNBDState *s)
13691e0998fSVladimir Sementsov-Ogievskiy {
13791e0998fSVladimir Sementsov-Ogievskiy     return qatomic_load_acquire(&s->state) == NBD_CLIENT_CONNECTED;
13891e0998fSVladimir Sementsov-Ogievskiy }
13991e0998fSVladimir Sementsov-Ogievskiy 
1400c43c6fcSPaolo Bonzini static bool coroutine_fn nbd_recv_coroutine_wake_one(NBDClientRequest *req)
14104a953b2SVladimir Sementsov-Ogievskiy {
14204a953b2SVladimir Sementsov-Ogievskiy     if (req->receiving) {
14304a953b2SVladimir Sementsov-Ogievskiy         req->receiving = false;
14404a953b2SVladimir Sementsov-Ogievskiy         aio_co_wake(req->coroutine);
14504a953b2SVladimir Sementsov-Ogievskiy         return true;
14604a953b2SVladimir Sementsov-Ogievskiy     }
14704a953b2SVladimir Sementsov-Ogievskiy 
14804a953b2SVladimir Sementsov-Ogievskiy     return false;
14904a953b2SVladimir Sementsov-Ogievskiy }
15004a953b2SVladimir Sementsov-Ogievskiy 
1510c43c6fcSPaolo Bonzini static void coroutine_fn nbd_recv_coroutines_wake(BDRVNBDState *s, bool all)
1523bc0bd1fSVladimir Sementsov-Ogievskiy {
1533bc0bd1fSVladimir Sementsov-Ogievskiy     int i;
1543bc0bd1fSVladimir Sementsov-Ogievskiy 
1553bc0bd1fSVladimir Sementsov-Ogievskiy     for (i = 0; i < MAX_NBD_REQUESTS; i++) {
15604a953b2SVladimir Sementsov-Ogievskiy         if (nbd_recv_coroutine_wake_one(&s->requests[i]) && !all) {
15704a953b2SVladimir Sementsov-Ogievskiy             return;
1583bc0bd1fSVladimir Sementsov-Ogievskiy         }
1593bc0bd1fSVladimir Sementsov-Ogievskiy     }
1603bc0bd1fSVladimir Sementsov-Ogievskiy }
1613bc0bd1fSVladimir Sementsov-Ogievskiy 
1620c43c6fcSPaolo Bonzini static void coroutine_fn nbd_channel_error(BDRVNBDState *s, int ret)
163a34b1e5eSVladimir Sementsov-Ogievskiy {
164cb116da7SVladimir Sementsov-Ogievskiy     if (nbd_client_connected(s)) {
165cb116da7SVladimir Sementsov-Ogievskiy         qio_channel_shutdown(s->ioc, QIO_CHANNEL_SHUTDOWN_BOTH, NULL);
166cb116da7SVladimir Sementsov-Ogievskiy     }
167cb116da7SVladimir Sementsov-Ogievskiy 
168f7651539SVladimir Sementsov-Ogievskiy     if (ret == -EIO) {
16991e0998fSVladimir Sementsov-Ogievskiy         if (nbd_client_connected(s)) {
170f7651539SVladimir Sementsov-Ogievskiy             s->state = s->reconnect_delay ? NBD_CLIENT_CONNECTING_WAIT :
171f7651539SVladimir Sementsov-Ogievskiy                                             NBD_CLIENT_CONNECTING_NOWAIT;
172f7651539SVladimir Sementsov-Ogievskiy         }
173f7651539SVladimir Sementsov-Ogievskiy     } else {
174a34b1e5eSVladimir Sementsov-Ogievskiy         s->state = NBD_CLIENT_QUIT;
175a34b1e5eSVladimir Sementsov-Ogievskiy     }
1764ddb5d2fSVladimir Sementsov-Ogievskiy 
1774ddb5d2fSVladimir Sementsov-Ogievskiy     nbd_recv_coroutines_wake(s, true);
178f7651539SVladimir Sementsov-Ogievskiy }
179a34b1e5eSVladimir Sementsov-Ogievskiy 
18046f56631SVladimir Sementsov-Ogievskiy static void reconnect_delay_timer_del(BDRVNBDState *s)
18146f56631SVladimir Sementsov-Ogievskiy {
18246f56631SVladimir Sementsov-Ogievskiy     if (s->reconnect_delay_timer) {
18346f56631SVladimir Sementsov-Ogievskiy         timer_free(s->reconnect_delay_timer);
18446f56631SVladimir Sementsov-Ogievskiy         s->reconnect_delay_timer = NULL;
18546f56631SVladimir Sementsov-Ogievskiy     }
18646f56631SVladimir Sementsov-Ogievskiy }
18746f56631SVladimir Sementsov-Ogievskiy 
18846f56631SVladimir Sementsov-Ogievskiy static void reconnect_delay_timer_cb(void *opaque)
18946f56631SVladimir Sementsov-Ogievskiy {
19046f56631SVladimir Sementsov-Ogievskiy     BDRVNBDState *s = opaque;
19146f56631SVladimir Sementsov-Ogievskiy 
192fee091cdSLukas Straub     if (qatomic_load_acquire(&s->state) == NBD_CLIENT_CONNECTING_WAIT) {
19346f56631SVladimir Sementsov-Ogievskiy         s->state = NBD_CLIENT_CONNECTING_NOWAIT;
1944ddb5d2fSVladimir Sementsov-Ogievskiy         nbd_co_establish_connection_cancel(s->conn);
19546f56631SVladimir Sementsov-Ogievskiy     }
19646f56631SVladimir Sementsov-Ogievskiy 
19746f56631SVladimir Sementsov-Ogievskiy     reconnect_delay_timer_del(s);
19846f56631SVladimir Sementsov-Ogievskiy }
19946f56631SVladimir Sementsov-Ogievskiy 
20046f56631SVladimir Sementsov-Ogievskiy static void reconnect_delay_timer_init(BDRVNBDState *s, uint64_t expire_time_ns)
20146f56631SVladimir Sementsov-Ogievskiy {
202fee091cdSLukas Straub     if (qatomic_load_acquire(&s->state) != NBD_CLIENT_CONNECTING_WAIT) {
20346f56631SVladimir Sementsov-Ogievskiy         return;
20446f56631SVladimir Sementsov-Ogievskiy     }
20546f56631SVladimir Sementsov-Ogievskiy 
20646f56631SVladimir Sementsov-Ogievskiy     assert(!s->reconnect_delay_timer);
20746f56631SVladimir Sementsov-Ogievskiy     s->reconnect_delay_timer = aio_timer_new(bdrv_get_aio_context(s->bs),
20846f56631SVladimir Sementsov-Ogievskiy                                              QEMU_CLOCK_REALTIME,
20946f56631SVladimir Sementsov-Ogievskiy                                              SCALE_NS,
21046f56631SVladimir Sementsov-Ogievskiy                                              reconnect_delay_timer_cb, s);
21146f56631SVladimir Sementsov-Ogievskiy     timer_mod(s->reconnect_delay_timer, expire_time_ns);
21246f56631SVladimir Sementsov-Ogievskiy }
21346f56631SVladimir Sementsov-Ogievskiy 
21486f8cdf3SVladimir Sementsov-Ogievskiy static void nbd_teardown_connection(BlockDriverState *bs)
21586f8cdf3SVladimir Sementsov-Ogievskiy {
216611ae1d7SVladimir Sementsov-Ogievskiy     BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
21786f8cdf3SVladimir Sementsov-Ogievskiy 
2184ddb5d2fSVladimir Sementsov-Ogievskiy     assert(!s->in_flight);
2194ddb5d2fSVladimir Sementsov-Ogievskiy 
220fbeb3e63SVladimir Sementsov-Ogievskiy     if (s->ioc) {
221f7651539SVladimir Sementsov-Ogievskiy         qio_channel_shutdown(s->ioc, QIO_CHANNEL_SHUTDOWN_BOTH, NULL);
2224ddb5d2fSVladimir Sementsov-Ogievskiy         yank_unregister_function(BLOCKDEV_YANK_INSTANCE(s->bs->node_name),
2234ddb5d2fSVladimir Sementsov-Ogievskiy                                  nbd_yank, s->bs);
2244ddb5d2fSVladimir Sementsov-Ogievskiy         object_unref(OBJECT(s->ioc));
2254ddb5d2fSVladimir Sementsov-Ogievskiy         s->ioc = NULL;
226f7651539SVladimir Sementsov-Ogievskiy     }
227fbeb3e63SVladimir Sementsov-Ogievskiy 
228f7651539SVladimir Sementsov-Ogievskiy     s->state = NBD_CLIENT_QUIT;
22978c81a3fSMax Reitz }
23086f8cdf3SVladimir Sementsov-Ogievskiy 
231be16b8bfSVladimir Sementsov-Ogievskiy static void open_timer_del(BDRVNBDState *s)
232be16b8bfSVladimir Sementsov-Ogievskiy {
233be16b8bfSVladimir Sementsov-Ogievskiy     if (s->open_timer) {
234be16b8bfSVladimir Sementsov-Ogievskiy         timer_free(s->open_timer);
235be16b8bfSVladimir Sementsov-Ogievskiy         s->open_timer = NULL;
236be16b8bfSVladimir Sementsov-Ogievskiy     }
237be16b8bfSVladimir Sementsov-Ogievskiy }
238be16b8bfSVladimir Sementsov-Ogievskiy 
239be16b8bfSVladimir Sementsov-Ogievskiy static void open_timer_cb(void *opaque)
240be16b8bfSVladimir Sementsov-Ogievskiy {
241be16b8bfSVladimir Sementsov-Ogievskiy     BDRVNBDState *s = opaque;
242be16b8bfSVladimir Sementsov-Ogievskiy 
243be16b8bfSVladimir Sementsov-Ogievskiy     nbd_co_establish_connection_cancel(s->conn);
244be16b8bfSVladimir Sementsov-Ogievskiy     open_timer_del(s);
245be16b8bfSVladimir Sementsov-Ogievskiy }
246be16b8bfSVladimir Sementsov-Ogievskiy 
247be16b8bfSVladimir Sementsov-Ogievskiy static void open_timer_init(BDRVNBDState *s, uint64_t expire_time_ns)
248be16b8bfSVladimir Sementsov-Ogievskiy {
249be16b8bfSVladimir Sementsov-Ogievskiy     assert(!s->open_timer);
250be16b8bfSVladimir Sementsov-Ogievskiy     s->open_timer = aio_timer_new(bdrv_get_aio_context(s->bs),
251be16b8bfSVladimir Sementsov-Ogievskiy                                   QEMU_CLOCK_REALTIME,
252be16b8bfSVladimir Sementsov-Ogievskiy                                   SCALE_NS,
253be16b8bfSVladimir Sementsov-Ogievskiy                                   open_timer_cb, s);
254be16b8bfSVladimir Sementsov-Ogievskiy     timer_mod(s->open_timer, expire_time_ns);
255be16b8bfSVladimir Sementsov-Ogievskiy }
256be16b8bfSVladimir Sementsov-Ogievskiy 
257f7651539SVladimir Sementsov-Ogievskiy static bool nbd_client_connecting_wait(BDRVNBDState *s)
258f7651539SVladimir Sementsov-Ogievskiy {
259fee091cdSLukas Straub     return qatomic_load_acquire(&s->state) == NBD_CLIENT_CONNECTING_WAIT;
260f7651539SVladimir Sementsov-Ogievskiy }
261f7651539SVladimir Sementsov-Ogievskiy 
262*8d45185cSPaolo Bonzini static bool nbd_client_will_reconnect(BDRVNBDState *s)
263*8d45185cSPaolo Bonzini {
264*8d45185cSPaolo Bonzini     return qatomic_load_acquire(&s->state) == NBD_CLIENT_CONNECTING_WAIT;
265*8d45185cSPaolo Bonzini }
266e9ba7788SVladimir Sementsov-Ogievskiy /*
267e9ba7788SVladimir Sementsov-Ogievskiy  * Update @bs with information learned during a completed negotiation process.
268e9ba7788SVladimir Sementsov-Ogievskiy  * Return failure if the server's advertised options are incompatible with the
269e9ba7788SVladimir Sementsov-Ogievskiy  * client's needs.
270e9ba7788SVladimir Sementsov-Ogievskiy  */
271e9ba7788SVladimir Sementsov-Ogievskiy static int nbd_handle_updated_info(BlockDriverState *bs, Error **errp)
272e9ba7788SVladimir Sementsov-Ogievskiy {
273e9ba7788SVladimir Sementsov-Ogievskiy     BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
274e9ba7788SVladimir Sementsov-Ogievskiy     int ret;
275e9ba7788SVladimir Sementsov-Ogievskiy 
276e9ba7788SVladimir Sementsov-Ogievskiy     if (s->x_dirty_bitmap) {
277e9ba7788SVladimir Sementsov-Ogievskiy         if (!s->info.base_allocation) {
278e9ba7788SVladimir Sementsov-Ogievskiy             error_setg(errp, "requested x-dirty-bitmap %s not found",
279e9ba7788SVladimir Sementsov-Ogievskiy                        s->x_dirty_bitmap);
280e9ba7788SVladimir Sementsov-Ogievskiy             return -EINVAL;
281e9ba7788SVladimir Sementsov-Ogievskiy         }
282e9ba7788SVladimir Sementsov-Ogievskiy         if (strcmp(s->x_dirty_bitmap, "qemu:allocation-depth") == 0) {
283e9ba7788SVladimir Sementsov-Ogievskiy             s->alloc_depth = true;
284e9ba7788SVladimir Sementsov-Ogievskiy         }
285e9ba7788SVladimir Sementsov-Ogievskiy     }
286e9ba7788SVladimir Sementsov-Ogievskiy 
287e9ba7788SVladimir Sementsov-Ogievskiy     if (s->info.flags & NBD_FLAG_READ_ONLY) {
288e9ba7788SVladimir Sementsov-Ogievskiy         ret = bdrv_apply_auto_read_only(bs, "NBD export is read-only", errp);
289e9ba7788SVladimir Sementsov-Ogievskiy         if (ret < 0) {
290e9ba7788SVladimir Sementsov-Ogievskiy             return ret;
291e9ba7788SVladimir Sementsov-Ogievskiy         }
292e9ba7788SVladimir Sementsov-Ogievskiy     }
293e9ba7788SVladimir Sementsov-Ogievskiy 
294e9ba7788SVladimir Sementsov-Ogievskiy     if (s->info.flags & NBD_FLAG_SEND_FUA) {
295e9ba7788SVladimir Sementsov-Ogievskiy         bs->supported_write_flags = BDRV_REQ_FUA;
296e9ba7788SVladimir Sementsov-Ogievskiy         bs->supported_zero_flags |= BDRV_REQ_FUA;
297e9ba7788SVladimir Sementsov-Ogievskiy     }
298e9ba7788SVladimir Sementsov-Ogievskiy 
299e9ba7788SVladimir Sementsov-Ogievskiy     if (s->info.flags & NBD_FLAG_SEND_WRITE_ZEROES) {
300e9ba7788SVladimir Sementsov-Ogievskiy         bs->supported_zero_flags |= BDRV_REQ_MAY_UNMAP;
301e9ba7788SVladimir Sementsov-Ogievskiy         if (s->info.flags & NBD_FLAG_SEND_FAST_ZERO) {
302e9ba7788SVladimir Sementsov-Ogievskiy             bs->supported_zero_flags |= BDRV_REQ_NO_FALLBACK;
303e9ba7788SVladimir Sementsov-Ogievskiy         }
304e9ba7788SVladimir Sementsov-Ogievskiy     }
305e9ba7788SVladimir Sementsov-Ogievskiy 
306e9ba7788SVladimir Sementsov-Ogievskiy     trace_nbd_client_handshake_success(s->export);
307e9ba7788SVladimir Sementsov-Ogievskiy 
308e9ba7788SVladimir Sementsov-Ogievskiy     return 0;
309e9ba7788SVladimir Sementsov-Ogievskiy }
310e9ba7788SVladimir Sementsov-Ogievskiy 
311a71d597bSVladimir Sementsov-Ogievskiy int coroutine_fn nbd_co_do_establish_connection(BlockDriverState *bs,
3128610b449SPaolo Bonzini                                                 bool blocking, Error **errp)
31351edbf53SVladimir Sementsov-Ogievskiy {
31451edbf53SVladimir Sementsov-Ogievskiy     BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
31551edbf53SVladimir Sementsov-Ogievskiy     int ret;
3161581a70dSEmanuele Giuseppe Esposito     IO_CODE();
31751edbf53SVladimir Sementsov-Ogievskiy 
31851edbf53SVladimir Sementsov-Ogievskiy     assert(!s->ioc);
31951edbf53SVladimir Sementsov-Ogievskiy 
3204ddb5d2fSVladimir Sementsov-Ogievskiy     s->ioc = nbd_co_establish_connection(s->conn, &s->info, blocking, errp);
32151edbf53SVladimir Sementsov-Ogievskiy     if (!s->ioc) {
32251edbf53SVladimir Sementsov-Ogievskiy         return -ECONNREFUSED;
32351edbf53SVladimir Sementsov-Ogievskiy     }
32451edbf53SVladimir Sementsov-Ogievskiy 
3250b9cd6b9SLukas Straub     yank_register_function(BLOCKDEV_YANK_INSTANCE(s->bs->node_name), nbd_yank,
3260b9cd6b9SLukas Straub                            bs);
3270b9cd6b9SLukas Straub 
32851edbf53SVladimir Sementsov-Ogievskiy     ret = nbd_handle_updated_info(s->bs, NULL);
32951edbf53SVladimir Sementsov-Ogievskiy     if (ret < 0) {
33051edbf53SVladimir Sementsov-Ogievskiy         /*
33151edbf53SVladimir Sementsov-Ogievskiy          * We have connected, but must fail for other reasons.
33251edbf53SVladimir Sementsov-Ogievskiy          * Send NBD_CMD_DISC as a courtesy to the server.
33351edbf53SVladimir Sementsov-Ogievskiy          */
33451edbf53SVladimir Sementsov-Ogievskiy         NBDRequest request = { .type = NBD_CMD_DISC };
33551edbf53SVladimir Sementsov-Ogievskiy 
33651edbf53SVladimir Sementsov-Ogievskiy         nbd_send_request(s->ioc, &request);
33751edbf53SVladimir Sementsov-Ogievskiy 
3380b9cd6b9SLukas Straub         yank_unregister_function(BLOCKDEV_YANK_INSTANCE(s->bs->node_name),
3390b9cd6b9SLukas Straub                                  nbd_yank, bs);
34051edbf53SVladimir Sementsov-Ogievskiy         object_unref(OBJECT(s->ioc));
34151edbf53SVladimir Sementsov-Ogievskiy         s->ioc = NULL;
34251edbf53SVladimir Sementsov-Ogievskiy 
34351edbf53SVladimir Sementsov-Ogievskiy         return ret;
34451edbf53SVladimir Sementsov-Ogievskiy     }
34551edbf53SVladimir Sementsov-Ogievskiy 
34651edbf53SVladimir Sementsov-Ogievskiy     qio_channel_set_blocking(s->ioc, false, NULL);
34751edbf53SVladimir Sementsov-Ogievskiy     qio_channel_attach_aio_context(s->ioc, bdrv_get_aio_context(bs));
34851edbf53SVladimir Sementsov-Ogievskiy 
34951edbf53SVladimir Sementsov-Ogievskiy     /* successfully connected */
35051edbf53SVladimir Sementsov-Ogievskiy     s->state = NBD_CLIENT_CONNECTED;
35151edbf53SVladimir Sementsov-Ogievskiy 
35251edbf53SVladimir Sementsov-Ogievskiy     return 0;
35351edbf53SVladimir Sementsov-Ogievskiy }
35451edbf53SVladimir Sementsov-Ogievskiy 
355*8d45185cSPaolo Bonzini static bool nbd_client_connecting(BDRVNBDState *s)
356*8d45185cSPaolo Bonzini {
357*8d45185cSPaolo Bonzini     NBDClientState state = qatomic_load_acquire(&s->state);
358*8d45185cSPaolo Bonzini     return state == NBD_CLIENT_CONNECTING_WAIT ||
359*8d45185cSPaolo Bonzini         state == NBD_CLIENT_CONNECTING_NOWAIT;
360*8d45185cSPaolo Bonzini }
361*8d45185cSPaolo Bonzini 
362ee19d953SPaolo Bonzini /* Called with s->requests_lock taken.  */
363f7651539SVladimir Sementsov-Ogievskiy static coroutine_fn void nbd_reconnect_attempt(BDRVNBDState *s)
364f7651539SVladimir Sementsov-Ogievskiy {
3658610b449SPaolo Bonzini     bool blocking = nbd_client_connecting_wait(s);
366f7651539SVladimir Sementsov-Ogievskiy 
367f7651539SVladimir Sementsov-Ogievskiy     /*
368f7651539SVladimir Sementsov-Ogievskiy      * Now we are sure that nobody is accessing the channel, and no one will
369f7651539SVladimir Sementsov-Ogievskiy      * try until we set the state to CONNECTED.
370f7651539SVladimir Sementsov-Ogievskiy      */
3718610b449SPaolo Bonzini     assert(nbd_client_connecting(s));
3728610b449SPaolo Bonzini     assert(s->in_flight == 1);
3738610b449SPaolo Bonzini 
3748610b449SPaolo Bonzini     if (blocking && !s->reconnect_delay_timer) {
3758610b449SPaolo Bonzini         /*
3768610b449SPaolo Bonzini          * It's the first reconnect attempt after switching to
3778610b449SPaolo Bonzini          * NBD_CLIENT_CONNECTING_WAIT
3788610b449SPaolo Bonzini          */
3798610b449SPaolo Bonzini         g_assert(s->reconnect_delay);
3808610b449SPaolo Bonzini         reconnect_delay_timer_init(s,
3818610b449SPaolo Bonzini             qemu_clock_get_ns(QEMU_CLOCK_REALTIME) +
3828610b449SPaolo Bonzini             s->reconnect_delay * NANOSECONDS_PER_SECOND);
3838610b449SPaolo Bonzini     }
384f7651539SVladimir Sementsov-Ogievskiy 
385f7651539SVladimir Sementsov-Ogievskiy     /* Finalize previous connection if any */
386f7651539SVladimir Sementsov-Ogievskiy     if (s->ioc) {
3878a509afdSVladimir Sementsov-Ogievskiy         qio_channel_detach_aio_context(QIO_CHANNEL(s->ioc));
388fee091cdSLukas Straub         yank_unregister_function(BLOCKDEV_YANK_INSTANCE(s->bs->node_name),
389fee091cdSLukas Straub                                  nbd_yank, s->bs);
390611ae1d7SVladimir Sementsov-Ogievskiy         object_unref(OBJECT(s->ioc));
391611ae1d7SVladimir Sementsov-Ogievskiy         s->ioc = NULL;
39286f8cdf3SVladimir Sementsov-Ogievskiy     }
39386f8cdf3SVladimir Sementsov-Ogievskiy 
394ee19d953SPaolo Bonzini     qemu_mutex_unlock(&s->requests_lock);
3958610b449SPaolo Bonzini     nbd_co_do_establish_connection(s->bs, blocking, NULL);
396ee19d953SPaolo Bonzini     qemu_mutex_lock(&s->requests_lock);
3973ce1fc16SHanna Reitz 
3983ce1fc16SHanna Reitz     /*
3993ce1fc16SHanna Reitz      * The reconnect attempt is done (maybe successfully, maybe not), so
4003ce1fc16SHanna Reitz      * we no longer need this timer.  Delete it so it will not outlive
4013ce1fc16SHanna Reitz      * this I/O request (so draining removes all timers).
4023ce1fc16SHanna Reitz      */
4033ce1fc16SHanna Reitz     reconnect_delay_timer_del(s);
404fa35591bSVladimir Sementsov-Ogievskiy }
405f7651539SVladimir Sementsov-Ogievskiy 
4064ddb5d2fSVladimir Sementsov-Ogievskiy static coroutine_fn int nbd_receive_replies(BDRVNBDState *s, uint64_t handle)
407f7651539SVladimir Sementsov-Ogievskiy {
4084ddb5d2fSVladimir Sementsov-Ogievskiy     int ret;
4094ddb5d2fSVladimir Sementsov-Ogievskiy     uint64_t ind = HANDLE_TO_INDEX(s, handle), ind2;
4104ddb5d2fSVladimir Sementsov-Ogievskiy     QEMU_LOCK_GUARD(&s->receive_mutex);
411f7651539SVladimir Sementsov-Ogievskiy 
4124ddb5d2fSVladimir Sementsov-Ogievskiy     while (true) {
4134ddb5d2fSVladimir Sementsov-Ogievskiy         if (s->reply.handle == handle) {
4144ddb5d2fSVladimir Sementsov-Ogievskiy             /* We are done */
4154ddb5d2fSVladimir Sementsov-Ogievskiy             return 0;
416f7651539SVladimir Sementsov-Ogievskiy         }
417f7651539SVladimir Sementsov-Ogievskiy 
4184ddb5d2fSVladimir Sementsov-Ogievskiy         if (s->reply.handle != 0) {
41986f8cdf3SVladimir Sementsov-Ogievskiy             /*
4204ddb5d2fSVladimir Sementsov-Ogievskiy              * Some other request is being handled now. It should already be
4214ddb5d2fSVladimir Sementsov-Ogievskiy              * woken by whoever set s->reply.handle (or never wait in this
4224ddb5d2fSVladimir Sementsov-Ogievskiy              * yield). So, we should not wake it here.
42386f8cdf3SVladimir Sementsov-Ogievskiy              */
4244ddb5d2fSVladimir Sementsov-Ogievskiy             ind2 = HANDLE_TO_INDEX(s, s->reply.handle);
4254ddb5d2fSVladimir Sementsov-Ogievskiy             assert(!s->requests[ind2].receiving);
42686f8cdf3SVladimir Sementsov-Ogievskiy 
4274ddb5d2fSVladimir Sementsov-Ogievskiy             s->requests[ind].receiving = true;
4284ddb5d2fSVladimir Sementsov-Ogievskiy             qemu_co_mutex_unlock(&s->receive_mutex);
4294ddb5d2fSVladimir Sementsov-Ogievskiy 
43086f8cdf3SVladimir Sementsov-Ogievskiy             qemu_coroutine_yield();
4314ddb5d2fSVladimir Sementsov-Ogievskiy             /*
4324ddb5d2fSVladimir Sementsov-Ogievskiy              * We may be woken for 3 reasons:
4334ddb5d2fSVladimir Sementsov-Ogievskiy              * 1. From this function, executing in parallel coroutine, when our
4344ddb5d2fSVladimir Sementsov-Ogievskiy              *    handle is received.
4354ddb5d2fSVladimir Sementsov-Ogievskiy              * 2. From nbd_channel_error(), when connection is lost.
4364ddb5d2fSVladimir Sementsov-Ogievskiy              * 3. From nbd_co_receive_one_chunk(), when previous request is
4374ddb5d2fSVladimir Sementsov-Ogievskiy              *    finished and s->reply.handle set to 0.
4384ddb5d2fSVladimir Sementsov-Ogievskiy              * Anyway, it's OK to lock the mutex and go to the next iteration.
4394ddb5d2fSVladimir Sementsov-Ogievskiy              */
4404ddb5d2fSVladimir Sementsov-Ogievskiy 
4414ddb5d2fSVladimir Sementsov-Ogievskiy             qemu_co_mutex_lock(&s->receive_mutex);
4424ddb5d2fSVladimir Sementsov-Ogievskiy             assert(!s->requests[ind].receiving);
4434ddb5d2fSVladimir Sementsov-Ogievskiy             continue;
44486f8cdf3SVladimir Sementsov-Ogievskiy         }
44586f8cdf3SVladimir Sementsov-Ogievskiy 
4464ddb5d2fSVladimir Sementsov-Ogievskiy         /* We are under mutex and handle is 0. We have to do the dirty work. */
4474ddb5d2fSVladimir Sementsov-Ogievskiy         assert(s->reply.handle == 0);
4484ddb5d2fSVladimir Sementsov-Ogievskiy         ret = nbd_receive_reply(s->bs, s->ioc, &s->reply, NULL);
4494ddb5d2fSVladimir Sementsov-Ogievskiy         if (ret <= 0) {
4504ddb5d2fSVladimir Sementsov-Ogievskiy             ret = ret ? ret : -EIO;
4514ddb5d2fSVladimir Sementsov-Ogievskiy             nbd_channel_error(s, ret);
4524ddb5d2fSVladimir Sementsov-Ogievskiy             return ret;
453f7651539SVladimir Sementsov-Ogievskiy         }
4544ddb5d2fSVladimir Sementsov-Ogievskiy         if (nbd_reply_is_structured(&s->reply) && !s->info.structured_reply) {
4554ddb5d2fSVladimir Sementsov-Ogievskiy             nbd_channel_error(s, -EINVAL);
4564ddb5d2fSVladimir Sementsov-Ogievskiy             return -EINVAL;
45778c81a3fSMax Reitz         }
4588846b7d1SPaolo Bonzini         ind2 = HANDLE_TO_INDEX(s, s->reply.handle);
4598846b7d1SPaolo Bonzini         if (ind2 >= MAX_NBD_REQUESTS || !s->requests[ind2].coroutine) {
4608846b7d1SPaolo Bonzini             nbd_channel_error(s, -EINVAL);
4618846b7d1SPaolo Bonzini             return -EINVAL;
4628846b7d1SPaolo Bonzini         }
4634ddb5d2fSVladimir Sementsov-Ogievskiy         if (s->reply.handle == handle) {
4644ddb5d2fSVladimir Sementsov-Ogievskiy             /* We are done */
4654ddb5d2fSVladimir Sementsov-Ogievskiy             return 0;
4664ddb5d2fSVladimir Sementsov-Ogievskiy         }
4674ddb5d2fSVladimir Sementsov-Ogievskiy         nbd_recv_coroutine_wake_one(&s->requests[ind2]);
4684ddb5d2fSVladimir Sementsov-Ogievskiy     }
46986f8cdf3SVladimir Sementsov-Ogievskiy }
47086f8cdf3SVladimir Sementsov-Ogievskiy 
4710c43c6fcSPaolo Bonzini static int coroutine_fn nbd_co_send_request(BlockDriverState *bs,
47286f8cdf3SVladimir Sementsov-Ogievskiy                                             NBDRequest *request,
47386f8cdf3SVladimir Sementsov-Ogievskiy                                             QEMUIOVector *qiov)
47486f8cdf3SVladimir Sementsov-Ogievskiy {
475611ae1d7SVladimir Sementsov-Ogievskiy     BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
476a34b1e5eSVladimir Sementsov-Ogievskiy     int rc, i = -1;
47786f8cdf3SVladimir Sementsov-Ogievskiy 
478ee19d953SPaolo Bonzini     qemu_mutex_lock(&s->requests_lock);
4794ddb5d2fSVladimir Sementsov-Ogievskiy     while (s->in_flight == MAX_NBD_REQUESTS ||
4808610b449SPaolo Bonzini            (!nbd_client_connected(s) && s->in_flight > 0)) {
481ee19d953SPaolo Bonzini         qemu_co_queue_wait(&s->free_sema, &s->requests_lock);
48286f8cdf3SVladimir Sementsov-Ogievskiy     }
483a34b1e5eSVladimir Sementsov-Ogievskiy 
4848610b449SPaolo Bonzini     s->in_flight++;
4858610b449SPaolo Bonzini     if (!nbd_client_connected(s)) {
4864ddb5d2fSVladimir Sementsov-Ogievskiy         if (nbd_client_connecting(s)) {
4874ddb5d2fSVladimir Sementsov-Ogievskiy             nbd_reconnect_attempt(s);
4888610b449SPaolo Bonzini             qemu_co_queue_restart_all(&s->free_sema);
4894ddb5d2fSVladimir Sementsov-Ogievskiy         }
49091e0998fSVladimir Sementsov-Ogievskiy         if (!nbd_client_connected(s)) {
491a34b1e5eSVladimir Sementsov-Ogievskiy             rc = -EIO;
492a34b1e5eSVladimir Sementsov-Ogievskiy             goto err;
493a34b1e5eSVladimir Sementsov-Ogievskiy         }
4948610b449SPaolo Bonzini     }
49586f8cdf3SVladimir Sementsov-Ogievskiy 
49686f8cdf3SVladimir Sementsov-Ogievskiy     for (i = 0; i < MAX_NBD_REQUESTS; i++) {
49786f8cdf3SVladimir Sementsov-Ogievskiy         if (s->requests[i].coroutine == NULL) {
49886f8cdf3SVladimir Sementsov-Ogievskiy             break;
49986f8cdf3SVladimir Sementsov-Ogievskiy         }
50086f8cdf3SVladimir Sementsov-Ogievskiy     }
50186f8cdf3SVladimir Sementsov-Ogievskiy 
50286f8cdf3SVladimir Sementsov-Ogievskiy     assert(i < MAX_NBD_REQUESTS);
50386f8cdf3SVladimir Sementsov-Ogievskiy     s->requests[i].coroutine = qemu_coroutine_self();
50486f8cdf3SVladimir Sementsov-Ogievskiy     s->requests[i].offset = request->from;
50586f8cdf3SVladimir Sementsov-Ogievskiy     s->requests[i].receiving = false;
506ee19d953SPaolo Bonzini     qemu_mutex_unlock(&s->requests_lock);
50786f8cdf3SVladimir Sementsov-Ogievskiy 
508ee19d953SPaolo Bonzini     qemu_co_mutex_lock(&s->send_mutex);
50986f8cdf3SVladimir Sementsov-Ogievskiy     request->handle = INDEX_TO_HANDLE(s, i);
51086f8cdf3SVladimir Sementsov-Ogievskiy 
51186f8cdf3SVladimir Sementsov-Ogievskiy     assert(s->ioc);
51286f8cdf3SVladimir Sementsov-Ogievskiy 
51386f8cdf3SVladimir Sementsov-Ogievskiy     if (qiov) {
51486f8cdf3SVladimir Sementsov-Ogievskiy         qio_channel_set_cork(s->ioc, true);
51586f8cdf3SVladimir Sementsov-Ogievskiy         rc = nbd_send_request(s->ioc, request);
516172f5f1aSPaolo Bonzini         if (rc >= 0) {
51786f8cdf3SVladimir Sementsov-Ogievskiy             if (qio_channel_writev_all(s->ioc, qiov->iov, qiov->niov,
51886f8cdf3SVladimir Sementsov-Ogievskiy                                        NULL) < 0) {
51986f8cdf3SVladimir Sementsov-Ogievskiy                 rc = -EIO;
52086f8cdf3SVladimir Sementsov-Ogievskiy             }
52186f8cdf3SVladimir Sementsov-Ogievskiy         } else if (rc >= 0) {
52286f8cdf3SVladimir Sementsov-Ogievskiy             rc = -EIO;
52386f8cdf3SVladimir Sementsov-Ogievskiy         }
52486f8cdf3SVladimir Sementsov-Ogievskiy         qio_channel_set_cork(s->ioc, false);
52586f8cdf3SVladimir Sementsov-Ogievskiy     } else {
52686f8cdf3SVladimir Sementsov-Ogievskiy         rc = nbd_send_request(s->ioc, request);
52786f8cdf3SVladimir Sementsov-Ogievskiy     }
528ee19d953SPaolo Bonzini     qemu_co_mutex_unlock(&s->send_mutex);
52986f8cdf3SVladimir Sementsov-Ogievskiy 
53086f8cdf3SVladimir Sementsov-Ogievskiy     if (rc < 0) {
531ee19d953SPaolo Bonzini         qemu_mutex_lock(&s->requests_lock);
532ee19d953SPaolo Bonzini err:
533a34b1e5eSVladimir Sementsov-Ogievskiy         nbd_channel_error(s, rc);
534a34b1e5eSVladimir Sementsov-Ogievskiy         if (i != -1) {
53586f8cdf3SVladimir Sementsov-Ogievskiy             s->requests[i].coroutine = NULL;
53686f8cdf3SVladimir Sementsov-Ogievskiy         }
5378610b449SPaolo Bonzini         s->in_flight--;
5386690302bSRao Lei         qemu_co_queue_next(&s->free_sema);
539ee19d953SPaolo Bonzini         qemu_mutex_unlock(&s->requests_lock);
540f7651539SVladimir Sementsov-Ogievskiy     }
54186f8cdf3SVladimir Sementsov-Ogievskiy     return rc;
54286f8cdf3SVladimir Sementsov-Ogievskiy }
54386f8cdf3SVladimir Sementsov-Ogievskiy 
54486f8cdf3SVladimir Sementsov-Ogievskiy static inline uint16_t payload_advance16(uint8_t **payload)
54586f8cdf3SVladimir Sementsov-Ogievskiy {
54686f8cdf3SVladimir Sementsov-Ogievskiy     *payload += 2;
54786f8cdf3SVladimir Sementsov-Ogievskiy     return lduw_be_p(*payload - 2);
54886f8cdf3SVladimir Sementsov-Ogievskiy }
54986f8cdf3SVladimir Sementsov-Ogievskiy 
55086f8cdf3SVladimir Sementsov-Ogievskiy static inline uint32_t payload_advance32(uint8_t **payload)
55186f8cdf3SVladimir Sementsov-Ogievskiy {
55286f8cdf3SVladimir Sementsov-Ogievskiy     *payload += 4;
55386f8cdf3SVladimir Sementsov-Ogievskiy     return ldl_be_p(*payload - 4);
55486f8cdf3SVladimir Sementsov-Ogievskiy }
55586f8cdf3SVladimir Sementsov-Ogievskiy 
55686f8cdf3SVladimir Sementsov-Ogievskiy static inline uint64_t payload_advance64(uint8_t **payload)
55786f8cdf3SVladimir Sementsov-Ogievskiy {
55886f8cdf3SVladimir Sementsov-Ogievskiy     *payload += 8;
55986f8cdf3SVladimir Sementsov-Ogievskiy     return ldq_be_p(*payload - 8);
56086f8cdf3SVladimir Sementsov-Ogievskiy }
56186f8cdf3SVladimir Sementsov-Ogievskiy 
562611ae1d7SVladimir Sementsov-Ogievskiy static int nbd_parse_offset_hole_payload(BDRVNBDState *s,
56386f8cdf3SVladimir Sementsov-Ogievskiy                                          NBDStructuredReplyChunk *chunk,
56486f8cdf3SVladimir Sementsov-Ogievskiy                                          uint8_t *payload, uint64_t orig_offset,
56586f8cdf3SVladimir Sementsov-Ogievskiy                                          QEMUIOVector *qiov, Error **errp)
56686f8cdf3SVladimir Sementsov-Ogievskiy {
56786f8cdf3SVladimir Sementsov-Ogievskiy     uint64_t offset;
56886f8cdf3SVladimir Sementsov-Ogievskiy     uint32_t hole_size;
56986f8cdf3SVladimir Sementsov-Ogievskiy 
57086f8cdf3SVladimir Sementsov-Ogievskiy     if (chunk->length != sizeof(offset) + sizeof(hole_size)) {
57186f8cdf3SVladimir Sementsov-Ogievskiy         error_setg(errp, "Protocol error: invalid payload for "
57286f8cdf3SVladimir Sementsov-Ogievskiy                          "NBD_REPLY_TYPE_OFFSET_HOLE");
57386f8cdf3SVladimir Sementsov-Ogievskiy         return -EINVAL;
57486f8cdf3SVladimir Sementsov-Ogievskiy     }
57586f8cdf3SVladimir Sementsov-Ogievskiy 
57686f8cdf3SVladimir Sementsov-Ogievskiy     offset = payload_advance64(&payload);
57786f8cdf3SVladimir Sementsov-Ogievskiy     hole_size = payload_advance32(&payload);
57886f8cdf3SVladimir Sementsov-Ogievskiy 
57986f8cdf3SVladimir Sementsov-Ogievskiy     if (!hole_size || offset < orig_offset || hole_size > qiov->size ||
58086f8cdf3SVladimir Sementsov-Ogievskiy         offset > orig_offset + qiov->size - hole_size) {
58186f8cdf3SVladimir Sementsov-Ogievskiy         error_setg(errp, "Protocol error: server sent chunk exceeding requested"
58286f8cdf3SVladimir Sementsov-Ogievskiy                          " region");
58386f8cdf3SVladimir Sementsov-Ogievskiy         return -EINVAL;
58486f8cdf3SVladimir Sementsov-Ogievskiy     }
585611ae1d7SVladimir Sementsov-Ogievskiy     if (s->info.min_block &&
586611ae1d7SVladimir Sementsov-Ogievskiy         !QEMU_IS_ALIGNED(hole_size, s->info.min_block)) {
58786f8cdf3SVladimir Sementsov-Ogievskiy         trace_nbd_structured_read_compliance("hole");
58886f8cdf3SVladimir Sementsov-Ogievskiy     }
58986f8cdf3SVladimir Sementsov-Ogievskiy 
59086f8cdf3SVladimir Sementsov-Ogievskiy     qemu_iovec_memset(qiov, offset - orig_offset, 0, hole_size);
59186f8cdf3SVladimir Sementsov-Ogievskiy 
59286f8cdf3SVladimir Sementsov-Ogievskiy     return 0;
59386f8cdf3SVladimir Sementsov-Ogievskiy }
59486f8cdf3SVladimir Sementsov-Ogievskiy 
59586f8cdf3SVladimir Sementsov-Ogievskiy /*
59686f8cdf3SVladimir Sementsov-Ogievskiy  * nbd_parse_blockstatus_payload
59786f8cdf3SVladimir Sementsov-Ogievskiy  * Based on our request, we expect only one extent in reply, for the
59886f8cdf3SVladimir Sementsov-Ogievskiy  * base:allocation context.
59986f8cdf3SVladimir Sementsov-Ogievskiy  */
600611ae1d7SVladimir Sementsov-Ogievskiy static int nbd_parse_blockstatus_payload(BDRVNBDState *s,
60186f8cdf3SVladimir Sementsov-Ogievskiy                                          NBDStructuredReplyChunk *chunk,
60286f8cdf3SVladimir Sementsov-Ogievskiy                                          uint8_t *payload, uint64_t orig_length,
60386f8cdf3SVladimir Sementsov-Ogievskiy                                          NBDExtent *extent, Error **errp)
60486f8cdf3SVladimir Sementsov-Ogievskiy {
60586f8cdf3SVladimir Sementsov-Ogievskiy     uint32_t context_id;
60686f8cdf3SVladimir Sementsov-Ogievskiy 
60786f8cdf3SVladimir Sementsov-Ogievskiy     /* The server succeeded, so it must have sent [at least] one extent */
60886f8cdf3SVladimir Sementsov-Ogievskiy     if (chunk->length < sizeof(context_id) + sizeof(*extent)) {
60986f8cdf3SVladimir Sementsov-Ogievskiy         error_setg(errp, "Protocol error: invalid payload for "
61086f8cdf3SVladimir Sementsov-Ogievskiy                          "NBD_REPLY_TYPE_BLOCK_STATUS");
61186f8cdf3SVladimir Sementsov-Ogievskiy         return -EINVAL;
61286f8cdf3SVladimir Sementsov-Ogievskiy     }
61386f8cdf3SVladimir Sementsov-Ogievskiy 
61486f8cdf3SVladimir Sementsov-Ogievskiy     context_id = payload_advance32(&payload);
615611ae1d7SVladimir Sementsov-Ogievskiy     if (s->info.context_id != context_id) {
61686f8cdf3SVladimir Sementsov-Ogievskiy         error_setg(errp, "Protocol error: unexpected context id %d for "
61786f8cdf3SVladimir Sementsov-Ogievskiy                          "NBD_REPLY_TYPE_BLOCK_STATUS, when negotiated context "
61886f8cdf3SVladimir Sementsov-Ogievskiy                          "id is %d", context_id,
619611ae1d7SVladimir Sementsov-Ogievskiy                          s->info.context_id);
62086f8cdf3SVladimir Sementsov-Ogievskiy         return -EINVAL;
62186f8cdf3SVladimir Sementsov-Ogievskiy     }
62286f8cdf3SVladimir Sementsov-Ogievskiy 
62386f8cdf3SVladimir Sementsov-Ogievskiy     extent->length = payload_advance32(&payload);
62486f8cdf3SVladimir Sementsov-Ogievskiy     extent->flags = payload_advance32(&payload);
62586f8cdf3SVladimir Sementsov-Ogievskiy 
62686f8cdf3SVladimir Sementsov-Ogievskiy     if (extent->length == 0) {
62786f8cdf3SVladimir Sementsov-Ogievskiy         error_setg(errp, "Protocol error: server sent status chunk with "
62886f8cdf3SVladimir Sementsov-Ogievskiy                    "zero length");
62986f8cdf3SVladimir Sementsov-Ogievskiy         return -EINVAL;
63086f8cdf3SVladimir Sementsov-Ogievskiy     }
63186f8cdf3SVladimir Sementsov-Ogievskiy 
63286f8cdf3SVladimir Sementsov-Ogievskiy     /*
63386f8cdf3SVladimir Sementsov-Ogievskiy      * A server sending unaligned block status is in violation of the
63486f8cdf3SVladimir Sementsov-Ogievskiy      * protocol, but as qemu-nbd 3.1 is such a server (at least for
63586f8cdf3SVladimir Sementsov-Ogievskiy      * POSIX files that are not a multiple of 512 bytes, since qemu
63686f8cdf3SVladimir Sementsov-Ogievskiy      * rounds files up to 512-byte multiples but lseek(SEEK_HOLE)
63786f8cdf3SVladimir Sementsov-Ogievskiy      * still sees an implicit hole beyond the real EOF), it's nicer to
63886f8cdf3SVladimir Sementsov-Ogievskiy      * work around the misbehaving server. If the request included
63986f8cdf3SVladimir Sementsov-Ogievskiy      * more than the final unaligned block, truncate it back to an
64086f8cdf3SVladimir Sementsov-Ogievskiy      * aligned result; if the request was only the final block, round
64186f8cdf3SVladimir Sementsov-Ogievskiy      * up to the full block and change the status to fully-allocated
64286f8cdf3SVladimir Sementsov-Ogievskiy      * (always a safe status, even if it loses information).
64386f8cdf3SVladimir Sementsov-Ogievskiy      */
644611ae1d7SVladimir Sementsov-Ogievskiy     if (s->info.min_block && !QEMU_IS_ALIGNED(extent->length,
645611ae1d7SVladimir Sementsov-Ogievskiy                                                    s->info.min_block)) {
64686f8cdf3SVladimir Sementsov-Ogievskiy         trace_nbd_parse_blockstatus_compliance("extent length is unaligned");
647611ae1d7SVladimir Sementsov-Ogievskiy         if (extent->length > s->info.min_block) {
64886f8cdf3SVladimir Sementsov-Ogievskiy             extent->length = QEMU_ALIGN_DOWN(extent->length,
649611ae1d7SVladimir Sementsov-Ogievskiy                                              s->info.min_block);
65086f8cdf3SVladimir Sementsov-Ogievskiy         } else {
651611ae1d7SVladimir Sementsov-Ogievskiy             extent->length = s->info.min_block;
65286f8cdf3SVladimir Sementsov-Ogievskiy             extent->flags = 0;
65386f8cdf3SVladimir Sementsov-Ogievskiy         }
65486f8cdf3SVladimir Sementsov-Ogievskiy     }
65586f8cdf3SVladimir Sementsov-Ogievskiy 
65686f8cdf3SVladimir Sementsov-Ogievskiy     /*
65786f8cdf3SVladimir Sementsov-Ogievskiy      * We used NBD_CMD_FLAG_REQ_ONE, so the server should not have
65886f8cdf3SVladimir Sementsov-Ogievskiy      * sent us any more than one extent, nor should it have included
65986f8cdf3SVladimir Sementsov-Ogievskiy      * status beyond our request in that extent. However, it's easy
66086f8cdf3SVladimir Sementsov-Ogievskiy      * enough to ignore the server's noncompliance without killing the
66186f8cdf3SVladimir Sementsov-Ogievskiy      * connection; just ignore trailing extents, and clamp things to
66286f8cdf3SVladimir Sementsov-Ogievskiy      * the length of our request.
66386f8cdf3SVladimir Sementsov-Ogievskiy      */
66486f8cdf3SVladimir Sementsov-Ogievskiy     if (chunk->length > sizeof(context_id) + sizeof(*extent)) {
66586f8cdf3SVladimir Sementsov-Ogievskiy         trace_nbd_parse_blockstatus_compliance("more than one extent");
66686f8cdf3SVladimir Sementsov-Ogievskiy     }
66786f8cdf3SVladimir Sementsov-Ogievskiy     if (extent->length > orig_length) {
66886f8cdf3SVladimir Sementsov-Ogievskiy         extent->length = orig_length;
66986f8cdf3SVladimir Sementsov-Ogievskiy         trace_nbd_parse_blockstatus_compliance("extent length too large");
67086f8cdf3SVladimir Sementsov-Ogievskiy     }
67186f8cdf3SVladimir Sementsov-Ogievskiy 
672dbc7b014SEric Blake     /*
673dbc7b014SEric Blake      * HACK: if we are using x-dirty-bitmaps to access
674dbc7b014SEric Blake      * qemu:allocation-depth, treat all depths > 2 the same as 2,
675dbc7b014SEric Blake      * since nbd_client_co_block_status is only expecting the low two
676dbc7b014SEric Blake      * bits to be set.
677dbc7b014SEric Blake      */
678dbc7b014SEric Blake     if (s->alloc_depth && extent->flags > 2) {
679dbc7b014SEric Blake         extent->flags = 2;
680dbc7b014SEric Blake     }
681dbc7b014SEric Blake 
68286f8cdf3SVladimir Sementsov-Ogievskiy     return 0;
68386f8cdf3SVladimir Sementsov-Ogievskiy }
68486f8cdf3SVladimir Sementsov-Ogievskiy 
68586f8cdf3SVladimir Sementsov-Ogievskiy /*
68686f8cdf3SVladimir Sementsov-Ogievskiy  * nbd_parse_error_payload
68786f8cdf3SVladimir Sementsov-Ogievskiy  * on success @errp contains message describing nbd error reply
68886f8cdf3SVladimir Sementsov-Ogievskiy  */
68986f8cdf3SVladimir Sementsov-Ogievskiy static int nbd_parse_error_payload(NBDStructuredReplyChunk *chunk,
69086f8cdf3SVladimir Sementsov-Ogievskiy                                    uint8_t *payload, int *request_ret,
69186f8cdf3SVladimir Sementsov-Ogievskiy                                    Error **errp)
69286f8cdf3SVladimir Sementsov-Ogievskiy {
69386f8cdf3SVladimir Sementsov-Ogievskiy     uint32_t error;
69486f8cdf3SVladimir Sementsov-Ogievskiy     uint16_t message_size;
69586f8cdf3SVladimir Sementsov-Ogievskiy 
69686f8cdf3SVladimir Sementsov-Ogievskiy     assert(chunk->type & (1 << 15));
69786f8cdf3SVladimir Sementsov-Ogievskiy 
69886f8cdf3SVladimir Sementsov-Ogievskiy     if (chunk->length < sizeof(error) + sizeof(message_size)) {
69986f8cdf3SVladimir Sementsov-Ogievskiy         error_setg(errp,
70086f8cdf3SVladimir Sementsov-Ogievskiy                    "Protocol error: invalid payload for structured error");
70186f8cdf3SVladimir Sementsov-Ogievskiy         return -EINVAL;
70286f8cdf3SVladimir Sementsov-Ogievskiy     }
70386f8cdf3SVladimir Sementsov-Ogievskiy 
70486f8cdf3SVladimir Sementsov-Ogievskiy     error = nbd_errno_to_system_errno(payload_advance32(&payload));
70586f8cdf3SVladimir Sementsov-Ogievskiy     if (error == 0) {
70686f8cdf3SVladimir Sementsov-Ogievskiy         error_setg(errp, "Protocol error: server sent structured error chunk "
70786f8cdf3SVladimir Sementsov-Ogievskiy                          "with error = 0");
70886f8cdf3SVladimir Sementsov-Ogievskiy         return -EINVAL;
70986f8cdf3SVladimir Sementsov-Ogievskiy     }
71086f8cdf3SVladimir Sementsov-Ogievskiy 
71186f8cdf3SVladimir Sementsov-Ogievskiy     *request_ret = -error;
71286f8cdf3SVladimir Sementsov-Ogievskiy     message_size = payload_advance16(&payload);
71386f8cdf3SVladimir Sementsov-Ogievskiy 
71486f8cdf3SVladimir Sementsov-Ogievskiy     if (message_size > chunk->length - sizeof(error) - sizeof(message_size)) {
71586f8cdf3SVladimir Sementsov-Ogievskiy         error_setg(errp, "Protocol error: server sent structured error chunk "
71686f8cdf3SVladimir Sementsov-Ogievskiy                          "with incorrect message size");
71786f8cdf3SVladimir Sementsov-Ogievskiy         return -EINVAL;
71886f8cdf3SVladimir Sementsov-Ogievskiy     }
71986f8cdf3SVladimir Sementsov-Ogievskiy 
72086f8cdf3SVladimir Sementsov-Ogievskiy     /* TODO: Add a trace point to mention the server complaint */
72186f8cdf3SVladimir Sementsov-Ogievskiy 
72286f8cdf3SVladimir Sementsov-Ogievskiy     /* TODO handle ERROR_OFFSET */
72386f8cdf3SVladimir Sementsov-Ogievskiy 
72486f8cdf3SVladimir Sementsov-Ogievskiy     return 0;
72586f8cdf3SVladimir Sementsov-Ogievskiy }
72686f8cdf3SVladimir Sementsov-Ogievskiy 
7270c43c6fcSPaolo Bonzini static int coroutine_fn
7280c43c6fcSPaolo Bonzini nbd_co_receive_offset_data_payload(BDRVNBDState *s, uint64_t orig_offset,
72986f8cdf3SVladimir Sementsov-Ogievskiy                                    QEMUIOVector *qiov, Error **errp)
73086f8cdf3SVladimir Sementsov-Ogievskiy {
73186f8cdf3SVladimir Sementsov-Ogievskiy     QEMUIOVector sub_qiov;
73286f8cdf3SVladimir Sementsov-Ogievskiy     uint64_t offset;
73386f8cdf3SVladimir Sementsov-Ogievskiy     size_t data_size;
73486f8cdf3SVladimir Sementsov-Ogievskiy     int ret;
73586f8cdf3SVladimir Sementsov-Ogievskiy     NBDStructuredReplyChunk *chunk = &s->reply.structured;
73686f8cdf3SVladimir Sementsov-Ogievskiy 
73786f8cdf3SVladimir Sementsov-Ogievskiy     assert(nbd_reply_is_structured(&s->reply));
73886f8cdf3SVladimir Sementsov-Ogievskiy 
73986f8cdf3SVladimir Sementsov-Ogievskiy     /* The NBD spec requires at least one byte of payload */
74086f8cdf3SVladimir Sementsov-Ogievskiy     if (chunk->length <= sizeof(offset)) {
74186f8cdf3SVladimir Sementsov-Ogievskiy         error_setg(errp, "Protocol error: invalid payload for "
74286f8cdf3SVladimir Sementsov-Ogievskiy                          "NBD_REPLY_TYPE_OFFSET_DATA");
74386f8cdf3SVladimir Sementsov-Ogievskiy         return -EINVAL;
74486f8cdf3SVladimir Sementsov-Ogievskiy     }
74586f8cdf3SVladimir Sementsov-Ogievskiy 
74686f8cdf3SVladimir Sementsov-Ogievskiy     if (nbd_read64(s->ioc, &offset, "OFFSET_DATA offset", errp) < 0) {
74786f8cdf3SVladimir Sementsov-Ogievskiy         return -EIO;
74886f8cdf3SVladimir Sementsov-Ogievskiy     }
74986f8cdf3SVladimir Sementsov-Ogievskiy 
75086f8cdf3SVladimir Sementsov-Ogievskiy     data_size = chunk->length - sizeof(offset);
75186f8cdf3SVladimir Sementsov-Ogievskiy     assert(data_size);
75286f8cdf3SVladimir Sementsov-Ogievskiy     if (offset < orig_offset || data_size > qiov->size ||
75386f8cdf3SVladimir Sementsov-Ogievskiy         offset > orig_offset + qiov->size - data_size) {
75486f8cdf3SVladimir Sementsov-Ogievskiy         error_setg(errp, "Protocol error: server sent chunk exceeding requested"
75586f8cdf3SVladimir Sementsov-Ogievskiy                          " region");
75686f8cdf3SVladimir Sementsov-Ogievskiy         return -EINVAL;
75786f8cdf3SVladimir Sementsov-Ogievskiy     }
75886f8cdf3SVladimir Sementsov-Ogievskiy     if (s->info.min_block && !QEMU_IS_ALIGNED(data_size, s->info.min_block)) {
75986f8cdf3SVladimir Sementsov-Ogievskiy         trace_nbd_structured_read_compliance("data");
76086f8cdf3SVladimir Sementsov-Ogievskiy     }
76186f8cdf3SVladimir Sementsov-Ogievskiy 
76286f8cdf3SVladimir Sementsov-Ogievskiy     qemu_iovec_init(&sub_qiov, qiov->niov);
76386f8cdf3SVladimir Sementsov-Ogievskiy     qemu_iovec_concat(&sub_qiov, qiov, offset - orig_offset, data_size);
76486f8cdf3SVladimir Sementsov-Ogievskiy     ret = qio_channel_readv_all(s->ioc, sub_qiov.iov, sub_qiov.niov, errp);
76586f8cdf3SVladimir Sementsov-Ogievskiy     qemu_iovec_destroy(&sub_qiov);
76686f8cdf3SVladimir Sementsov-Ogievskiy 
76786f8cdf3SVladimir Sementsov-Ogievskiy     return ret < 0 ? -EIO : 0;
76886f8cdf3SVladimir Sementsov-Ogievskiy }
76986f8cdf3SVladimir Sementsov-Ogievskiy 
77086f8cdf3SVladimir Sementsov-Ogievskiy #define NBD_MAX_MALLOC_PAYLOAD 1000
77186f8cdf3SVladimir Sementsov-Ogievskiy static coroutine_fn int nbd_co_receive_structured_payload(
772611ae1d7SVladimir Sementsov-Ogievskiy         BDRVNBDState *s, void **payload, Error **errp)
77386f8cdf3SVladimir Sementsov-Ogievskiy {
77486f8cdf3SVladimir Sementsov-Ogievskiy     int ret;
77586f8cdf3SVladimir Sementsov-Ogievskiy     uint32_t len;
77686f8cdf3SVladimir Sementsov-Ogievskiy 
77786f8cdf3SVladimir Sementsov-Ogievskiy     assert(nbd_reply_is_structured(&s->reply));
77886f8cdf3SVladimir Sementsov-Ogievskiy 
77986f8cdf3SVladimir Sementsov-Ogievskiy     len = s->reply.structured.length;
78086f8cdf3SVladimir Sementsov-Ogievskiy 
78186f8cdf3SVladimir Sementsov-Ogievskiy     if (len == 0) {
78286f8cdf3SVladimir Sementsov-Ogievskiy         return 0;
78386f8cdf3SVladimir Sementsov-Ogievskiy     }
78486f8cdf3SVladimir Sementsov-Ogievskiy 
78586f8cdf3SVladimir Sementsov-Ogievskiy     if (payload == NULL) {
78686f8cdf3SVladimir Sementsov-Ogievskiy         error_setg(errp, "Unexpected structured payload");
78786f8cdf3SVladimir Sementsov-Ogievskiy         return -EINVAL;
78886f8cdf3SVladimir Sementsov-Ogievskiy     }
78986f8cdf3SVladimir Sementsov-Ogievskiy 
79086f8cdf3SVladimir Sementsov-Ogievskiy     if (len > NBD_MAX_MALLOC_PAYLOAD) {
79186f8cdf3SVladimir Sementsov-Ogievskiy         error_setg(errp, "Payload too large");
79286f8cdf3SVladimir Sementsov-Ogievskiy         return -EINVAL;
79386f8cdf3SVladimir Sementsov-Ogievskiy     }
79486f8cdf3SVladimir Sementsov-Ogievskiy 
79586f8cdf3SVladimir Sementsov-Ogievskiy     *payload = g_new(char, len);
79686f8cdf3SVladimir Sementsov-Ogievskiy     ret = nbd_read(s->ioc, *payload, len, "structured payload", errp);
79786f8cdf3SVladimir Sementsov-Ogievskiy     if (ret < 0) {
79886f8cdf3SVladimir Sementsov-Ogievskiy         g_free(*payload);
79986f8cdf3SVladimir Sementsov-Ogievskiy         *payload = NULL;
80086f8cdf3SVladimir Sementsov-Ogievskiy         return ret;
80186f8cdf3SVladimir Sementsov-Ogievskiy     }
80286f8cdf3SVladimir Sementsov-Ogievskiy 
80386f8cdf3SVladimir Sementsov-Ogievskiy     return 0;
80486f8cdf3SVladimir Sementsov-Ogievskiy }
80586f8cdf3SVladimir Sementsov-Ogievskiy 
80686f8cdf3SVladimir Sementsov-Ogievskiy /*
80786f8cdf3SVladimir Sementsov-Ogievskiy  * nbd_co_do_receive_one_chunk
80886f8cdf3SVladimir Sementsov-Ogievskiy  * for simple reply:
80986f8cdf3SVladimir Sementsov-Ogievskiy  *   set request_ret to received reply error
81086f8cdf3SVladimir Sementsov-Ogievskiy  *   if qiov is not NULL: read payload to @qiov
81186f8cdf3SVladimir Sementsov-Ogievskiy  * for structured reply chunk:
81286f8cdf3SVladimir Sementsov-Ogievskiy  *   if error chunk: read payload, set @request_ret, do not set @payload
81386f8cdf3SVladimir Sementsov-Ogievskiy  *   else if offset_data chunk: read payload data to @qiov, do not set @payload
81486f8cdf3SVladimir Sementsov-Ogievskiy  *   else: read payload to @payload
81586f8cdf3SVladimir Sementsov-Ogievskiy  *
81686f8cdf3SVladimir Sementsov-Ogievskiy  * If function fails, @errp contains corresponding error message, and the
81786f8cdf3SVladimir Sementsov-Ogievskiy  * connection with the server is suspect.  If it returns 0, then the
81886f8cdf3SVladimir Sementsov-Ogievskiy  * transaction succeeded (although @request_ret may be a negative errno
81986f8cdf3SVladimir Sementsov-Ogievskiy  * corresponding to the server's error reply), and errp is unchanged.
82086f8cdf3SVladimir Sementsov-Ogievskiy  */
82186f8cdf3SVladimir Sementsov-Ogievskiy static coroutine_fn int nbd_co_do_receive_one_chunk(
822611ae1d7SVladimir Sementsov-Ogievskiy         BDRVNBDState *s, uint64_t handle, bool only_structured,
82386f8cdf3SVladimir Sementsov-Ogievskiy         int *request_ret, QEMUIOVector *qiov, void **payload, Error **errp)
82486f8cdf3SVladimir Sementsov-Ogievskiy {
82586f8cdf3SVladimir Sementsov-Ogievskiy     int ret;
82686f8cdf3SVladimir Sementsov-Ogievskiy     int i = HANDLE_TO_INDEX(s, handle);
82786f8cdf3SVladimir Sementsov-Ogievskiy     void *local_payload = NULL;
82886f8cdf3SVladimir Sementsov-Ogievskiy     NBDStructuredReplyChunk *chunk;
82986f8cdf3SVladimir Sementsov-Ogievskiy 
83086f8cdf3SVladimir Sementsov-Ogievskiy     if (payload) {
83186f8cdf3SVladimir Sementsov-Ogievskiy         *payload = NULL;
83286f8cdf3SVladimir Sementsov-Ogievskiy     }
83386f8cdf3SVladimir Sementsov-Ogievskiy     *request_ret = 0;
83486f8cdf3SVladimir Sementsov-Ogievskiy 
835172f5f1aSPaolo Bonzini     ret = nbd_receive_replies(s, handle);
836172f5f1aSPaolo Bonzini     if (ret < 0) {
83786f8cdf3SVladimir Sementsov-Ogievskiy         error_setg(errp, "Connection closed");
83886f8cdf3SVladimir Sementsov-Ogievskiy         return -EIO;
83986f8cdf3SVladimir Sementsov-Ogievskiy     }
84086f8cdf3SVladimir Sementsov-Ogievskiy     assert(s->ioc);
84186f8cdf3SVladimir Sementsov-Ogievskiy 
84286f8cdf3SVladimir Sementsov-Ogievskiy     assert(s->reply.handle == handle);
84386f8cdf3SVladimir Sementsov-Ogievskiy 
84486f8cdf3SVladimir Sementsov-Ogievskiy     if (nbd_reply_is_simple(&s->reply)) {
84586f8cdf3SVladimir Sementsov-Ogievskiy         if (only_structured) {
84686f8cdf3SVladimir Sementsov-Ogievskiy             error_setg(errp, "Protocol error: simple reply when structured "
84786f8cdf3SVladimir Sementsov-Ogievskiy                              "reply chunk was expected");
84886f8cdf3SVladimir Sementsov-Ogievskiy             return -EINVAL;
84986f8cdf3SVladimir Sementsov-Ogievskiy         }
85086f8cdf3SVladimir Sementsov-Ogievskiy 
85186f8cdf3SVladimir Sementsov-Ogievskiy         *request_ret = -nbd_errno_to_system_errno(s->reply.simple.error);
85286f8cdf3SVladimir Sementsov-Ogievskiy         if (*request_ret < 0 || !qiov) {
85386f8cdf3SVladimir Sementsov-Ogievskiy             return 0;
85486f8cdf3SVladimir Sementsov-Ogievskiy         }
85586f8cdf3SVladimir Sementsov-Ogievskiy 
85686f8cdf3SVladimir Sementsov-Ogievskiy         return qio_channel_readv_all(s->ioc, qiov->iov, qiov->niov,
85786f8cdf3SVladimir Sementsov-Ogievskiy                                      errp) < 0 ? -EIO : 0;
85886f8cdf3SVladimir Sementsov-Ogievskiy     }
85986f8cdf3SVladimir Sementsov-Ogievskiy 
86086f8cdf3SVladimir Sementsov-Ogievskiy     /* handle structured reply chunk */
86186f8cdf3SVladimir Sementsov-Ogievskiy     assert(s->info.structured_reply);
86286f8cdf3SVladimir Sementsov-Ogievskiy     chunk = &s->reply.structured;
86386f8cdf3SVladimir Sementsov-Ogievskiy 
86486f8cdf3SVladimir Sementsov-Ogievskiy     if (chunk->type == NBD_REPLY_TYPE_NONE) {
86586f8cdf3SVladimir Sementsov-Ogievskiy         if (!(chunk->flags & NBD_REPLY_FLAG_DONE)) {
86686f8cdf3SVladimir Sementsov-Ogievskiy             error_setg(errp, "Protocol error: NBD_REPLY_TYPE_NONE chunk without"
86786f8cdf3SVladimir Sementsov-Ogievskiy                        " NBD_REPLY_FLAG_DONE flag set");
86886f8cdf3SVladimir Sementsov-Ogievskiy             return -EINVAL;
86986f8cdf3SVladimir Sementsov-Ogievskiy         }
87086f8cdf3SVladimir Sementsov-Ogievskiy         if (chunk->length) {
87186f8cdf3SVladimir Sementsov-Ogievskiy             error_setg(errp, "Protocol error: NBD_REPLY_TYPE_NONE chunk with"
87286f8cdf3SVladimir Sementsov-Ogievskiy                        " nonzero length");
87386f8cdf3SVladimir Sementsov-Ogievskiy             return -EINVAL;
87486f8cdf3SVladimir Sementsov-Ogievskiy         }
87586f8cdf3SVladimir Sementsov-Ogievskiy         return 0;
87686f8cdf3SVladimir Sementsov-Ogievskiy     }
87786f8cdf3SVladimir Sementsov-Ogievskiy 
87886f8cdf3SVladimir Sementsov-Ogievskiy     if (chunk->type == NBD_REPLY_TYPE_OFFSET_DATA) {
87986f8cdf3SVladimir Sementsov-Ogievskiy         if (!qiov) {
88086f8cdf3SVladimir Sementsov-Ogievskiy             error_setg(errp, "Unexpected NBD_REPLY_TYPE_OFFSET_DATA chunk");
88186f8cdf3SVladimir Sementsov-Ogievskiy             return -EINVAL;
88286f8cdf3SVladimir Sementsov-Ogievskiy         }
88386f8cdf3SVladimir Sementsov-Ogievskiy 
88486f8cdf3SVladimir Sementsov-Ogievskiy         return nbd_co_receive_offset_data_payload(s, s->requests[i].offset,
88586f8cdf3SVladimir Sementsov-Ogievskiy                                                   qiov, errp);
88686f8cdf3SVladimir Sementsov-Ogievskiy     }
88786f8cdf3SVladimir Sementsov-Ogievskiy 
88886f8cdf3SVladimir Sementsov-Ogievskiy     if (nbd_reply_type_is_error(chunk->type)) {
88986f8cdf3SVladimir Sementsov-Ogievskiy         payload = &local_payload;
89086f8cdf3SVladimir Sementsov-Ogievskiy     }
89186f8cdf3SVladimir Sementsov-Ogievskiy 
89286f8cdf3SVladimir Sementsov-Ogievskiy     ret = nbd_co_receive_structured_payload(s, payload, errp);
89386f8cdf3SVladimir Sementsov-Ogievskiy     if (ret < 0) {
89486f8cdf3SVladimir Sementsov-Ogievskiy         return ret;
89586f8cdf3SVladimir Sementsov-Ogievskiy     }
89686f8cdf3SVladimir Sementsov-Ogievskiy 
89786f8cdf3SVladimir Sementsov-Ogievskiy     if (nbd_reply_type_is_error(chunk->type)) {
89886f8cdf3SVladimir Sementsov-Ogievskiy         ret = nbd_parse_error_payload(chunk, local_payload, request_ret, errp);
89986f8cdf3SVladimir Sementsov-Ogievskiy         g_free(local_payload);
90086f8cdf3SVladimir Sementsov-Ogievskiy         return ret;
90186f8cdf3SVladimir Sementsov-Ogievskiy     }
90286f8cdf3SVladimir Sementsov-Ogievskiy 
90386f8cdf3SVladimir Sementsov-Ogievskiy     return 0;
90486f8cdf3SVladimir Sementsov-Ogievskiy }
90586f8cdf3SVladimir Sementsov-Ogievskiy 
90686f8cdf3SVladimir Sementsov-Ogievskiy /*
90786f8cdf3SVladimir Sementsov-Ogievskiy  * nbd_co_receive_one_chunk
90886f8cdf3SVladimir Sementsov-Ogievskiy  * Read reply, wake up connection_co and set s->quit if needed.
90986f8cdf3SVladimir Sementsov-Ogievskiy  * Return value is a fatal error code or normal nbd reply error code
91086f8cdf3SVladimir Sementsov-Ogievskiy  */
91186f8cdf3SVladimir Sementsov-Ogievskiy static coroutine_fn int nbd_co_receive_one_chunk(
912611ae1d7SVladimir Sementsov-Ogievskiy         BDRVNBDState *s, uint64_t handle, bool only_structured,
91386f8cdf3SVladimir Sementsov-Ogievskiy         int *request_ret, QEMUIOVector *qiov, NBDReply *reply, void **payload,
91486f8cdf3SVladimir Sementsov-Ogievskiy         Error **errp)
91586f8cdf3SVladimir Sementsov-Ogievskiy {
91686f8cdf3SVladimir Sementsov-Ogievskiy     int ret = nbd_co_do_receive_one_chunk(s, handle, only_structured,
91786f8cdf3SVladimir Sementsov-Ogievskiy                                           request_ret, qiov, payload, errp);
91886f8cdf3SVladimir Sementsov-Ogievskiy 
91986f8cdf3SVladimir Sementsov-Ogievskiy     if (ret < 0) {
9205cf42b1cSEric Blake         memset(reply, 0, sizeof(*reply));
921a34b1e5eSVladimir Sementsov-Ogievskiy         nbd_channel_error(s, ret);
92286f8cdf3SVladimir Sementsov-Ogievskiy     } else {
92386f8cdf3SVladimir Sementsov-Ogievskiy         /* For assert at loop start in nbd_connection_entry */
92486f8cdf3SVladimir Sementsov-Ogievskiy         *reply = s->reply;
92586f8cdf3SVladimir Sementsov-Ogievskiy     }
926f7651539SVladimir Sementsov-Ogievskiy     s->reply.handle = 0;
92786f8cdf3SVladimir Sementsov-Ogievskiy 
9284ddb5d2fSVladimir Sementsov-Ogievskiy     nbd_recv_coroutines_wake(s, false);
92986f8cdf3SVladimir Sementsov-Ogievskiy 
93086f8cdf3SVladimir Sementsov-Ogievskiy     return ret;
93186f8cdf3SVladimir Sementsov-Ogievskiy }
93286f8cdf3SVladimir Sementsov-Ogievskiy 
93386f8cdf3SVladimir Sementsov-Ogievskiy typedef struct NBDReplyChunkIter {
93486f8cdf3SVladimir Sementsov-Ogievskiy     int ret;
93586f8cdf3SVladimir Sementsov-Ogievskiy     int request_ret;
93686f8cdf3SVladimir Sementsov-Ogievskiy     Error *err;
93786f8cdf3SVladimir Sementsov-Ogievskiy     bool done, only_structured;
93886f8cdf3SVladimir Sementsov-Ogievskiy } NBDReplyChunkIter;
93986f8cdf3SVladimir Sementsov-Ogievskiy 
94086f8cdf3SVladimir Sementsov-Ogievskiy static void nbd_iter_channel_error(NBDReplyChunkIter *iter,
94186f8cdf3SVladimir Sementsov-Ogievskiy                                    int ret, Error **local_err)
94286f8cdf3SVladimir Sementsov-Ogievskiy {
943d9366135SVladimir Sementsov-Ogievskiy     assert(local_err && *local_err);
94486f8cdf3SVladimir Sementsov-Ogievskiy     assert(ret < 0);
94586f8cdf3SVladimir Sementsov-Ogievskiy 
94686f8cdf3SVladimir Sementsov-Ogievskiy     if (!iter->ret) {
94786f8cdf3SVladimir Sementsov-Ogievskiy         iter->ret = ret;
94886f8cdf3SVladimir Sementsov-Ogievskiy         error_propagate(&iter->err, *local_err);
94986f8cdf3SVladimir Sementsov-Ogievskiy     } else {
95086f8cdf3SVladimir Sementsov-Ogievskiy         error_free(*local_err);
95186f8cdf3SVladimir Sementsov-Ogievskiy     }
95286f8cdf3SVladimir Sementsov-Ogievskiy 
95386f8cdf3SVladimir Sementsov-Ogievskiy     *local_err = NULL;
95486f8cdf3SVladimir Sementsov-Ogievskiy }
95586f8cdf3SVladimir Sementsov-Ogievskiy 
95686f8cdf3SVladimir Sementsov-Ogievskiy static void nbd_iter_request_error(NBDReplyChunkIter *iter, int ret)
95786f8cdf3SVladimir Sementsov-Ogievskiy {
95886f8cdf3SVladimir Sementsov-Ogievskiy     assert(ret < 0);
95986f8cdf3SVladimir Sementsov-Ogievskiy 
96086f8cdf3SVladimir Sementsov-Ogievskiy     if (!iter->request_ret) {
96186f8cdf3SVladimir Sementsov-Ogievskiy         iter->request_ret = ret;
96286f8cdf3SVladimir Sementsov-Ogievskiy     }
96386f8cdf3SVladimir Sementsov-Ogievskiy }
96486f8cdf3SVladimir Sementsov-Ogievskiy 
96586f8cdf3SVladimir Sementsov-Ogievskiy /*
96686f8cdf3SVladimir Sementsov-Ogievskiy  * NBD_FOREACH_REPLY_CHUNK
96786f8cdf3SVladimir Sementsov-Ogievskiy  * The pointer stored in @payload requires g_free() to free it.
96886f8cdf3SVladimir Sementsov-Ogievskiy  */
96986f8cdf3SVladimir Sementsov-Ogievskiy #define NBD_FOREACH_REPLY_CHUNK(s, iter, handle, structured, \
97086f8cdf3SVladimir Sementsov-Ogievskiy                                 qiov, reply, payload) \
97186f8cdf3SVladimir Sementsov-Ogievskiy     for (iter = (NBDReplyChunkIter) { .only_structured = structured }; \
97286f8cdf3SVladimir Sementsov-Ogievskiy          nbd_reply_chunk_iter_receive(s, &iter, handle, qiov, reply, payload);)
97386f8cdf3SVladimir Sementsov-Ogievskiy 
97486f8cdf3SVladimir Sementsov-Ogievskiy /*
97586f8cdf3SVladimir Sementsov-Ogievskiy  * nbd_reply_chunk_iter_receive
97686f8cdf3SVladimir Sementsov-Ogievskiy  * The pointer stored in @payload requires g_free() to free it.
97786f8cdf3SVladimir Sementsov-Ogievskiy  */
978611ae1d7SVladimir Sementsov-Ogievskiy static bool nbd_reply_chunk_iter_receive(BDRVNBDState *s,
97986f8cdf3SVladimir Sementsov-Ogievskiy                                          NBDReplyChunkIter *iter,
98086f8cdf3SVladimir Sementsov-Ogievskiy                                          uint64_t handle,
98186f8cdf3SVladimir Sementsov-Ogievskiy                                          QEMUIOVector *qiov, NBDReply *reply,
98286f8cdf3SVladimir Sementsov-Ogievskiy                                          void **payload)
98386f8cdf3SVladimir Sementsov-Ogievskiy {
98486f8cdf3SVladimir Sementsov-Ogievskiy     int ret, request_ret;
98586f8cdf3SVladimir Sementsov-Ogievskiy     NBDReply local_reply;
98686f8cdf3SVladimir Sementsov-Ogievskiy     NBDStructuredReplyChunk *chunk;
98786f8cdf3SVladimir Sementsov-Ogievskiy     Error *local_err = NULL;
98886f8cdf3SVladimir Sementsov-Ogievskiy 
98986f8cdf3SVladimir Sementsov-Ogievskiy     if (iter->done) {
99086f8cdf3SVladimir Sementsov-Ogievskiy         /* Previous iteration was last. */
99186f8cdf3SVladimir Sementsov-Ogievskiy         goto break_loop;
99286f8cdf3SVladimir Sementsov-Ogievskiy     }
99386f8cdf3SVladimir Sementsov-Ogievskiy 
99486f8cdf3SVladimir Sementsov-Ogievskiy     if (reply == NULL) {
99586f8cdf3SVladimir Sementsov-Ogievskiy         reply = &local_reply;
99686f8cdf3SVladimir Sementsov-Ogievskiy     }
99786f8cdf3SVladimir Sementsov-Ogievskiy 
99886f8cdf3SVladimir Sementsov-Ogievskiy     ret = nbd_co_receive_one_chunk(s, handle, iter->only_structured,
99986f8cdf3SVladimir Sementsov-Ogievskiy                                    &request_ret, qiov, reply, payload,
100086f8cdf3SVladimir Sementsov-Ogievskiy                                    &local_err);
100186f8cdf3SVladimir Sementsov-Ogievskiy     if (ret < 0) {
100286f8cdf3SVladimir Sementsov-Ogievskiy         nbd_iter_channel_error(iter, ret, &local_err);
100386f8cdf3SVladimir Sementsov-Ogievskiy     } else if (request_ret < 0) {
100486f8cdf3SVladimir Sementsov-Ogievskiy         nbd_iter_request_error(iter, request_ret);
100586f8cdf3SVladimir Sementsov-Ogievskiy     }
100686f8cdf3SVladimir Sementsov-Ogievskiy 
100786f8cdf3SVladimir Sementsov-Ogievskiy     /* Do not execute the body of NBD_FOREACH_REPLY_CHUNK for simple reply. */
1008172f5f1aSPaolo Bonzini     if (nbd_reply_is_simple(reply) || iter->ret < 0) {
100986f8cdf3SVladimir Sementsov-Ogievskiy         goto break_loop;
101086f8cdf3SVladimir Sementsov-Ogievskiy     }
101186f8cdf3SVladimir Sementsov-Ogievskiy 
101286f8cdf3SVladimir Sementsov-Ogievskiy     chunk = &reply->structured;
101386f8cdf3SVladimir Sementsov-Ogievskiy     iter->only_structured = true;
101486f8cdf3SVladimir Sementsov-Ogievskiy 
101586f8cdf3SVladimir Sementsov-Ogievskiy     if (chunk->type == NBD_REPLY_TYPE_NONE) {
101686f8cdf3SVladimir Sementsov-Ogievskiy         /* NBD_REPLY_FLAG_DONE is already checked in nbd_co_receive_one_chunk */
101786f8cdf3SVladimir Sementsov-Ogievskiy         assert(chunk->flags & NBD_REPLY_FLAG_DONE);
101886f8cdf3SVladimir Sementsov-Ogievskiy         goto break_loop;
101986f8cdf3SVladimir Sementsov-Ogievskiy     }
102086f8cdf3SVladimir Sementsov-Ogievskiy 
102186f8cdf3SVladimir Sementsov-Ogievskiy     if (chunk->flags & NBD_REPLY_FLAG_DONE) {
102286f8cdf3SVladimir Sementsov-Ogievskiy         /* This iteration is last. */
102386f8cdf3SVladimir Sementsov-Ogievskiy         iter->done = true;
102486f8cdf3SVladimir Sementsov-Ogievskiy     }
102586f8cdf3SVladimir Sementsov-Ogievskiy 
102686f8cdf3SVladimir Sementsov-Ogievskiy     /* Execute the loop body */
102786f8cdf3SVladimir Sementsov-Ogievskiy     return true;
102886f8cdf3SVladimir Sementsov-Ogievskiy 
102986f8cdf3SVladimir Sementsov-Ogievskiy break_loop:
1030ee19d953SPaolo Bonzini     qemu_mutex_lock(&s->requests_lock);
103186f8cdf3SVladimir Sementsov-Ogievskiy     s->requests[HANDLE_TO_INDEX(s, handle)].coroutine = NULL;
103286f8cdf3SVladimir Sementsov-Ogievskiy     s->in_flight--;
103386f8cdf3SVladimir Sementsov-Ogievskiy     qemu_co_queue_next(&s->free_sema);
1034ee19d953SPaolo Bonzini     qemu_mutex_unlock(&s->requests_lock);
103586f8cdf3SVladimir Sementsov-Ogievskiy 
103686f8cdf3SVladimir Sementsov-Ogievskiy     return false;
103786f8cdf3SVladimir Sementsov-Ogievskiy }
103886f8cdf3SVladimir Sementsov-Ogievskiy 
10390c43c6fcSPaolo Bonzini static int coroutine_fn nbd_co_receive_return_code(BDRVNBDState *s, uint64_t handle,
104086f8cdf3SVladimir Sementsov-Ogievskiy                                                    int *request_ret, Error **errp)
104186f8cdf3SVladimir Sementsov-Ogievskiy {
104286f8cdf3SVladimir Sementsov-Ogievskiy     NBDReplyChunkIter iter;
104386f8cdf3SVladimir Sementsov-Ogievskiy 
104486f8cdf3SVladimir Sementsov-Ogievskiy     NBD_FOREACH_REPLY_CHUNK(s, iter, handle, false, NULL, NULL, NULL) {
104586f8cdf3SVladimir Sementsov-Ogievskiy         /* nbd_reply_chunk_iter_receive does all the work */
104686f8cdf3SVladimir Sementsov-Ogievskiy     }
104786f8cdf3SVladimir Sementsov-Ogievskiy 
104886f8cdf3SVladimir Sementsov-Ogievskiy     error_propagate(errp, iter.err);
104986f8cdf3SVladimir Sementsov-Ogievskiy     *request_ret = iter.request_ret;
105086f8cdf3SVladimir Sementsov-Ogievskiy     return iter.ret;
105186f8cdf3SVladimir Sementsov-Ogievskiy }
105286f8cdf3SVladimir Sementsov-Ogievskiy 
10530c43c6fcSPaolo Bonzini static int coroutine_fn nbd_co_receive_cmdread_reply(BDRVNBDState *s, uint64_t handle,
105486f8cdf3SVladimir Sementsov-Ogievskiy                                                      uint64_t offset, QEMUIOVector *qiov,
105586f8cdf3SVladimir Sementsov-Ogievskiy                                                      int *request_ret, Error **errp)
105686f8cdf3SVladimir Sementsov-Ogievskiy {
105786f8cdf3SVladimir Sementsov-Ogievskiy     NBDReplyChunkIter iter;
105886f8cdf3SVladimir Sementsov-Ogievskiy     NBDReply reply;
105986f8cdf3SVladimir Sementsov-Ogievskiy     void *payload = NULL;
106086f8cdf3SVladimir Sementsov-Ogievskiy     Error *local_err = NULL;
106186f8cdf3SVladimir Sementsov-Ogievskiy 
106286f8cdf3SVladimir Sementsov-Ogievskiy     NBD_FOREACH_REPLY_CHUNK(s, iter, handle, s->info.structured_reply,
106386f8cdf3SVladimir Sementsov-Ogievskiy                             qiov, &reply, &payload)
106486f8cdf3SVladimir Sementsov-Ogievskiy     {
106586f8cdf3SVladimir Sementsov-Ogievskiy         int ret;
106686f8cdf3SVladimir Sementsov-Ogievskiy         NBDStructuredReplyChunk *chunk = &reply.structured;
106786f8cdf3SVladimir Sementsov-Ogievskiy 
106886f8cdf3SVladimir Sementsov-Ogievskiy         assert(nbd_reply_is_structured(&reply));
106986f8cdf3SVladimir Sementsov-Ogievskiy 
107086f8cdf3SVladimir Sementsov-Ogievskiy         switch (chunk->type) {
107186f8cdf3SVladimir Sementsov-Ogievskiy         case NBD_REPLY_TYPE_OFFSET_DATA:
107286f8cdf3SVladimir Sementsov-Ogievskiy             /*
107386f8cdf3SVladimir Sementsov-Ogievskiy              * special cased in nbd_co_receive_one_chunk, data is already
107486f8cdf3SVladimir Sementsov-Ogievskiy              * in qiov
107586f8cdf3SVladimir Sementsov-Ogievskiy              */
107686f8cdf3SVladimir Sementsov-Ogievskiy             break;
107786f8cdf3SVladimir Sementsov-Ogievskiy         case NBD_REPLY_TYPE_OFFSET_HOLE:
107886f8cdf3SVladimir Sementsov-Ogievskiy             ret = nbd_parse_offset_hole_payload(s, &reply.structured, payload,
107986f8cdf3SVladimir Sementsov-Ogievskiy                                                 offset, qiov, &local_err);
108086f8cdf3SVladimir Sementsov-Ogievskiy             if (ret < 0) {
1081a34b1e5eSVladimir Sementsov-Ogievskiy                 nbd_channel_error(s, ret);
108286f8cdf3SVladimir Sementsov-Ogievskiy                 nbd_iter_channel_error(&iter, ret, &local_err);
108386f8cdf3SVladimir Sementsov-Ogievskiy             }
108486f8cdf3SVladimir Sementsov-Ogievskiy             break;
108586f8cdf3SVladimir Sementsov-Ogievskiy         default:
108686f8cdf3SVladimir Sementsov-Ogievskiy             if (!nbd_reply_type_is_error(chunk->type)) {
108786f8cdf3SVladimir Sementsov-Ogievskiy                 /* not allowed reply type */
1088a34b1e5eSVladimir Sementsov-Ogievskiy                 nbd_channel_error(s, -EINVAL);
108986f8cdf3SVladimir Sementsov-Ogievskiy                 error_setg(&local_err,
109086f8cdf3SVladimir Sementsov-Ogievskiy                            "Unexpected reply type: %d (%s) for CMD_READ",
109186f8cdf3SVladimir Sementsov-Ogievskiy                            chunk->type, nbd_reply_type_lookup(chunk->type));
109286f8cdf3SVladimir Sementsov-Ogievskiy                 nbd_iter_channel_error(&iter, -EINVAL, &local_err);
109386f8cdf3SVladimir Sementsov-Ogievskiy             }
109486f8cdf3SVladimir Sementsov-Ogievskiy         }
109586f8cdf3SVladimir Sementsov-Ogievskiy 
109686f8cdf3SVladimir Sementsov-Ogievskiy         g_free(payload);
109786f8cdf3SVladimir Sementsov-Ogievskiy         payload = NULL;
109886f8cdf3SVladimir Sementsov-Ogievskiy     }
109986f8cdf3SVladimir Sementsov-Ogievskiy 
110086f8cdf3SVladimir Sementsov-Ogievskiy     error_propagate(errp, iter.err);
110186f8cdf3SVladimir Sementsov-Ogievskiy     *request_ret = iter.request_ret;
110286f8cdf3SVladimir Sementsov-Ogievskiy     return iter.ret;
110386f8cdf3SVladimir Sementsov-Ogievskiy }
110486f8cdf3SVladimir Sementsov-Ogievskiy 
11050c43c6fcSPaolo Bonzini static int coroutine_fn nbd_co_receive_blockstatus_reply(BDRVNBDState *s,
110686f8cdf3SVladimir Sementsov-Ogievskiy                                                          uint64_t handle, uint64_t length,
110786f8cdf3SVladimir Sementsov-Ogievskiy                                                          NBDExtent *extent,
110886f8cdf3SVladimir Sementsov-Ogievskiy                                                          int *request_ret, Error **errp)
110986f8cdf3SVladimir Sementsov-Ogievskiy {
111086f8cdf3SVladimir Sementsov-Ogievskiy     NBDReplyChunkIter iter;
111186f8cdf3SVladimir Sementsov-Ogievskiy     NBDReply reply;
111286f8cdf3SVladimir Sementsov-Ogievskiy     void *payload = NULL;
111386f8cdf3SVladimir Sementsov-Ogievskiy     Error *local_err = NULL;
111486f8cdf3SVladimir Sementsov-Ogievskiy     bool received = false;
111586f8cdf3SVladimir Sementsov-Ogievskiy 
111686f8cdf3SVladimir Sementsov-Ogievskiy     assert(!extent->length);
111786f8cdf3SVladimir Sementsov-Ogievskiy     NBD_FOREACH_REPLY_CHUNK(s, iter, handle, false, NULL, &reply, &payload) {
111886f8cdf3SVladimir Sementsov-Ogievskiy         int ret;
111986f8cdf3SVladimir Sementsov-Ogievskiy         NBDStructuredReplyChunk *chunk = &reply.structured;
112086f8cdf3SVladimir Sementsov-Ogievskiy 
112186f8cdf3SVladimir Sementsov-Ogievskiy         assert(nbd_reply_is_structured(&reply));
112286f8cdf3SVladimir Sementsov-Ogievskiy 
112386f8cdf3SVladimir Sementsov-Ogievskiy         switch (chunk->type) {
112486f8cdf3SVladimir Sementsov-Ogievskiy         case NBD_REPLY_TYPE_BLOCK_STATUS:
112586f8cdf3SVladimir Sementsov-Ogievskiy             if (received) {
1126a34b1e5eSVladimir Sementsov-Ogievskiy                 nbd_channel_error(s, -EINVAL);
112786f8cdf3SVladimir Sementsov-Ogievskiy                 error_setg(&local_err, "Several BLOCK_STATUS chunks in reply");
112886f8cdf3SVladimir Sementsov-Ogievskiy                 nbd_iter_channel_error(&iter, -EINVAL, &local_err);
112986f8cdf3SVladimir Sementsov-Ogievskiy             }
113086f8cdf3SVladimir Sementsov-Ogievskiy             received = true;
113186f8cdf3SVladimir Sementsov-Ogievskiy 
113286f8cdf3SVladimir Sementsov-Ogievskiy             ret = nbd_parse_blockstatus_payload(s, &reply.structured,
113386f8cdf3SVladimir Sementsov-Ogievskiy                                                 payload, length, extent,
113486f8cdf3SVladimir Sementsov-Ogievskiy                                                 &local_err);
113586f8cdf3SVladimir Sementsov-Ogievskiy             if (ret < 0) {
1136a34b1e5eSVladimir Sementsov-Ogievskiy                 nbd_channel_error(s, ret);
113786f8cdf3SVladimir Sementsov-Ogievskiy                 nbd_iter_channel_error(&iter, ret, &local_err);
113886f8cdf3SVladimir Sementsov-Ogievskiy             }
113986f8cdf3SVladimir Sementsov-Ogievskiy             break;
114086f8cdf3SVladimir Sementsov-Ogievskiy         default:
114186f8cdf3SVladimir Sementsov-Ogievskiy             if (!nbd_reply_type_is_error(chunk->type)) {
1142a34b1e5eSVladimir Sementsov-Ogievskiy                 nbd_channel_error(s, -EINVAL);
114386f8cdf3SVladimir Sementsov-Ogievskiy                 error_setg(&local_err,
114486f8cdf3SVladimir Sementsov-Ogievskiy                            "Unexpected reply type: %d (%s) "
114586f8cdf3SVladimir Sementsov-Ogievskiy                            "for CMD_BLOCK_STATUS",
114686f8cdf3SVladimir Sementsov-Ogievskiy                            chunk->type, nbd_reply_type_lookup(chunk->type));
114786f8cdf3SVladimir Sementsov-Ogievskiy                 nbd_iter_channel_error(&iter, -EINVAL, &local_err);
114886f8cdf3SVladimir Sementsov-Ogievskiy             }
114986f8cdf3SVladimir Sementsov-Ogievskiy         }
115086f8cdf3SVladimir Sementsov-Ogievskiy 
115186f8cdf3SVladimir Sementsov-Ogievskiy         g_free(payload);
115286f8cdf3SVladimir Sementsov-Ogievskiy         payload = NULL;
115386f8cdf3SVladimir Sementsov-Ogievskiy     }
115486f8cdf3SVladimir Sementsov-Ogievskiy 
115586f8cdf3SVladimir Sementsov-Ogievskiy     if (!extent->length && !iter.request_ret) {
115686f8cdf3SVladimir Sementsov-Ogievskiy         error_setg(&local_err, "Server did not reply with any status extents");
115786f8cdf3SVladimir Sementsov-Ogievskiy         nbd_iter_channel_error(&iter, -EIO, &local_err);
115886f8cdf3SVladimir Sementsov-Ogievskiy     }
115986f8cdf3SVladimir Sementsov-Ogievskiy 
116086f8cdf3SVladimir Sementsov-Ogievskiy     error_propagate(errp, iter.err);
116186f8cdf3SVladimir Sementsov-Ogievskiy     *request_ret = iter.request_ret;
116286f8cdf3SVladimir Sementsov-Ogievskiy     return iter.ret;
116386f8cdf3SVladimir Sementsov-Ogievskiy }
116486f8cdf3SVladimir Sementsov-Ogievskiy 
11650c43c6fcSPaolo Bonzini static int coroutine_fn nbd_co_request(BlockDriverState *bs, NBDRequest *request,
116686f8cdf3SVladimir Sementsov-Ogievskiy                                        QEMUIOVector *write_qiov)
116786f8cdf3SVladimir Sementsov-Ogievskiy {
116886f8cdf3SVladimir Sementsov-Ogievskiy     int ret, request_ret;
116986f8cdf3SVladimir Sementsov-Ogievskiy     Error *local_err = NULL;
1170611ae1d7SVladimir Sementsov-Ogievskiy     BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
117186f8cdf3SVladimir Sementsov-Ogievskiy 
117286f8cdf3SVladimir Sementsov-Ogievskiy     assert(request->type != NBD_CMD_READ);
117386f8cdf3SVladimir Sementsov-Ogievskiy     if (write_qiov) {
117486f8cdf3SVladimir Sementsov-Ogievskiy         assert(request->type == NBD_CMD_WRITE);
117586f8cdf3SVladimir Sementsov-Ogievskiy         assert(request->len == iov_size(write_qiov->iov, write_qiov->niov));
117686f8cdf3SVladimir Sementsov-Ogievskiy     } else {
117786f8cdf3SVladimir Sementsov-Ogievskiy         assert(request->type != NBD_CMD_WRITE);
117886f8cdf3SVladimir Sementsov-Ogievskiy     }
1179f7651539SVladimir Sementsov-Ogievskiy 
1180f7651539SVladimir Sementsov-Ogievskiy     do {
118186f8cdf3SVladimir Sementsov-Ogievskiy         ret = nbd_co_send_request(bs, request, write_qiov);
118286f8cdf3SVladimir Sementsov-Ogievskiy         if (ret < 0) {
1183f7651539SVladimir Sementsov-Ogievskiy             continue;
118486f8cdf3SVladimir Sementsov-Ogievskiy         }
118586f8cdf3SVladimir Sementsov-Ogievskiy 
1186611ae1d7SVladimir Sementsov-Ogievskiy         ret = nbd_co_receive_return_code(s, request->handle,
118786f8cdf3SVladimir Sementsov-Ogievskiy                                          &request_ret, &local_err);
118886f8cdf3SVladimir Sementsov-Ogievskiy         if (local_err) {
1189f7651539SVladimir Sementsov-Ogievskiy             trace_nbd_co_request_fail(request->from, request->len,
1190f7651539SVladimir Sementsov-Ogievskiy                                       request->handle, request->flags,
1191f7651539SVladimir Sementsov-Ogievskiy                                       request->type,
119286f8cdf3SVladimir Sementsov-Ogievskiy                                       nbd_cmd_lookup(request->type),
119386f8cdf3SVladimir Sementsov-Ogievskiy                                       ret, error_get_pretty(local_err));
119486f8cdf3SVladimir Sementsov-Ogievskiy             error_free(local_err);
1195f7651539SVladimir Sementsov-Ogievskiy             local_err = NULL;
119686f8cdf3SVladimir Sementsov-Ogievskiy         }
1197*8d45185cSPaolo Bonzini     } while (ret < 0 && nbd_client_will_reconnect(s));
1198f7651539SVladimir Sementsov-Ogievskiy 
119986f8cdf3SVladimir Sementsov-Ogievskiy     return ret ? ret : request_ret;
120086f8cdf3SVladimir Sementsov-Ogievskiy }
120186f8cdf3SVladimir Sementsov-Ogievskiy 
12020c43c6fcSPaolo Bonzini static int coroutine_fn nbd_client_co_preadv(BlockDriverState *bs, int64_t offset,
1203f7ef38ddSVladimir Sementsov-Ogievskiy                                              int64_t bytes, QEMUIOVector *qiov,
1204f7ef38ddSVladimir Sementsov-Ogievskiy                                              BdrvRequestFlags flags)
120586f8cdf3SVladimir Sementsov-Ogievskiy {
120686f8cdf3SVladimir Sementsov-Ogievskiy     int ret, request_ret;
120786f8cdf3SVladimir Sementsov-Ogievskiy     Error *local_err = NULL;
1208611ae1d7SVladimir Sementsov-Ogievskiy     BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
120986f8cdf3SVladimir Sementsov-Ogievskiy     NBDRequest request = {
121086f8cdf3SVladimir Sementsov-Ogievskiy         .type = NBD_CMD_READ,
121186f8cdf3SVladimir Sementsov-Ogievskiy         .from = offset,
121286f8cdf3SVladimir Sementsov-Ogievskiy         .len = bytes,
121386f8cdf3SVladimir Sementsov-Ogievskiy     };
121486f8cdf3SVladimir Sementsov-Ogievskiy 
121586f8cdf3SVladimir Sementsov-Ogievskiy     assert(bytes <= NBD_MAX_BUFFER_SIZE);
121686f8cdf3SVladimir Sementsov-Ogievskiy     assert(!flags);
121786f8cdf3SVladimir Sementsov-Ogievskiy 
121886f8cdf3SVladimir Sementsov-Ogievskiy     if (!bytes) {
121986f8cdf3SVladimir Sementsov-Ogievskiy         return 0;
122086f8cdf3SVladimir Sementsov-Ogievskiy     }
122186f8cdf3SVladimir Sementsov-Ogievskiy     /*
122286f8cdf3SVladimir Sementsov-Ogievskiy      * Work around the fact that the block layer doesn't do
122386f8cdf3SVladimir Sementsov-Ogievskiy      * byte-accurate sizing yet - if the read exceeds the server's
122486f8cdf3SVladimir Sementsov-Ogievskiy      * advertised size because the block layer rounded size up, then
122586f8cdf3SVladimir Sementsov-Ogievskiy      * truncate the request to the server and tail-pad with zero.
122686f8cdf3SVladimir Sementsov-Ogievskiy      */
1227611ae1d7SVladimir Sementsov-Ogievskiy     if (offset >= s->info.size) {
122886f8cdf3SVladimir Sementsov-Ogievskiy         assert(bytes < BDRV_SECTOR_SIZE);
122986f8cdf3SVladimir Sementsov-Ogievskiy         qemu_iovec_memset(qiov, 0, 0, bytes);
123086f8cdf3SVladimir Sementsov-Ogievskiy         return 0;
123186f8cdf3SVladimir Sementsov-Ogievskiy     }
1232611ae1d7SVladimir Sementsov-Ogievskiy     if (offset + bytes > s->info.size) {
1233611ae1d7SVladimir Sementsov-Ogievskiy         uint64_t slop = offset + bytes - s->info.size;
123486f8cdf3SVladimir Sementsov-Ogievskiy 
123586f8cdf3SVladimir Sementsov-Ogievskiy         assert(slop < BDRV_SECTOR_SIZE);
123686f8cdf3SVladimir Sementsov-Ogievskiy         qemu_iovec_memset(qiov, bytes - slop, 0, slop);
123786f8cdf3SVladimir Sementsov-Ogievskiy         request.len -= slop;
123886f8cdf3SVladimir Sementsov-Ogievskiy     }
123986f8cdf3SVladimir Sementsov-Ogievskiy 
1240f7651539SVladimir Sementsov-Ogievskiy     do {
124186f8cdf3SVladimir Sementsov-Ogievskiy         ret = nbd_co_send_request(bs, &request, NULL);
124286f8cdf3SVladimir Sementsov-Ogievskiy         if (ret < 0) {
1243f7651539SVladimir Sementsov-Ogievskiy             continue;
124486f8cdf3SVladimir Sementsov-Ogievskiy         }
124586f8cdf3SVladimir Sementsov-Ogievskiy 
1246611ae1d7SVladimir Sementsov-Ogievskiy         ret = nbd_co_receive_cmdread_reply(s, request.handle, offset, qiov,
124786f8cdf3SVladimir Sementsov-Ogievskiy                                            &request_ret, &local_err);
124886f8cdf3SVladimir Sementsov-Ogievskiy         if (local_err) {
124986f8cdf3SVladimir Sementsov-Ogievskiy             trace_nbd_co_request_fail(request.from, request.len, request.handle,
125086f8cdf3SVladimir Sementsov-Ogievskiy                                       request.flags, request.type,
125186f8cdf3SVladimir Sementsov-Ogievskiy                                       nbd_cmd_lookup(request.type),
125286f8cdf3SVladimir Sementsov-Ogievskiy                                       ret, error_get_pretty(local_err));
125386f8cdf3SVladimir Sementsov-Ogievskiy             error_free(local_err);
1254f7651539SVladimir Sementsov-Ogievskiy             local_err = NULL;
125586f8cdf3SVladimir Sementsov-Ogievskiy         }
1256*8d45185cSPaolo Bonzini     } while (ret < 0 && nbd_client_will_reconnect(s));
1257f7651539SVladimir Sementsov-Ogievskiy 
125886f8cdf3SVladimir Sementsov-Ogievskiy     return ret ? ret : request_ret;
125986f8cdf3SVladimir Sementsov-Ogievskiy }
126086f8cdf3SVladimir Sementsov-Ogievskiy 
12610c43c6fcSPaolo Bonzini static int coroutine_fn nbd_client_co_pwritev(BlockDriverState *bs, int64_t offset,
1262e75abedaSVladimir Sementsov-Ogievskiy                                               int64_t bytes, QEMUIOVector *qiov,
1263e75abedaSVladimir Sementsov-Ogievskiy                                               BdrvRequestFlags flags)
126486f8cdf3SVladimir Sementsov-Ogievskiy {
1265611ae1d7SVladimir Sementsov-Ogievskiy     BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
126686f8cdf3SVladimir Sementsov-Ogievskiy     NBDRequest request = {
126786f8cdf3SVladimir Sementsov-Ogievskiy         .type = NBD_CMD_WRITE,
126886f8cdf3SVladimir Sementsov-Ogievskiy         .from = offset,
126986f8cdf3SVladimir Sementsov-Ogievskiy         .len = bytes,
127086f8cdf3SVladimir Sementsov-Ogievskiy     };
127186f8cdf3SVladimir Sementsov-Ogievskiy 
1272611ae1d7SVladimir Sementsov-Ogievskiy     assert(!(s->info.flags & NBD_FLAG_READ_ONLY));
127386f8cdf3SVladimir Sementsov-Ogievskiy     if (flags & BDRV_REQ_FUA) {
1274611ae1d7SVladimir Sementsov-Ogievskiy         assert(s->info.flags & NBD_FLAG_SEND_FUA);
127586f8cdf3SVladimir Sementsov-Ogievskiy         request.flags |= NBD_CMD_FLAG_FUA;
127686f8cdf3SVladimir Sementsov-Ogievskiy     }
127786f8cdf3SVladimir Sementsov-Ogievskiy 
127886f8cdf3SVladimir Sementsov-Ogievskiy     assert(bytes <= NBD_MAX_BUFFER_SIZE);
127986f8cdf3SVladimir Sementsov-Ogievskiy 
128086f8cdf3SVladimir Sementsov-Ogievskiy     if (!bytes) {
128186f8cdf3SVladimir Sementsov-Ogievskiy         return 0;
128286f8cdf3SVladimir Sementsov-Ogievskiy     }
128386f8cdf3SVladimir Sementsov-Ogievskiy     return nbd_co_request(bs, &request, qiov);
128486f8cdf3SVladimir Sementsov-Ogievskiy }
128586f8cdf3SVladimir Sementsov-Ogievskiy 
12860c43c6fcSPaolo Bonzini static int coroutine_fn nbd_client_co_pwrite_zeroes(BlockDriverState *bs, int64_t offset,
1287f34b2bcfSVladimir Sementsov-Ogievskiy                                                     int64_t bytes, BdrvRequestFlags flags)
128886f8cdf3SVladimir Sementsov-Ogievskiy {
1289611ae1d7SVladimir Sementsov-Ogievskiy     BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
129086f8cdf3SVladimir Sementsov-Ogievskiy     NBDRequest request = {
129186f8cdf3SVladimir Sementsov-Ogievskiy         .type = NBD_CMD_WRITE_ZEROES,
129286f8cdf3SVladimir Sementsov-Ogievskiy         .from = offset,
1293f34b2bcfSVladimir Sementsov-Ogievskiy         .len = bytes,  /* .len is uint32_t actually */
129486f8cdf3SVladimir Sementsov-Ogievskiy     };
129586f8cdf3SVladimir Sementsov-Ogievskiy 
1296f34b2bcfSVladimir Sementsov-Ogievskiy     assert(bytes <= UINT32_MAX); /* rely on max_pwrite_zeroes */
1297f34b2bcfSVladimir Sementsov-Ogievskiy 
1298611ae1d7SVladimir Sementsov-Ogievskiy     assert(!(s->info.flags & NBD_FLAG_READ_ONLY));
1299611ae1d7SVladimir Sementsov-Ogievskiy     if (!(s->info.flags & NBD_FLAG_SEND_WRITE_ZEROES)) {
130086f8cdf3SVladimir Sementsov-Ogievskiy         return -ENOTSUP;
130186f8cdf3SVladimir Sementsov-Ogievskiy     }
130286f8cdf3SVladimir Sementsov-Ogievskiy 
130386f8cdf3SVladimir Sementsov-Ogievskiy     if (flags & BDRV_REQ_FUA) {
1304611ae1d7SVladimir Sementsov-Ogievskiy         assert(s->info.flags & NBD_FLAG_SEND_FUA);
130586f8cdf3SVladimir Sementsov-Ogievskiy         request.flags |= NBD_CMD_FLAG_FUA;
130686f8cdf3SVladimir Sementsov-Ogievskiy     }
130786f8cdf3SVladimir Sementsov-Ogievskiy     if (!(flags & BDRV_REQ_MAY_UNMAP)) {
130886f8cdf3SVladimir Sementsov-Ogievskiy         request.flags |= NBD_CMD_FLAG_NO_HOLE;
130986f8cdf3SVladimir Sementsov-Ogievskiy     }
1310f061656cSEric Blake     if (flags & BDRV_REQ_NO_FALLBACK) {
1311f061656cSEric Blake         assert(s->info.flags & NBD_FLAG_SEND_FAST_ZERO);
1312f061656cSEric Blake         request.flags |= NBD_CMD_FLAG_FAST_ZERO;
1313f061656cSEric Blake     }
131486f8cdf3SVladimir Sementsov-Ogievskiy 
131586f8cdf3SVladimir Sementsov-Ogievskiy     if (!bytes) {
131686f8cdf3SVladimir Sementsov-Ogievskiy         return 0;
131786f8cdf3SVladimir Sementsov-Ogievskiy     }
131886f8cdf3SVladimir Sementsov-Ogievskiy     return nbd_co_request(bs, &request, NULL);
131986f8cdf3SVladimir Sementsov-Ogievskiy }
132086f8cdf3SVladimir Sementsov-Ogievskiy 
13210c43c6fcSPaolo Bonzini static int coroutine_fn nbd_client_co_flush(BlockDriverState *bs)
132286f8cdf3SVladimir Sementsov-Ogievskiy {
1323611ae1d7SVladimir Sementsov-Ogievskiy     BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
132486f8cdf3SVladimir Sementsov-Ogievskiy     NBDRequest request = { .type = NBD_CMD_FLUSH };
132586f8cdf3SVladimir Sementsov-Ogievskiy 
1326611ae1d7SVladimir Sementsov-Ogievskiy     if (!(s->info.flags & NBD_FLAG_SEND_FLUSH)) {
132786f8cdf3SVladimir Sementsov-Ogievskiy         return 0;
132886f8cdf3SVladimir Sementsov-Ogievskiy     }
132986f8cdf3SVladimir Sementsov-Ogievskiy 
133086f8cdf3SVladimir Sementsov-Ogievskiy     request.from = 0;
133186f8cdf3SVladimir Sementsov-Ogievskiy     request.len = 0;
133286f8cdf3SVladimir Sementsov-Ogievskiy 
133386f8cdf3SVladimir Sementsov-Ogievskiy     return nbd_co_request(bs, &request, NULL);
133486f8cdf3SVladimir Sementsov-Ogievskiy }
133586f8cdf3SVladimir Sementsov-Ogievskiy 
13360c43c6fcSPaolo Bonzini static int coroutine_fn nbd_client_co_pdiscard(BlockDriverState *bs, int64_t offset,
13370c802287SVladimir Sementsov-Ogievskiy                                                int64_t bytes)
133886f8cdf3SVladimir Sementsov-Ogievskiy {
1339611ae1d7SVladimir Sementsov-Ogievskiy     BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
134086f8cdf3SVladimir Sementsov-Ogievskiy     NBDRequest request = {
134186f8cdf3SVladimir Sementsov-Ogievskiy         .type = NBD_CMD_TRIM,
134286f8cdf3SVladimir Sementsov-Ogievskiy         .from = offset,
13430c802287SVladimir Sementsov-Ogievskiy         .len = bytes, /* len is uint32_t */
134486f8cdf3SVladimir Sementsov-Ogievskiy     };
134586f8cdf3SVladimir Sementsov-Ogievskiy 
13460c802287SVladimir Sementsov-Ogievskiy     assert(bytes <= UINT32_MAX); /* rely on max_pdiscard */
13470c802287SVladimir Sementsov-Ogievskiy 
1348611ae1d7SVladimir Sementsov-Ogievskiy     assert(!(s->info.flags & NBD_FLAG_READ_ONLY));
1349611ae1d7SVladimir Sementsov-Ogievskiy     if (!(s->info.flags & NBD_FLAG_SEND_TRIM) || !bytes) {
135086f8cdf3SVladimir Sementsov-Ogievskiy         return 0;
135186f8cdf3SVladimir Sementsov-Ogievskiy     }
135286f8cdf3SVladimir Sementsov-Ogievskiy 
135386f8cdf3SVladimir Sementsov-Ogievskiy     return nbd_co_request(bs, &request, NULL);
135486f8cdf3SVladimir Sementsov-Ogievskiy }
135586f8cdf3SVladimir Sementsov-Ogievskiy 
135686f8cdf3SVladimir Sementsov-Ogievskiy static int coroutine_fn nbd_client_co_block_status(
135786f8cdf3SVladimir Sementsov-Ogievskiy         BlockDriverState *bs, bool want_zero, int64_t offset, int64_t bytes,
135886f8cdf3SVladimir Sementsov-Ogievskiy         int64_t *pnum, int64_t *map, BlockDriverState **file)
135986f8cdf3SVladimir Sementsov-Ogievskiy {
136086f8cdf3SVladimir Sementsov-Ogievskiy     int ret, request_ret;
136186f8cdf3SVladimir Sementsov-Ogievskiy     NBDExtent extent = { 0 };
1362611ae1d7SVladimir Sementsov-Ogievskiy     BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
136386f8cdf3SVladimir Sementsov-Ogievskiy     Error *local_err = NULL;
136486f8cdf3SVladimir Sementsov-Ogievskiy 
136586f8cdf3SVladimir Sementsov-Ogievskiy     NBDRequest request = {
136686f8cdf3SVladimir Sementsov-Ogievskiy         .type = NBD_CMD_BLOCK_STATUS,
136786f8cdf3SVladimir Sementsov-Ogievskiy         .from = offset,
13686bf792b4SVladimir Sementsov-Ogievskiy         .len = MIN(QEMU_ALIGN_DOWN(INT_MAX, bs->bl.request_alignment),
1369611ae1d7SVladimir Sementsov-Ogievskiy                    MIN(bytes, s->info.size - offset)),
137086f8cdf3SVladimir Sementsov-Ogievskiy         .flags = NBD_CMD_FLAG_REQ_ONE,
137186f8cdf3SVladimir Sementsov-Ogievskiy     };
137286f8cdf3SVladimir Sementsov-Ogievskiy 
1373611ae1d7SVladimir Sementsov-Ogievskiy     if (!s->info.base_allocation) {
137486f8cdf3SVladimir Sementsov-Ogievskiy         *pnum = bytes;
137586f8cdf3SVladimir Sementsov-Ogievskiy         *map = offset;
137686f8cdf3SVladimir Sementsov-Ogievskiy         *file = bs;
137786f8cdf3SVladimir Sementsov-Ogievskiy         return BDRV_BLOCK_DATA | BDRV_BLOCK_OFFSET_VALID;
137886f8cdf3SVladimir Sementsov-Ogievskiy     }
137986f8cdf3SVladimir Sementsov-Ogievskiy 
138086f8cdf3SVladimir Sementsov-Ogievskiy     /*
138186f8cdf3SVladimir Sementsov-Ogievskiy      * Work around the fact that the block layer doesn't do
138286f8cdf3SVladimir Sementsov-Ogievskiy      * byte-accurate sizing yet - if the status request exceeds the
138386f8cdf3SVladimir Sementsov-Ogievskiy      * server's advertised size because the block layer rounded size
138486f8cdf3SVladimir Sementsov-Ogievskiy      * up, we truncated the request to the server (above), or are
138586f8cdf3SVladimir Sementsov-Ogievskiy      * called on just the hole.
138686f8cdf3SVladimir Sementsov-Ogievskiy      */
1387611ae1d7SVladimir Sementsov-Ogievskiy     if (offset >= s->info.size) {
138886f8cdf3SVladimir Sementsov-Ogievskiy         *pnum = bytes;
138986f8cdf3SVladimir Sementsov-Ogievskiy         assert(bytes < BDRV_SECTOR_SIZE);
139086f8cdf3SVladimir Sementsov-Ogievskiy         /* Intentionally don't report offset_valid for the hole */
139186f8cdf3SVladimir Sementsov-Ogievskiy         return BDRV_BLOCK_ZERO;
139286f8cdf3SVladimir Sementsov-Ogievskiy     }
139386f8cdf3SVladimir Sementsov-Ogievskiy 
1394611ae1d7SVladimir Sementsov-Ogievskiy     if (s->info.min_block) {
1395611ae1d7SVladimir Sementsov-Ogievskiy         assert(QEMU_IS_ALIGNED(request.len, s->info.min_block));
139686f8cdf3SVladimir Sementsov-Ogievskiy     }
1397f7651539SVladimir Sementsov-Ogievskiy     do {
139886f8cdf3SVladimir Sementsov-Ogievskiy         ret = nbd_co_send_request(bs, &request, NULL);
139986f8cdf3SVladimir Sementsov-Ogievskiy         if (ret < 0) {
1400f7651539SVladimir Sementsov-Ogievskiy             continue;
140186f8cdf3SVladimir Sementsov-Ogievskiy         }
140286f8cdf3SVladimir Sementsov-Ogievskiy 
1403611ae1d7SVladimir Sementsov-Ogievskiy         ret = nbd_co_receive_blockstatus_reply(s, request.handle, bytes,
1404f7651539SVladimir Sementsov-Ogievskiy                                                &extent, &request_ret,
1405f7651539SVladimir Sementsov-Ogievskiy                                                &local_err);
140686f8cdf3SVladimir Sementsov-Ogievskiy         if (local_err) {
140786f8cdf3SVladimir Sementsov-Ogievskiy             trace_nbd_co_request_fail(request.from, request.len, request.handle,
140886f8cdf3SVladimir Sementsov-Ogievskiy                                       request.flags, request.type,
140986f8cdf3SVladimir Sementsov-Ogievskiy                                       nbd_cmd_lookup(request.type),
141086f8cdf3SVladimir Sementsov-Ogievskiy                                       ret, error_get_pretty(local_err));
141186f8cdf3SVladimir Sementsov-Ogievskiy             error_free(local_err);
1412f7651539SVladimir Sementsov-Ogievskiy             local_err = NULL;
141386f8cdf3SVladimir Sementsov-Ogievskiy         }
1414*8d45185cSPaolo Bonzini     } while (ret < 0 && nbd_client_will_reconnect(s));
1415f7651539SVladimir Sementsov-Ogievskiy 
141686f8cdf3SVladimir Sementsov-Ogievskiy     if (ret < 0 || request_ret < 0) {
141786f8cdf3SVladimir Sementsov-Ogievskiy         return ret ? ret : request_ret;
141886f8cdf3SVladimir Sementsov-Ogievskiy     }
141986f8cdf3SVladimir Sementsov-Ogievskiy 
142086f8cdf3SVladimir Sementsov-Ogievskiy     assert(extent.length);
142186f8cdf3SVladimir Sementsov-Ogievskiy     *pnum = extent.length;
142286f8cdf3SVladimir Sementsov-Ogievskiy     *map = offset;
142386f8cdf3SVladimir Sementsov-Ogievskiy     *file = bs;
142486f8cdf3SVladimir Sementsov-Ogievskiy     return (extent.flags & NBD_STATE_HOLE ? 0 : BDRV_BLOCK_DATA) |
142586f8cdf3SVladimir Sementsov-Ogievskiy         (extent.flags & NBD_STATE_ZERO ? BDRV_BLOCK_ZERO : 0) |
142686f8cdf3SVladimir Sementsov-Ogievskiy         BDRV_BLOCK_OFFSET_VALID;
142786f8cdf3SVladimir Sementsov-Ogievskiy }
142886f8cdf3SVladimir Sementsov-Ogievskiy 
1429e99754b4SMaxim Levitsky static int nbd_client_reopen_prepare(BDRVReopenState *state,
1430e99754b4SMaxim Levitsky                                      BlockReopenQueue *queue, Error **errp)
1431e99754b4SMaxim Levitsky {
1432e99754b4SMaxim Levitsky     BDRVNBDState *s = (BDRVNBDState *)state->bs->opaque;
1433e99754b4SMaxim Levitsky 
1434e99754b4SMaxim Levitsky     if ((state->flags & BDRV_O_RDWR) && (s->info.flags & NBD_FLAG_READ_ONLY)) {
1435e99754b4SMaxim Levitsky         error_setg(errp, "Can't reopen read-only NBD mount as read/write");
1436e99754b4SMaxim Levitsky         return -EACCES;
1437e99754b4SMaxim Levitsky     }
1438e99754b4SMaxim Levitsky     return 0;
1439e99754b4SMaxim Levitsky }
1440e99754b4SMaxim Levitsky 
1441fee091cdSLukas Straub static void nbd_yank(void *opaque)
1442fee091cdSLukas Straub {
1443fee091cdSLukas Straub     BlockDriverState *bs = opaque;
1444fee091cdSLukas Straub     BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
1445fee091cdSLukas Straub 
1446fee091cdSLukas Straub     qatomic_store_release(&s->state, NBD_CLIENT_QUIT);
144795a078eaSVladimir Sementsov-Ogievskiy     qio_channel_shutdown(QIO_CHANNEL(s->ioc), QIO_CHANNEL_SHUTDOWN_BOTH, NULL);
1448fee091cdSLukas Straub }
1449fee091cdSLukas Straub 
145086f8cdf3SVladimir Sementsov-Ogievskiy static void nbd_client_close(BlockDriverState *bs)
145186f8cdf3SVladimir Sementsov-Ogievskiy {
1452611ae1d7SVladimir Sementsov-Ogievskiy     BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
145386f8cdf3SVladimir Sementsov-Ogievskiy     NBDRequest request = { .type = NBD_CMD_DISC };
145486f8cdf3SVladimir Sementsov-Ogievskiy 
1455f7651539SVladimir Sementsov-Ogievskiy     if (s->ioc) {
1456611ae1d7SVladimir Sementsov-Ogievskiy         nbd_send_request(s->ioc, &request);
1457f7651539SVladimir Sementsov-Ogievskiy     }
145886f8cdf3SVladimir Sementsov-Ogievskiy 
145986f8cdf3SVladimir Sementsov-Ogievskiy     nbd_teardown_connection(bs);
146086f8cdf3SVladimir Sementsov-Ogievskiy }
146186f8cdf3SVladimir Sementsov-Ogievskiy 
146286f8cdf3SVladimir Sementsov-Ogievskiy 
14638f071c9dSVladimir Sementsov-Ogievskiy /*
14648f071c9dSVladimir Sementsov-Ogievskiy  * Parse nbd_open options
14658f071c9dSVladimir Sementsov-Ogievskiy  */
146686f8cdf3SVladimir Sementsov-Ogievskiy 
1467f53a1febSKevin Wolf static int nbd_parse_uri(const char *filename, QDict *options)
14681d7d2a9dSPaolo Bonzini {
14691d7d2a9dSPaolo Bonzini     URI *uri;
14701d7d2a9dSPaolo Bonzini     const char *p;
14711d7d2a9dSPaolo Bonzini     QueryParams *qp = NULL;
14721d7d2a9dSPaolo Bonzini     int ret = 0;
1473f53a1febSKevin Wolf     bool is_unix;
14741d7d2a9dSPaolo Bonzini 
14751d7d2a9dSPaolo Bonzini     uri = uri_parse(filename);
14761d7d2a9dSPaolo Bonzini     if (!uri) {
14771d7d2a9dSPaolo Bonzini         return -EINVAL;
14781d7d2a9dSPaolo Bonzini     }
14791d7d2a9dSPaolo Bonzini 
14801d7d2a9dSPaolo Bonzini     /* transport */
1481f69165a8SMax Reitz     if (!g_strcmp0(uri->scheme, "nbd")) {
1482f53a1febSKevin Wolf         is_unix = false;
1483f69165a8SMax Reitz     } else if (!g_strcmp0(uri->scheme, "nbd+tcp")) {
1484f53a1febSKevin Wolf         is_unix = false;
1485f69165a8SMax Reitz     } else if (!g_strcmp0(uri->scheme, "nbd+unix")) {
1486f53a1febSKevin Wolf         is_unix = true;
14871d7d2a9dSPaolo Bonzini     } else {
14881d7d2a9dSPaolo Bonzini         ret = -EINVAL;
14891d7d2a9dSPaolo Bonzini         goto out;
14901d7d2a9dSPaolo Bonzini     }
14911d7d2a9dSPaolo Bonzini 
14922485f22fSEric Blake     p = uri->path ? uri->path : "";
14932485f22fSEric Blake     if (p[0] == '/') {
14942485f22fSEric Blake         p++;
14952485f22fSEric Blake     }
14961d7d2a9dSPaolo Bonzini     if (p[0]) {
149746f5ac20SEric Blake         qdict_put_str(options, "export", p);
14981d7d2a9dSPaolo Bonzini     }
14991d7d2a9dSPaolo Bonzini 
15001d7d2a9dSPaolo Bonzini     qp = query_params_parse(uri->query);
1501f53a1febSKevin Wolf     if (qp->n > 1 || (is_unix && !qp->n) || (!is_unix && qp->n)) {
15021d7d2a9dSPaolo Bonzini         ret = -EINVAL;
15031d7d2a9dSPaolo Bonzini         goto out;
15041d7d2a9dSPaolo Bonzini     }
15051d7d2a9dSPaolo Bonzini 
1506f53a1febSKevin Wolf     if (is_unix) {
15071d7d2a9dSPaolo Bonzini         /* nbd+unix:///export?socket=path */
15081d7d2a9dSPaolo Bonzini         if (uri->server || uri->port || strcmp(qp->p[0].name, "socket")) {
15091d7d2a9dSPaolo Bonzini             ret = -EINVAL;
15101d7d2a9dSPaolo Bonzini             goto out;
15111d7d2a9dSPaolo Bonzini         }
151246f5ac20SEric Blake         qdict_put_str(options, "server.type", "unix");
151346f5ac20SEric Blake         qdict_put_str(options, "server.path", qp->p[0].value);
15141d7d2a9dSPaolo Bonzini     } else {
151523307908SJán Tomko         QString *host;
1516f84d431bSMax Reitz         char *port_str;
1517f84d431bSMax Reitz 
1518bebbf7faSKevin Wolf         /* nbd[+tcp]://host[:port]/export */
15191d7d2a9dSPaolo Bonzini         if (!uri->server) {
15201d7d2a9dSPaolo Bonzini             ret = -EINVAL;
15211d7d2a9dSPaolo Bonzini             goto out;
15221d7d2a9dSPaolo Bonzini         }
1523f17c90beSKevin Wolf 
152423307908SJán Tomko         /* strip braces from literal IPv6 address */
152523307908SJán Tomko         if (uri->server[0] == '[') {
152623307908SJán Tomko             host = qstring_from_substr(uri->server, 1,
1527ba891d68SMarkus Armbruster                                        strlen(uri->server) - 1);
152823307908SJán Tomko         } else {
152923307908SJán Tomko             host = qstring_from_str(uri->server);
153023307908SJán Tomko         }
153123307908SJán Tomko 
153246f5ac20SEric Blake         qdict_put_str(options, "server.type", "inet");
15339445673eSMarkus Armbruster         qdict_put(options, "server.host", host);
1534f84d431bSMax Reitz 
1535f84d431bSMax Reitz         port_str = g_strdup_printf("%d", uri->port ?: NBD_DEFAULT_PORT);
153646f5ac20SEric Blake         qdict_put_str(options, "server.port", port_str);
1537f53a1febSKevin Wolf         g_free(port_str);
15381d7d2a9dSPaolo Bonzini     }
15391d7d2a9dSPaolo Bonzini 
15401d7d2a9dSPaolo Bonzini out:
15411d7d2a9dSPaolo Bonzini     if (qp) {
15421d7d2a9dSPaolo Bonzini         query_params_free(qp);
15431d7d2a9dSPaolo Bonzini     }
15441d7d2a9dSPaolo Bonzini     uri_free(uri);
15451d7d2a9dSPaolo Bonzini     return ret;
15461d7d2a9dSPaolo Bonzini }
15471d7d2a9dSPaolo Bonzini 
154848c38e0bSMax Reitz static bool nbd_has_filename_options_conflict(QDict *options, Error **errp)
154948c38e0bSMax Reitz {
155048c38e0bSMax Reitz     const QDictEntry *e;
155148c38e0bSMax Reitz 
155248c38e0bSMax Reitz     for (e = qdict_first(options); e; e = qdict_next(options, e)) {
155348c38e0bSMax Reitz         if (!strcmp(e->key, "host") ||
155448c38e0bSMax Reitz             !strcmp(e->key, "port") ||
155548c38e0bSMax Reitz             !strcmp(e->key, "path") ||
1556491d6c7cSMax Reitz             !strcmp(e->key, "export") ||
1557491d6c7cSMax Reitz             strstart(e->key, "server.", NULL))
155848c38e0bSMax Reitz         {
155948c38e0bSMax Reitz             error_setg(errp, "Option '%s' cannot be used with a file name",
156048c38e0bSMax Reitz                        e->key);
156148c38e0bSMax Reitz             return true;
156248c38e0bSMax Reitz         }
156348c38e0bSMax Reitz     }
156448c38e0bSMax Reitz 
156548c38e0bSMax Reitz     return false;
156648c38e0bSMax Reitz }
156748c38e0bSMax Reitz 
15686963a30dSKevin Wolf static void nbd_parse_filename(const char *filename, QDict *options,
15696963a30dSKevin Wolf                                Error **errp)
1570019d6b8fSAnthony Liguori {
1571df18c04eSEric Blake     g_autofree char *file = NULL;
157233897dc7SNick Thomas     char *export_name;
157333897dc7SNick Thomas     const char *host_spec;
1574019d6b8fSAnthony Liguori     const char *unixpath;
1575019d6b8fSAnthony Liguori 
157648c38e0bSMax Reitz     if (nbd_has_filename_options_conflict(options, errp)) {
1577681e7ad0SKevin Wolf         return;
1578681e7ad0SKevin Wolf     }
1579681e7ad0SKevin Wolf 
15801d7d2a9dSPaolo Bonzini     if (strstr(filename, "://")) {
15816963a30dSKevin Wolf         int ret = nbd_parse_uri(filename, options);
15826963a30dSKevin Wolf         if (ret < 0) {
15836963a30dSKevin Wolf             error_setg(errp, "No valid URL specified");
15846963a30dSKevin Wolf         }
15856963a30dSKevin Wolf         return;
15861d7d2a9dSPaolo Bonzini     }
15871d7d2a9dSPaolo Bonzini 
15887267c094SAnthony Liguori     file = g_strdup(filename);
15891d45f8b5SLaurent Vivier 
159033897dc7SNick Thomas     export_name = strstr(file, EN_OPTSTR);
159133897dc7SNick Thomas     if (export_name) {
159233897dc7SNick Thomas         if (export_name[strlen(EN_OPTSTR)] == 0) {
1593df18c04eSEric Blake             return;
15941d45f8b5SLaurent Vivier         }
159533897dc7SNick Thomas         export_name[0] = 0; /* truncate 'file' */
159633897dc7SNick Thomas         export_name += strlen(EN_OPTSTR);
1597f53a1febSKevin Wolf 
159846f5ac20SEric Blake         qdict_put_str(options, "export", export_name);
15991d45f8b5SLaurent Vivier     }
16001d45f8b5SLaurent Vivier 
160133897dc7SNick Thomas     /* extract the host_spec - fail if it's not nbd:... */
160233897dc7SNick Thomas     if (!strstart(file, "nbd:", &host_spec)) {
16036963a30dSKevin Wolf         error_setg(errp, "File name string for NBD must start with 'nbd:'");
1604df18c04eSEric Blake         return;
16051d45f8b5SLaurent Vivier     }
1606019d6b8fSAnthony Liguori 
1607f53a1febSKevin Wolf     if (!*host_spec) {
1608df18c04eSEric Blake         return;
1609f53a1febSKevin Wolf     }
1610f53a1febSKevin Wolf 
161133897dc7SNick Thomas     /* are we a UNIX or TCP socket? */
161233897dc7SNick Thomas     if (strstart(host_spec, "unix:", &unixpath)) {
161346f5ac20SEric Blake         qdict_put_str(options, "server.type", "unix");
161446f5ac20SEric Blake         qdict_put_str(options, "server.path", unixpath);
1615019d6b8fSAnthony Liguori     } else {
16160785bd7aSMarkus Armbruster         InetSocketAddress *addr = g_new(InetSocketAddress, 1);
1617f53a1febSKevin Wolf 
16180785bd7aSMarkus Armbruster         if (inet_parse(addr, host_spec, errp)) {
16190785bd7aSMarkus Armbruster             goto out_inet;
1620f17c90beSKevin Wolf         }
1621f53a1febSKevin Wolf 
162246f5ac20SEric Blake         qdict_put_str(options, "server.type", "inet");
162346f5ac20SEric Blake         qdict_put_str(options, "server.host", addr->host);
162446f5ac20SEric Blake         qdict_put_str(options, "server.port", addr->port);
16250785bd7aSMarkus Armbruster     out_inet:
1626f53a1febSKevin Wolf         qapi_free_InetSocketAddress(addr);
16271d45f8b5SLaurent Vivier     }
162833897dc7SNick Thomas }
1629f53a1febSKevin Wolf 
1630491d6c7cSMax Reitz static bool nbd_process_legacy_socket_options(QDict *output_options,
1631491d6c7cSMax Reitz                                               QemuOpts *legacy_opts,
1632491d6c7cSMax Reitz                                               Error **errp)
1633f53a1febSKevin Wolf {
1634491d6c7cSMax Reitz     const char *path = qemu_opt_get(legacy_opts, "path");
1635491d6c7cSMax Reitz     const char *host = qemu_opt_get(legacy_opts, "host");
1636491d6c7cSMax Reitz     const char *port = qemu_opt_get(legacy_opts, "port");
1637491d6c7cSMax Reitz     const QDictEntry *e;
1638f53a1febSKevin Wolf 
1639491d6c7cSMax Reitz     if (!path && !host && !port) {
1640491d6c7cSMax Reitz         return true;
1641491d6c7cSMax Reitz     }
164203504d05SMax Reitz 
1643491d6c7cSMax Reitz     for (e = qdict_first(output_options); e; e = qdict_next(output_options, e))
1644491d6c7cSMax Reitz     {
1645491d6c7cSMax Reitz         if (strstart(e->key, "server.", NULL)) {
1646491d6c7cSMax Reitz             error_setg(errp, "Cannot use 'server' and path/host/port at the "
1647491d6c7cSMax Reitz                        "same time");
1648491d6c7cSMax Reitz             return false;
1649491d6c7cSMax Reitz         }
1650491d6c7cSMax Reitz     }
1651491d6c7cSMax Reitz 
1652491d6c7cSMax Reitz     if (path && host) {
165382d73014SMax Reitz         error_setg(errp, "path and host may not be used at the same time");
1654491d6c7cSMax Reitz         return false;
1655491d6c7cSMax Reitz     } else if (path) {
1656491d6c7cSMax Reitz         if (port) {
1657442045cbSMax Reitz             error_setg(errp, "port may not be used without host");
1658491d6c7cSMax Reitz             return false;
1659442045cbSMax Reitz         }
1660019d6b8fSAnthony Liguori 
166146f5ac20SEric Blake         qdict_put_str(output_options, "server.type", "unix");
166246f5ac20SEric Blake         qdict_put_str(output_options, "server.path", path);
1663491d6c7cSMax Reitz     } else if (host) {
166446f5ac20SEric Blake         qdict_put_str(output_options, "server.type", "inet");
166546f5ac20SEric Blake         qdict_put_str(output_options, "server.host", host);
166646f5ac20SEric Blake         qdict_put_str(output_options, "server.port",
166746f5ac20SEric Blake                       port ?: stringify(NBD_DEFAULT_PORT));
16687a5ed437SDaniel P. Berrange     }
1669491d6c7cSMax Reitz 
1670491d6c7cSMax Reitz     return true;
1671491d6c7cSMax Reitz }
1672491d6c7cSMax Reitz 
167362cf396bSMarkus Armbruster static SocketAddress *nbd_config(BDRVNBDState *s, QDict *options,
16749445673eSMarkus Armbruster                                  Error **errp)
1675491d6c7cSMax Reitz {
167662cf396bSMarkus Armbruster     SocketAddress *saddr = NULL;
1677491d6c7cSMax Reitz     QDict *addr = NULL;
1678491d6c7cSMax Reitz     Visitor *iv = NULL;
1679491d6c7cSMax Reitz 
1680491d6c7cSMax Reitz     qdict_extract_subqdict(options, &addr, "server.");
1681491d6c7cSMax Reitz     if (!qdict_size(addr)) {
1682491d6c7cSMax Reitz         error_setg(errp, "NBD server address missing");
1683491d6c7cSMax Reitz         goto done;
1684491d6c7cSMax Reitz     }
1685491d6c7cSMax Reitz 
1686af91062eSMarkus Armbruster     iv = qobject_input_visitor_new_flat_confused(addr, errp);
1687af91062eSMarkus Armbruster     if (!iv) {
1688491d6c7cSMax Reitz         goto done;
1689491d6c7cSMax Reitz     }
1690491d6c7cSMax Reitz 
1691af175e85SMarkus Armbruster     if (!visit_type_SocketAddress(iv, NULL, &saddr, errp)) {
1692491d6c7cSMax Reitz         goto done;
1693f53a1febSKevin Wolf     }
1694f53a1febSKevin Wolf 
16956cc702beSVladimir Sementsov-Ogievskiy     if (socket_address_parse_named_fd(saddr, errp) < 0) {
16966cc702beSVladimir Sementsov-Ogievskiy         qapi_free_SocketAddress(saddr);
16976cc702beSVladimir Sementsov-Ogievskiy         saddr = NULL;
16986cc702beSVladimir Sementsov-Ogievskiy         goto done;
16996cc702beSVladimir Sementsov-Ogievskiy     }
17006cc702beSVladimir Sementsov-Ogievskiy 
1701491d6c7cSMax Reitz done:
1702cb3e7f08SMarc-André Lureau     qobject_unref(addr);
1703491d6c7cSMax Reitz     visit_free(iv);
17047a5ed437SDaniel P. Berrange     return saddr;
1705f53a1febSKevin Wolf }
1706f53a1febSKevin Wolf 
170775822a12SDaniel P. Berrange static QCryptoTLSCreds *nbd_get_tls_creds(const char *id, Error **errp)
170875822a12SDaniel P. Berrange {
170975822a12SDaniel P. Berrange     Object *obj;
171075822a12SDaniel P. Berrange     QCryptoTLSCreds *creds;
171175822a12SDaniel P. Berrange 
171275822a12SDaniel P. Berrange     obj = object_resolve_path_component(
171375822a12SDaniel P. Berrange         object_get_objects_root(), id);
171475822a12SDaniel P. Berrange     if (!obj) {
171575822a12SDaniel P. Berrange         error_setg(errp, "No TLS credentials with id '%s'",
171675822a12SDaniel P. Berrange                    id);
171775822a12SDaniel P. Berrange         return NULL;
171875822a12SDaniel P. Berrange     }
171975822a12SDaniel P. Berrange     creds = (QCryptoTLSCreds *)
172075822a12SDaniel P. Berrange         object_dynamic_cast(obj, TYPE_QCRYPTO_TLS_CREDS);
172175822a12SDaniel P. Berrange     if (!creds) {
172275822a12SDaniel P. Berrange         error_setg(errp, "Object with id '%s' is not TLS credentials",
172375822a12SDaniel P. Berrange                    id);
172475822a12SDaniel P. Berrange         return NULL;
172575822a12SDaniel P. Berrange     }
172675822a12SDaniel P. Berrange 
17277b3b6168SPhilippe Mathieu-Daudé     if (!qcrypto_tls_creds_check_endpoint(creds,
17287b3b6168SPhilippe Mathieu-Daudé                                           QCRYPTO_TLS_CREDS_ENDPOINT_CLIENT,
17297b3b6168SPhilippe Mathieu-Daudé                                           errp)) {
173075822a12SDaniel P. Berrange         return NULL;
173175822a12SDaniel P. Berrange     }
173275822a12SDaniel P. Berrange     object_ref(obj);
173375822a12SDaniel P. Berrange     return creds;
173475822a12SDaniel P. Berrange }
173575822a12SDaniel P. Berrange 
173675822a12SDaniel P. Berrange 
17377ccc44fdSMax Reitz static QemuOptsList nbd_runtime_opts = {
17387ccc44fdSMax Reitz     .name = "nbd",
17397ccc44fdSMax Reitz     .head = QTAILQ_HEAD_INITIALIZER(nbd_runtime_opts.head),
17407ccc44fdSMax Reitz     .desc = {
17417ccc44fdSMax Reitz         {
17427ccc44fdSMax Reitz             .name = "host",
17437ccc44fdSMax Reitz             .type = QEMU_OPT_STRING,
17447ccc44fdSMax Reitz             .help = "TCP host to connect to",
17457ccc44fdSMax Reitz         },
17467ccc44fdSMax Reitz         {
17477ccc44fdSMax Reitz             .name = "port",
17487ccc44fdSMax Reitz             .type = QEMU_OPT_STRING,
17497ccc44fdSMax Reitz             .help = "TCP port to connect to",
17507ccc44fdSMax Reitz         },
17517ccc44fdSMax Reitz         {
17527ccc44fdSMax Reitz             .name = "path",
17537ccc44fdSMax Reitz             .type = QEMU_OPT_STRING,
17547ccc44fdSMax Reitz             .help = "Unix socket path to connect to",
17557ccc44fdSMax Reitz         },
17567ccc44fdSMax Reitz         {
17577ccc44fdSMax Reitz             .name = "export",
17587ccc44fdSMax Reitz             .type = QEMU_OPT_STRING,
17597ccc44fdSMax Reitz             .help = "Name of the NBD export to open",
17607ccc44fdSMax Reitz         },
17617ccc44fdSMax Reitz         {
17627ccc44fdSMax Reitz             .name = "tls-creds",
17637ccc44fdSMax Reitz             .type = QEMU_OPT_STRING,
17647ccc44fdSMax Reitz             .help = "ID of the TLS credentials to use",
17657ccc44fdSMax Reitz         },
1766216ee365SEric Blake         {
1767a0cd6d29SDaniel P. Berrangé             .name = "tls-hostname",
1768a0cd6d29SDaniel P. Berrangé             .type = QEMU_OPT_STRING,
1769a0cd6d29SDaniel P. Berrangé             .help = "Override hostname for validating TLS x509 certificate",
1770a0cd6d29SDaniel P. Berrangé         },
1771a0cd6d29SDaniel P. Berrangé         {
1772216ee365SEric Blake             .name = "x-dirty-bitmap",
1773216ee365SEric Blake             .type = QEMU_OPT_STRING,
1774216ee365SEric Blake             .help = "experimental: expose named dirty bitmap in place of "
1775216ee365SEric Blake                     "block status",
1776216ee365SEric Blake         },
1777b172ae2eSVladimir Sementsov-Ogievskiy         {
1778b172ae2eSVladimir Sementsov-Ogievskiy             .name = "reconnect-delay",
1779b172ae2eSVladimir Sementsov-Ogievskiy             .type = QEMU_OPT_NUMBER,
1780b172ae2eSVladimir Sementsov-Ogievskiy             .help = "On an unexpected disconnect, the nbd client tries to "
1781b172ae2eSVladimir Sementsov-Ogievskiy                     "connect again until succeeding or encountering a serious "
1782b172ae2eSVladimir Sementsov-Ogievskiy                     "error.  During the first @reconnect-delay seconds, all "
1783b172ae2eSVladimir Sementsov-Ogievskiy                     "requests are paused and will be rerun on a successful "
1784b172ae2eSVladimir Sementsov-Ogievskiy                     "reconnect. After that time, any delayed requests and all "
1785b172ae2eSVladimir Sementsov-Ogievskiy                     "future requests before a successful reconnect will "
1786b172ae2eSVladimir Sementsov-Ogievskiy                     "immediately fail. Default 0",
1787b172ae2eSVladimir Sementsov-Ogievskiy         },
1788be16b8bfSVladimir Sementsov-Ogievskiy         {
1789be16b8bfSVladimir Sementsov-Ogievskiy             .name = "open-timeout",
1790be16b8bfSVladimir Sementsov-Ogievskiy             .type = QEMU_OPT_NUMBER,
1791be16b8bfSVladimir Sementsov-Ogievskiy             .help = "In seconds. If zero, the nbd driver tries the connection "
1792be16b8bfSVladimir Sementsov-Ogievskiy                     "only once, and fails to open if the connection fails. "
1793be16b8bfSVladimir Sementsov-Ogievskiy                     "If non-zero, the nbd driver will repeat connection "
1794be16b8bfSVladimir Sementsov-Ogievskiy                     "attempts until successful or until @open-timeout seconds "
1795be16b8bfSVladimir Sementsov-Ogievskiy                     "have elapsed. Default 0",
1796be16b8bfSVladimir Sementsov-Ogievskiy         },
1797c4365735SMurilo Opsfelder Araujo         { /* end of list */ }
17987ccc44fdSMax Reitz     },
17997ccc44fdSMax Reitz };
18007ccc44fdSMax Reitz 
18018f071c9dSVladimir Sementsov-Ogievskiy static int nbd_process_options(BlockDriverState *bs, QDict *options,
1802015a1036SMax Reitz                                Error **errp)
180333897dc7SNick Thomas {
180433897dc7SNick Thomas     BDRVNBDState *s = bs->opaque;
18058f071c9dSVladimir Sementsov-Ogievskiy     QemuOpts *opts;
180675822a12SDaniel P. Berrange     int ret = -EINVAL;
1807ae255e52SPaolo Bonzini 
18087ccc44fdSMax Reitz     opts = qemu_opts_create(&nbd_runtime_opts, NULL, 0, &error_abort);
1809af175e85SMarkus Armbruster     if (!qemu_opts_absorb_qdict(opts, options, errp)) {
18107ccc44fdSMax Reitz         goto error;
18117ccc44fdSMax Reitz     }
18127ccc44fdSMax Reitz 
181362cf396bSMarkus Armbruster     /* Translate @host, @port, and @path to a SocketAddress */
1814491d6c7cSMax Reitz     if (!nbd_process_legacy_socket_options(options, opts, errp)) {
181575822a12SDaniel P. Berrange         goto error;
181675822a12SDaniel P. Berrange     }
181775822a12SDaniel P. Berrange 
1818491d6c7cSMax Reitz     /* Pop the config into our state object. Exit if invalid. */
1819491d6c7cSMax Reitz     s->saddr = nbd_config(s, options, errp);
1820491d6c7cSMax Reitz     if (!s->saddr) {
1821491d6c7cSMax Reitz         goto error;
1822491d6c7cSMax Reitz     }
1823491d6c7cSMax Reitz 
1824491d6c7cSMax Reitz     s->export = g_strdup(qemu_opt_get(opts, "export"));
182593676c88SEric Blake     if (s->export && strlen(s->export) > NBD_MAX_STRING_SIZE) {
182693676c88SEric Blake         error_setg(errp, "export name too long to send to server");
182793676c88SEric Blake         goto error;
182893676c88SEric Blake     }
1829491d6c7cSMax Reitz 
183003504d05SMax Reitz     s->tlscredsid = g_strdup(qemu_opt_get(opts, "tls-creds"));
183103504d05SMax Reitz     if (s->tlscredsid) {
18328f071c9dSVladimir Sementsov-Ogievskiy         s->tlscreds = nbd_get_tls_creds(s->tlscredsid, errp);
18338f071c9dSVladimir Sementsov-Ogievskiy         if (!s->tlscreds) {
183475822a12SDaniel P. Berrange             goto error;
183575822a12SDaniel P. Berrange         }
183675822a12SDaniel P. Berrange 
1837a0cd6d29SDaniel P. Berrangé         s->tlshostname = g_strdup(qemu_opt_get(opts, "tls-hostname"));
1838e8ae8b1aSDaniel P. Berrangé         if (!s->tlshostname &&
1839e8ae8b1aSDaniel P. Berrangé             s->saddr->type == SOCKET_ADDRESS_TYPE_INET) {
1840a0cd6d29SDaniel P. Berrangé             s->tlshostname = g_strdup(s->saddr->u.inet.host);
1841a0cd6d29SDaniel P. Berrangé         }
184233897dc7SNick Thomas     }
184333897dc7SNick Thomas 
18448f071c9dSVladimir Sementsov-Ogievskiy     s->x_dirty_bitmap = g_strdup(qemu_opt_get(opts, "x-dirty-bitmap"));
184593676c88SEric Blake     if (s->x_dirty_bitmap && strlen(s->x_dirty_bitmap) > NBD_MAX_STRING_SIZE) {
184693676c88SEric Blake         error_setg(errp, "x-dirty-bitmap query too long to send to server");
184793676c88SEric Blake         goto error;
184893676c88SEric Blake     }
184993676c88SEric Blake 
18508f071c9dSVladimir Sementsov-Ogievskiy     s->reconnect_delay = qemu_opt_get_number(opts, "reconnect-delay", 0);
1851be16b8bfSVladimir Sementsov-Ogievskiy     s->open_timeout = qemu_opt_get_number(opts, "open-timeout", 0);
18528f071c9dSVladimir Sementsov-Ogievskiy 
18538f071c9dSVladimir Sementsov-Ogievskiy     ret = 0;
1854d42f78e9SVladimir Sementsov-Ogievskiy 
185575822a12SDaniel P. Berrange  error:
18567ccc44fdSMax Reitz     qemu_opts_del(opts);
185775822a12SDaniel P. Berrange     return ret;
1858ae255e52SPaolo Bonzini }
1859d9b09f13SPaolo Bonzini 
18608f071c9dSVladimir Sementsov-Ogievskiy static int nbd_open(BlockDriverState *bs, QDict *options, int flags,
18618f071c9dSVladimir Sementsov-Ogievskiy                     Error **errp)
18628f071c9dSVladimir Sementsov-Ogievskiy {
18638f071c9dSVladimir Sementsov-Ogievskiy     int ret;
18648f071c9dSVladimir Sementsov-Ogievskiy     BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
18658f071c9dSVladimir Sementsov-Ogievskiy 
18668f071c9dSVladimir Sementsov-Ogievskiy     s->bs = bs;
1867ee19d953SPaolo Bonzini     qemu_mutex_init(&s->requests_lock);
18688f071c9dSVladimir Sementsov-Ogievskiy     qemu_co_queue_init(&s->free_sema);
1869ee19d953SPaolo Bonzini     qemu_co_mutex_init(&s->send_mutex);
18704ddb5d2fSVladimir Sementsov-Ogievskiy     qemu_co_mutex_init(&s->receive_mutex);
18718f071c9dSVladimir Sementsov-Ogievskiy 
1872fee091cdSLukas Straub     if (!yank_register_instance(BLOCKDEV_YANK_INSTANCE(bs->node_name), errp)) {
1873fee091cdSLukas Straub         return -EEXIST;
1874fee091cdSLukas Straub     }
1875fee091cdSLukas Straub 
1876bbba1c37SVladimir Sementsov-Ogievskiy     ret = nbd_process_options(bs, options, errp);
1877bbba1c37SVladimir Sementsov-Ogievskiy     if (ret < 0) {
1878bbba1c37SVladimir Sementsov-Ogievskiy         goto fail;
1879bbba1c37SVladimir Sementsov-Ogievskiy     }
1880bbba1c37SVladimir Sementsov-Ogievskiy 
18816d2b0332SVladimir Sementsov-Ogievskiy     s->conn = nbd_client_connection_new(s->saddr, true, s->export,
1882046f98d0SDaniel P. Berrangé                                         s->x_dirty_bitmap, s->tlscreds,
1883046f98d0SDaniel P. Berrangé                                         s->tlshostname);
1884e8b35bf5SRoman Kagan 
1885be16b8bfSVladimir Sementsov-Ogievskiy     if (s->open_timeout) {
1886be16b8bfSVladimir Sementsov-Ogievskiy         nbd_client_connection_enable_retry(s->conn);
1887be16b8bfSVladimir Sementsov-Ogievskiy         open_timer_init(s, qemu_clock_get_ns(QEMU_CLOCK_REALTIME) +
1888be16b8bfSVladimir Sementsov-Ogievskiy                         s->open_timeout * NANOSECONDS_PER_SECOND);
1889be16b8bfSVladimir Sementsov-Ogievskiy     }
1890be16b8bfSVladimir Sementsov-Ogievskiy 
18914ddb5d2fSVladimir Sementsov-Ogievskiy     s->state = NBD_CLIENT_CONNECTING_WAIT;
18928610b449SPaolo Bonzini     ret = nbd_do_establish_connection(bs, true, errp);
18938f071c9dSVladimir Sementsov-Ogievskiy     if (ret < 0) {
1894bbba1c37SVladimir Sementsov-Ogievskiy         goto fail;
18958f071c9dSVladimir Sementsov-Ogievskiy     }
18968f071c9dSVladimir Sementsov-Ogievskiy 
1897717be964SHanna Reitz     /*
1898717be964SHanna Reitz      * The connect attempt is done, so we no longer need this timer.
1899717be964SHanna Reitz      * Delete it, because we do not want it to be around when this node
1900717be964SHanna Reitz      * is drained or closed.
1901717be964SHanna Reitz      */
1902717be964SHanna Reitz     open_timer_del(s);
1903717be964SHanna Reitz 
19044ddb5d2fSVladimir Sementsov-Ogievskiy     nbd_client_connection_enable_retry(s->conn);
19058f071c9dSVladimir Sementsov-Ogievskiy 
19068f071c9dSVladimir Sementsov-Ogievskiy     return 0;
1907bbba1c37SVladimir Sementsov-Ogievskiy 
1908bbba1c37SVladimir Sementsov-Ogievskiy fail:
1909717be964SHanna Reitz     open_timer_del(s);
1910bbba1c37SVladimir Sementsov-Ogievskiy     nbd_clear_bdrvstate(bs);
1911bbba1c37SVladimir Sementsov-Ogievskiy     return ret;
19128f071c9dSVladimir Sementsov-Ogievskiy }
19138f071c9dSVladimir Sementsov-Ogievskiy 
19140c43c6fcSPaolo Bonzini static int coroutine_fn nbd_co_flush(BlockDriverState *bs)
19151486d04aSPaolo Bonzini {
1916f53a829bSMax Reitz     return nbd_client_co_flush(bs);
19171486d04aSPaolo Bonzini }
19181486d04aSPaolo Bonzini 
1919fa21e6faSDenis V. Lunev static void nbd_refresh_limits(BlockDriverState *bs, Error **errp)
1920fa21e6faSDenis V. Lunev {
1921611ae1d7SVladimir Sementsov-Ogievskiy     BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
1922fd8d372dSEric Blake     uint32_t min = s->info.min_block;
1923081dd1feSEric Blake     uint32_t max = MIN_NON_ZERO(NBD_MAX_BUFFER_SIZE, s->info.max_block);
1924081dd1feSEric Blake 
19257da537f7SEric Blake     /*
19267da537f7SEric Blake      * If the server did not advertise an alignment:
19277da537f7SEric Blake      * - a size that is not sector-aligned implies that an alignment
19287da537f7SEric Blake      *   of 1 can be used to access those tail bytes
19297da537f7SEric Blake      * - advertisement of block status requires an alignment of 1, so
19307da537f7SEric Blake      *   that we don't violate block layer constraints that block
19317da537f7SEric Blake      *   status is always aligned (as we can't control whether the
19327da537f7SEric Blake      *   server will report sub-sector extents, such as a hole at EOF
19337da537f7SEric Blake      *   on an unaligned POSIX file)
19347da537f7SEric Blake      * - otherwise, assume the server is so old that we are safer avoiding
19357da537f7SEric Blake      *   sub-sector requests
19367da537f7SEric Blake      */
19377da537f7SEric Blake     if (!min) {
19387da537f7SEric Blake         min = (!QEMU_IS_ALIGNED(s->info.size, BDRV_SECTOR_SIZE) ||
19397da537f7SEric Blake                s->info.base_allocation) ? 1 : BDRV_SECTOR_SIZE;
19407da537f7SEric Blake     }
19417da537f7SEric Blake 
19427da537f7SEric Blake     bs->bl.request_alignment = min;
1943714eb0dbSVladimir Sementsov-Ogievskiy     bs->bl.max_pdiscard = QEMU_ALIGN_DOWN(INT_MAX, min);
1944081dd1feSEric Blake     bs->bl.max_pwrite_zeroes = max;
1945081dd1feSEric Blake     bs->bl.max_transfer = max;
1946081dd1feSEric Blake 
1947081dd1feSEric Blake     if (s->info.opt_block &&
1948081dd1feSEric Blake         s->info.opt_block > bs->bl.opt_transfer) {
1949081dd1feSEric Blake         bs->bl.opt_transfer = s->info.opt_block;
1950081dd1feSEric Blake     }
1951fa21e6faSDenis V. Lunev }
1952fa21e6faSDenis V. Lunev 
1953019d6b8fSAnthony Liguori static void nbd_close(BlockDriverState *bs)
1954019d6b8fSAnthony Liguori {
1955f53a829bSMax Reitz     nbd_client_close(bs);
1956bbba1c37SVladimir Sementsov-Ogievskiy     nbd_clear_bdrvstate(bs);
1957019d6b8fSAnthony Liguori }
1958019d6b8fSAnthony Liguori 
1959a2b333c0SNir Soffer /*
1960a2b333c0SNir Soffer  * NBD cannot truncate, but if the caller asks to truncate to the same size, or
1961a2b333c0SNir Soffer  * to a smaller size with exact=false, there is no reason to fail the
1962a2b333c0SNir Soffer  * operation.
1963a2b333c0SNir Soffer  *
1964a2b333c0SNir Soffer  * Preallocation mode is ignored since it does not seems useful to fail when
1965a2b333c0SNir Soffer  * we never change anything.
1966a2b333c0SNir Soffer  */
1967a2b333c0SNir Soffer static int coroutine_fn nbd_co_truncate(BlockDriverState *bs, int64_t offset,
1968a2b333c0SNir Soffer                                         bool exact, PreallocMode prealloc,
1969a2b333c0SNir Soffer                                         BdrvRequestFlags flags, Error **errp)
1970a2b333c0SNir Soffer {
1971a2b333c0SNir Soffer     BDRVNBDState *s = bs->opaque;
1972a2b333c0SNir Soffer 
1973a2b333c0SNir Soffer     if (offset != s->info.size && exact) {
1974a2b333c0SNir Soffer         error_setg(errp, "Cannot resize NBD nodes");
1975a2b333c0SNir Soffer         return -ENOTSUP;
1976a2b333c0SNir Soffer     }
1977a2b333c0SNir Soffer 
1978a2b333c0SNir Soffer     if (offset > s->info.size) {
1979a2b333c0SNir Soffer         error_setg(errp, "Cannot grow NBD nodes");
1980a2b333c0SNir Soffer         return -EINVAL;
1981a2b333c0SNir Soffer     }
1982a2b333c0SNir Soffer 
1983a2b333c0SNir Soffer     return 0;
1984a2b333c0SNir Soffer }
1985a2b333c0SNir Soffer 
1986019d6b8fSAnthony Liguori static int64_t nbd_getlength(BlockDriverState *bs)
1987019d6b8fSAnthony Liguori {
1988019d6b8fSAnthony Liguori     BDRVNBDState *s = bs->opaque;
1989019d6b8fSAnthony Liguori 
1990611ae1d7SVladimir Sementsov-Ogievskiy     return s->info.size;
1991019d6b8fSAnthony Liguori }
1992019d6b8fSAnthony Liguori 
1993998b3a1eSMax Reitz static void nbd_refresh_filename(BlockDriverState *bs)
19942019d68bSMax Reitz {
199503504d05SMax Reitz     BDRVNBDState *s = bs->opaque;
1996491d6c7cSMax Reitz     const char *host = NULL, *port = NULL, *path = NULL;
19975c86bdf1SEric Blake     size_t len = 0;
1998491d6c7cSMax Reitz 
199962cf396bSMarkus Armbruster     if (s->saddr->type == SOCKET_ADDRESS_TYPE_INET) {
20009445673eSMarkus Armbruster         const InetSocketAddress *inet = &s->saddr->u.inet;
2001491d6c7cSMax Reitz         if (!inet->has_ipv4 && !inet->has_ipv6 && !inet->has_to) {
2002491d6c7cSMax Reitz             host = inet->host;
2003491d6c7cSMax Reitz             port = inet->port;
2004491d6c7cSMax Reitz         }
200562cf396bSMarkus Armbruster     } else if (s->saddr->type == SOCKET_ADDRESS_TYPE_UNIX) {
20069445673eSMarkus Armbruster         path = s->saddr->u.q_unix.path;
20079445673eSMarkus Armbruster     } /* else can't represent as pseudo-filename */
20082019d68bSMax Reitz 
2009491d6c7cSMax Reitz     if (path && s->export) {
20105c86bdf1SEric Blake         len = snprintf(bs->exact_filename, sizeof(bs->exact_filename),
2011491d6c7cSMax Reitz                        "nbd+unix:///%s?socket=%s", s->export, path);
2012491d6c7cSMax Reitz     } else if (path && !s->export) {
20135c86bdf1SEric Blake         len = snprintf(bs->exact_filename, sizeof(bs->exact_filename),
2014491d6c7cSMax Reitz                        "nbd+unix://?socket=%s", path);
2015491d6c7cSMax Reitz     } else if (host && s->export) {
20165c86bdf1SEric Blake         len = snprintf(bs->exact_filename, sizeof(bs->exact_filename),
2017491d6c7cSMax Reitz                        "nbd://%s:%s/%s", host, port, s->export);
2018491d6c7cSMax Reitz     } else if (host && !s->export) {
20195c86bdf1SEric Blake         len = snprintf(bs->exact_filename, sizeof(bs->exact_filename),
2020491d6c7cSMax Reitz                        "nbd://%s:%s", host, port);
2021ec0de768SMax Reitz     }
202200d69986SEric Blake     if (len >= sizeof(bs->exact_filename)) {
20235c86bdf1SEric Blake         /* Name is too long to represent exactly, so leave it empty. */
20245c86bdf1SEric Blake         bs->exact_filename[0] = '\0';
20255c86bdf1SEric Blake     }
20262019d68bSMax Reitz }
20272019d68bSMax Reitz 
20288a6239c0SMax Reitz static char *nbd_dirname(BlockDriverState *bs, Error **errp)
20298a6239c0SMax Reitz {
20308a6239c0SMax Reitz     /* The generic bdrv_dirname() implementation is able to work out some
20318a6239c0SMax Reitz      * directory name for NBD nodes, but that would be wrong. So far there is no
20328a6239c0SMax Reitz      * specification for how "export paths" would work, so NBD does not have
20338a6239c0SMax Reitz      * directory names. */
20348a6239c0SMax Reitz     error_setg(errp, "Cannot generate a base directory for NBD nodes");
20358a6239c0SMax Reitz     return NULL;
20368a6239c0SMax Reitz }
20378a6239c0SMax Reitz 
20382654267cSMax Reitz static const char *const nbd_strong_runtime_opts[] = {
20392654267cSMax Reitz     "path",
20402654267cSMax Reitz     "host",
20412654267cSMax Reitz     "port",
20422654267cSMax Reitz     "export",
20432654267cSMax Reitz     "tls-creds",
2044a0cd6d29SDaniel P. Berrangé     "tls-hostname",
20452654267cSMax Reitz     "server.",
20462654267cSMax Reitz 
20472654267cSMax Reitz     NULL
20482654267cSMax Reitz };
20492654267cSMax Reitz 
2050c4f7f24eSVladimir Sementsov-Ogievskiy static void nbd_cancel_in_flight(BlockDriverState *bs)
2051c4f7f24eSVladimir Sementsov-Ogievskiy {
2052c4f7f24eSVladimir Sementsov-Ogievskiy     BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
2053c4f7f24eSVladimir Sementsov-Ogievskiy 
2054c4f7f24eSVladimir Sementsov-Ogievskiy     reconnect_delay_timer_del(s);
2055c4f7f24eSVladimir Sementsov-Ogievskiy 
2056ee19d953SPaolo Bonzini     qemu_mutex_lock(&s->requests_lock);
2057c4f7f24eSVladimir Sementsov-Ogievskiy     if (s->state == NBD_CLIENT_CONNECTING_WAIT) {
2058c4f7f24eSVladimir Sementsov-Ogievskiy         s->state = NBD_CLIENT_CONNECTING_NOWAIT;
2059c4f7f24eSVladimir Sementsov-Ogievskiy     }
2060ee19d953SPaolo Bonzini     qemu_mutex_unlock(&s->requests_lock);
20614ddb5d2fSVladimir Sementsov-Ogievskiy 
20624ddb5d2fSVladimir Sementsov-Ogievskiy     nbd_co_establish_connection_cancel(s->conn);
2063c4f7f24eSVladimir Sementsov-Ogievskiy }
2064c4f7f24eSVladimir Sementsov-Ogievskiy 
2065e15f3a66SHanna Reitz static void nbd_attach_aio_context(BlockDriverState *bs,
2066e15f3a66SHanna Reitz                                    AioContext *new_context)
2067e15f3a66SHanna Reitz {
2068e15f3a66SHanna Reitz     BDRVNBDState *s = bs->opaque;
2069e15f3a66SHanna Reitz 
2070e15f3a66SHanna Reitz     /* The open_timer is used only during nbd_open() */
2071e15f3a66SHanna Reitz     assert(!s->open_timer);
2072e15f3a66SHanna Reitz 
2073e15f3a66SHanna Reitz     /*
2074e15f3a66SHanna Reitz      * The reconnect_delay_timer is scheduled in I/O paths when the
2075e15f3a66SHanna Reitz      * connection is lost, to cancel the reconnection attempt after a
2076e15f3a66SHanna Reitz      * given time.  Once this attempt is done (successfully or not),
2077e15f3a66SHanna Reitz      * nbd_reconnect_attempt() ensures the timer is deleted before the
2078e15f3a66SHanna Reitz      * respective I/O request is resumed.
2079e15f3a66SHanna Reitz      * Since the AioContext can only be changed when a node is drained,
2080e15f3a66SHanna Reitz      * the reconnect_delay_timer cannot be active here.
2081e15f3a66SHanna Reitz      */
2082e15f3a66SHanna Reitz     assert(!s->reconnect_delay_timer);
2083e15f3a66SHanna Reitz 
2084e15f3a66SHanna Reitz     if (s->ioc) {
2085e15f3a66SHanna Reitz         qio_channel_attach_aio_context(s->ioc, new_context);
2086e15f3a66SHanna Reitz     }
2087e15f3a66SHanna Reitz }
2088e15f3a66SHanna Reitz 
2089e15f3a66SHanna Reitz static void nbd_detach_aio_context(BlockDriverState *bs)
2090e15f3a66SHanna Reitz {
2091e15f3a66SHanna Reitz     BDRVNBDState *s = bs->opaque;
2092e15f3a66SHanna Reitz 
2093e15f3a66SHanna Reitz     assert(!s->open_timer);
2094e15f3a66SHanna Reitz     assert(!s->reconnect_delay_timer);
2095e15f3a66SHanna Reitz 
2096e15f3a66SHanna Reitz     if (s->ioc) {
2097e15f3a66SHanna Reitz         qio_channel_detach_aio_context(s->ioc);
2098e15f3a66SHanna Reitz     }
2099e15f3a66SHanna Reitz }
2100e15f3a66SHanna Reitz 
2101019d6b8fSAnthony Liguori static BlockDriver bdrv_nbd = {
2102019d6b8fSAnthony Liguori     .format_name                = "nbd",
21031d7d2a9dSPaolo Bonzini     .protocol_name              = "nbd",
2104019d6b8fSAnthony Liguori     .instance_size              = sizeof(BDRVNBDState),
21056963a30dSKevin Wolf     .bdrv_parse_filename        = nbd_parse_filename,
21065a5e7f8cSMaxim Levitsky     .bdrv_co_create_opts        = bdrv_co_create_opts_simple,
21075a5e7f8cSMaxim Levitsky     .create_opts                = &bdrv_create_opts_simple,
210866f82ceeSKevin Wolf     .bdrv_file_open             = nbd_open,
2109e99754b4SMaxim Levitsky     .bdrv_reopen_prepare        = nbd_client_reopen_prepare,
211070c4fb26SEric Blake     .bdrv_co_preadv             = nbd_client_co_preadv,
211170c4fb26SEric Blake     .bdrv_co_pwritev            = nbd_client_co_pwritev,
2112fa778fffSEric Blake     .bdrv_co_pwrite_zeroes      = nbd_client_co_pwrite_zeroes,
2113019d6b8fSAnthony Liguori     .bdrv_close                 = nbd_close,
21141486d04aSPaolo Bonzini     .bdrv_co_flush_to_os        = nbd_co_flush,
2115447e57c3SEric Blake     .bdrv_co_pdiscard           = nbd_client_co_pdiscard,
2116fa21e6faSDenis V. Lunev     .bdrv_refresh_limits        = nbd_refresh_limits,
2117a2b333c0SNir Soffer     .bdrv_co_truncate           = nbd_co_truncate,
2118019d6b8fSAnthony Liguori     .bdrv_getlength             = nbd_getlength,
21192019d68bSMax Reitz     .bdrv_refresh_filename      = nbd_refresh_filename,
212078a33ab5SVladimir Sementsov-Ogievskiy     .bdrv_co_block_status       = nbd_client_co_block_status,
21218a6239c0SMax Reitz     .bdrv_dirname               = nbd_dirname,
21222654267cSMax Reitz     .strong_runtime_opts        = nbd_strong_runtime_opts,
2123c4f7f24eSVladimir Sementsov-Ogievskiy     .bdrv_cancel_in_flight      = nbd_cancel_in_flight,
2124e15f3a66SHanna Reitz 
2125e15f3a66SHanna Reitz     .bdrv_attach_aio_context    = nbd_attach_aio_context,
2126e15f3a66SHanna Reitz     .bdrv_detach_aio_context    = nbd_detach_aio_context,
21271d7d2a9dSPaolo Bonzini };
21281d7d2a9dSPaolo Bonzini 
21291d7d2a9dSPaolo Bonzini static BlockDriver bdrv_nbd_tcp = {
21301d7d2a9dSPaolo Bonzini     .format_name                = "nbd",
21311d7d2a9dSPaolo Bonzini     .protocol_name              = "nbd+tcp",
21321d7d2a9dSPaolo Bonzini     .instance_size              = sizeof(BDRVNBDState),
21336963a30dSKevin Wolf     .bdrv_parse_filename        = nbd_parse_filename,
21345a5e7f8cSMaxim Levitsky     .bdrv_co_create_opts        = bdrv_co_create_opts_simple,
21355a5e7f8cSMaxim Levitsky     .create_opts                = &bdrv_create_opts_simple,
21361d7d2a9dSPaolo Bonzini     .bdrv_file_open             = nbd_open,
2137e99754b4SMaxim Levitsky     .bdrv_reopen_prepare        = nbd_client_reopen_prepare,
213870c4fb26SEric Blake     .bdrv_co_preadv             = nbd_client_co_preadv,
213970c4fb26SEric Blake     .bdrv_co_pwritev            = nbd_client_co_pwritev,
2140fa778fffSEric Blake     .bdrv_co_pwrite_zeroes      = nbd_client_co_pwrite_zeroes,
21411d7d2a9dSPaolo Bonzini     .bdrv_close                 = nbd_close,
21421d7d2a9dSPaolo Bonzini     .bdrv_co_flush_to_os        = nbd_co_flush,
2143447e57c3SEric Blake     .bdrv_co_pdiscard           = nbd_client_co_pdiscard,
2144fa21e6faSDenis V. Lunev     .bdrv_refresh_limits        = nbd_refresh_limits,
2145a2b333c0SNir Soffer     .bdrv_co_truncate           = nbd_co_truncate,
21461d7d2a9dSPaolo Bonzini     .bdrv_getlength             = nbd_getlength,
21472019d68bSMax Reitz     .bdrv_refresh_filename      = nbd_refresh_filename,
214878a33ab5SVladimir Sementsov-Ogievskiy     .bdrv_co_block_status       = nbd_client_co_block_status,
21498a6239c0SMax Reitz     .bdrv_dirname               = nbd_dirname,
21502654267cSMax Reitz     .strong_runtime_opts        = nbd_strong_runtime_opts,
2151c4f7f24eSVladimir Sementsov-Ogievskiy     .bdrv_cancel_in_flight      = nbd_cancel_in_flight,
2152e15f3a66SHanna Reitz 
2153e15f3a66SHanna Reitz     .bdrv_attach_aio_context    = nbd_attach_aio_context,
2154e15f3a66SHanna Reitz     .bdrv_detach_aio_context    = nbd_detach_aio_context,
21551d7d2a9dSPaolo Bonzini };
21561d7d2a9dSPaolo Bonzini 
21571d7d2a9dSPaolo Bonzini static BlockDriver bdrv_nbd_unix = {
21581d7d2a9dSPaolo Bonzini     .format_name                = "nbd",
21591d7d2a9dSPaolo Bonzini     .protocol_name              = "nbd+unix",
21601d7d2a9dSPaolo Bonzini     .instance_size              = sizeof(BDRVNBDState),
21616963a30dSKevin Wolf     .bdrv_parse_filename        = nbd_parse_filename,
21625a5e7f8cSMaxim Levitsky     .bdrv_co_create_opts        = bdrv_co_create_opts_simple,
21635a5e7f8cSMaxim Levitsky     .create_opts                = &bdrv_create_opts_simple,
21641d7d2a9dSPaolo Bonzini     .bdrv_file_open             = nbd_open,
2165e99754b4SMaxim Levitsky     .bdrv_reopen_prepare        = nbd_client_reopen_prepare,
216670c4fb26SEric Blake     .bdrv_co_preadv             = nbd_client_co_preadv,
216770c4fb26SEric Blake     .bdrv_co_pwritev            = nbd_client_co_pwritev,
2168fa778fffSEric Blake     .bdrv_co_pwrite_zeroes      = nbd_client_co_pwrite_zeroes,
21691d7d2a9dSPaolo Bonzini     .bdrv_close                 = nbd_close,
21701d7d2a9dSPaolo Bonzini     .bdrv_co_flush_to_os        = nbd_co_flush,
2171447e57c3SEric Blake     .bdrv_co_pdiscard           = nbd_client_co_pdiscard,
2172fa21e6faSDenis V. Lunev     .bdrv_refresh_limits        = nbd_refresh_limits,
2173a2b333c0SNir Soffer     .bdrv_co_truncate           = nbd_co_truncate,
21741d7d2a9dSPaolo Bonzini     .bdrv_getlength             = nbd_getlength,
21752019d68bSMax Reitz     .bdrv_refresh_filename      = nbd_refresh_filename,
217678a33ab5SVladimir Sementsov-Ogievskiy     .bdrv_co_block_status       = nbd_client_co_block_status,
21778a6239c0SMax Reitz     .bdrv_dirname               = nbd_dirname,
21782654267cSMax Reitz     .strong_runtime_opts        = nbd_strong_runtime_opts,
2179c4f7f24eSVladimir Sementsov-Ogievskiy     .bdrv_cancel_in_flight      = nbd_cancel_in_flight,
2180e15f3a66SHanna Reitz 
2181e15f3a66SHanna Reitz     .bdrv_attach_aio_context    = nbd_attach_aio_context,
2182e15f3a66SHanna Reitz     .bdrv_detach_aio_context    = nbd_detach_aio_context,
2183019d6b8fSAnthony Liguori };
2184019d6b8fSAnthony Liguori 
2185019d6b8fSAnthony Liguori static void bdrv_nbd_init(void)
2186019d6b8fSAnthony Liguori {
2187019d6b8fSAnthony Liguori     bdrv_register(&bdrv_nbd);
21881d7d2a9dSPaolo Bonzini     bdrv_register(&bdrv_nbd_tcp);
21891d7d2a9dSPaolo Bonzini     bdrv_register(&bdrv_nbd_unix);
2190019d6b8fSAnthony Liguori }
2191019d6b8fSAnthony Liguori 
2192019d6b8fSAnthony Liguori block_init(bdrv_nbd_init);
2193