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