]> git.proxmox.com Git - mirror_qemu.git/blame - block/nbd-client.c
CODING_STYLE: specify the indent rule for multiline code
[mirror_qemu.git] / block / nbd-client.c
CommitLineData
2302c1ca
MAL
1/*
2 * QEMU Block driver for NBD
3 *
b626b51a 4 * Copyright (C) 2016 Red Hat, Inc.
2302c1ca
MAL
5 * Copyright (C) 2008 Bull S.A.S.
6 * Author: Laurent Vivier <Laurent.Vivier@bull.net>
7 *
8 * Some parts:
9 * Copyright (C) 2007 Anthony Liguori <anthony@codemonkey.ws>
10 *
11 * Permission is hereby granted, free of charge, to any person obtaining a copy
12 * of this software and associated documentation files (the "Software"), to deal
13 * in the Software without restriction, including without limitation the rights
14 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
15 * copies of the Software, and to permit persons to whom the Software is
16 * furnished to do so, subject to the following conditions:
17 *
18 * The above copyright notice and this permission notice shall be included in
19 * all copies or substantial portions of the Software.
20 *
21 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
22 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
23 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
24 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
25 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
26 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
27 * THE SOFTWARE.
28 */
29
80c71a24 30#include "qemu/osdep.h"
d8b4bad8
VSO
31
32#include "trace.h"
be41c100 33#include "qapi/error.h"
2302c1ca 34#include "nbd-client.h"
2302c1ca 35
cfa3ad63
EB
36#define HANDLE_TO_INDEX(bs, handle) ((handle) ^ (uint64_t)(intptr_t)(bs))
37#define INDEX_TO_HANDLE(bs, index) ((index) ^ (uint64_t)(intptr_t)(bs))
2302c1ca 38
07b1b99c 39static void nbd_recv_coroutines_wake_all(NBDClientSession *s)
69152c09
MAL
40{
41 int i;
42
43 for (i = 0; i < MAX_NBD_REQUESTS; i++) {
40f4a218
SH
44 NBDClientRequest *req = &s->requests[i];
45
46 if (req->coroutine && req->receiving) {
47 aio_co_wake(req->coroutine);
69152c09
MAL
48 }
49 }
50}
51
f53a829b 52static void nbd_teardown_connection(BlockDriverState *bs)
4a41a2d6 53{
10676b81 54 NBDClientSession *client = nbd_get_client_session(bs);
f53a829b 55
88ed4e1b 56 assert(client->ioc);
064097d9 57
4a41a2d6 58 /* finish any pending coroutines */
064097d9
DB
59 qio_channel_shutdown(client->ioc,
60 QIO_CHANNEL_SHUTDOWN_BOTH,
61 NULL);
bc5a0335 62 BDRV_POLL_WHILE(bs, client->connection_co);
4a41a2d6 63
f53a829b 64 nbd_client_detach_aio_context(bs);
064097d9
DB
65 object_unref(OBJECT(client->sioc));
66 client->sioc = NULL;
67 object_unref(OBJECT(client->ioc));
68 client->ioc = NULL;
4a41a2d6
SH
69}
70
bc5a0335 71static coroutine_fn void nbd_connection_entry(void *opaque)
2302c1ca 72{
ff82911c 73 NBDClientSession *s = opaque;
2302c1ca 74 uint64_t i;
d0a18013 75 int ret = 0;
be41c100 76 Error *local_err = NULL;
2302c1ca 77
72b6ffc7 78 while (!s->quit) {
5ad81b49
KW
79 /*
80 * The NBD client can only really be considered idle when it has
81 * yielded from qio_channel_readv_all_eof(), waiting for data. This is
82 * the point where the additional scheduled coroutine entry happens
83 * after nbd_client_attach_aio_context().
84 *
85 * Therefore we keep an additional in_flight reference all the time and
86 * only drop it temporarily here.
5ad81b49 87 */
ff82911c 88 assert(s->reply.handle == 0);
d3bd5b90 89 ret = nbd_receive_reply(s->bs, s->ioc, &s->reply, &local_err);
5ad81b49 90
08ace1d7 91 if (local_err) {
d8b4bad8
VSO
92 trace_nbd_read_reply_entry_fail(ret, error_get_pretty(local_err));
93 error_free(local_err);
be41c100 94 }
a12a712a 95 if (ret <= 0) {
ff82911c 96 break;
2302c1ca 97 }
2302c1ca 98
ff82911c
PB
99 /* There's no need for a mutex on the receive side, because the
100 * handler acts as a synchronization point and ensures that only
101 * one coroutine is called until the reply finishes.
102 */
103 i = HANDLE_TO_INDEX(s, s->reply.handle);
40f4a218
SH
104 if (i >= MAX_NBD_REQUESTS ||
105 !s->requests[i].coroutine ||
d2febedb 106 !s->requests[i].receiving ||
f140e300 107 (nbd_reply_is_structured(&s->reply) && !s->info.structured_reply))
d2febedb 108 {
ff82911c
PB
109 break;
110 }
2302c1ca 111
40f4a218 112 /* We're woken up again by the request itself. Note that there
bc5a0335 113 * is no race between yielding and reentering connection_co. This
ff82911c
PB
114 * is because:
115 *
40f4a218 116 * - if the request runs on the same AioContext, it is only
ff82911c
PB
117 * entered after we yield
118 *
40f4a218 119 * - if the request runs on a different AioContext, reentering
bc5a0335 120 * connection_co happens through a bottom half, which can only
ff82911c
PB
121 * run after we yield.
122 */
40f4a218 123 aio_co_wake(s->requests[i].coroutine);
ff82911c 124 qemu_coroutine_yield();
2302c1ca 125 }
a12a712a 126
40f4a218 127 s->quit = true;
07b1b99c 128 nbd_recv_coroutines_wake_all(s);
5ad81b49
KW
129 bdrv_dec_in_flight(s->bs);
130
bc5a0335 131 s->connection_co = NULL;
4720cbee 132 aio_wait_kick();
2302c1ca
MAL
133}
134
f53a829b 135static int nbd_co_send_request(BlockDriverState *bs,
ed2dd912 136 NBDRequest *request,
1e2a77a8 137 QEMUIOVector *qiov)
2302c1ca 138{
10676b81 139 NBDClientSession *s = nbd_get_client_session(bs);
030fa7f6 140 int rc, i;
2302c1ca
MAL
141
142 qemu_co_mutex_lock(&s->send_mutex);
6bdcc018
PB
143 while (s->in_flight == MAX_NBD_REQUESTS) {
144 qemu_co_queue_wait(&s->free_sema, &s->send_mutex);
145 }
146 s->in_flight++;
141cabe6
BW
147
148 for (i = 0; i < MAX_NBD_REQUESTS; i++) {
40f4a218 149 if (s->requests[i].coroutine == NULL) {
141cabe6
BW
150 break;
151 }
152 }
153
1c778ef7 154 g_assert(qemu_in_coroutine());
141cabe6 155 assert(i < MAX_NBD_REQUESTS);
40f4a218
SH
156
157 s->requests[i].coroutine = qemu_coroutine_self();
f140e300 158 s->requests[i].offset = request->from;
40f4a218
SH
159 s->requests[i].receiving = false;
160
141cabe6 161 request->handle = INDEX_TO_HANDLE(s, i);
064097d9 162
72b6ffc7 163 if (s->quit) {
3c2d5183
SH
164 rc = -EIO;
165 goto err;
72b6ffc7 166 }
88ed4e1b 167 assert(s->ioc);
064097d9 168
2302c1ca 169 if (qiov) {
064097d9 170 qio_channel_set_cork(s->ioc, true);
1c778ef7 171 rc = nbd_send_request(s->ioc, request);
72b6ffc7 172 if (rc >= 0 && !s->quit) {
030fa7f6
EB
173 if (qio_channel_writev_all(s->ioc, qiov->iov, qiov->niov,
174 NULL) < 0) {
2302c1ca
MAL
175 rc = -EIO;
176 }
a6934370
VSO
177 } else if (rc >= 0) {
178 rc = -EIO;
2302c1ca 179 }
064097d9 180 qio_channel_set_cork(s->ioc, false);
2302c1ca 181 } else {
1c778ef7 182 rc = nbd_send_request(s->ioc, request);
2302c1ca 183 }
3c2d5183
SH
184
185err:
72b6ffc7
EB
186 if (rc < 0) {
187 s->quit = true;
3c2d5183
SH
188 s->requests[i].coroutine = NULL;
189 s->in_flight--;
190 qemu_co_queue_next(&s->free_sema);
72b6ffc7 191 }
2302c1ca
MAL
192 qemu_co_mutex_unlock(&s->send_mutex);
193 return rc;
194}
195
f140e300
VSO
196static inline uint16_t payload_advance16(uint8_t **payload)
197{
198 *payload += 2;
199 return lduw_be_p(*payload - 2);
200}
201
202static inline uint32_t payload_advance32(uint8_t **payload)
203{
204 *payload += 4;
205 return ldl_be_p(*payload - 4);
206}
207
208static inline uint64_t payload_advance64(uint8_t **payload)
209{
210 *payload += 8;
211 return ldq_be_p(*payload - 8);
212}
213
75d34eb9
EB
214static int nbd_parse_offset_hole_payload(NBDClientSession *client,
215 NBDStructuredReplyChunk *chunk,
f140e300
VSO
216 uint8_t *payload, uint64_t orig_offset,
217 QEMUIOVector *qiov, Error **errp)
218{
219 uint64_t offset;
220 uint32_t hole_size;
221
222 if (chunk->length != sizeof(offset) + sizeof(hole_size)) {
223 error_setg(errp, "Protocol error: invalid payload for "
224 "NBD_REPLY_TYPE_OFFSET_HOLE");
225 return -EINVAL;
226 }
227
228 offset = payload_advance64(&payload);
229 hole_size = payload_advance32(&payload);
230
b4176cb3 231 if (!hole_size || offset < orig_offset || hole_size > qiov->size ||
f140e300
VSO
232 offset > orig_offset + qiov->size - hole_size) {
233 error_setg(errp, "Protocol error: server sent chunk exceeding requested"
234 " region");
235 return -EINVAL;
236 }
75d34eb9
EB
237 if (client->info.min_block &&
238 !QEMU_IS_ALIGNED(hole_size, client->info.min_block)) {
239 trace_nbd_structured_read_compliance("hole");
240 }
f140e300
VSO
241
242 qemu_iovec_memset(qiov, offset - orig_offset, 0, hole_size);
243
244 return 0;
245}
246
78a33ab5 247/* nbd_parse_blockstatus_payload
a39286dd
EB
248 * Based on our request, we expect only one extent in reply, for the
249 * base:allocation context.
78a33ab5
VSO
250 */
251static int nbd_parse_blockstatus_payload(NBDClientSession *client,
252 NBDStructuredReplyChunk *chunk,
253 uint8_t *payload, uint64_t orig_length,
254 NBDExtent *extent, Error **errp)
255{
256 uint32_t context_id;
257
a39286dd
EB
258 /* The server succeeded, so it must have sent [at least] one extent */
259 if (chunk->length < sizeof(context_id) + sizeof(*extent)) {
78a33ab5
VSO
260 error_setg(errp, "Protocol error: invalid payload for "
261 "NBD_REPLY_TYPE_BLOCK_STATUS");
262 return -EINVAL;
263 }
264
265 context_id = payload_advance32(&payload);
2df94eb5 266 if (client->info.context_id != context_id) {
78a33ab5
VSO
267 error_setg(errp, "Protocol error: unexpected context id %d for "
268 "NBD_REPLY_TYPE_BLOCK_STATUS, when negotiated context "
269 "id is %d", context_id,
2df94eb5 270 client->info.context_id);
78a33ab5
VSO
271 return -EINVAL;
272 }
273
274 extent->length = payload_advance32(&payload);
275 extent->flags = payload_advance32(&payload);
276
737d3f52 277 if (extent->length == 0) {
78a33ab5 278 error_setg(errp, "Protocol error: server sent status chunk with "
737d3f52 279 "zero length");
78a33ab5
VSO
280 return -EINVAL;
281 }
282
737d3f52
EB
283 /*
284 * A server sending unaligned block status is in violation of the
285 * protocol, but as qemu-nbd 3.1 is such a server (at least for
286 * POSIX files that are not a multiple of 512 bytes, since qemu
287 * rounds files up to 512-byte multiples but lseek(SEEK_HOLE)
288 * still sees an implicit hole beyond the real EOF), it's nicer to
289 * work around the misbehaving server. If the request included
290 * more than the final unaligned block, truncate it back to an
291 * aligned result; if the request was only the final block, round
292 * up to the full block and change the status to fully-allocated
293 * (always a safe status, even if it loses information).
294 */
295 if (client->info.min_block && !QEMU_IS_ALIGNED(extent->length,
296 client->info.min_block)) {
297 trace_nbd_parse_blockstatus_compliance("extent length is unaligned");
298 if (extent->length > client->info.min_block) {
299 extent->length = QEMU_ALIGN_DOWN(extent->length,
300 client->info.min_block);
301 } else {
302 extent->length = client->info.min_block;
303 extent->flags = 0;
304 }
305 }
306
a39286dd
EB
307 /*
308 * We used NBD_CMD_FLAG_REQ_ONE, so the server should not have
309 * sent us any more than one extent, nor should it have included
310 * status beyond our request in that extent. However, it's easy
311 * enough to ignore the server's noncompliance without killing the
312 * connection; just ignore trailing extents, and clamp things to
313 * the length of our request.
314 */
315 if (chunk->length > sizeof(context_id) + sizeof(*extent)) {
316 trace_nbd_parse_blockstatus_compliance("more than one extent");
317 }
acfd8f7a
EB
318 if (extent->length > orig_length) {
319 extent->length = orig_length;
a39286dd 320 trace_nbd_parse_blockstatus_compliance("extent length too large");
acfd8f7a
EB
321 }
322
78a33ab5
VSO
323 return 0;
324}
325
f140e300
VSO
326/* nbd_parse_error_payload
327 * on success @errp contains message describing nbd error reply
328 */
329static int nbd_parse_error_payload(NBDStructuredReplyChunk *chunk,
330 uint8_t *payload, int *request_ret,
331 Error **errp)
332{
333 uint32_t error;
334 uint16_t message_size;
335
336 assert(chunk->type & (1 << 15));
337
338 if (chunk->length < sizeof(error) + sizeof(message_size)) {
339 error_setg(errp,
340 "Protocol error: invalid payload for structured error");
341 return -EINVAL;
342 }
343
344 error = nbd_errno_to_system_errno(payload_advance32(&payload));
345 if (error == 0) {
e659fb3b 346 error_setg(errp, "Protocol error: server sent structured error chunk "
f140e300
VSO
347 "with error = 0");
348 return -EINVAL;
349 }
350
351 *request_ret = -error;
352 message_size = payload_advance16(&payload);
353
354 if (message_size > chunk->length - sizeof(error) - sizeof(message_size)) {
e659fb3b 355 error_setg(errp, "Protocol error: server sent structured error chunk "
f140e300
VSO
356 "with incorrect message size");
357 return -EINVAL;
358 }
359
360 /* TODO: Add a trace point to mention the server complaint */
361
362 /* TODO handle ERROR_OFFSET */
363
364 return 0;
365}
366
367static int nbd_co_receive_offset_data_payload(NBDClientSession *s,
368 uint64_t orig_offset,
369 QEMUIOVector *qiov, Error **errp)
370{
371 QEMUIOVector sub_qiov;
372 uint64_t offset;
373 size_t data_size;
374 int ret;
375 NBDStructuredReplyChunk *chunk = &s->reply.structured;
376
377 assert(nbd_reply_is_structured(&s->reply));
378
b4176cb3
EB
379 /* The NBD spec requires at least one byte of payload */
380 if (chunk->length <= sizeof(offset)) {
f140e300
VSO
381 error_setg(errp, "Protocol error: invalid payload for "
382 "NBD_REPLY_TYPE_OFFSET_DATA");
383 return -EINVAL;
384 }
385
e6798f06 386 if (nbd_read64(s->ioc, &offset, "OFFSET_DATA offset", errp) < 0) {
f140e300
VSO
387 return -EIO;
388 }
f140e300
VSO
389
390 data_size = chunk->length - sizeof(offset);
b4176cb3 391 assert(data_size);
f140e300
VSO
392 if (offset < orig_offset || data_size > qiov->size ||
393 offset > orig_offset + qiov->size - data_size) {
394 error_setg(errp, "Protocol error: server sent chunk exceeding requested"
395 " region");
396 return -EINVAL;
397 }
75d34eb9
EB
398 if (s->info.min_block && !QEMU_IS_ALIGNED(data_size, s->info.min_block)) {
399 trace_nbd_structured_read_compliance("data");
400 }
f140e300
VSO
401
402 qemu_iovec_init(&sub_qiov, qiov->niov);
403 qemu_iovec_concat(&sub_qiov, qiov, offset - orig_offset, data_size);
404 ret = qio_channel_readv_all(s->ioc, sub_qiov.iov, sub_qiov.niov, errp);
405 qemu_iovec_destroy(&sub_qiov);
406
407 return ret < 0 ? -EIO : 0;
408}
409
410#define NBD_MAX_MALLOC_PAYLOAD 1000
411/* nbd_co_receive_structured_payload
412 */
413static coroutine_fn int nbd_co_receive_structured_payload(
414 NBDClientSession *s, void **payload, Error **errp)
415{
416 int ret;
417 uint32_t len;
418
419 assert(nbd_reply_is_structured(&s->reply));
420
421 len = s->reply.structured.length;
422
423 if (len == 0) {
424 return 0;
425 }
426
427 if (payload == NULL) {
428 error_setg(errp, "Unexpected structured payload");
429 return -EINVAL;
430 }
431
432 if (len > NBD_MAX_MALLOC_PAYLOAD) {
433 error_setg(errp, "Payload too large");
434 return -EINVAL;
435 }
436
437 *payload = g_new(char, len);
e6798f06 438 ret = nbd_read(s->ioc, *payload, len, "structured payload", errp);
f140e300
VSO
439 if (ret < 0) {
440 g_free(*payload);
441 *payload = NULL;
442 return ret;
443 }
444
445 return 0;
446}
447
448/* nbd_co_do_receive_one_chunk
449 * for simple reply:
450 * set request_ret to received reply error
451 * if qiov is not NULL: read payload to @qiov
452 * for structured reply chunk:
453 * if error chunk: read payload, set @request_ret, do not set @payload
454 * else if offset_data chunk: read payload data to @qiov, do not set @payload
455 * else: read payload to @payload
456 *
457 * If function fails, @errp contains corresponding error message, and the
458 * connection with the server is suspect. If it returns 0, then the
459 * transaction succeeded (although @request_ret may be a negative errno
460 * corresponding to the server's error reply), and errp is unchanged.
461 */
462static coroutine_fn int nbd_co_do_receive_one_chunk(
463 NBDClientSession *s, uint64_t handle, bool only_structured,
464 int *request_ret, QEMUIOVector *qiov, void **payload, Error **errp)
2302c1ca 465{
319a56cd 466 int ret;
ed397b2f 467 int i = HANDLE_TO_INDEX(s, handle);
f140e300
VSO
468 void *local_payload = NULL;
469 NBDStructuredReplyChunk *chunk;
470
471 if (payload) {
472 *payload = NULL;
473 }
474 *request_ret = 0;
2302c1ca 475
bc5a0335 476 /* Wait until we're woken up by nbd_connection_entry. */
40f4a218 477 s->requests[i].receiving = true;
2302c1ca 478 qemu_coroutine_yield();
40f4a218 479 s->requests[i].receiving = false;
88ed4e1b 480 if (s->quit) {
f140e300
VSO
481 error_setg(errp, "Connection closed");
482 return -EIO;
483 }
88ed4e1b 484 assert(s->ioc);
f140e300
VSO
485
486 assert(s->reply.handle == handle);
487
488 if (nbd_reply_is_simple(&s->reply)) {
489 if (only_structured) {
490 error_setg(errp, "Protocol error: simple reply when structured "
491 "reply chunk was expected");
492 return -EINVAL;
2302c1ca
MAL
493 }
494
f140e300
VSO
495 *request_ret = -nbd_errno_to_system_errno(s->reply.simple.error);
496 if (*request_ret < 0 || !qiov) {
497 return 0;
498 }
499
500 return qio_channel_readv_all(s->ioc, qiov->iov, qiov->niov,
501 errp) < 0 ? -EIO : 0;
502 }
503
504 /* handle structured reply chunk */
505 assert(s->info.structured_reply);
506 chunk = &s->reply.structured;
507
508 if (chunk->type == NBD_REPLY_TYPE_NONE) {
509 if (!(chunk->flags & NBD_REPLY_FLAG_DONE)) {
510 error_setg(errp, "Protocol error: NBD_REPLY_TYPE_NONE chunk without"
e659fb3b 511 " NBD_REPLY_FLAG_DONE flag set");
f140e300
VSO
512 return -EINVAL;
513 }
b4176cb3
EB
514 if (chunk->length) {
515 error_setg(errp, "Protocol error: NBD_REPLY_TYPE_NONE chunk with"
516 " nonzero length");
517 return -EINVAL;
518 }
f140e300
VSO
519 return 0;
520 }
521
522 if (chunk->type == NBD_REPLY_TYPE_OFFSET_DATA) {
523 if (!qiov) {
524 error_setg(errp, "Unexpected NBD_REPLY_TYPE_OFFSET_DATA chunk");
525 return -EINVAL;
526 }
527
528 return nbd_co_receive_offset_data_payload(s, s->requests[i].offset,
529 qiov, errp);
530 }
531
532 if (nbd_reply_type_is_error(chunk->type)) {
533 payload = &local_payload;
534 }
535
536 ret = nbd_co_receive_structured_payload(s, payload, errp);
537 if (ret < 0) {
538 return ret;
2302c1ca 539 }
ff82911c 540
f140e300
VSO
541 if (nbd_reply_type_is_error(chunk->type)) {
542 ret = nbd_parse_error_payload(chunk, local_payload, request_ret, errp);
543 g_free(local_payload);
544 return ret;
545 }
546
547 return 0;
548}
549
550/* nbd_co_receive_one_chunk
bc5a0335 551 * Read reply, wake up connection_co and set s->quit if needed.
f140e300
VSO
552 * Return value is a fatal error code or normal nbd reply error code
553 */
554static coroutine_fn int nbd_co_receive_one_chunk(
555 NBDClientSession *s, uint64_t handle, bool only_structured,
7f86068d
VSO
556 int *request_ret, QEMUIOVector *qiov, NBDReply *reply, void **payload,
557 Error **errp)
f140e300 558{
f140e300 559 int ret = nbd_co_do_receive_one_chunk(s, handle, only_structured,
7f86068d 560 request_ret, qiov, payload, errp);
f140e300
VSO
561
562 if (ret < 0) {
563 s->quit = true;
564 } else {
bc5a0335 565 /* For assert at loop start in nbd_connection_entry */
f140e300
VSO
566 if (reply) {
567 *reply = s->reply;
568 }
569 s->reply.handle = 0;
f140e300 570 }
ff82911c 571
bc5a0335
VSO
572 if (s->connection_co) {
573 aio_co_wake(s->connection_co);
2302c1ca 574 }
6bdcc018 575
f140e300
VSO
576 return ret;
577}
578
579typedef struct NBDReplyChunkIter {
580 int ret;
7f86068d 581 int request_ret;
f140e300
VSO
582 Error *err;
583 bool done, only_structured;
584} NBDReplyChunkIter;
585
7f86068d
VSO
586static void nbd_iter_channel_error(NBDReplyChunkIter *iter,
587 int ret, Error **local_err)
f140e300
VSO
588{
589 assert(ret < 0);
590
7f86068d 591 if (!iter->ret) {
f140e300
VSO
592 iter->ret = ret;
593 error_propagate(&iter->err, *local_err);
594 } else {
595 error_free(*local_err);
596 }
597
598 *local_err = NULL;
599}
600
7f86068d
VSO
601static void nbd_iter_request_error(NBDReplyChunkIter *iter, int ret)
602{
603 assert(ret < 0);
604
605 if (!iter->request_ret) {
606 iter->request_ret = ret;
607 }
608}
609
f140e300
VSO
610/* NBD_FOREACH_REPLY_CHUNK
611 */
612#define NBD_FOREACH_REPLY_CHUNK(s, iter, handle, structured, \
613 qiov, reply, payload) \
614 for (iter = (NBDReplyChunkIter) { .only_structured = structured }; \
615 nbd_reply_chunk_iter_receive(s, &iter, handle, qiov, reply, payload);)
616
617/* nbd_reply_chunk_iter_receive
618 */
619static bool nbd_reply_chunk_iter_receive(NBDClientSession *s,
620 NBDReplyChunkIter *iter,
621 uint64_t handle,
622 QEMUIOVector *qiov, NBDReply *reply,
623 void **payload)
624{
7f86068d 625 int ret, request_ret;
f140e300
VSO
626 NBDReply local_reply;
627 NBDStructuredReplyChunk *chunk;
628 Error *local_err = NULL;
629 if (s->quit) {
630 error_setg(&local_err, "Connection closed");
7f86068d 631 nbd_iter_channel_error(iter, -EIO, &local_err);
f140e300
VSO
632 goto break_loop;
633 }
634
635 if (iter->done) {
636 /* Previous iteration was last. */
637 goto break_loop;
638 }
639
640 if (reply == NULL) {
641 reply = &local_reply;
642 }
643
644 ret = nbd_co_receive_one_chunk(s, handle, iter->only_structured,
7f86068d
VSO
645 &request_ret, qiov, reply, payload,
646 &local_err);
f140e300 647 if (ret < 0) {
7f86068d
VSO
648 nbd_iter_channel_error(iter, ret, &local_err);
649 } else if (request_ret < 0) {
650 nbd_iter_request_error(iter, request_ret);
f140e300
VSO
651 }
652
653 /* Do not execute the body of NBD_FOREACH_REPLY_CHUNK for simple reply. */
65e01d47 654 if (nbd_reply_is_simple(reply) || s->quit) {
f140e300
VSO
655 goto break_loop;
656 }
657
658 chunk = &reply->structured;
659 iter->only_structured = true;
660
661 if (chunk->type == NBD_REPLY_TYPE_NONE) {
662 /* NBD_REPLY_FLAG_DONE is already checked in nbd_co_receive_one_chunk */
663 assert(chunk->flags & NBD_REPLY_FLAG_DONE);
664 goto break_loop;
665 }
666
667 if (chunk->flags & NBD_REPLY_FLAG_DONE) {
668 /* This iteration is last. */
669 iter->done = true;
670 }
671
672 /* Execute the loop body */
673 return true;
674
675break_loop:
676 s->requests[HANDLE_TO_INDEX(s, handle)].coroutine = NULL;
677
6bdcc018
PB
678 qemu_co_mutex_lock(&s->send_mutex);
679 s->in_flight--;
680 qemu_co_queue_next(&s->free_sema);
681 qemu_co_mutex_unlock(&s->send_mutex);
319a56cd 682
f140e300 683 return false;
2302c1ca
MAL
684}
685
f140e300 686static int nbd_co_receive_return_code(NBDClientSession *s, uint64_t handle,
7f86068d 687 int *request_ret, Error **errp)
f140e300
VSO
688{
689 NBDReplyChunkIter iter;
690
691 NBD_FOREACH_REPLY_CHUNK(s, iter, handle, false, NULL, NULL, NULL) {
692 /* nbd_reply_chunk_iter_receive does all the work */
693 }
694
695 error_propagate(errp, iter.err);
7f86068d 696 *request_ret = iter.request_ret;
f140e300
VSO
697 return iter.ret;
698}
699
700static int nbd_co_receive_cmdread_reply(NBDClientSession *s, uint64_t handle,
701 uint64_t offset, QEMUIOVector *qiov,
7f86068d 702 int *request_ret, Error **errp)
f140e300
VSO
703{
704 NBDReplyChunkIter iter;
705 NBDReply reply;
706 void *payload = NULL;
707 Error *local_err = NULL;
708
709 NBD_FOREACH_REPLY_CHUNK(s, iter, handle, s->info.structured_reply,
710 qiov, &reply, &payload)
711 {
712 int ret;
713 NBDStructuredReplyChunk *chunk = &reply.structured;
714
715 assert(nbd_reply_is_structured(&reply));
716
717 switch (chunk->type) {
718 case NBD_REPLY_TYPE_OFFSET_DATA:
719 /* special cased in nbd_co_receive_one_chunk, data is already
720 * in qiov */
721 break;
722 case NBD_REPLY_TYPE_OFFSET_HOLE:
75d34eb9 723 ret = nbd_parse_offset_hole_payload(s, &reply.structured, payload,
f140e300
VSO
724 offset, qiov, &local_err);
725 if (ret < 0) {
726 s->quit = true;
7f86068d 727 nbd_iter_channel_error(&iter, ret, &local_err);
f140e300
VSO
728 }
729 break;
730 default:
731 if (!nbd_reply_type_is_error(chunk->type)) {
732 /* not allowed reply type */
733 s->quit = true;
734 error_setg(&local_err,
735 "Unexpected reply type: %d (%s) for CMD_READ",
736 chunk->type, nbd_reply_type_lookup(chunk->type));
7f86068d 737 nbd_iter_channel_error(&iter, -EINVAL, &local_err);
f140e300
VSO
738 }
739 }
740
741 g_free(payload);
742 payload = NULL;
743 }
744
745 error_propagate(errp, iter.err);
7f86068d 746 *request_ret = iter.request_ret;
f140e300
VSO
747 return iter.ret;
748}
749
78a33ab5
VSO
750static int nbd_co_receive_blockstatus_reply(NBDClientSession *s,
751 uint64_t handle, uint64_t length,
7f86068d
VSO
752 NBDExtent *extent,
753 int *request_ret, Error **errp)
78a33ab5
VSO
754{
755 NBDReplyChunkIter iter;
756 NBDReply reply;
757 void *payload = NULL;
758 Error *local_err = NULL;
759 bool received = false;
760
761 assert(!extent->length);
ebd82cd8 762 NBD_FOREACH_REPLY_CHUNK(s, iter, handle, false, NULL, &reply, &payload) {
78a33ab5
VSO
763 int ret;
764 NBDStructuredReplyChunk *chunk = &reply.structured;
765
766 assert(nbd_reply_is_structured(&reply));
767
768 switch (chunk->type) {
769 case NBD_REPLY_TYPE_BLOCK_STATUS:
770 if (received) {
771 s->quit = true;
772 error_setg(&local_err, "Several BLOCK_STATUS chunks in reply");
7f86068d 773 nbd_iter_channel_error(&iter, -EINVAL, &local_err);
78a33ab5
VSO
774 }
775 received = true;
776
777 ret = nbd_parse_blockstatus_payload(s, &reply.structured,
778 payload, length, extent,
779 &local_err);
780 if (ret < 0) {
781 s->quit = true;
7f86068d 782 nbd_iter_channel_error(&iter, ret, &local_err);
78a33ab5
VSO
783 }
784 break;
785 default:
786 if (!nbd_reply_type_is_error(chunk->type)) {
787 s->quit = true;
788 error_setg(&local_err,
789 "Unexpected reply type: %d (%s) "
790 "for CMD_BLOCK_STATUS",
791 chunk->type, nbd_reply_type_lookup(chunk->type));
7f86068d 792 nbd_iter_channel_error(&iter, -EINVAL, &local_err);
78a33ab5
VSO
793 }
794 }
795
796 g_free(payload);
797 payload = NULL;
798 }
799
b29f3a3d
EB
800 if (!extent->length && !iter.request_ret) {
801 error_setg(&local_err, "Server did not reply with any status extents");
802 nbd_iter_channel_error(&iter, -EIO, &local_err);
78a33ab5 803 }
7f86068d 804
78a33ab5 805 error_propagate(errp, iter.err);
7f86068d 806 *request_ret = iter.request_ret;
78a33ab5
VSO
807 return iter.ret;
808}
809
f140e300
VSO
810static int nbd_co_request(BlockDriverState *bs, NBDRequest *request,
811 QEMUIOVector *write_qiov)
f35dff7e 812{
7f86068d 813 int ret, request_ret;
f140e300
VSO
814 Error *local_err = NULL;
815 NBDClientSession *client = nbd_get_client_session(bs);
f35dff7e 816
f140e300
VSO
817 assert(request->type != NBD_CMD_READ);
818 if (write_qiov) {
819 assert(request->type == NBD_CMD_WRITE);
820 assert(request->len == iov_size(write_qiov->iov, write_qiov->niov));
4bfe4478 821 } else {
f140e300 822 assert(request->type != NBD_CMD_WRITE);
4bfe4478 823 }
f140e300 824 ret = nbd_co_send_request(bs, request, write_qiov);
f35dff7e 825 if (ret < 0) {
319a56cd 826 return ret;
f35dff7e 827 }
319a56cd 828
7f86068d
VSO
829 ret = nbd_co_receive_return_code(client, request->handle,
830 &request_ret, &local_err);
f140e300 831 if (local_err) {
d8b4bad8
VSO
832 trace_nbd_co_request_fail(request->from, request->len, request->handle,
833 request->flags, request->type,
834 nbd_cmd_lookup(request->type),
835 ret, error_get_pretty(local_err));
836 error_free(local_err);
f140e300 837 }
7f86068d 838 return ret ? ret : request_ret;
f35dff7e
VSO
839}
840
70c4fb26
EB
841int nbd_client_co_preadv(BlockDriverState *bs, uint64_t offset,
842 uint64_t bytes, QEMUIOVector *qiov, int flags)
2302c1ca 843{
7f86068d 844 int ret, request_ret;
f140e300
VSO
845 Error *local_err = NULL;
846 NBDClientSession *client = nbd_get_client_session(bs);
ed2dd912 847 NBDRequest request = {
70c4fb26
EB
848 .type = NBD_CMD_READ,
849 .from = offset,
850 .len = bytes,
851 };
2302c1ca 852
70c4fb26
EB
853 assert(bytes <= NBD_MAX_BUFFER_SIZE);
854 assert(!flags);
2302c1ca 855
9d8f818c
EB
856 if (!bytes) {
857 return 0;
858 }
9cf63850
EB
859 /*
860 * Work around the fact that the block layer doesn't do
861 * byte-accurate sizing yet - if the read exceeds the server's
862 * advertised size because the block layer rounded size up, then
863 * truncate the request to the server and tail-pad with zero.
864 */
865 if (offset >= client->info.size) {
866 assert(bytes < BDRV_SECTOR_SIZE);
867 qemu_iovec_memset(qiov, 0, 0, bytes);
868 return 0;
869 }
870 if (offset + bytes > client->info.size) {
871 uint64_t slop = offset + bytes - client->info.size;
872
873 assert(slop < BDRV_SECTOR_SIZE);
874 qemu_iovec_memset(qiov, bytes - slop, 0, slop);
875 request.len -= slop;
876 }
877
f140e300
VSO
878 ret = nbd_co_send_request(bs, &request, NULL);
879 if (ret < 0) {
880 return ret;
881 }
882
883 ret = nbd_co_receive_cmdread_reply(client, request.handle, offset, qiov,
7f86068d 884 &request_ret, &local_err);
08ace1d7 885 if (local_err) {
d8b4bad8
VSO
886 trace_nbd_co_request_fail(request.from, request.len, request.handle,
887 request.flags, request.type,
888 nbd_cmd_lookup(request.type),
889 ret, error_get_pretty(local_err));
890 error_free(local_err);
f140e300 891 }
7f86068d 892 return ret ? ret : request_ret;
2302c1ca
MAL
893}
894
70c4fb26
EB
895int nbd_client_co_pwritev(BlockDriverState *bs, uint64_t offset,
896 uint64_t bytes, QEMUIOVector *qiov, int flags)
2302c1ca 897{
10676b81 898 NBDClientSession *client = nbd_get_client_session(bs);
ed2dd912 899 NBDRequest request = {
70c4fb26
EB
900 .type = NBD_CMD_WRITE,
901 .from = offset,
902 .len = bytes,
903 };
2302c1ca 904
1104d83c 905 assert(!(client->info.flags & NBD_FLAG_READ_ONLY));
52a46505 906 if (flags & BDRV_REQ_FUA) {
004a89fc 907 assert(client->info.flags & NBD_FLAG_SEND_FUA);
b626b51a 908 request.flags |= NBD_CMD_FLAG_FUA;
2302c1ca
MAL
909 }
910
70c4fb26 911 assert(bytes <= NBD_MAX_BUFFER_SIZE);
2302c1ca 912
9d8f818c
EB
913 if (!bytes) {
914 return 0;
915 }
f35dff7e 916 return nbd_co_request(bs, &request, qiov);
2302c1ca
MAL
917}
918
fa778fff 919int nbd_client_co_pwrite_zeroes(BlockDriverState *bs, int64_t offset,
f5a5ca79 920 int bytes, BdrvRequestFlags flags)
fa778fff 921{
fa778fff
EB
922 NBDClientSession *client = nbd_get_client_session(bs);
923 NBDRequest request = {
924 .type = NBD_CMD_WRITE_ZEROES,
925 .from = offset,
f5a5ca79 926 .len = bytes,
fa778fff 927 };
fa778fff 928
1104d83c 929 assert(!(client->info.flags & NBD_FLAG_READ_ONLY));
004a89fc 930 if (!(client->info.flags & NBD_FLAG_SEND_WRITE_ZEROES)) {
fa778fff
EB
931 return -ENOTSUP;
932 }
933
934 if (flags & BDRV_REQ_FUA) {
004a89fc 935 assert(client->info.flags & NBD_FLAG_SEND_FUA);
fa778fff
EB
936 request.flags |= NBD_CMD_FLAG_FUA;
937 }
938 if (!(flags & BDRV_REQ_MAY_UNMAP)) {
939 request.flags |= NBD_CMD_FLAG_NO_HOLE;
940 }
941
9d8f818c
EB
942 if (!bytes) {
943 return 0;
944 }
f35dff7e 945 return nbd_co_request(bs, &request, NULL);
fa778fff
EB
946}
947
f53a829b 948int nbd_client_co_flush(BlockDriverState *bs)
2302c1ca 949{
10676b81 950 NBDClientSession *client = nbd_get_client_session(bs);
ed2dd912 951 NBDRequest request = { .type = NBD_CMD_FLUSH };
2302c1ca 952
004a89fc 953 if (!(client->info.flags & NBD_FLAG_SEND_FLUSH)) {
2302c1ca
MAL
954 return 0;
955 }
956
2302c1ca
MAL
957 request.from = 0;
958 request.len = 0;
959
f35dff7e 960 return nbd_co_request(bs, &request, NULL);
2302c1ca
MAL
961}
962
f5a5ca79 963int nbd_client_co_pdiscard(BlockDriverState *bs, int64_t offset, int bytes)
2302c1ca 964{
10676b81 965 NBDClientSession *client = nbd_get_client_session(bs);
ed2dd912 966 NBDRequest request = {
447e57c3
EB
967 .type = NBD_CMD_TRIM,
968 .from = offset,
f5a5ca79 969 .len = bytes,
447e57c3 970 };
2302c1ca 971
1104d83c 972 assert(!(client->info.flags & NBD_FLAG_READ_ONLY));
9d8f818c 973 if (!(client->info.flags & NBD_FLAG_SEND_TRIM) || !bytes) {
2302c1ca
MAL
974 return 0;
975 }
2302c1ca 976
f35dff7e 977 return nbd_co_request(bs, &request, NULL);
2302c1ca
MAL
978}
979
78a33ab5
VSO
980int coroutine_fn nbd_client_co_block_status(BlockDriverState *bs,
981 bool want_zero,
982 int64_t offset, int64_t bytes,
983 int64_t *pnum, int64_t *map,
984 BlockDriverState **file)
985{
7f86068d 986 int ret, request_ret;
78a33ab5
VSO
987 NBDExtent extent = { 0 };
988 NBDClientSession *client = nbd_get_client_session(bs);
989 Error *local_err = NULL;
990
991 NBDRequest request = {
992 .type = NBD_CMD_BLOCK_STATUS,
993 .from = offset,
994 .len = MIN(MIN_NON_ZERO(QEMU_ALIGN_DOWN(INT_MAX,
995 bs->bl.request_alignment),
9cf63850
EB
996 client->info.max_block),
997 MIN(bytes, client->info.size - offset)),
78a33ab5
VSO
998 .flags = NBD_CMD_FLAG_REQ_ONE,
999 };
1000
1001 if (!client->info.base_allocation) {
1002 *pnum = bytes;
a62a85ef
EB
1003 *map = offset;
1004 *file = bs;
1005 return BDRV_BLOCK_DATA | BDRV_BLOCK_OFFSET_VALID;
78a33ab5
VSO
1006 }
1007
9cf63850
EB
1008 /*
1009 * Work around the fact that the block layer doesn't do
1010 * byte-accurate sizing yet - if the status request exceeds the
1011 * server's advertised size because the block layer rounded size
1012 * up, we truncated the request to the server (above), or are
1013 * called on just the hole.
1014 */
1015 if (offset >= client->info.size) {
1016 *pnum = bytes;
1017 assert(bytes < BDRV_SECTOR_SIZE);
1018 /* Intentionally don't report offset_valid for the hole */
1019 return BDRV_BLOCK_ZERO;
1020 }
1021
1022 if (client->info.min_block) {
1023 assert(QEMU_IS_ALIGNED(request.len, client->info.min_block));
1024 }
78a33ab5
VSO
1025 ret = nbd_co_send_request(bs, &request, NULL);
1026 if (ret < 0) {
1027 return ret;
1028 }
1029
1030 ret = nbd_co_receive_blockstatus_reply(client, request.handle, bytes,
7f86068d 1031 &extent, &request_ret, &local_err);
78a33ab5 1032 if (local_err) {
d8b4bad8
VSO
1033 trace_nbd_co_request_fail(request.from, request.len, request.handle,
1034 request.flags, request.type,
1035 nbd_cmd_lookup(request.type),
1036 ret, error_get_pretty(local_err));
1037 error_free(local_err);
78a33ab5 1038 }
7f86068d
VSO
1039 if (ret < 0 || request_ret < 0) {
1040 return ret ? ret : request_ret;
78a33ab5
VSO
1041 }
1042
1043 assert(extent.length);
1044 *pnum = extent.length;
a62a85ef
EB
1045 *map = offset;
1046 *file = bs;
78a33ab5 1047 return (extent.flags & NBD_STATE_HOLE ? 0 : BDRV_BLOCK_DATA) |
a62a85ef
EB
1048 (extent.flags & NBD_STATE_ZERO ? BDRV_BLOCK_ZERO : 0) |
1049 BDRV_BLOCK_OFFSET_VALID;
78a33ab5
VSO
1050}
1051
f53a829b 1052void nbd_client_detach_aio_context(BlockDriverState *bs)
69447cd8 1053{
ff82911c 1054 NBDClientSession *client = nbd_get_client_session(bs);
96d06835 1055 qio_channel_detach_aio_context(QIO_CHANNEL(client->ioc));
69447cd8
SH
1056}
1057
28e0b2d2
KW
1058static void nbd_client_attach_aio_context_bh(void *opaque)
1059{
1060 BlockDriverState *bs = opaque;
1061 NBDClientSession *client = nbd_get_client_session(bs);
1062
1063 /* The node is still drained, so we know the coroutine has yielded in
1064 * nbd_read_eof(), the only place where bs->in_flight can reach 0, or it is
1065 * entered for the first time. Both places are safe for entering the
1066 * coroutine.*/
1067 qemu_aio_coroutine_enter(bs->aio_context, client->connection_co);
1068 bdrv_dec_in_flight(bs);
1069}
1070
f53a829b
HR
1071void nbd_client_attach_aio_context(BlockDriverState *bs,
1072 AioContext *new_context)
69447cd8 1073{
ff82911c 1074 NBDClientSession *client = nbd_get_client_session(bs);
96d06835 1075 qio_channel_attach_aio_context(QIO_CHANNEL(client->ioc), new_context);
5ad81b49 1076
28e0b2d2
KW
1077 bdrv_inc_in_flight(bs);
1078
1079 /* Need to wait here for the BH to run because the BH must run while the
1080 * node is still drained. */
1081 aio_wait_bh_oneshot(new_context, nbd_client_attach_aio_context_bh, bs);
69447cd8
SH
1082}
1083
f53a829b 1084void nbd_client_close(BlockDriverState *bs)
2302c1ca 1085{
10676b81 1086 NBDClientSession *client = nbd_get_client_session(bs);
ed2dd912 1087 NBDRequest request = { .type = NBD_CMD_DISC };
2302c1ca 1088
88ed4e1b 1089 assert(client->ioc);
4a41a2d6 1090
1c778ef7 1091 nbd_send_request(client->ioc, &request);
5ad283eb 1092
f53a829b 1093 nbd_teardown_connection(bs);
2302c1ca
MAL
1094}
1095
d42f78e9
VSO
1096static QIOChannelSocket *nbd_establish_connection(SocketAddress *saddr,
1097 Error **errp)
1098{
1099 QIOChannelSocket *sioc;
1100 Error *local_err = NULL;
1101
1102 sioc = qio_channel_socket_new();
1103 qio_channel_set_name(QIO_CHANNEL(sioc), "nbd-client");
1104
1105 qio_channel_socket_connect_sync(sioc, saddr, &local_err);
1106 if (local_err) {
1107 object_unref(OBJECT(sioc));
1108 error_propagate(errp, local_err);
1109 return NULL;
1110 }
1111
1112 qio_channel_set_delay(QIO_CHANNEL(sioc), false);
1113
1114 return sioc;
1115}
1116
b0e4b5a5
VSO
1117static int nbd_client_connect(BlockDriverState *bs,
1118 SocketAddress *saddr,
1119 const char *export,
1120 QCryptoTLSCreds *tlscreds,
1121 const char *hostname,
1122 const char *x_dirty_bitmap,
1123 Error **errp)
2302c1ca 1124{
10676b81 1125 NBDClientSession *client = nbd_get_client_session(bs);
2302c1ca
MAL
1126 int ret;
1127
d42f78e9
VSO
1128 /*
1129 * establish TCP connection, return error if it fails
1130 * TODO: Configurable retry-until-timeout behaviour.
1131 */
1132 QIOChannelSocket *sioc = nbd_establish_connection(saddr, errp);
1133
1134 if (!sioc) {
1135 return -ECONNREFUSED;
1136 }
1137
2302c1ca 1138 /* NBD handshake */
e2bc625f 1139 logout("session init %s\n", export);
064097d9
DB
1140 qio_channel_set_blocking(QIO_CHANNEL(sioc), true, NULL);
1141
081dd1fe 1142 client->info.request_sizes = true;
f140e300 1143 client->info.structured_reply = true;
78a33ab5 1144 client->info.base_allocation = true;
216ee365 1145 client->info.x_dirty_bitmap = g_strdup(x_dirty_bitmap);
6dc1667d
EB
1146 client->info.name = g_strdup(export ?: "");
1147 ret = nbd_receive_negotiate(QIO_CHANNEL(sioc), tlscreds, hostname,
004a89fc 1148 &client->ioc, &client->info, errp);
216ee365 1149 g_free(client->info.x_dirty_bitmap);
6dc1667d 1150 g_free(client->info.name);
2302c1ca
MAL
1151 if (ret < 0) {
1152 logout("Failed to negotiate with the NBD server\n");
d42f78e9 1153 object_unref(OBJECT(sioc));
2302c1ca
MAL
1154 return ret;
1155 }
47829c40
EB
1156 if (x_dirty_bitmap && !client->info.base_allocation) {
1157 error_setg(errp, "requested x-dirty-bitmap %s not found",
1158 x_dirty_bitmap);
c688e6ca
EB
1159 ret = -EINVAL;
1160 goto fail;
47829c40 1161 }
6c2e581d
KW
1162 if (client->info.flags & NBD_FLAG_READ_ONLY) {
1163 ret = bdrv_apply_auto_read_only(bs, "NBD export is read-only", errp);
1164 if (ret < 0) {
c688e6ca 1165 goto fail;
6c2e581d 1166 }
1104d83c 1167 }
004a89fc 1168 if (client->info.flags & NBD_FLAG_SEND_FUA) {
4df863f3 1169 bs->supported_write_flags = BDRV_REQ_FUA;
169407e1
EB
1170 bs->supported_zero_flags |= BDRV_REQ_FUA;
1171 }
004a89fc 1172 if (client->info.flags & NBD_FLAG_SEND_WRITE_ZEROES) {
169407e1 1173 bs->supported_zero_flags |= BDRV_REQ_MAY_UNMAP;
4df863f3 1174 }
2302c1ca 1175
064097d9 1176 client->sioc = sioc;
f95910fe
DB
1177
1178 if (!client->ioc) {
1179 client->ioc = QIO_CHANNEL(sioc);
1180 object_ref(OBJECT(client->ioc));
1181 }
2302c1ca
MAL
1182
1183 /* Now that we're connected, set the socket to be non-blocking and
1184 * kick the reply mechanism. */
064097d9 1185 qio_channel_set_blocking(QIO_CHANNEL(sioc), false, NULL);
bc5a0335 1186 client->connection_co = qemu_coroutine_create(nbd_connection_entry, client);
5ad81b49 1187 bdrv_inc_in_flight(bs);
f53a829b 1188 nbd_client_attach_aio_context(bs, bdrv_get_aio_context(bs));
2302c1ca
MAL
1189
1190 logout("Established connection with NBD server\n");
1191 return 0;
c688e6ca
EB
1192
1193 fail:
1194 /*
1195 * We have connected, but must fail for other reasons. The
1196 * connection is still blocking; send NBD_CMD_DISC as a courtesy
1197 * to the server.
1198 */
1199 {
1200 NBDRequest request = { .type = NBD_CMD_DISC };
1201
1202 nbd_send_request(client->ioc ?: QIO_CHANNEL(sioc), &request);
d42f78e9
VSO
1203
1204 object_unref(OBJECT(sioc));
1205
c688e6ca
EB
1206 return ret;
1207 }
2302c1ca 1208}
b0e4b5a5
VSO
1209
1210int nbd_client_init(BlockDriverState *bs,
1211 SocketAddress *saddr,
1212 const char *export,
1213 QCryptoTLSCreds *tlscreds,
1214 const char *hostname,
1215 const char *x_dirty_bitmap,
1216 Error **errp)
1217{
1218 NBDClientSession *client = nbd_get_client_session(bs);
1219
5ad81b49 1220 client->bs = bs;
b0e4b5a5
VSO
1221 qemu_co_mutex_init(&client->send_mutex);
1222 qemu_co_queue_init(&client->free_sema);
1223
1224 return nbd_client_connect(bs, saddr, export, tlscreds, hostname,
1225 x_dirty_bitmap, errp);
1226}