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