]> git.proxmox.com Git - mirror_qemu.git/blame - block/nbd.c
Merge tag 'win32-pull-request' of https://gitlab.com/marcandre.lureau/qemu into staging
[mirror_qemu.git] / block / nbd.c
CommitLineData
75818250
TS
1/*
2 * QEMU Block driver for NBD
3 *
f7651539 4 * Copyright (c) 2019 Virtuozzo International GmbH.
86f8cdf3 5 * Copyright (C) 2016 Red Hat, Inc.
75818250 6 * Copyright (C) 2008 Bull S.A.S.
bd5921b4 7 * Author: Laurent Vivier <Laurent.Vivier@bull.net>
75818250
TS
8 *
9 * Some parts:
10 * Copyright (C) 2007 Anthony Liguori <anthony@codemonkey.ws>
11 *
12 * Permission is hereby granted, free of charge, to any person obtaining a copy
13 * of this software and associated documentation files (the "Software"), to deal
14 * in the Software without restriction, including without limitation the rights
15 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
16 * copies of the Software, and to permit persons to whom the Software is
17 * furnished to do so, subject to the following conditions:
18 *
19 * The above copyright notice and this permission notice shall be included in
20 * all copies or substantial portions of the Software.
21 *
22 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
23 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
24 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
25 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
26 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
27 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
28 * THE SOFTWARE.
29 */
30
80c71a24 31#include "qemu/osdep.h"
86f8cdf3
VSO
32
33#include "trace.h"
1de7afc9 34#include "qemu/uri.h"
922a01a0 35#include "qemu/option.h"
86f8cdf3 36#include "qemu/cutils.h"
db725815 37#include "qemu/main-loop.h"
86f8cdf3 38
9af23989 39#include "qapi/qapi-visit-sockets.h"
2019d68b 40#include "qapi/qmp/qstring.h"
1dc4718d 41#include "qapi/clone-visitor.h"
86f8cdf3
VSO
42
43#include "block/qdict.h"
44#include "block/nbd.h"
45#include "block/block_int.h"
a71d597b 46#include "block/coroutines.h"
75818250 47
fee091cd
LS
48#include "qemu/yank.h"
49
1d45f8b5 50#define EN_OPTSTR ":exportname="
86f8cdf3
VSO
51#define MAX_NBD_REQUESTS 16
52
53#define HANDLE_TO_INDEX(bs, handle) ((handle) ^ (uint64_t)(intptr_t)(bs))
54#define INDEX_TO_HANDLE(bs, index) ((index) ^ (uint64_t)(intptr_t)(bs))
55
56typedef struct {
57 Coroutine *coroutine;
58 uint64_t offset; /* original offset of the request */
4ddb5d2f 59 bool receiving; /* sleeping in the yield in nbd_receive_replies */
86f8cdf3
VSO
60} NBDClientRequest;
61
a34b1e5e 62typedef enum NBDClientState {
f7651539
VSO
63 NBD_CLIENT_CONNECTING_WAIT,
64 NBD_CLIENT_CONNECTING_NOWAIT,
a34b1e5e
VSO
65 NBD_CLIENT_CONNECTED,
66 NBD_CLIENT_QUIT
67} NBDClientState;
68
611ae1d7 69typedef struct BDRVNBDState {
95a078ea 70 QIOChannel *ioc; /* The current I/O channel */
86f8cdf3
VSO
71 NBDExportInfo info;
72
ee19d953 73 /*
dba5156c 74 * Protects state, free_sema, in_flight, requests[].coroutine,
ee19d953
PB
75 * reconnect_delay_timer.
76 */
77 QemuMutex requests_lock;
dba5156c 78 NBDClientState state;
86f8cdf3 79 CoQueue free_sema;
1b8f7776 80 unsigned in_flight;
ee19d953
PB
81 NBDClientRequest requests[MAX_NBD_REQUESTS];
82 QEMUTimer *reconnect_delay_timer;
4ddb5d2f 83
620c5cb5 84 /* Protects sending data on the socket. */
ee19d953 85 CoMutex send_mutex;
620c5cb5
PB
86
87 /*
88 * Protects receiving reply headers from the socket, as well as the
89 * fields reply and requests[].receiving
90 */
4ddb5d2f 91 CoMutex receive_mutex;
620c5cb5 92 NBDReply reply;
86f8cdf3 93
be16b8bf 94 QEMUTimer *open_timer;
46f56631 95
86f8cdf3 96 BlockDriverState *bs;
03504d05 97
8f071c9d
VSO
98 /* Connection parameters */
99 uint32_t reconnect_delay;
be16b8bf 100 uint32_t open_timeout;
62cf396b 101 SocketAddress *saddr;
a0cd6d29
DB
102 char *export;
103 char *tlscredsid;
8f071c9d 104 QCryptoTLSCreds *tlscreds;
a0cd6d29 105 char *tlshostname;
8f071c9d 106 char *x_dirty_bitmap;
dbc7b014 107 bool alloc_depth;
1dc4718d 108
90ddc64f 109 NBDClientConnection *conn;
75818250
TS
110} BDRVNBDState;
111
fee091cd 112static void nbd_yank(void *opaque);
f7651539 113
bbba1c37 114static void nbd_clear_bdrvstate(BlockDriverState *bs)
7f493662 115{
bbba1c37 116 BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
e8b35bf5 117
248d4701
VSO
118 nbd_client_connection_release(s->conn);
119 s->conn = NULL;
bbba1c37
VSO
120
121 yank_unregister_instance(BLOCKDEV_YANK_INSTANCE(bs->node_name));
122
8a39c381
HR
123 /* Must not leave timers behind that would access freed data */
124 assert(!s->reconnect_delay_timer);
125 assert(!s->open_timer);
126
7f493662
PN
127 object_unref(OBJECT(s->tlscreds));
128 qapi_free_SocketAddress(s->saddr);
129 s->saddr = NULL;
130 g_free(s->export);
131 s->export = NULL;
132 g_free(s->tlscredsid);
133 s->tlscredsid = NULL;
a0cd6d29
DB
134 g_free(s->tlshostname);
135 s->tlshostname = NULL;
7f493662
PN
136 g_free(s->x_dirty_bitmap);
137 s->x_dirty_bitmap = NULL;
138}
139
a80a9a1c 140/* Called with s->receive_mutex taken. */
0c43c6fc 141static bool coroutine_fn nbd_recv_coroutine_wake_one(NBDClientRequest *req)
04a953b2
VSO
142{
143 if (req->receiving) {
144 req->receiving = false;
145 aio_co_wake(req->coroutine);
146 return true;
147 }
148
149 return false;
150}
151
a80a9a1c 152static void coroutine_fn nbd_recv_coroutines_wake(BDRVNBDState *s)
3bc0bd1f
VSO
153{
154 int i;
155
a80a9a1c 156 QEMU_LOCK_GUARD(&s->receive_mutex);
3bc0bd1f 157 for (i = 0; i < MAX_NBD_REQUESTS; i++) {
a80a9a1c 158 if (nbd_recv_coroutine_wake_one(&s->requests[i])) {
04a953b2 159 return;
3bc0bd1f
VSO
160 }
161 }
162}
163
dba5156c
PB
164/* Called with s->requests_lock held. */
165static void coroutine_fn nbd_channel_error_locked(BDRVNBDState *s, int ret)
a34b1e5e 166{
dba5156c 167 if (s->state == NBD_CLIENT_CONNECTED) {
cb116da7
VSO
168 qio_channel_shutdown(s->ioc, QIO_CHANNEL_SHUTDOWN_BOTH, NULL);
169 }
170
f7651539 171 if (ret == -EIO) {
dba5156c 172 if (s->state == NBD_CLIENT_CONNECTED) {
f7651539
VSO
173 s->state = s->reconnect_delay ? NBD_CLIENT_CONNECTING_WAIT :
174 NBD_CLIENT_CONNECTING_NOWAIT;
175 }
176 } else {
f7651539
VSO
177 s->state = NBD_CLIENT_QUIT;
178 }
a34b1e5e
VSO
179}
180
dba5156c
PB
181static void coroutine_fn nbd_channel_error(BDRVNBDState *s, int ret)
182{
183 QEMU_LOCK_GUARD(&s->requests_lock);
184 nbd_channel_error_locked(s, ret);
185}
186
46f56631
VSO
187static void reconnect_delay_timer_del(BDRVNBDState *s)
188{
189 if (s->reconnect_delay_timer) {
46f56631
VSO
190 timer_free(s->reconnect_delay_timer);
191 s->reconnect_delay_timer = NULL;
192 }
193}
194
195static void reconnect_delay_timer_cb(void *opaque)
196{
197 BDRVNBDState *s = opaque;
198
dba5156c
PB
199 reconnect_delay_timer_del(s);
200 WITH_QEMU_LOCK_GUARD(&s->requests_lock) {
201 if (s->state != NBD_CLIENT_CONNECTING_WAIT) {
202 return;
203 }
46f56631 204 s->state = NBD_CLIENT_CONNECTING_NOWAIT;
46f56631 205 }
dba5156c 206 nbd_co_establish_connection_cancel(s->conn);
46f56631
VSO
207}
208
209static void reconnect_delay_timer_init(BDRVNBDState *s, uint64_t expire_time_ns)
210{
46f56631
VSO
211 assert(!s->reconnect_delay_timer);
212 s->reconnect_delay_timer = aio_timer_new(bdrv_get_aio_context(s->bs),
213 QEMU_CLOCK_REALTIME,
214 SCALE_NS,
215 reconnect_delay_timer_cb, s);
216 timer_mod(s->reconnect_delay_timer, expire_time_ns);
217}
218
f7651539
VSO
219static void nbd_teardown_connection(BlockDriverState *bs)
220{
221 BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
222
4ddb5d2f
VSO
223 assert(!s->in_flight);
224
fbeb3e63 225 if (s->ioc) {
f7651539 226 qio_channel_shutdown(s->ioc, QIO_CHANNEL_SHUTDOWN_BOTH, NULL);
4ddb5d2f
VSO
227 yank_unregister_function(BLOCKDEV_YANK_INSTANCE(s->bs->node_name),
228 nbd_yank, s->bs);
229 object_unref(OBJECT(s->ioc));
230 s->ioc = NULL;
f7651539 231 }
fbeb3e63 232
dba5156c
PB
233 WITH_QEMU_LOCK_GUARD(&s->requests_lock) {
234 s->state = NBD_CLIENT_QUIT;
235 }
f7651539 236}
86f8cdf3 237
be16b8bf
VSO
238static void open_timer_del(BDRVNBDState *s)
239{
240 if (s->open_timer) {
241 timer_free(s->open_timer);
242 s->open_timer = NULL;
243 }
244}
245
246static void open_timer_cb(void *opaque)
247{
248 BDRVNBDState *s = opaque;
249
250 nbd_co_establish_connection_cancel(s->conn);
251 open_timer_del(s);
252}
253
254static void open_timer_init(BDRVNBDState *s, uint64_t expire_time_ns)
255{
256 assert(!s->open_timer);
257 s->open_timer = aio_timer_new(bdrv_get_aio_context(s->bs),
258 QEMU_CLOCK_REALTIME,
259 SCALE_NS,
260 open_timer_cb, s);
261 timer_mod(s->open_timer, expire_time_ns);
262}
263
8d45185c 264static bool nbd_client_will_reconnect(BDRVNBDState *s)
f7651539 265{
dba5156c
PB
266 /*
267 * Called only after a socket error, so this is not performance sensitive.
268 */
269 QEMU_LOCK_GUARD(&s->requests_lock);
270 return s->state == NBD_CLIENT_CONNECTING_WAIT;
f7651539 271}
dba5156c 272
e9ba7788
VSO
273/*
274 * Update @bs with information learned during a completed negotiation process.
275 * Return failure if the server's advertised options are incompatible with the
276 * client's needs.
277 */
278static int nbd_handle_updated_info(BlockDriverState *bs, Error **errp)
279{
280 BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
281 int ret;
282
283 if (s->x_dirty_bitmap) {
284 if (!s->info.base_allocation) {
285 error_setg(errp, "requested x-dirty-bitmap %s not found",
286 s->x_dirty_bitmap);
287 return -EINVAL;
288 }
289 if (strcmp(s->x_dirty_bitmap, "qemu:allocation-depth") == 0) {
290 s->alloc_depth = true;
291 }
292 }
293
294 if (s->info.flags & NBD_FLAG_READ_ONLY) {
295 ret = bdrv_apply_auto_read_only(bs, "NBD export is read-only", errp);
296 if (ret < 0) {
297 return ret;
298 }
299 }
300
301 if (s->info.flags & NBD_FLAG_SEND_FUA) {
302 bs->supported_write_flags = BDRV_REQ_FUA;
303 bs->supported_zero_flags |= BDRV_REQ_FUA;
304 }
305
306 if (s->info.flags & NBD_FLAG_SEND_WRITE_ZEROES) {
307 bs->supported_zero_flags |= BDRV_REQ_MAY_UNMAP;
308 if (s->info.flags & NBD_FLAG_SEND_FAST_ZERO) {
309 bs->supported_zero_flags |= BDRV_REQ_NO_FALLBACK;
310 }
311 }
312
313 trace_nbd_client_handshake_success(s->export);
314
315 return 0;
316}
317
a71d597b 318int coroutine_fn nbd_co_do_establish_connection(BlockDriverState *bs,
8610b449 319 bool blocking, Error **errp)
f7651539 320{
51edbf53 321 BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
fa35591b 322 int ret;
1581a70d 323 IO_CODE();
f7651539 324
51edbf53
VSO
325 assert(!s->ioc);
326
4ddb5d2f 327 s->ioc = nbd_co_establish_connection(s->conn, &s->info, blocking, errp);
51edbf53
VSO
328 if (!s->ioc) {
329 return -ECONNREFUSED;
330 }
331
0b9cd6b9
LS
332 yank_register_function(BLOCKDEV_YANK_INSTANCE(s->bs->node_name), nbd_yank,
333 bs);
334
51edbf53
VSO
335 ret = nbd_handle_updated_info(s->bs, NULL);
336 if (ret < 0) {
337 /*
338 * We have connected, but must fail for other reasons.
339 * Send NBD_CMD_DISC as a courtesy to the server.
340 */
341 NBDRequest request = { .type = NBD_CMD_DISC };
342
343 nbd_send_request(s->ioc, &request);
344
0b9cd6b9
LS
345 yank_unregister_function(BLOCKDEV_YANK_INSTANCE(s->bs->node_name),
346 nbd_yank, bs);
51edbf53
VSO
347 object_unref(OBJECT(s->ioc));
348 s->ioc = NULL;
349
350 return ret;
351 }
352
353 qio_channel_set_blocking(s->ioc, false, NULL);
354 qio_channel_attach_aio_context(s->ioc, bdrv_get_aio_context(bs));
355
51edbf53 356 /* successfully connected */
dba5156c
PB
357 WITH_QEMU_LOCK_GUARD(&s->requests_lock) {
358 s->state = NBD_CLIENT_CONNECTED;
359 }
51edbf53
VSO
360
361 return 0;
362}
363
dba5156c 364/* Called with s->requests_lock held. */
8d45185c
PB
365static bool nbd_client_connecting(BDRVNBDState *s)
366{
dba5156c
PB
367 return s->state == NBD_CLIENT_CONNECTING_WAIT ||
368 s->state == NBD_CLIENT_CONNECTING_NOWAIT;
8d45185c
PB
369}
370
ee19d953 371/* Called with s->requests_lock taken. */
51edbf53
VSO
372static coroutine_fn void nbd_reconnect_attempt(BDRVNBDState *s)
373{
8bb100c9 374 int ret;
dba5156c 375 bool blocking = s->state == NBD_CLIENT_CONNECTING_WAIT;
8610b449
PB
376
377 /*
378 * Now we are sure that nobody is accessing the channel, and no one will
379 * try until we set the state to CONNECTED.
380 */
4ddb5d2f 381 assert(nbd_client_connecting(s));
8610b449 382 assert(s->in_flight == 1);
f7651539 383
8bb100c9
DL
384 trace_nbd_reconnect_attempt(s->bs->in_flight);
385
8610b449 386 if (blocking && !s->reconnect_delay_timer) {
4ddb5d2f 387 /*
8610b449 388 * It's the first reconnect attempt after switching to
4ddb5d2f
VSO
389 * NBD_CLIENT_CONNECTING_WAIT
390 */
8610b449 391 g_assert(s->reconnect_delay);
4ddb5d2f
VSO
392 reconnect_delay_timer_init(s,
393 qemu_clock_get_ns(QEMU_CLOCK_REALTIME) +
394 s->reconnect_delay * NANOSECONDS_PER_SECOND);
f7651539
VSO
395 }
396
f7651539
VSO
397 /* Finalize previous connection if any */
398 if (s->ioc) {
8a509afd 399 qio_channel_detach_aio_context(QIO_CHANNEL(s->ioc));
fee091cd
LS
400 yank_unregister_function(BLOCKDEV_YANK_INSTANCE(s->bs->node_name),
401 nbd_yank, s->bs);
f7651539
VSO
402 object_unref(OBJECT(s->ioc));
403 s->ioc = NULL;
404 }
405
ee19d953 406 qemu_mutex_unlock(&s->requests_lock);
8bb100c9
DL
407 ret = nbd_co_do_establish_connection(s->bs, blocking, NULL);
408 trace_nbd_reconnect_attempt_result(ret, s->bs->in_flight);
ee19d953 409 qemu_mutex_lock(&s->requests_lock);
3ce1fc16
HR
410
411 /*
412 * The reconnect attempt is done (maybe successfully, maybe not), so
413 * we no longer need this timer. Delete it so it will not outlive
414 * this I/O request (so draining removes all timers).
415 */
416 reconnect_delay_timer_del(s);
f7651539
VSO
417}
418
4ddb5d2f 419static coroutine_fn int nbd_receive_replies(BDRVNBDState *s, uint64_t handle)
f7651539 420{
4ddb5d2f
VSO
421 int ret;
422 uint64_t ind = HANDLE_TO_INDEX(s, handle), ind2;
423 QEMU_LOCK_GUARD(&s->receive_mutex);
f7651539 424
4ddb5d2f
VSO
425 while (true) {
426 if (s->reply.handle == handle) {
427 /* We are done */
428 return 0;
f7651539
VSO
429 }
430
4ddb5d2f
VSO
431 if (s->reply.handle != 0) {
432 /*
433 * Some other request is being handled now. It should already be
434 * woken by whoever set s->reply.handle (or never wait in this
435 * yield). So, we should not wake it here.
436 */
437 ind2 = HANDLE_TO_INDEX(s, s->reply.handle);
438 assert(!s->requests[ind2].receiving);
86f8cdf3 439
4ddb5d2f
VSO
440 s->requests[ind].receiving = true;
441 qemu_co_mutex_unlock(&s->receive_mutex);
f7651539 442
4ddb5d2f
VSO
443 qemu_coroutine_yield();
444 /*
a80a9a1c 445 * We may be woken for 2 reasons:
4ddb5d2f
VSO
446 * 1. From this function, executing in parallel coroutine, when our
447 * handle is received.
a80a9a1c 448 * 2. From nbd_co_receive_one_chunk(), when previous request is
4ddb5d2f
VSO
449 * finished and s->reply.handle set to 0.
450 * Anyway, it's OK to lock the mutex and go to the next iteration.
451 */
f7651539 452
4ddb5d2f
VSO
453 qemu_co_mutex_lock(&s->receive_mutex);
454 assert(!s->requests[ind].receiving);
f7651539
VSO
455 continue;
456 }
457
4ddb5d2f 458 /* We are under mutex and handle is 0. We have to do the dirty work. */
86f8cdf3 459 assert(s->reply.handle == 0);
4ddb5d2f 460 ret = nbd_receive_reply(s->bs, s->ioc, &s->reply, NULL);
86f8cdf3 461 if (ret <= 0) {
4ddb5d2f
VSO
462 ret = ret ? ret : -EIO;
463 nbd_channel_error(s, ret);
464 return ret;
86f8cdf3 465 }
4ddb5d2f 466 if (nbd_reply_is_structured(&s->reply) && !s->info.structured_reply) {
a34b1e5e 467 nbd_channel_error(s, -EINVAL);
4ddb5d2f 468 return -EINVAL;
86f8cdf3 469 }
4ddb5d2f 470 ind2 = HANDLE_TO_INDEX(s, s->reply.handle);
8846b7d1 471 if (ind2 >= MAX_NBD_REQUESTS || !s->requests[ind2].coroutine) {
4ddb5d2f
VSO
472 nbd_channel_error(s, -EINVAL);
473 return -EINVAL;
474 }
8846b7d1
PB
475 if (s->reply.handle == handle) {
476 /* We are done */
477 return 0;
478 }
4ddb5d2f 479 nbd_recv_coroutine_wake_one(&s->requests[ind2]);
78c81a3f 480 }
86f8cdf3
VSO
481}
482
0c43c6fc
PB
483static int coroutine_fn nbd_co_send_request(BlockDriverState *bs,
484 NBDRequest *request,
485 QEMUIOVector *qiov)
86f8cdf3 486{
611ae1d7 487 BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
a34b1e5e 488 int rc, i = -1;
86f8cdf3 489
ee19d953 490 qemu_mutex_lock(&s->requests_lock);
4ddb5d2f 491 while (s->in_flight == MAX_NBD_REQUESTS ||
dba5156c 492 (s->state != NBD_CLIENT_CONNECTED && s->in_flight > 0)) {
ee19d953 493 qemu_co_queue_wait(&s->free_sema, &s->requests_lock);
86f8cdf3 494 }
a34b1e5e 495
8610b449 496 s->in_flight++;
dba5156c 497 if (s->state != NBD_CLIENT_CONNECTED) {
8610b449
PB
498 if (nbd_client_connecting(s)) {
499 nbd_reconnect_attempt(s);
500 qemu_co_queue_restart_all(&s->free_sema);
501 }
dba5156c 502 if (s->state != NBD_CLIENT_CONNECTED) {
8610b449
PB
503 rc = -EIO;
504 goto err;
505 }
a34b1e5e
VSO
506 }
507
86f8cdf3
VSO
508 for (i = 0; i < MAX_NBD_REQUESTS; i++) {
509 if (s->requests[i].coroutine == NULL) {
510 break;
511 }
512 }
513
86f8cdf3 514 assert(i < MAX_NBD_REQUESTS);
86f8cdf3
VSO
515 s->requests[i].coroutine = qemu_coroutine_self();
516 s->requests[i].offset = request->from;
517 s->requests[i].receiving = false;
ee19d953 518 qemu_mutex_unlock(&s->requests_lock);
86f8cdf3 519
ee19d953 520 qemu_co_mutex_lock(&s->send_mutex);
86f8cdf3
VSO
521 request->handle = INDEX_TO_HANDLE(s, i);
522
86f8cdf3
VSO
523 assert(s->ioc);
524
525 if (qiov) {
526 qio_channel_set_cork(s->ioc, true);
527 rc = nbd_send_request(s->ioc, request);
2866ddd1
EB
528 if (rc >= 0 && qio_channel_writev_all(s->ioc, qiov->iov, qiov->niov,
529 NULL) < 0) {
86f8cdf3
VSO
530 rc = -EIO;
531 }
532 qio_channel_set_cork(s->ioc, false);
533 } else {
534 rc = nbd_send_request(s->ioc, request);
535 }
ee19d953 536 qemu_co_mutex_unlock(&s->send_mutex);
86f8cdf3 537
86f8cdf3 538 if (rc < 0) {
ee19d953
PB
539 qemu_mutex_lock(&s->requests_lock);
540err:
dba5156c 541 nbd_channel_error_locked(s, rc);
a34b1e5e
VSO
542 if (i != -1) {
543 s->requests[i].coroutine = NULL;
f7651539 544 }
8610b449 545 s->in_flight--;
6690302b 546 qemu_co_queue_next(&s->free_sema);
ee19d953 547 qemu_mutex_unlock(&s->requests_lock);
86f8cdf3 548 }
86f8cdf3
VSO
549 return rc;
550}
551
552static inline uint16_t payload_advance16(uint8_t **payload)
553{
554 *payload += 2;
555 return lduw_be_p(*payload - 2);
556}
557
558static inline uint32_t payload_advance32(uint8_t **payload)
559{
560 *payload += 4;
561 return ldl_be_p(*payload - 4);
562}
563
564static inline uint64_t payload_advance64(uint8_t **payload)
565{
566 *payload += 8;
567 return ldq_be_p(*payload - 8);
568}
569
611ae1d7 570static int nbd_parse_offset_hole_payload(BDRVNBDState *s,
86f8cdf3
VSO
571 NBDStructuredReplyChunk *chunk,
572 uint8_t *payload, uint64_t orig_offset,
573 QEMUIOVector *qiov, Error **errp)
574{
575 uint64_t offset;
576 uint32_t hole_size;
577
578 if (chunk->length != sizeof(offset) + sizeof(hole_size)) {
579 error_setg(errp, "Protocol error: invalid payload for "
580 "NBD_REPLY_TYPE_OFFSET_HOLE");
581 return -EINVAL;
582 }
583
584 offset = payload_advance64(&payload);
585 hole_size = payload_advance32(&payload);
586
587 if (!hole_size || offset < orig_offset || hole_size > qiov->size ||
588 offset > orig_offset + qiov->size - hole_size) {
589 error_setg(errp, "Protocol error: server sent chunk exceeding requested"
590 " region");
591 return -EINVAL;
592 }
611ae1d7
VSO
593 if (s->info.min_block &&
594 !QEMU_IS_ALIGNED(hole_size, s->info.min_block)) {
86f8cdf3
VSO
595 trace_nbd_structured_read_compliance("hole");
596 }
597
598 qemu_iovec_memset(qiov, offset - orig_offset, 0, hole_size);
599
600 return 0;
601}
602
603/*
604 * nbd_parse_blockstatus_payload
605 * Based on our request, we expect only one extent in reply, for the
606 * base:allocation context.
607 */
611ae1d7 608static int nbd_parse_blockstatus_payload(BDRVNBDState *s,
86f8cdf3
VSO
609 NBDStructuredReplyChunk *chunk,
610 uint8_t *payload, uint64_t orig_length,
611 NBDExtent *extent, Error **errp)
612{
613 uint32_t context_id;
614
615 /* The server succeeded, so it must have sent [at least] one extent */
616 if (chunk->length < sizeof(context_id) + sizeof(*extent)) {
617 error_setg(errp, "Protocol error: invalid payload for "
618 "NBD_REPLY_TYPE_BLOCK_STATUS");
619 return -EINVAL;
620 }
621
622 context_id = payload_advance32(&payload);
611ae1d7 623 if (s->info.context_id != context_id) {
86f8cdf3
VSO
624 error_setg(errp, "Protocol error: unexpected context id %d for "
625 "NBD_REPLY_TYPE_BLOCK_STATUS, when negotiated context "
626 "id is %d", context_id,
611ae1d7 627 s->info.context_id);
86f8cdf3
VSO
628 return -EINVAL;
629 }
630
631 extent->length = payload_advance32(&payload);
632 extent->flags = payload_advance32(&payload);
633
634 if (extent->length == 0) {
635 error_setg(errp, "Protocol error: server sent status chunk with "
636 "zero length");
637 return -EINVAL;
638 }
639
640 /*
641 * A server sending unaligned block status is in violation of the
642 * protocol, but as qemu-nbd 3.1 is such a server (at least for
643 * POSIX files that are not a multiple of 512 bytes, since qemu
644 * rounds files up to 512-byte multiples but lseek(SEEK_HOLE)
645 * still sees an implicit hole beyond the real EOF), it's nicer to
646 * work around the misbehaving server. If the request included
647 * more than the final unaligned block, truncate it back to an
648 * aligned result; if the request was only the final block, round
649 * up to the full block and change the status to fully-allocated
650 * (always a safe status, even if it loses information).
651 */
611ae1d7
VSO
652 if (s->info.min_block && !QEMU_IS_ALIGNED(extent->length,
653 s->info.min_block)) {
86f8cdf3 654 trace_nbd_parse_blockstatus_compliance("extent length is unaligned");
611ae1d7 655 if (extent->length > s->info.min_block) {
86f8cdf3 656 extent->length = QEMU_ALIGN_DOWN(extent->length,
611ae1d7 657 s->info.min_block);
86f8cdf3 658 } else {
611ae1d7 659 extent->length = s->info.min_block;
86f8cdf3
VSO
660 extent->flags = 0;
661 }
662 }
663
664 /*
665 * We used NBD_CMD_FLAG_REQ_ONE, so the server should not have
666 * sent us any more than one extent, nor should it have included
667 * status beyond our request in that extent. However, it's easy
668 * enough to ignore the server's noncompliance without killing the
669 * connection; just ignore trailing extents, and clamp things to
670 * the length of our request.
671 */
672 if (chunk->length > sizeof(context_id) + sizeof(*extent)) {
673 trace_nbd_parse_blockstatus_compliance("more than one extent");
674 }
675 if (extent->length > orig_length) {
676 extent->length = orig_length;
677 trace_nbd_parse_blockstatus_compliance("extent length too large");
678 }
679
dbc7b014
EB
680 /*
681 * HACK: if we are using x-dirty-bitmaps to access
682 * qemu:allocation-depth, treat all depths > 2 the same as 2,
683 * since nbd_client_co_block_status is only expecting the low two
684 * bits to be set.
685 */
686 if (s->alloc_depth && extent->flags > 2) {
687 extent->flags = 2;
688 }
689
86f8cdf3
VSO
690 return 0;
691}
692
693/*
694 * nbd_parse_error_payload
695 * on success @errp contains message describing nbd error reply
696 */
697static int nbd_parse_error_payload(NBDStructuredReplyChunk *chunk,
698 uint8_t *payload, int *request_ret,
699 Error **errp)
700{
701 uint32_t error;
702 uint16_t message_size;
703
704 assert(chunk->type & (1 << 15));
705
706 if (chunk->length < sizeof(error) + sizeof(message_size)) {
707 error_setg(errp,
708 "Protocol error: invalid payload for structured error");
709 return -EINVAL;
710 }
711
712 error = nbd_errno_to_system_errno(payload_advance32(&payload));
713 if (error == 0) {
714 error_setg(errp, "Protocol error: server sent structured error chunk "
715 "with error = 0");
716 return -EINVAL;
717 }
718
719 *request_ret = -error;
720 message_size = payload_advance16(&payload);
721
722 if (message_size > chunk->length - sizeof(error) - sizeof(message_size)) {
723 error_setg(errp, "Protocol error: server sent structured error chunk "
724 "with incorrect message size");
725 return -EINVAL;
726 }
727
728 /* TODO: Add a trace point to mention the server complaint */
729
730 /* TODO handle ERROR_OFFSET */
731
732 return 0;
733}
734
0c43c6fc
PB
735static int coroutine_fn
736nbd_co_receive_offset_data_payload(BDRVNBDState *s, uint64_t orig_offset,
737 QEMUIOVector *qiov, Error **errp)
86f8cdf3
VSO
738{
739 QEMUIOVector sub_qiov;
740 uint64_t offset;
741 size_t data_size;
742 int ret;
743 NBDStructuredReplyChunk *chunk = &s->reply.structured;
744
745 assert(nbd_reply_is_structured(&s->reply));
746
747 /* The NBD spec requires at least one byte of payload */
748 if (chunk->length <= sizeof(offset)) {
749 error_setg(errp, "Protocol error: invalid payload for "
750 "NBD_REPLY_TYPE_OFFSET_DATA");
751 return -EINVAL;
752 }
753
754 if (nbd_read64(s->ioc, &offset, "OFFSET_DATA offset", errp) < 0) {
755 return -EIO;
756 }
757
758 data_size = chunk->length - sizeof(offset);
759 assert(data_size);
760 if (offset < orig_offset || data_size > qiov->size ||
761 offset > orig_offset + qiov->size - data_size) {
762 error_setg(errp, "Protocol error: server sent chunk exceeding requested"
763 " region");
764 return -EINVAL;
765 }
766 if (s->info.min_block && !QEMU_IS_ALIGNED(data_size, s->info.min_block)) {
767 trace_nbd_structured_read_compliance("data");
768 }
769
770 qemu_iovec_init(&sub_qiov, qiov->niov);
771 qemu_iovec_concat(&sub_qiov, qiov, offset - orig_offset, data_size);
772 ret = qio_channel_readv_all(s->ioc, sub_qiov.iov, sub_qiov.niov, errp);
773 qemu_iovec_destroy(&sub_qiov);
774
775 return ret < 0 ? -EIO : 0;
776}
777
778#define NBD_MAX_MALLOC_PAYLOAD 1000
779static coroutine_fn int nbd_co_receive_structured_payload(
611ae1d7 780 BDRVNBDState *s, void **payload, Error **errp)
86f8cdf3
VSO
781{
782 int ret;
783 uint32_t len;
784
785 assert(nbd_reply_is_structured(&s->reply));
786
787 len = s->reply.structured.length;
788
789 if (len == 0) {
790 return 0;
791 }
792
793 if (payload == NULL) {
794 error_setg(errp, "Unexpected structured payload");
795 return -EINVAL;
796 }
797
798 if (len > NBD_MAX_MALLOC_PAYLOAD) {
799 error_setg(errp, "Payload too large");
800 return -EINVAL;
801 }
802
803 *payload = g_new(char, len);
804 ret = nbd_read(s->ioc, *payload, len, "structured payload", errp);
805 if (ret < 0) {
806 g_free(*payload);
807 *payload = NULL;
808 return ret;
809 }
810
811 return 0;
812}
813
814/*
815 * nbd_co_do_receive_one_chunk
816 * for simple reply:
817 * set request_ret to received reply error
818 * if qiov is not NULL: read payload to @qiov
819 * for structured reply chunk:
820 * if error chunk: read payload, set @request_ret, do not set @payload
821 * else if offset_data chunk: read payload data to @qiov, do not set @payload
822 * else: read payload to @payload
823 *
824 * If function fails, @errp contains corresponding error message, and the
825 * connection with the server is suspect. If it returns 0, then the
826 * transaction succeeded (although @request_ret may be a negative errno
827 * corresponding to the server's error reply), and errp is unchanged.
828 */
829static coroutine_fn int nbd_co_do_receive_one_chunk(
611ae1d7 830 BDRVNBDState *s, uint64_t handle, bool only_structured,
86f8cdf3
VSO
831 int *request_ret, QEMUIOVector *qiov, void **payload, Error **errp)
832{
833 int ret;
834 int i = HANDLE_TO_INDEX(s, handle);
835 void *local_payload = NULL;
836 NBDStructuredReplyChunk *chunk;
837
838 if (payload) {
839 *payload = NULL;
840 }
841 *request_ret = 0;
842
172f5f1a
PB
843 ret = nbd_receive_replies(s, handle);
844 if (ret < 0) {
86f8cdf3
VSO
845 error_setg(errp, "Connection closed");
846 return -EIO;
847 }
848 assert(s->ioc);
849
850 assert(s->reply.handle == handle);
851
852 if (nbd_reply_is_simple(&s->reply)) {
853 if (only_structured) {
854 error_setg(errp, "Protocol error: simple reply when structured "
855 "reply chunk was expected");
856 return -EINVAL;
857 }
858
859 *request_ret = -nbd_errno_to_system_errno(s->reply.simple.error);
860 if (*request_ret < 0 || !qiov) {
861 return 0;
862 }
863
864 return qio_channel_readv_all(s->ioc, qiov->iov, qiov->niov,
865 errp) < 0 ? -EIO : 0;
866 }
867
868 /* handle structured reply chunk */
869 assert(s->info.structured_reply);
870 chunk = &s->reply.structured;
871
872 if (chunk->type == NBD_REPLY_TYPE_NONE) {
873 if (!(chunk->flags & NBD_REPLY_FLAG_DONE)) {
874 error_setg(errp, "Protocol error: NBD_REPLY_TYPE_NONE chunk without"
875 " NBD_REPLY_FLAG_DONE flag set");
876 return -EINVAL;
877 }
878 if (chunk->length) {
879 error_setg(errp, "Protocol error: NBD_REPLY_TYPE_NONE chunk with"
880 " nonzero length");
881 return -EINVAL;
882 }
883 return 0;
884 }
885
886 if (chunk->type == NBD_REPLY_TYPE_OFFSET_DATA) {
887 if (!qiov) {
888 error_setg(errp, "Unexpected NBD_REPLY_TYPE_OFFSET_DATA chunk");
889 return -EINVAL;
890 }
891
892 return nbd_co_receive_offset_data_payload(s, s->requests[i].offset,
893 qiov, errp);
894 }
895
896 if (nbd_reply_type_is_error(chunk->type)) {
897 payload = &local_payload;
898 }
899
900 ret = nbd_co_receive_structured_payload(s, payload, errp);
901 if (ret < 0) {
902 return ret;
903 }
904
905 if (nbd_reply_type_is_error(chunk->type)) {
906 ret = nbd_parse_error_payload(chunk, local_payload, request_ret, errp);
907 g_free(local_payload);
908 return ret;
909 }
910
911 return 0;
912}
913
914/*
915 * nbd_co_receive_one_chunk
916 * Read reply, wake up connection_co and set s->quit if needed.
917 * Return value is a fatal error code or normal nbd reply error code
918 */
919static coroutine_fn int nbd_co_receive_one_chunk(
611ae1d7 920 BDRVNBDState *s, uint64_t handle, bool only_structured,
86f8cdf3
VSO
921 int *request_ret, QEMUIOVector *qiov, NBDReply *reply, void **payload,
922 Error **errp)
923{
924 int ret = nbd_co_do_receive_one_chunk(s, handle, only_structured,
925 request_ret, qiov, payload, errp);
926
927 if (ret < 0) {
5cf42b1c 928 memset(reply, 0, sizeof(*reply));
a34b1e5e 929 nbd_channel_error(s, ret);
86f8cdf3
VSO
930 } else {
931 /* For assert at loop start in nbd_connection_entry */
5cf42b1c 932 *reply = s->reply;
86f8cdf3 933 }
f7651539 934 s->reply.handle = 0;
86f8cdf3 935
a80a9a1c 936 nbd_recv_coroutines_wake(s);
86f8cdf3
VSO
937
938 return ret;
939}
940
941typedef struct NBDReplyChunkIter {
942 int ret;
943 int request_ret;
944 Error *err;
945 bool done, only_structured;
946} NBDReplyChunkIter;
947
948static void nbd_iter_channel_error(NBDReplyChunkIter *iter,
949 int ret, Error **local_err)
950{
d9366135 951 assert(local_err && *local_err);
86f8cdf3
VSO
952 assert(ret < 0);
953
954 if (!iter->ret) {
955 iter->ret = ret;
956 error_propagate(&iter->err, *local_err);
957 } else {
958 error_free(*local_err);
959 }
960
961 *local_err = NULL;
962}
963
964static void nbd_iter_request_error(NBDReplyChunkIter *iter, int ret)
965{
966 assert(ret < 0);
967
968 if (!iter->request_ret) {
969 iter->request_ret = ret;
970 }
971}
972
973/*
974 * NBD_FOREACH_REPLY_CHUNK
975 * The pointer stored in @payload requires g_free() to free it.
976 */
977#define NBD_FOREACH_REPLY_CHUNK(s, iter, handle, structured, \
978 qiov, reply, payload) \
979 for (iter = (NBDReplyChunkIter) { .only_structured = structured }; \
980 nbd_reply_chunk_iter_receive(s, &iter, handle, qiov, reply, payload);)
981
982/*
983 * nbd_reply_chunk_iter_receive
984 * The pointer stored in @payload requires g_free() to free it.
985 */
8e5a19df
PB
986static bool coroutine_fn nbd_reply_chunk_iter_receive(BDRVNBDState *s,
987 NBDReplyChunkIter *iter,
988 uint64_t handle,
989 QEMUIOVector *qiov,
990 NBDReply *reply,
991 void **payload)
86f8cdf3
VSO
992{
993 int ret, request_ret;
994 NBDReply local_reply;
995 NBDStructuredReplyChunk *chunk;
996 Error *local_err = NULL;
86f8cdf3
VSO
997
998 if (iter->done) {
999 /* Previous iteration was last. */
1000 goto break_loop;
1001 }
1002
1003 if (reply == NULL) {
1004 reply = &local_reply;
1005 }
1006
1007 ret = nbd_co_receive_one_chunk(s, handle, iter->only_structured,
1008 &request_ret, qiov, reply, payload,
1009 &local_err);
1010 if (ret < 0) {
1011 nbd_iter_channel_error(iter, ret, &local_err);
1012 } else if (request_ret < 0) {
1013 nbd_iter_request_error(iter, request_ret);
1014 }
1015
1016 /* Do not execute the body of NBD_FOREACH_REPLY_CHUNK for simple reply. */
172f5f1a 1017 if (nbd_reply_is_simple(reply) || iter->ret < 0) {
86f8cdf3
VSO
1018 goto break_loop;
1019 }
1020
1021 chunk = &reply->structured;
1022 iter->only_structured = true;
1023
1024 if (chunk->type == NBD_REPLY_TYPE_NONE) {
1025 /* NBD_REPLY_FLAG_DONE is already checked in nbd_co_receive_one_chunk */
1026 assert(chunk->flags & NBD_REPLY_FLAG_DONE);
1027 goto break_loop;
1028 }
1029
1030 if (chunk->flags & NBD_REPLY_FLAG_DONE) {
1031 /* This iteration is last. */
1032 iter->done = true;
1033 }
1034
1035 /* Execute the loop body */
1036 return true;
1037
1038break_loop:
ee19d953 1039 qemu_mutex_lock(&s->requests_lock);
86f8cdf3 1040 s->requests[HANDLE_TO_INDEX(s, handle)].coroutine = NULL;
86f8cdf3 1041 s->in_flight--;
4ddb5d2f 1042 qemu_co_queue_next(&s->free_sema);
ee19d953 1043 qemu_mutex_unlock(&s->requests_lock);
86f8cdf3
VSO
1044
1045 return false;
1046}
1047
0c43c6fc
PB
1048static int coroutine_fn nbd_co_receive_return_code(BDRVNBDState *s, uint64_t handle,
1049 int *request_ret, Error **errp)
86f8cdf3
VSO
1050{
1051 NBDReplyChunkIter iter;
1052
1053 NBD_FOREACH_REPLY_CHUNK(s, iter, handle, false, NULL, NULL, NULL) {
1054 /* nbd_reply_chunk_iter_receive does all the work */
1055 }
1056
1057 error_propagate(errp, iter.err);
1058 *request_ret = iter.request_ret;
1059 return iter.ret;
1060}
1061
0c43c6fc
PB
1062static int coroutine_fn nbd_co_receive_cmdread_reply(BDRVNBDState *s, uint64_t handle,
1063 uint64_t offset, QEMUIOVector *qiov,
1064 int *request_ret, Error **errp)
86f8cdf3
VSO
1065{
1066 NBDReplyChunkIter iter;
1067 NBDReply reply;
1068 void *payload = NULL;
1069 Error *local_err = NULL;
1070
1071 NBD_FOREACH_REPLY_CHUNK(s, iter, handle, s->info.structured_reply,
1072 qiov, &reply, &payload)
1073 {
1074 int ret;
1075 NBDStructuredReplyChunk *chunk = &reply.structured;
1076
1077 assert(nbd_reply_is_structured(&reply));
1078
1079 switch (chunk->type) {
1080 case NBD_REPLY_TYPE_OFFSET_DATA:
1081 /*
1082 * special cased in nbd_co_receive_one_chunk, data is already
1083 * in qiov
1084 */
1085 break;
1086 case NBD_REPLY_TYPE_OFFSET_HOLE:
1087 ret = nbd_parse_offset_hole_payload(s, &reply.structured, payload,
1088 offset, qiov, &local_err);
1089 if (ret < 0) {
a34b1e5e 1090 nbd_channel_error(s, ret);
86f8cdf3
VSO
1091 nbd_iter_channel_error(&iter, ret, &local_err);
1092 }
1093 break;
1094 default:
1095 if (!nbd_reply_type_is_error(chunk->type)) {
1096 /* not allowed reply type */
a34b1e5e 1097 nbd_channel_error(s, -EINVAL);
86f8cdf3
VSO
1098 error_setg(&local_err,
1099 "Unexpected reply type: %d (%s) for CMD_READ",
1100 chunk->type, nbd_reply_type_lookup(chunk->type));
1101 nbd_iter_channel_error(&iter, -EINVAL, &local_err);
1102 }
1103 }
1104
1105 g_free(payload);
1106 payload = NULL;
1107 }
1108
1109 error_propagate(errp, iter.err);
1110 *request_ret = iter.request_ret;
1111 return iter.ret;
1112}
1113
0c43c6fc
PB
1114static int coroutine_fn nbd_co_receive_blockstatus_reply(BDRVNBDState *s,
1115 uint64_t handle, uint64_t length,
1116 NBDExtent *extent,
1117 int *request_ret, Error **errp)
86f8cdf3
VSO
1118{
1119 NBDReplyChunkIter iter;
1120 NBDReply reply;
1121 void *payload = NULL;
1122 Error *local_err = NULL;
1123 bool received = false;
1124
1125 assert(!extent->length);
1126 NBD_FOREACH_REPLY_CHUNK(s, iter, handle, false, NULL, &reply, &payload) {
1127 int ret;
1128 NBDStructuredReplyChunk *chunk = &reply.structured;
1129
1130 assert(nbd_reply_is_structured(&reply));
1131
1132 switch (chunk->type) {
1133 case NBD_REPLY_TYPE_BLOCK_STATUS:
1134 if (received) {
a34b1e5e 1135 nbd_channel_error(s, -EINVAL);
86f8cdf3
VSO
1136 error_setg(&local_err, "Several BLOCK_STATUS chunks in reply");
1137 nbd_iter_channel_error(&iter, -EINVAL, &local_err);
1138 }
1139 received = true;
1140
1141 ret = nbd_parse_blockstatus_payload(s, &reply.structured,
1142 payload, length, extent,
1143 &local_err);
1144 if (ret < 0) {
a34b1e5e 1145 nbd_channel_error(s, ret);
86f8cdf3
VSO
1146 nbd_iter_channel_error(&iter, ret, &local_err);
1147 }
1148 break;
1149 default:
1150 if (!nbd_reply_type_is_error(chunk->type)) {
a34b1e5e 1151 nbd_channel_error(s, -EINVAL);
86f8cdf3
VSO
1152 error_setg(&local_err,
1153 "Unexpected reply type: %d (%s) "
1154 "for CMD_BLOCK_STATUS",
1155 chunk->type, nbd_reply_type_lookup(chunk->type));
1156 nbd_iter_channel_error(&iter, -EINVAL, &local_err);
1157 }
1158 }
1159
1160 g_free(payload);
1161 payload = NULL;
1162 }
1163
1164 if (!extent->length && !iter.request_ret) {
1165 error_setg(&local_err, "Server did not reply with any status extents");
1166 nbd_iter_channel_error(&iter, -EIO, &local_err);
1167 }
1168
1169 error_propagate(errp, iter.err);
1170 *request_ret = iter.request_ret;
1171 return iter.ret;
1172}
1173
0c43c6fc
PB
1174static int coroutine_fn nbd_co_request(BlockDriverState *bs, NBDRequest *request,
1175 QEMUIOVector *write_qiov)
86f8cdf3
VSO
1176{
1177 int ret, request_ret;
1178 Error *local_err = NULL;
611ae1d7 1179 BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
86f8cdf3
VSO
1180
1181 assert(request->type != NBD_CMD_READ);
1182 if (write_qiov) {
1183 assert(request->type == NBD_CMD_WRITE);
1184 assert(request->len == iov_size(write_qiov->iov, write_qiov->niov));
1185 } else {
1186 assert(request->type != NBD_CMD_WRITE);
1187 }
86f8cdf3 1188
f7651539
VSO
1189 do {
1190 ret = nbd_co_send_request(bs, request, write_qiov);
1191 if (ret < 0) {
1192 continue;
1193 }
1194
1195 ret = nbd_co_receive_return_code(s, request->handle,
1196 &request_ret, &local_err);
1197 if (local_err) {
1198 trace_nbd_co_request_fail(request->from, request->len,
1199 request->handle, request->flags,
1200 request->type,
1201 nbd_cmd_lookup(request->type),
1202 ret, error_get_pretty(local_err));
1203 error_free(local_err);
1204 local_err = NULL;
1205 }
8d45185c 1206 } while (ret < 0 && nbd_client_will_reconnect(s));
f7651539 1207
86f8cdf3
VSO
1208 return ret ? ret : request_ret;
1209}
1210
0c43c6fc
PB
1211static int coroutine_fn nbd_client_co_preadv(BlockDriverState *bs, int64_t offset,
1212 int64_t bytes, QEMUIOVector *qiov,
1213 BdrvRequestFlags flags)
86f8cdf3
VSO
1214{
1215 int ret, request_ret;
1216 Error *local_err = NULL;
611ae1d7 1217 BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
86f8cdf3
VSO
1218 NBDRequest request = {
1219 .type = NBD_CMD_READ,
1220 .from = offset,
1221 .len = bytes,
1222 };
1223
1224 assert(bytes <= NBD_MAX_BUFFER_SIZE);
1225 assert(!flags);
1226
1227 if (!bytes) {
1228 return 0;
1229 }
1230 /*
1231 * Work around the fact that the block layer doesn't do
1232 * byte-accurate sizing yet - if the read exceeds the server's
1233 * advertised size because the block layer rounded size up, then
1234 * truncate the request to the server and tail-pad with zero.
1235 */
611ae1d7 1236 if (offset >= s->info.size) {
86f8cdf3
VSO
1237 assert(bytes < BDRV_SECTOR_SIZE);
1238 qemu_iovec_memset(qiov, 0, 0, bytes);
1239 return 0;
1240 }
611ae1d7
VSO
1241 if (offset + bytes > s->info.size) {
1242 uint64_t slop = offset + bytes - s->info.size;
86f8cdf3
VSO
1243
1244 assert(slop < BDRV_SECTOR_SIZE);
1245 qemu_iovec_memset(qiov, bytes - slop, 0, slop);
1246 request.len -= slop;
1247 }
1248
f7651539
VSO
1249 do {
1250 ret = nbd_co_send_request(bs, &request, NULL);
1251 if (ret < 0) {
1252 continue;
1253 }
1254
1255 ret = nbd_co_receive_cmdread_reply(s, request.handle, offset, qiov,
1256 &request_ret, &local_err);
1257 if (local_err) {
1258 trace_nbd_co_request_fail(request.from, request.len, request.handle,
1259 request.flags, request.type,
1260 nbd_cmd_lookup(request.type),
1261 ret, error_get_pretty(local_err));
1262 error_free(local_err);
1263 local_err = NULL;
1264 }
8d45185c 1265 } while (ret < 0 && nbd_client_will_reconnect(s));
86f8cdf3 1266
86f8cdf3
VSO
1267 return ret ? ret : request_ret;
1268}
1269
0c43c6fc
PB
1270static int coroutine_fn nbd_client_co_pwritev(BlockDriverState *bs, int64_t offset,
1271 int64_t bytes, QEMUIOVector *qiov,
1272 BdrvRequestFlags flags)
86f8cdf3 1273{
611ae1d7 1274 BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
86f8cdf3
VSO
1275 NBDRequest request = {
1276 .type = NBD_CMD_WRITE,
1277 .from = offset,
1278 .len = bytes,
1279 };
1280
611ae1d7 1281 assert(!(s->info.flags & NBD_FLAG_READ_ONLY));
86f8cdf3 1282 if (flags & BDRV_REQ_FUA) {
611ae1d7 1283 assert(s->info.flags & NBD_FLAG_SEND_FUA);
86f8cdf3
VSO
1284 request.flags |= NBD_CMD_FLAG_FUA;
1285 }
1286
1287 assert(bytes <= NBD_MAX_BUFFER_SIZE);
1288
1289 if (!bytes) {
1290 return 0;
1291 }
1292 return nbd_co_request(bs, &request, qiov);
1293}
1294
0c43c6fc
PB
1295static int coroutine_fn nbd_client_co_pwrite_zeroes(BlockDriverState *bs, int64_t offset,
1296 int64_t bytes, BdrvRequestFlags flags)
86f8cdf3 1297{
611ae1d7 1298 BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
86f8cdf3
VSO
1299 NBDRequest request = {
1300 .type = NBD_CMD_WRITE_ZEROES,
1301 .from = offset,
f34b2bcf 1302 .len = bytes, /* .len is uint32_t actually */
86f8cdf3
VSO
1303 };
1304
f34b2bcf
VSO
1305 assert(bytes <= UINT32_MAX); /* rely on max_pwrite_zeroes */
1306
611ae1d7
VSO
1307 assert(!(s->info.flags & NBD_FLAG_READ_ONLY));
1308 if (!(s->info.flags & NBD_FLAG_SEND_WRITE_ZEROES)) {
86f8cdf3
VSO
1309 return -ENOTSUP;
1310 }
1311
1312 if (flags & BDRV_REQ_FUA) {
611ae1d7 1313 assert(s->info.flags & NBD_FLAG_SEND_FUA);
86f8cdf3
VSO
1314 request.flags |= NBD_CMD_FLAG_FUA;
1315 }
1316 if (!(flags & BDRV_REQ_MAY_UNMAP)) {
1317 request.flags |= NBD_CMD_FLAG_NO_HOLE;
1318 }
f061656c
EB
1319 if (flags & BDRV_REQ_NO_FALLBACK) {
1320 assert(s->info.flags & NBD_FLAG_SEND_FAST_ZERO);
1321 request.flags |= NBD_CMD_FLAG_FAST_ZERO;
1322 }
86f8cdf3
VSO
1323
1324 if (!bytes) {
1325 return 0;
1326 }
1327 return nbd_co_request(bs, &request, NULL);
1328}
1329
0c43c6fc 1330static int coroutine_fn nbd_client_co_flush(BlockDriverState *bs)
86f8cdf3 1331{
611ae1d7 1332 BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
86f8cdf3
VSO
1333 NBDRequest request = { .type = NBD_CMD_FLUSH };
1334
611ae1d7 1335 if (!(s->info.flags & NBD_FLAG_SEND_FLUSH)) {
86f8cdf3
VSO
1336 return 0;
1337 }
1338
1339 request.from = 0;
1340 request.len = 0;
1341
1342 return nbd_co_request(bs, &request, NULL);
1343}
1344
0c43c6fc
PB
1345static int coroutine_fn nbd_client_co_pdiscard(BlockDriverState *bs, int64_t offset,
1346 int64_t bytes)
86f8cdf3 1347{
611ae1d7 1348 BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
86f8cdf3
VSO
1349 NBDRequest request = {
1350 .type = NBD_CMD_TRIM,
1351 .from = offset,
0c802287 1352 .len = bytes, /* len is uint32_t */
86f8cdf3
VSO
1353 };
1354
0c802287
VSO
1355 assert(bytes <= UINT32_MAX); /* rely on max_pdiscard */
1356
611ae1d7
VSO
1357 assert(!(s->info.flags & NBD_FLAG_READ_ONLY));
1358 if (!(s->info.flags & NBD_FLAG_SEND_TRIM) || !bytes) {
86f8cdf3
VSO
1359 return 0;
1360 }
1361
1362 return nbd_co_request(bs, &request, NULL);
1363}
1364
1365static int coroutine_fn nbd_client_co_block_status(
1366 BlockDriverState *bs, bool want_zero, int64_t offset, int64_t bytes,
1367 int64_t *pnum, int64_t *map, BlockDriverState **file)
1368{
1369 int ret, request_ret;
1370 NBDExtent extent = { 0 };
611ae1d7 1371 BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
86f8cdf3
VSO
1372 Error *local_err = NULL;
1373
1374 NBDRequest request = {
1375 .type = NBD_CMD_BLOCK_STATUS,
1376 .from = offset,
6bf792b4 1377 .len = MIN(QEMU_ALIGN_DOWN(INT_MAX, bs->bl.request_alignment),
611ae1d7 1378 MIN(bytes, s->info.size - offset)),
86f8cdf3
VSO
1379 .flags = NBD_CMD_FLAG_REQ_ONE,
1380 };
1381
611ae1d7 1382 if (!s->info.base_allocation) {
86f8cdf3
VSO
1383 *pnum = bytes;
1384 *map = offset;
1385 *file = bs;
1386 return BDRV_BLOCK_DATA | BDRV_BLOCK_OFFSET_VALID;
1387 }
1388
1389 /*
1390 * Work around the fact that the block layer doesn't do
1391 * byte-accurate sizing yet - if the status request exceeds the
1392 * server's advertised size because the block layer rounded size
1393 * up, we truncated the request to the server (above), or are
1394 * called on just the hole.
1395 */
611ae1d7 1396 if (offset >= s->info.size) {
86f8cdf3
VSO
1397 *pnum = bytes;
1398 assert(bytes < BDRV_SECTOR_SIZE);
1399 /* Intentionally don't report offset_valid for the hole */
1400 return BDRV_BLOCK_ZERO;
1401 }
1402
611ae1d7
VSO
1403 if (s->info.min_block) {
1404 assert(QEMU_IS_ALIGNED(request.len, s->info.min_block));
86f8cdf3 1405 }
f7651539
VSO
1406 do {
1407 ret = nbd_co_send_request(bs, &request, NULL);
1408 if (ret < 0) {
1409 continue;
1410 }
1411
1412 ret = nbd_co_receive_blockstatus_reply(s, request.handle, bytes,
1413 &extent, &request_ret,
1414 &local_err);
1415 if (local_err) {
1416 trace_nbd_co_request_fail(request.from, request.len, request.handle,
1417 request.flags, request.type,
1418 nbd_cmd_lookup(request.type),
1419 ret, error_get_pretty(local_err));
1420 error_free(local_err);
1421 local_err = NULL;
1422 }
8d45185c 1423 } while (ret < 0 && nbd_client_will_reconnect(s));
86f8cdf3 1424
86f8cdf3
VSO
1425 if (ret < 0 || request_ret < 0) {
1426 return ret ? ret : request_ret;
1427 }
1428
1429 assert(extent.length);
1430 *pnum = extent.length;
1431 *map = offset;
1432 *file = bs;
1433 return (extent.flags & NBD_STATE_HOLE ? 0 : BDRV_BLOCK_DATA) |
1434 (extent.flags & NBD_STATE_ZERO ? BDRV_BLOCK_ZERO : 0) |
1435 BDRV_BLOCK_OFFSET_VALID;
1436}
1437
e99754b4
ML
1438static int nbd_client_reopen_prepare(BDRVReopenState *state,
1439 BlockReopenQueue *queue, Error **errp)
1440{
1441 BDRVNBDState *s = (BDRVNBDState *)state->bs->opaque;
1442
1443 if ((state->flags & BDRV_O_RDWR) && (s->info.flags & NBD_FLAG_READ_ONLY)) {
1444 error_setg(errp, "Can't reopen read-only NBD mount as read/write");
1445 return -EACCES;
1446 }
1447 return 0;
1448}
1449
fee091cd
LS
1450static void nbd_yank(void *opaque)
1451{
1452 BlockDriverState *bs = opaque;
1453 BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
1454
dba5156c 1455 QEMU_LOCK_GUARD(&s->requests_lock);
95a078ea 1456 qio_channel_shutdown(QIO_CHANNEL(s->ioc), QIO_CHANNEL_SHUTDOWN_BOTH, NULL);
dba5156c 1457 s->state = NBD_CLIENT_QUIT;
fee091cd
LS
1458}
1459
86f8cdf3
VSO
1460static void nbd_client_close(BlockDriverState *bs)
1461{
611ae1d7 1462 BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
86f8cdf3
VSO
1463 NBDRequest request = { .type = NBD_CMD_DISC };
1464
f7651539
VSO
1465 if (s->ioc) {
1466 nbd_send_request(s->ioc, &request);
1467 }
86f8cdf3
VSO
1468
1469 nbd_teardown_connection(bs);
1470}
1471
86f8cdf3 1472
8f071c9d
VSO
1473/*
1474 * Parse nbd_open options
1475 */
86f8cdf3 1476
f53a1feb 1477static int nbd_parse_uri(const char *filename, QDict *options)
1d7d2a9d
PB
1478{
1479 URI *uri;
1480 const char *p;
1481 QueryParams *qp = NULL;
1482 int ret = 0;
f53a1feb 1483 bool is_unix;
1d7d2a9d
PB
1484
1485 uri = uri_parse(filename);
1486 if (!uri) {
1487 return -EINVAL;
1488 }
1489
1490 /* transport */
f69165a8 1491 if (!g_strcmp0(uri->scheme, "nbd")) {
f53a1feb 1492 is_unix = false;
f69165a8 1493 } else if (!g_strcmp0(uri->scheme, "nbd+tcp")) {
f53a1feb 1494 is_unix = false;
f69165a8 1495 } else if (!g_strcmp0(uri->scheme, "nbd+unix")) {
f53a1feb 1496 is_unix = true;
1d7d2a9d
PB
1497 } else {
1498 ret = -EINVAL;
1499 goto out;
1500 }
1501
2485f22f
EB
1502 p = uri->path ? uri->path : "";
1503 if (p[0] == '/') {
1504 p++;
1505 }
1d7d2a9d 1506 if (p[0]) {
46f5ac20 1507 qdict_put_str(options, "export", p);
1d7d2a9d
PB
1508 }
1509
1510 qp = query_params_parse(uri->query);
f53a1feb 1511 if (qp->n > 1 || (is_unix && !qp->n) || (!is_unix && qp->n)) {
1d7d2a9d
PB
1512 ret = -EINVAL;
1513 goto out;
1514 }
1515
f53a1feb 1516 if (is_unix) {
1d7d2a9d
PB
1517 /* nbd+unix:///export?socket=path */
1518 if (uri->server || uri->port || strcmp(qp->p[0].name, "socket")) {
1519 ret = -EINVAL;
1520 goto out;
1521 }
46f5ac20
EB
1522 qdict_put_str(options, "server.type", "unix");
1523 qdict_put_str(options, "server.path", qp->p[0].value);
1d7d2a9d 1524 } else {
23307908 1525 QString *host;
f84d431b
HR
1526 char *port_str;
1527
bebbf7fa 1528 /* nbd[+tcp]://host[:port]/export */
1d7d2a9d
PB
1529 if (!uri->server) {
1530 ret = -EINVAL;
1531 goto out;
1532 }
f17c90be 1533
23307908
JT
1534 /* strip braces from literal IPv6 address */
1535 if (uri->server[0] == '[') {
1536 host = qstring_from_substr(uri->server, 1,
ba891d68 1537 strlen(uri->server) - 1);
23307908
JT
1538 } else {
1539 host = qstring_from_str(uri->server);
1540 }
1541
46f5ac20 1542 qdict_put_str(options, "server.type", "inet");
9445673e 1543 qdict_put(options, "server.host", host);
f84d431b
HR
1544
1545 port_str = g_strdup_printf("%d", uri->port ?: NBD_DEFAULT_PORT);
46f5ac20 1546 qdict_put_str(options, "server.port", port_str);
f84d431b 1547 g_free(port_str);
1d7d2a9d
PB
1548 }
1549
1550out:
1551 if (qp) {
1552 query_params_free(qp);
1553 }
1554 uri_free(uri);
1555 return ret;
1556}
1557
48c38e0b
HR
1558static bool nbd_has_filename_options_conflict(QDict *options, Error **errp)
1559{
1560 const QDictEntry *e;
1561
1562 for (e = qdict_first(options); e; e = qdict_next(options, e)) {
1563 if (!strcmp(e->key, "host") ||
1564 !strcmp(e->key, "port") ||
1565 !strcmp(e->key, "path") ||
491d6c7c
HR
1566 !strcmp(e->key, "export") ||
1567 strstart(e->key, "server.", NULL))
48c38e0b
HR
1568 {
1569 error_setg(errp, "Option '%s' cannot be used with a file name",
1570 e->key);
1571 return true;
1572 }
1573 }
1574
1575 return false;
1576}
1577
6963a30d
KW
1578static void nbd_parse_filename(const char *filename, QDict *options,
1579 Error **errp)
75818250 1580{
df18c04e 1581 g_autofree char *file = NULL;
33897dc7
NT
1582 char *export_name;
1583 const char *host_spec;
75818250 1584 const char *unixpath;
75818250 1585
48c38e0b 1586 if (nbd_has_filename_options_conflict(options, errp)) {
681e7ad0
KW
1587 return;
1588 }
1589
1d7d2a9d 1590 if (strstr(filename, "://")) {
6963a30d
KW
1591 int ret = nbd_parse_uri(filename, options);
1592 if (ret < 0) {
1593 error_setg(errp, "No valid URL specified");
1594 }
1595 return;
1d7d2a9d
PB
1596 }
1597
7267c094 1598 file = g_strdup(filename);
1d45f8b5 1599
33897dc7
NT
1600 export_name = strstr(file, EN_OPTSTR);
1601 if (export_name) {
1602 if (export_name[strlen(EN_OPTSTR)] == 0) {
df18c04e 1603 return;
1d45f8b5 1604 }
33897dc7
NT
1605 export_name[0] = 0; /* truncate 'file' */
1606 export_name += strlen(EN_OPTSTR);
f53a1feb 1607
46f5ac20 1608 qdict_put_str(options, "export", export_name);
1d45f8b5
LV
1609 }
1610
33897dc7
NT
1611 /* extract the host_spec - fail if it's not nbd:... */
1612 if (!strstart(file, "nbd:", &host_spec)) {
6963a30d 1613 error_setg(errp, "File name string for NBD must start with 'nbd:'");
df18c04e 1614 return;
1d45f8b5 1615 }
75818250 1616
f53a1feb 1617 if (!*host_spec) {
df18c04e 1618 return;
f53a1feb
KW
1619 }
1620
33897dc7
NT
1621 /* are we a UNIX or TCP socket? */
1622 if (strstart(host_spec, "unix:", &unixpath)) {
46f5ac20
EB
1623 qdict_put_str(options, "server.type", "unix");
1624 qdict_put_str(options, "server.path", unixpath);
75818250 1625 } else {
0785bd7a 1626 InetSocketAddress *addr = g_new(InetSocketAddress, 1);
f53a1feb 1627
0785bd7a
MA
1628 if (inet_parse(addr, host_spec, errp)) {
1629 goto out_inet;
f17c90be 1630 }
75818250 1631
46f5ac20
EB
1632 qdict_put_str(options, "server.type", "inet");
1633 qdict_put_str(options, "server.host", addr->host);
1634 qdict_put_str(options, "server.port", addr->port);
0785bd7a 1635 out_inet:
f53a1feb
KW
1636 qapi_free_InetSocketAddress(addr);
1637 }
f53a1feb
KW
1638}
1639
491d6c7c
HR
1640static bool nbd_process_legacy_socket_options(QDict *output_options,
1641 QemuOpts *legacy_opts,
1642 Error **errp)
f53a1feb 1643{
491d6c7c
HR
1644 const char *path = qemu_opt_get(legacy_opts, "path");
1645 const char *host = qemu_opt_get(legacy_opts, "host");
1646 const char *port = qemu_opt_get(legacy_opts, "port");
1647 const QDictEntry *e;
f53a1feb 1648
491d6c7c
HR
1649 if (!path && !host && !port) {
1650 return true;
1651 }
03504d05 1652
491d6c7c
HR
1653 for (e = qdict_first(output_options); e; e = qdict_next(output_options, e))
1654 {
1655 if (strstart(e->key, "server.", NULL)) {
1656 error_setg(errp, "Cannot use 'server' and path/host/port at the "
1657 "same time");
1658 return false;
681e7ad0 1659 }
33897dc7 1660 }
491d6c7c
HR
1661
1662 if (path && host) {
1663 error_setg(errp, "path and host may not be used at the same time");
1664 return false;
1665 } else if (path) {
1666 if (port) {
1667 error_setg(errp, "port may not be used without host");
1668 return false;
1669 }
1670
46f5ac20
EB
1671 qdict_put_str(output_options, "server.type", "unix");
1672 qdict_put_str(output_options, "server.path", path);
491d6c7c 1673 } else if (host) {
46f5ac20
EB
1674 qdict_put_str(output_options, "server.type", "inet");
1675 qdict_put_str(output_options, "server.host", host);
1676 qdict_put_str(output_options, "server.port",
1677 port ?: stringify(NBD_DEFAULT_PORT));
442045cb 1678 }
f53a1feb 1679
491d6c7c
HR
1680 return true;
1681}
f53a1feb 1682
62cf396b
MA
1683static SocketAddress *nbd_config(BDRVNBDState *s, QDict *options,
1684 Error **errp)
491d6c7c 1685{
62cf396b 1686 SocketAddress *saddr = NULL;
491d6c7c 1687 QDict *addr = NULL;
491d6c7c 1688 Visitor *iv = NULL;
491d6c7c
HR
1689
1690 qdict_extract_subqdict(options, &addr, "server.");
1691 if (!qdict_size(addr)) {
1692 error_setg(errp, "NBD server address missing");
1693 goto done;
f53a1feb
KW
1694 }
1695
af91062e
MA
1696 iv = qobject_input_visitor_new_flat_confused(addr, errp);
1697 if (!iv) {
491d6c7c
HR
1698 goto done;
1699 }
bebbf7fa 1700
af175e85 1701 if (!visit_type_SocketAddress(iv, NULL, &saddr, errp)) {
491d6c7c
HR
1702 goto done;
1703 }
7a5ed437 1704
6cc702be
VSO
1705 if (socket_address_parse_named_fd(saddr, errp) < 0) {
1706 qapi_free_SocketAddress(saddr);
1707 saddr = NULL;
1708 goto done;
1709 }
1710
491d6c7c 1711done:
cb3e7f08 1712 qobject_unref(addr);
491d6c7c 1713 visit_free(iv);
7a5ed437 1714 return saddr;
33897dc7 1715}
1d45f8b5 1716
75822a12
DB
1717static QCryptoTLSCreds *nbd_get_tls_creds(const char *id, Error **errp)
1718{
1719 Object *obj;
1720 QCryptoTLSCreds *creds;
1721
1722 obj = object_resolve_path_component(
1723 object_get_objects_root(), id);
1724 if (!obj) {
1725 error_setg(errp, "No TLS credentials with id '%s'",
1726 id);
1727 return NULL;
1728 }
1729 creds = (QCryptoTLSCreds *)
1730 object_dynamic_cast(obj, TYPE_QCRYPTO_TLS_CREDS);
1731 if (!creds) {
1732 error_setg(errp, "Object with id '%s' is not TLS credentials",
1733 id);
1734 return NULL;
1735 }
1736
7b3b6168
PMD
1737 if (!qcrypto_tls_creds_check_endpoint(creds,
1738 QCRYPTO_TLS_CREDS_ENDPOINT_CLIENT,
1739 errp)) {
75822a12
DB
1740 return NULL;
1741 }
1742 object_ref(obj);
1743 return creds;
1744}
1745
1746
7ccc44fd
HR
1747static QemuOptsList nbd_runtime_opts = {
1748 .name = "nbd",
1749 .head = QTAILQ_HEAD_INITIALIZER(nbd_runtime_opts.head),
1750 .desc = {
1751 {
1752 .name = "host",
1753 .type = QEMU_OPT_STRING,
1754 .help = "TCP host to connect to",
1755 },
1756 {
1757 .name = "port",
1758 .type = QEMU_OPT_STRING,
1759 .help = "TCP port to connect to",
1760 },
1761 {
1762 .name = "path",
1763 .type = QEMU_OPT_STRING,
1764 .help = "Unix socket path to connect to",
1765 },
1766 {
1767 .name = "export",
1768 .type = QEMU_OPT_STRING,
1769 .help = "Name of the NBD export to open",
1770 },
1771 {
1772 .name = "tls-creds",
1773 .type = QEMU_OPT_STRING,
1774 .help = "ID of the TLS credentials to use",
1775 },
a0cd6d29
DB
1776 {
1777 .name = "tls-hostname",
1778 .type = QEMU_OPT_STRING,
1779 .help = "Override hostname for validating TLS x509 certificate",
1780 },
216ee365
EB
1781 {
1782 .name = "x-dirty-bitmap",
1783 .type = QEMU_OPT_STRING,
1784 .help = "experimental: expose named dirty bitmap in place of "
1785 "block status",
1786 },
b172ae2e
VSO
1787 {
1788 .name = "reconnect-delay",
1789 .type = QEMU_OPT_NUMBER,
1790 .help = "On an unexpected disconnect, the nbd client tries to "
1791 "connect again until succeeding or encountering a serious "
1792 "error. During the first @reconnect-delay seconds, all "
1793 "requests are paused and will be rerun on a successful "
1794 "reconnect. After that time, any delayed requests and all "
1795 "future requests before a successful reconnect will "
1796 "immediately fail. Default 0",
1797 },
be16b8bf
VSO
1798 {
1799 .name = "open-timeout",
1800 .type = QEMU_OPT_NUMBER,
1801 .help = "In seconds. If zero, the nbd driver tries the connection "
1802 "only once, and fails to open if the connection fails. "
1803 "If non-zero, the nbd driver will repeat connection "
1804 "attempts until successful or until @open-timeout seconds "
1805 "have elapsed. Default 0",
1806 },
c4365735 1807 { /* end of list */ }
7ccc44fd
HR
1808 },
1809};
1810
8f071c9d
VSO
1811static int nbd_process_options(BlockDriverState *bs, QDict *options,
1812 Error **errp)
33897dc7
NT
1813{
1814 BDRVNBDState *s = bs->opaque;
8f071c9d 1815 QemuOpts *opts;
75822a12 1816 int ret = -EINVAL;
ae255e52 1817
7ccc44fd 1818 opts = qemu_opts_create(&nbd_runtime_opts, NULL, 0, &error_abort);
af175e85 1819 if (!qemu_opts_absorb_qdict(opts, options, errp)) {
7ccc44fd
HR
1820 goto error;
1821 }
1822
62cf396b 1823 /* Translate @host, @port, and @path to a SocketAddress */
491d6c7c
HR
1824 if (!nbd_process_legacy_socket_options(options, opts, errp)) {
1825 goto error;
1826 }
1827
33897dc7 1828 /* Pop the config into our state object. Exit if invalid. */
491d6c7c
HR
1829 s->saddr = nbd_config(s, options, errp);
1830 if (!s->saddr) {
75822a12
DB
1831 goto error;
1832 }
1833
491d6c7c 1834 s->export = g_strdup(qemu_opt_get(opts, "export"));
93676c88
EB
1835 if (s->export && strlen(s->export) > NBD_MAX_STRING_SIZE) {
1836 error_setg(errp, "export name too long to send to server");
1837 goto error;
1838 }
491d6c7c 1839
03504d05
HR
1840 s->tlscredsid = g_strdup(qemu_opt_get(opts, "tls-creds"));
1841 if (s->tlscredsid) {
8f071c9d
VSO
1842 s->tlscreds = nbd_get_tls_creds(s->tlscredsid, errp);
1843 if (!s->tlscreds) {
75822a12
DB
1844 goto error;
1845 }
1846
a0cd6d29 1847 s->tlshostname = g_strdup(qemu_opt_get(opts, "tls-hostname"));
e8ae8b1a
DB
1848 if (!s->tlshostname &&
1849 s->saddr->type == SOCKET_ADDRESS_TYPE_INET) {
a0cd6d29
DB
1850 s->tlshostname = g_strdup(s->saddr->u.inet.host);
1851 }
33897dc7
NT
1852 }
1853
8f071c9d 1854 s->x_dirty_bitmap = g_strdup(qemu_opt_get(opts, "x-dirty-bitmap"));
93676c88
EB
1855 if (s->x_dirty_bitmap && strlen(s->x_dirty_bitmap) > NBD_MAX_STRING_SIZE) {
1856 error_setg(errp, "x-dirty-bitmap query too long to send to server");
1857 goto error;
1858 }
1859
8f071c9d 1860 s->reconnect_delay = qemu_opt_get_number(opts, "reconnect-delay", 0);
be16b8bf 1861 s->open_timeout = qemu_opt_get_number(opts, "open-timeout", 0);
8f071c9d
VSO
1862
1863 ret = 0;
d42f78e9 1864
75822a12 1865 error:
7ccc44fd 1866 qemu_opts_del(opts);
75822a12 1867 return ret;
e183ef75
PB
1868}
1869
8f071c9d
VSO
1870static int nbd_open(BlockDriverState *bs, QDict *options, int flags,
1871 Error **errp)
1872{
1873 int ret;
1874 BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
1875
8f071c9d 1876 s->bs = bs;
ee19d953 1877 qemu_mutex_init(&s->requests_lock);
8f071c9d 1878 qemu_co_queue_init(&s->free_sema);
ee19d953 1879 qemu_co_mutex_init(&s->send_mutex);
4ddb5d2f 1880 qemu_co_mutex_init(&s->receive_mutex);
8f071c9d 1881
fee091cd
LS
1882 if (!yank_register_instance(BLOCKDEV_YANK_INSTANCE(bs->node_name), errp)) {
1883 return -EEXIST;
1884 }
1885
bbba1c37
VSO
1886 ret = nbd_process_options(bs, options, errp);
1887 if (ret < 0) {
1888 goto fail;
1889 }
1890
6d2b0332 1891 s->conn = nbd_client_connection_new(s->saddr, true, s->export,
046f98d0
DB
1892 s->x_dirty_bitmap, s->tlscreds,
1893 s->tlshostname);
e8b35bf5 1894
be16b8bf
VSO
1895 if (s->open_timeout) {
1896 nbd_client_connection_enable_retry(s->conn);
1897 open_timer_init(s, qemu_clock_get_ns(QEMU_CLOCK_REALTIME) +
1898 s->open_timeout * NANOSECONDS_PER_SECOND);
1899 }
1900
4ddb5d2f 1901 s->state = NBD_CLIENT_CONNECTING_WAIT;
8610b449 1902 ret = nbd_do_establish_connection(bs, true, errp);
8f071c9d 1903 if (ret < 0) {
bbba1c37 1904 goto fail;
8f071c9d 1905 }
8f071c9d 1906
717be964
HR
1907 /*
1908 * The connect attempt is done, so we no longer need this timer.
1909 * Delete it, because we do not want it to be around when this node
1910 * is drained or closed.
1911 */
1912 open_timer_del(s);
1913
4ddb5d2f 1914 nbd_client_connection_enable_retry(s->conn);
8f071c9d
VSO
1915
1916 return 0;
bbba1c37
VSO
1917
1918fail:
717be964 1919 open_timer_del(s);
bbba1c37
VSO
1920 nbd_clear_bdrvstate(bs);
1921 return ret;
8f071c9d
VSO
1922}
1923
0c43c6fc 1924static int coroutine_fn nbd_co_flush(BlockDriverState *bs)
1486d04a 1925{
f53a829b 1926 return nbd_client_co_flush(bs);
1486d04a
PB
1927}
1928
fa21e6fa
DL
1929static void nbd_refresh_limits(BlockDriverState *bs, Error **errp)
1930{
611ae1d7 1931 BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
fd8d372d 1932 uint32_t min = s->info.min_block;
081dd1fe
EB
1933 uint32_t max = MIN_NON_ZERO(NBD_MAX_BUFFER_SIZE, s->info.max_block);
1934
7da537f7
EB
1935 /*
1936 * If the server did not advertise an alignment:
1937 * - a size that is not sector-aligned implies that an alignment
1938 * of 1 can be used to access those tail bytes
1939 * - advertisement of block status requires an alignment of 1, so
1940 * that we don't violate block layer constraints that block
1941 * status is always aligned (as we can't control whether the
1942 * server will report sub-sector extents, such as a hole at EOF
1943 * on an unaligned POSIX file)
1944 * - otherwise, assume the server is so old that we are safer avoiding
1945 * sub-sector requests
1946 */
1947 if (!min) {
1948 min = (!QEMU_IS_ALIGNED(s->info.size, BDRV_SECTOR_SIZE) ||
1949 s->info.base_allocation) ? 1 : BDRV_SECTOR_SIZE;
1950 }
1951
1952 bs->bl.request_alignment = min;
714eb0db 1953 bs->bl.max_pdiscard = QEMU_ALIGN_DOWN(INT_MAX, min);
081dd1fe
EB
1954 bs->bl.max_pwrite_zeroes = max;
1955 bs->bl.max_transfer = max;
1956
1957 if (s->info.opt_block &&
1958 s->info.opt_block > bs->bl.opt_transfer) {
1959 bs->bl.opt_transfer = s->info.opt_block;
1960 }
fa21e6fa
DL
1961}
1962
75818250
TS
1963static void nbd_close(BlockDriverState *bs)
1964{
f53a829b 1965 nbd_client_close(bs);
bbba1c37 1966 nbd_clear_bdrvstate(bs);
75818250
TS
1967}
1968
a2b333c0
NS
1969/*
1970 * NBD cannot truncate, but if the caller asks to truncate to the same size, or
1971 * to a smaller size with exact=false, there is no reason to fail the
1972 * operation.
1973 *
1974 * Preallocation mode is ignored since it does not seems useful to fail when
1975 * we never change anything.
1976 */
1977static int coroutine_fn nbd_co_truncate(BlockDriverState *bs, int64_t offset,
1978 bool exact, PreallocMode prealloc,
1979 BdrvRequestFlags flags, Error **errp)
1980{
1981 BDRVNBDState *s = bs->opaque;
1982
1983 if (offset != s->info.size && exact) {
1984 error_setg(errp, "Cannot resize NBD nodes");
1985 return -ENOTSUP;
1986 }
1987
1988 if (offset > s->info.size) {
1989 error_setg(errp, "Cannot grow NBD nodes");
1990 return -EINVAL;
1991 }
1992
1993 return 0;
1994}
1995
75818250
TS
1996static int64_t nbd_getlength(BlockDriverState *bs)
1997{
1998 BDRVNBDState *s = bs->opaque;
1999
611ae1d7 2000 return s->info.size;
75818250
TS
2001}
2002
998b3a1e 2003static void nbd_refresh_filename(BlockDriverState *bs)
2019d68b 2004{
03504d05 2005 BDRVNBDState *s = bs->opaque;
491d6c7c 2006 const char *host = NULL, *port = NULL, *path = NULL;
5c86bdf1 2007 size_t len = 0;
491d6c7c 2008
62cf396b 2009 if (s->saddr->type == SOCKET_ADDRESS_TYPE_INET) {
9445673e 2010 const InetSocketAddress *inet = &s->saddr->u.inet;
491d6c7c
HR
2011 if (!inet->has_ipv4 && !inet->has_ipv6 && !inet->has_to) {
2012 host = inet->host;
2013 port = inet->port;
2014 }
62cf396b 2015 } else if (s->saddr->type == SOCKET_ADDRESS_TYPE_UNIX) {
9445673e
MA
2016 path = s->saddr->u.q_unix.path;
2017 } /* else can't represent as pseudo-filename */
2019d68b 2018
491d6c7c 2019 if (path && s->export) {
5c86bdf1
EB
2020 len = snprintf(bs->exact_filename, sizeof(bs->exact_filename),
2021 "nbd+unix:///%s?socket=%s", s->export, path);
491d6c7c 2022 } else if (path && !s->export) {
5c86bdf1
EB
2023 len = snprintf(bs->exact_filename, sizeof(bs->exact_filename),
2024 "nbd+unix://?socket=%s", path);
491d6c7c 2025 } else if (host && s->export) {
5c86bdf1
EB
2026 len = snprintf(bs->exact_filename, sizeof(bs->exact_filename),
2027 "nbd://%s:%s/%s", host, port, s->export);
491d6c7c 2028 } else if (host && !s->export) {
5c86bdf1
EB
2029 len = snprintf(bs->exact_filename, sizeof(bs->exact_filename),
2030 "nbd://%s:%s", host, port);
2031 }
00d69986 2032 if (len >= sizeof(bs->exact_filename)) {
5c86bdf1
EB
2033 /* Name is too long to represent exactly, so leave it empty. */
2034 bs->exact_filename[0] = '\0';
ec0de768 2035 }
2019d68b
HR
2036}
2037
8a6239c0
HR
2038static char *nbd_dirname(BlockDriverState *bs, Error **errp)
2039{
2040 /* The generic bdrv_dirname() implementation is able to work out some
2041 * directory name for NBD nodes, but that would be wrong. So far there is no
2042 * specification for how "export paths" would work, so NBD does not have
2043 * directory names. */
2044 error_setg(errp, "Cannot generate a base directory for NBD nodes");
2045 return NULL;
2046}
2047
2654267c
HR
2048static const char *const nbd_strong_runtime_opts[] = {
2049 "path",
2050 "host",
2051 "port",
2052 "export",
2053 "tls-creds",
a0cd6d29 2054 "tls-hostname",
2654267c
HR
2055 "server.",
2056
2057 NULL
2058};
2059
c4f7f24e
VSO
2060static void nbd_cancel_in_flight(BlockDriverState *bs)
2061{
2062 BDRVNBDState *s = (BDRVNBDState *)bs->opaque;
2063
2064 reconnect_delay_timer_del(s);
2065
ee19d953 2066 qemu_mutex_lock(&s->requests_lock);
c4f7f24e
VSO
2067 if (s->state == NBD_CLIENT_CONNECTING_WAIT) {
2068 s->state = NBD_CLIENT_CONNECTING_NOWAIT;
c4f7f24e 2069 }
ee19d953 2070 qemu_mutex_unlock(&s->requests_lock);
4ddb5d2f
VSO
2071
2072 nbd_co_establish_connection_cancel(s->conn);
c4f7f24e
VSO
2073}
2074
e15f3a66
HR
2075static void nbd_attach_aio_context(BlockDriverState *bs,
2076 AioContext *new_context)
2077{
2078 BDRVNBDState *s = bs->opaque;
2079
2080 /* The open_timer is used only during nbd_open() */
2081 assert(!s->open_timer);
2082
2083 /*
2084 * The reconnect_delay_timer is scheduled in I/O paths when the
2085 * connection is lost, to cancel the reconnection attempt after a
2086 * given time. Once this attempt is done (successfully or not),
2087 * nbd_reconnect_attempt() ensures the timer is deleted before the
2088 * respective I/O request is resumed.
2089 * Since the AioContext can only be changed when a node is drained,
2090 * the reconnect_delay_timer cannot be active here.
2091 */
2092 assert(!s->reconnect_delay_timer);
2093
2094 if (s->ioc) {
2095 qio_channel_attach_aio_context(s->ioc, new_context);
2096 }
2097}
2098
2099static void nbd_detach_aio_context(BlockDriverState *bs)
2100{
2101 BDRVNBDState *s = bs->opaque;
2102
2103 assert(!s->open_timer);
2104 assert(!s->reconnect_delay_timer);
2105
2106 if (s->ioc) {
2107 qio_channel_detach_aio_context(s->ioc);
2108 }
2109}
2110
5efa9d5a 2111static BlockDriver bdrv_nbd = {
69447cd8
SH
2112 .format_name = "nbd",
2113 .protocol_name = "nbd",
2114 .instance_size = sizeof(BDRVNBDState),
2115 .bdrv_parse_filename = nbd_parse_filename,
5a5e7f8c
ML
2116 .bdrv_co_create_opts = bdrv_co_create_opts_simple,
2117 .create_opts = &bdrv_create_opts_simple,
69447cd8 2118 .bdrv_file_open = nbd_open,
e99754b4 2119 .bdrv_reopen_prepare = nbd_client_reopen_prepare,
70c4fb26
EB
2120 .bdrv_co_preadv = nbd_client_co_preadv,
2121 .bdrv_co_pwritev = nbd_client_co_pwritev,
fa778fff 2122 .bdrv_co_pwrite_zeroes = nbd_client_co_pwrite_zeroes,
69447cd8
SH
2123 .bdrv_close = nbd_close,
2124 .bdrv_co_flush_to_os = nbd_co_flush,
447e57c3 2125 .bdrv_co_pdiscard = nbd_client_co_pdiscard,
fa21e6fa 2126 .bdrv_refresh_limits = nbd_refresh_limits,
a2b333c0 2127 .bdrv_co_truncate = nbd_co_truncate,
69447cd8 2128 .bdrv_getlength = nbd_getlength,
2019d68b 2129 .bdrv_refresh_filename = nbd_refresh_filename,
78a33ab5 2130 .bdrv_co_block_status = nbd_client_co_block_status,
8a6239c0 2131 .bdrv_dirname = nbd_dirname,
2654267c 2132 .strong_runtime_opts = nbd_strong_runtime_opts,
c4f7f24e 2133 .bdrv_cancel_in_flight = nbd_cancel_in_flight,
e15f3a66
HR
2134
2135 .bdrv_attach_aio_context = nbd_attach_aio_context,
2136 .bdrv_detach_aio_context = nbd_detach_aio_context,
1d7d2a9d
PB
2137};
2138
2139static BlockDriver bdrv_nbd_tcp = {
69447cd8
SH
2140 .format_name = "nbd",
2141 .protocol_name = "nbd+tcp",
2142 .instance_size = sizeof(BDRVNBDState),
2143 .bdrv_parse_filename = nbd_parse_filename,
5a5e7f8c
ML
2144 .bdrv_co_create_opts = bdrv_co_create_opts_simple,
2145 .create_opts = &bdrv_create_opts_simple,
69447cd8 2146 .bdrv_file_open = nbd_open,
e99754b4 2147 .bdrv_reopen_prepare = nbd_client_reopen_prepare,
70c4fb26
EB
2148 .bdrv_co_preadv = nbd_client_co_preadv,
2149 .bdrv_co_pwritev = nbd_client_co_pwritev,
fa778fff 2150 .bdrv_co_pwrite_zeroes = nbd_client_co_pwrite_zeroes,
69447cd8
SH
2151 .bdrv_close = nbd_close,
2152 .bdrv_co_flush_to_os = nbd_co_flush,
447e57c3 2153 .bdrv_co_pdiscard = nbd_client_co_pdiscard,
fa21e6fa 2154 .bdrv_refresh_limits = nbd_refresh_limits,
a2b333c0 2155 .bdrv_co_truncate = nbd_co_truncate,
69447cd8 2156 .bdrv_getlength = nbd_getlength,
2019d68b 2157 .bdrv_refresh_filename = nbd_refresh_filename,
78a33ab5 2158 .bdrv_co_block_status = nbd_client_co_block_status,
8a6239c0 2159 .bdrv_dirname = nbd_dirname,
2654267c 2160 .strong_runtime_opts = nbd_strong_runtime_opts,
c4f7f24e 2161 .bdrv_cancel_in_flight = nbd_cancel_in_flight,
e15f3a66
HR
2162
2163 .bdrv_attach_aio_context = nbd_attach_aio_context,
2164 .bdrv_detach_aio_context = nbd_detach_aio_context,
1d7d2a9d
PB
2165};
2166
2167static BlockDriver bdrv_nbd_unix = {
69447cd8
SH
2168 .format_name = "nbd",
2169 .protocol_name = "nbd+unix",
2170 .instance_size = sizeof(BDRVNBDState),
2171 .bdrv_parse_filename = nbd_parse_filename,
5a5e7f8c
ML
2172 .bdrv_co_create_opts = bdrv_co_create_opts_simple,
2173 .create_opts = &bdrv_create_opts_simple,
69447cd8 2174 .bdrv_file_open = nbd_open,
e99754b4 2175 .bdrv_reopen_prepare = nbd_client_reopen_prepare,
70c4fb26
EB
2176 .bdrv_co_preadv = nbd_client_co_preadv,
2177 .bdrv_co_pwritev = nbd_client_co_pwritev,
fa778fff 2178 .bdrv_co_pwrite_zeroes = nbd_client_co_pwrite_zeroes,
69447cd8
SH
2179 .bdrv_close = nbd_close,
2180 .bdrv_co_flush_to_os = nbd_co_flush,
447e57c3 2181 .bdrv_co_pdiscard = nbd_client_co_pdiscard,
fa21e6fa 2182 .bdrv_refresh_limits = nbd_refresh_limits,
a2b333c0 2183 .bdrv_co_truncate = nbd_co_truncate,
69447cd8 2184 .bdrv_getlength = nbd_getlength,
2019d68b 2185 .bdrv_refresh_filename = nbd_refresh_filename,
78a33ab5 2186 .bdrv_co_block_status = nbd_client_co_block_status,
8a6239c0 2187 .bdrv_dirname = nbd_dirname,
2654267c 2188 .strong_runtime_opts = nbd_strong_runtime_opts,
c4f7f24e 2189 .bdrv_cancel_in_flight = nbd_cancel_in_flight,
e15f3a66
HR
2190
2191 .bdrv_attach_aio_context = nbd_attach_aio_context,
2192 .bdrv_detach_aio_context = nbd_detach_aio_context,
75818250 2193};
5efa9d5a
AL
2194
2195static void bdrv_nbd_init(void)
2196{
2197 bdrv_register(&bdrv_nbd);
1d7d2a9d
PB
2198 bdrv_register(&bdrv_nbd_tcp);
2199 bdrv_register(&bdrv_nbd_unix);
5efa9d5a
AL
2200}
2201
2202block_init(bdrv_nbd_init);