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