]> git.ipfire.org Git - thirdparty/qemu.git/blame - nbd/server.c
nbd/server: Support 64-bit block status
[thirdparty/qemu.git] / nbd / server.c
CommitLineData
75818250 1/*
a7c8ed36 2 * Copyright Red Hat
7a5ca864
FB
3 * Copyright (C) 2005 Anthony Liguori <anthony@codemonkey.ws>
4 *
798bfe00 5 * Network Block Device Server Side
7a5ca864
FB
6 *
7 * This program is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; under version 2 of the License.
10 *
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License
8167ee88 17 * along with this program; if not, see <http://www.gnu.org/licenses/>.
75818250 18 */
7a5ca864 19
d38ea87a 20#include "qemu/osdep.h"
56ee8626 21
e2c1c34f 22#include "block/block_int.h"
56ee8626 23#include "block/export.h"
e2c1c34f 24#include "block/dirty-bitmap.h"
da34e65c 25#include "qapi/error.h"
dc5e9ac7 26#include "qemu/queue.h"
9588463e 27#include "trace.h"
798bfe00 28#include "nbd-internal.h"
416e34bd 29#include "qemu/units.h"
5df022cf 30#include "qemu/memalign.h"
ca441480 31
e7b1948d 32#define NBD_META_ID_BASE_ALLOCATION 0
71719cd5 33#define NBD_META_ID_ALLOCATION_DEPTH 1
3b1f244c 34/* Dirty bitmaps use 'NBD_META_ID_DIRTY_BITMAP + i', so keep this id last. */
71719cd5 35#define NBD_META_ID_DIRTY_BITMAP 2
3d068aff 36
416e34bd
EB
37/*
38 * NBD_MAX_BLOCK_STATUS_EXTENTS: 1 MiB of extents data. An empirical
3d068aff
VSO
39 * constant. If an increase is needed, note that the NBD protocol
40 * recommends no larger than 32 mb, so that the client won't consider
416e34bd
EB
41 * the reply as a denial of service attack.
42 */
43#define NBD_MAX_BLOCK_STATUS_EXTENTS (1 * MiB / 8)
e7b1948d 44
ca441480
PB
45static int system_errno_to_nbd_errno(int err)
46{
47 switch (err) {
48 case 0:
49 return NBD_SUCCESS;
50 case EPERM:
c0301fcc 51 case EROFS:
ca441480
PB
52 return NBD_EPERM;
53 case EIO:
54 return NBD_EIO;
55 case ENOMEM:
56 return NBD_ENOMEM;
57#ifdef EDQUOT
58 case EDQUOT:
59#endif
60 case EFBIG:
61 case ENOSPC:
62 return NBD_ENOSPC;
bae245d1
EB
63 case EOVERFLOW:
64 return NBD_EOVERFLOW;
0a479545
EB
65 case ENOTSUP:
66#if ENOTSUP != EOPNOTSUPP
67 case EOPNOTSUPP:
68#endif
69 return NBD_ENOTSUP;
b6f5d3b5
EB
70 case ESHUTDOWN:
71 return NBD_ESHUTDOWN;
ca441480
PB
72 case EINVAL:
73 default:
74 return NBD_EINVAL;
75 }
76}
77
9a304d29
PB
78/* Definitions for opaque data types */
79
315f78ab 80typedef struct NBDRequestData NBDRequestData;
9a304d29 81
315f78ab 82struct NBDRequestData {
9a304d29
PB
83 NBDClient *client;
84 uint8_t *data;
29b6c3b3 85 bool complete;
9a304d29
PB
86};
87
88struct NBDExport {
56ee8626 89 BlockExport common;
0ddf08db 90
ee0a19ec 91 char *name;
b1a75b33 92 char *description;
9d26dfcb 93 uint64_t size;
7423f417 94 uint16_t nbdflags;
4b9441f6 95 QTAILQ_HEAD(, NBDClient) clients;
ee0a19ec 96 QTAILQ_ENTRY(NBDExport) next;
958c717d 97
cd7fca95 98 BlockBackend *eject_notifier_blk;
741cc431 99 Notifier eject_notifier;
3d068aff 100
71719cd5 101 bool allocation_depth;
3b1f244c
EB
102 BdrvDirtyBitmap **export_bitmaps;
103 size_t nr_export_bitmaps;
9a304d29
PB
104};
105
ee0a19ec
PB
106static QTAILQ_HEAD(, NBDExport) exports = QTAILQ_HEAD_INITIALIZER(exports);
107
e7b1948d
VSO
108/* NBDExportMetaContexts represents a list of contexts to be exported,
109 * as selected by NBD_OPT_SET_META_CONTEXT. Also used for
110 * NBD_OPT_LIST_META_CONTEXT. */
111typedef struct NBDExportMetaContexts {
af736e54 112 NBDExport *exp;
47ec485e 113 size_t count; /* number of negotiated contexts */
e7b1948d 114 bool base_allocation; /* export base:allocation context (block status) */
71719cd5 115 bool allocation_depth; /* export qemu:allocation-depth */
3b1f244c
EB
116 bool *bitmaps; /*
117 * export qemu:dirty-bitmap:<export bitmap name>,
118 * sized by exp->nr_export_bitmaps
119 */
e7b1948d
VSO
120} NBDExportMetaContexts;
121
9a304d29
PB
122struct NBDClient {
123 int refcount;
0c9390d9 124 void (*close_fn)(NBDClient *client, bool negotiated);
9a304d29
PB
125
126 NBDExport *exp;
f95910fe 127 QCryptoTLSCreds *tlscreds;
b25e12da 128 char *tlsauthz;
1c778ef7
DB
129 QIOChannelSocket *sioc; /* The underlying data channel */
130 QIOChannel *ioc; /* The current I/O channel which may differ (eg TLS) */
9a304d29
PB
131
132 Coroutine *recv_coroutine;
133
134 CoMutex send_lock;
135 Coroutine *send_coroutine;
136
f148ae7d
SL
137 bool read_yielding;
138 bool quiescing;
139
4b9441f6 140 QTAILQ_ENTRY(NBDClient) next;
9a304d29 141 int nb_requests;
ff2b68aa 142 bool closing;
5c54e7fa 143
6e280648
EB
144 uint32_t check_align; /* If non-zero, check for aligned client requests */
145
ac132d05 146 NBDMode mode;
e7b1948d 147 NBDExportMetaContexts export_meta;
9a304d29 148
0cfae925
VSO
149 uint32_t opt; /* Current option being negotiated */
150 uint32_t optlen; /* remaining length of data in ioc for the option being
151 negotiated now */
152};
7a5ca864 153
ff82911c 154static void nbd_client_receive_next_request(NBDClient *client);
958c717d 155
6b8c01e7 156/* Basic flow for negotiation
7a5ca864
FB
157
158 Server Client
7a5ca864 159 Negotiate
6b8c01e7
PB
160
161 or
162
163 Server Client
164 Negotiate #1
165 Option
166 Negotiate #2
167
168 ----
169
170 followed by
171
172 Server Client
7a5ca864
FB
173 Request
174 Response
175 Request
176 Response
177 ...
178 ...
179 Request (type == 2)
6b8c01e7 180
7a5ca864
FB
181*/
182
1d17922a
VSO
183static inline void set_be_option_rep(NBDOptionReply *rep, uint32_t option,
184 uint32_t type, uint32_t length)
185{
186 stq_be_p(&rep->magic, NBD_REP_MAGIC);
187 stl_be_p(&rep->option, option);
188 stl_be_p(&rep->type, type);
189 stl_be_p(&rep->length, length);
190}
191
526e5c65
EB
192/* Send a reply header, including length, but no payload.
193 * Return -errno on error, 0 on success. */
0cfae925
VSO
194static int nbd_negotiate_send_rep_len(NBDClient *client, uint32_t type,
195 uint32_t len, Error **errp)
6b8c01e7 196{
1d17922a 197 NBDOptionReply rep;
6b8c01e7 198
1d17922a 199 trace_nbd_negotiate_send_rep_len(client->opt, nbd_opt_lookup(client->opt),
3736cc5b 200 type, nbd_rep_lookup(type), len);
f95910fe 201
f37708f6 202 assert(len < NBD_MAX_BUFFER_SIZE);
2fd2c840 203
1d17922a
VSO
204 set_be_option_rep(&rep, client->opt, type, len);
205 return nbd_write(client->ioc, &rep, sizeof(rep), errp);
f5076b5a 206}
6b8c01e7 207
526e5c65
EB
208/* Send a reply header with default 0 length.
209 * Return -errno on error, 0 on success. */
0cfae925 210static int nbd_negotiate_send_rep(NBDClient *client, uint32_t type,
2fd2c840 211 Error **errp)
526e5c65 212{
0cfae925 213 return nbd_negotiate_send_rep_len(client, type, 0, errp);
526e5c65
EB
214}
215
36683283
EB
216/* Send an error reply.
217 * Return -errno on error, 0 on success. */
9edc6313 218static int G_GNUC_PRINTF(4, 0)
41f5dfaf
EB
219nbd_negotiate_send_rep_verr(NBDClient *client, uint32_t type,
220 Error **errp, const char *fmt, va_list va)
36683283 221{
795d946d 222 ERRP_GUARD();
df18c04e 223 g_autofree char *msg = NULL;
36683283
EB
224 int ret;
225 size_t len;
226
36683283 227 msg = g_strdup_vprintf(fmt, va);
36683283 228 len = strlen(msg);
5c4fe018 229 assert(len < NBD_MAX_STRING_SIZE);
9588463e 230 trace_nbd_negotiate_send_rep_err(msg);
0cfae925 231 ret = nbd_negotiate_send_rep_len(client, type, len, errp);
36683283 232 if (ret < 0) {
df18c04e 233 return ret;
36683283 234 }
0cfae925 235 if (nbd_write(client->ioc, msg, len, errp) < 0) {
2fd2c840 236 error_prepend(errp, "write failed (error message): ");
df18c04e 237 return -EIO;
36683283 238 }
2fd2c840 239
df18c04e 240 return 0;
36683283
EB
241}
242
5c4fe018
EB
243/*
244 * Return a malloc'd copy of @name suitable for use in an error reply.
245 */
246static char *
247nbd_sanitize_name(const char *name)
248{
249 if (strnlen(name, 80) < 80) {
250 return g_strdup(name);
251 }
252 /* XXX Should we also try to sanitize any control characters? */
253 return g_strdup_printf("%.80s...", name);
254}
255
41f5dfaf
EB
256/* Send an error reply.
257 * Return -errno on error, 0 on success. */
9edc6313 258static int G_GNUC_PRINTF(4, 5)
41f5dfaf
EB
259nbd_negotiate_send_rep_err(NBDClient *client, uint32_t type,
260 Error **errp, const char *fmt, ...)
261{
262 va_list va;
263 int ret;
264
265 va_start(va, fmt);
266 ret = nbd_negotiate_send_rep_verr(client, type, errp, fmt, va);
267 va_end(va);
268 return ret;
269}
270
894e0280
EB
271/* Drop remainder of the current option, and send a reply with the
272 * given error type and message. Return -errno on read or write
273 * failure; or 0 if connection is still live. */
9edc6313 274static int G_GNUC_PRINTF(4, 0)
2e425fd5
VSO
275nbd_opt_vdrop(NBDClient *client, uint32_t type, Error **errp,
276 const char *fmt, va_list va)
894e0280
EB
277{
278 int ret = nbd_drop(client->ioc, client->optlen, errp);
894e0280
EB
279
280 client->optlen = 0;
281 if (!ret) {
894e0280 282 ret = nbd_negotiate_send_rep_verr(client, type, errp, fmt, va);
894e0280
EB
283 }
284 return ret;
285}
286
9edc6313 287static int G_GNUC_PRINTF(4, 5)
2e425fd5
VSO
288nbd_opt_drop(NBDClient *client, uint32_t type, Error **errp,
289 const char *fmt, ...)
290{
291 int ret;
292 va_list va;
293
294 va_start(va, fmt);
295 ret = nbd_opt_vdrop(client, type, errp, fmt, va);
296 va_end(va);
297
298 return ret;
299}
300
9edc6313 301static int G_GNUC_PRINTF(3, 4)
2e425fd5
VSO
302nbd_opt_invalid(NBDClient *client, Error **errp, const char *fmt, ...)
303{
304 int ret;
305 va_list va;
306
307 va_start(va, fmt);
308 ret = nbd_opt_vdrop(client, NBD_REP_ERR_INVALID, errp, fmt, va);
309 va_end(va);
310
311 return ret;
312}
313
894e0280 314/* Read size bytes from the unparsed payload of the current option.
d1e2c3e7 315 * If @check_nul, require that no NUL bytes appear in buffer.
894e0280
EB
316 * Return -errno on I/O error, 0 if option was completely handled by
317 * sending a reply about inconsistent lengths, or 1 on success. */
318static int nbd_opt_read(NBDClient *client, void *buffer, size_t size,
d1e2c3e7 319 bool check_nul, Error **errp)
894e0280
EB
320{
321 if (size > client->optlen) {
2e425fd5
VSO
322 return nbd_opt_invalid(client, errp,
323 "Inconsistent lengths in option %s",
324 nbd_opt_lookup(client->opt));
894e0280
EB
325 }
326 client->optlen -= size;
d1e2c3e7
EB
327 if (qio_channel_read_all(client->ioc, buffer, size, errp) < 0) {
328 return -EIO;
329 }
330
331 if (check_nul && strnlen(buffer, size) != size) {
332 return nbd_opt_invalid(client, errp,
333 "Unexpected embedded NUL in option %s",
334 nbd_opt_lookup(client->opt));
335 }
336 return 1;
894e0280
EB
337}
338
e7b1948d
VSO
339/* Drop size bytes from the unparsed payload of the current option.
340 * Return -errno on I/O error, 0 if option was completely handled by
341 * sending a reply about inconsistent lengths, or 1 on success. */
342static int nbd_opt_skip(NBDClient *client, size_t size, Error **errp)
343{
344 if (size > client->optlen) {
345 return nbd_opt_invalid(client, errp,
346 "Inconsistent lengths in option %s",
347 nbd_opt_lookup(client->opt));
348 }
349 client->optlen -= size;
350 return nbd_drop(client->ioc, size, errp) < 0 ? -EIO : 1;
351}
352
12296459
VSO
353/* nbd_opt_read_name
354 *
355 * Read a string with the format:
93676c88 356 * uint32_t len (<= NBD_MAX_STRING_SIZE)
12296459
VSO
357 * len bytes string (not 0-terminated)
358 *
9d7ab222 359 * On success, @name will be allocated.
12296459
VSO
360 * If @length is non-null, it will be set to the actual string length.
361 *
362 * Return -errno on I/O error, 0 if option was completely handled by
363 * sending a reply about inconsistent lengths, or 1 on success.
364 */
9d7ab222 365static int nbd_opt_read_name(NBDClient *client, char **name, uint32_t *length,
12296459
VSO
366 Error **errp)
367{
368 int ret;
369 uint32_t len;
9d7ab222 370 g_autofree char *local_name = NULL;
12296459 371
9d7ab222 372 *name = NULL;
d1e2c3e7 373 ret = nbd_opt_read(client, &len, sizeof(len), false, errp);
12296459
VSO
374 if (ret <= 0) {
375 return ret;
376 }
80c7c2b0 377 len = cpu_to_be32(len);
12296459 378
93676c88 379 if (len > NBD_MAX_STRING_SIZE) {
12296459
VSO
380 return nbd_opt_invalid(client, errp,
381 "Invalid name length: %" PRIu32, len);
382 }
383
9d7ab222 384 local_name = g_malloc(len + 1);
d1e2c3e7 385 ret = nbd_opt_read(client, local_name, len, true, errp);
12296459
VSO
386 if (ret <= 0) {
387 return ret;
388 }
9d7ab222 389 local_name[len] = '\0';
12296459
VSO
390
391 if (length) {
392 *length = len;
393 }
9d7ab222 394 *name = g_steal_pointer(&local_name);
12296459
VSO
395
396 return 1;
397}
398
526e5c65
EB
399/* Send a single NBD_REP_SERVER reply to NBD_OPT_LIST, including payload.
400 * Return -errno on error, 0 on success. */
0cfae925 401static int nbd_negotiate_send_rep_list(NBDClient *client, NBDExport *exp,
2fd2c840 402 Error **errp)
32d7d2e0 403{
795d946d 404 ERRP_GUARD();
b1a75b33 405 size_t name_len, desc_len;
526e5c65 406 uint32_t len;
b1a75b33
EB
407 const char *name = exp->name ? exp->name : "";
408 const char *desc = exp->description ? exp->description : "";
0cfae925 409 QIOChannel *ioc = client->ioc;
2e5c9ad6 410 int ret;
32d7d2e0 411
9588463e 412 trace_nbd_negotiate_send_rep_list(name, desc);
b1a75b33
EB
413 name_len = strlen(name);
414 desc_len = strlen(desc);
93676c88 415 assert(name_len <= NBD_MAX_STRING_SIZE && desc_len <= NBD_MAX_STRING_SIZE);
526e5c65 416 len = name_len + desc_len + sizeof(len);
0cfae925 417 ret = nbd_negotiate_send_rep_len(client, NBD_REP_SERVER, len, errp);
2e5c9ad6
VSO
418 if (ret < 0) {
419 return ret;
32d7d2e0 420 }
526e5c65 421
32d7d2e0 422 len = cpu_to_be32(name_len);
2fd2c840
VSO
423 if (nbd_write(ioc, &len, sizeof(len), errp) < 0) {
424 error_prepend(errp, "write failed (name length): ");
b1a75b33
EB
425 return -EINVAL;
426 }
2fd2c840
VSO
427
428 if (nbd_write(ioc, name, name_len, errp) < 0) {
429 error_prepend(errp, "write failed (name buffer): ");
32d7d2e0
HB
430 return -EINVAL;
431 }
2fd2c840
VSO
432
433 if (nbd_write(ioc, desc, desc_len, errp) < 0) {
434 error_prepend(errp, "write failed (description buffer): ");
32d7d2e0
HB
435 return -EINVAL;
436 }
2fd2c840 437
32d7d2e0
HB
438 return 0;
439}
440
526e5c65
EB
441/* Process the NBD_OPT_LIST command, with a potential series of replies.
442 * Return -errno on error, 0 on success. */
e68c35cf 443static int nbd_negotiate_handle_list(NBDClient *client, Error **errp)
32d7d2e0 444{
32d7d2e0 445 NBDExport *exp;
0cfae925 446 assert(client->opt == NBD_OPT_LIST);
32d7d2e0 447
32d7d2e0
HB
448 /* For each export, send a NBD_REP_SERVER reply. */
449 QTAILQ_FOREACH(exp, &exports, next) {
0cfae925 450 if (nbd_negotiate_send_rep_list(client, exp, errp)) {
32d7d2e0
HB
451 return -EINVAL;
452 }
453 }
454 /* Finish with a NBD_REP_ACK. */
0cfae925 455 return nbd_negotiate_send_rep(client, NBD_REP_ACK, errp);
32d7d2e0
HB
456}
457
af736e54 458static void nbd_check_meta_export(NBDClient *client)
e7b1948d 459{
47ec485e
EB
460 if (client->exp != client->export_meta.exp) {
461 client->export_meta.count = 0;
462 }
e7b1948d
VSO
463}
464
f37708f6
EB
465/* Send a reply to NBD_OPT_EXPORT_NAME.
466 * Return -errno on error, 0 on success. */
dbb38caa 467static int nbd_negotiate_handle_export_name(NBDClient *client, bool no_zeroes,
2fd2c840 468 Error **errp)
f5076b5a 469{
795d946d 470 ERRP_GUARD();
9d7ab222 471 g_autofree char *name = NULL;
5f66d060 472 char buf[NBD_REPLY_EXPORT_NAME_SIZE] = "";
23e099c3
EB
473 size_t len;
474 int ret;
dbb38caa 475 uint16_t myflags;
6b8c01e7 476
f5076b5a
HB
477 /* Client sends:
478 [20 .. xx] export name (length bytes)
5f66d060
EB
479 Server replies:
480 [ 0 .. 7] size
481 [ 8 .. 9] export flags
482 [10 .. 133] reserved (0) [unless no_zeroes]
f5076b5a 483 */
9588463e 484 trace_nbd_negotiate_handle_export_name();
93676c88 485 if (client->optlen > NBD_MAX_STRING_SIZE) {
2fd2c840 486 error_setg(errp, "Bad length received");
d9faeed8 487 return -EINVAL;
6b8c01e7 488 }
9d7ab222 489 name = g_malloc(client->optlen + 1);
e6798f06 490 if (nbd_read(client->ioc, name, client->optlen, "export name", errp) < 0) {
32f158a6 491 return -EIO;
6b8c01e7 492 }
0cfae925
VSO
493 name[client->optlen] = '\0';
494 client->optlen = 0;
6b8c01e7 495
9588463e 496 trace_nbd_negotiate_handle_export_name_request(name);
9344e5f5 497
6b8c01e7
PB
498 client->exp = nbd_export_find(name);
499 if (!client->exp) {
2fd2c840 500 error_setg(errp, "export not found");
d9faeed8 501 return -EINVAL;
6b8c01e7
PB
502 }
503
dbb38caa 504 myflags = client->exp->nbdflags;
ac132d05 505 if (client->mode >= NBD_MODE_STRUCTURED) {
dbb38caa
EB
506 myflags |= NBD_FLAG_SEND_DF;
507 }
508 trace_nbd_negotiate_new_style_size_flags(client->exp->size, myflags);
23e099c3 509 stq_be_p(buf, client->exp->size);
dbb38caa 510 stw_be_p(buf + 8, myflags);
23e099c3
EB
511 len = no_zeroes ? 10 : sizeof(buf);
512 ret = nbd_write(client->ioc, buf, len, errp);
513 if (ret < 0) {
514 error_prepend(errp, "write failed: ");
515 return ret;
516 }
517
6b8c01e7 518 QTAILQ_INSERT_TAIL(&client->exp->clients, client, next);
c69de1be 519 blk_exp_ref(&client->exp->common);
af736e54 520 nbd_check_meta_export(client);
d9faeed8
VSO
521
522 return 0;
6b8c01e7
PB
523}
524
f37708f6
EB
525/* Send a single NBD_REP_INFO, with a buffer @buf of @length bytes.
526 * The buffer does NOT include the info type prefix.
527 * Return -errno on error, 0 if ready to send more. */
0cfae925 528static int nbd_negotiate_send_info(NBDClient *client,
f37708f6
EB
529 uint16_t info, uint32_t length, void *buf,
530 Error **errp)
531{
532 int rc;
533
534 trace_nbd_negotiate_send_info(info, nbd_info_lookup(info), length);
0cfae925 535 rc = nbd_negotiate_send_rep_len(client, NBD_REP_INFO,
f37708f6
EB
536 sizeof(info) + length, errp);
537 if (rc < 0) {
538 return rc;
539 }
80c7c2b0 540 info = cpu_to_be16(info);
f37708f6
EB
541 if (nbd_write(client->ioc, &info, sizeof(info), errp) < 0) {
542 return -EIO;
543 }
544 if (nbd_write(client->ioc, buf, length, errp) < 0) {
545 return -EIO;
546 }
547 return 0;
548}
549
a16a7907
EB
550/* nbd_reject_length: Handle any unexpected payload.
551 * @fatal requests that we quit talking to the client, even if we are able
552 * to successfully send an error reply.
553 * Return:
554 * -errno transmission error occurred or @fatal was requested, errp is set
555 * 0 error message successfully sent to client, errp is not set
556 */
0cfae925 557static int nbd_reject_length(NBDClient *client, bool fatal, Error **errp)
a16a7907
EB
558{
559 int ret;
560
0cfae925 561 assert(client->optlen);
2e425fd5
VSO
562 ret = nbd_opt_invalid(client, errp, "option '%s' has unexpected length",
563 nbd_opt_lookup(client->opt));
a16a7907 564 if (fatal && !ret) {
894e0280 565 error_setg(errp, "option '%s' has unexpected length",
0cfae925 566 nbd_opt_lookup(client->opt));
a16a7907
EB
567 return -EINVAL;
568 }
569 return ret;
570}
571
f37708f6
EB
572/* Handle NBD_OPT_INFO and NBD_OPT_GO.
573 * Return -errno on error, 0 if ready for next option, and 1 to move
574 * into transmission phase. */
dbb38caa 575static int nbd_negotiate_handle_info(NBDClient *client, Error **errp)
f37708f6
EB
576{
577 int rc;
9d7ab222 578 g_autofree char *name = NULL;
f37708f6
EB
579 NBDExport *exp;
580 uint16_t requests;
581 uint16_t request;
bbc35fc2 582 uint32_t namelen = 0;
f37708f6 583 bool sendname = false;
0c1d50bd
EB
584 bool blocksize = false;
585 uint32_t sizes[3];
f37708f6 586 char buf[sizeof(uint64_t) + sizeof(uint16_t)];
6e280648 587 uint32_t check_align = 0;
dbb38caa 588 uint16_t myflags;
f37708f6
EB
589
590 /* Client sends:
591 4 bytes: L, name length (can be 0)
592 L bytes: export name
593 2 bytes: N, number of requests (can be 0)
594 N * 2 bytes: N requests
595 */
9d7ab222 596 rc = nbd_opt_read_name(client, &name, &namelen, errp);
894e0280
EB
597 if (rc <= 0) {
598 return rc;
f37708f6 599 }
f37708f6
EB
600 trace_nbd_negotiate_handle_export_name_request(name);
601
d1e2c3e7 602 rc = nbd_opt_read(client, &requests, sizeof(requests), false, errp);
894e0280
EB
603 if (rc <= 0) {
604 return rc;
f37708f6 605 }
80c7c2b0 606 requests = be16_to_cpu(requests);
f37708f6 607 trace_nbd_negotiate_handle_info_requests(requests);
f37708f6 608 while (requests--) {
d1e2c3e7 609 rc = nbd_opt_read(client, &request, sizeof(request), false, errp);
894e0280
EB
610 if (rc <= 0) {
611 return rc;
f37708f6 612 }
80c7c2b0 613 request = be16_to_cpu(request);
f37708f6
EB
614 trace_nbd_negotiate_handle_info_request(request,
615 nbd_info_lookup(request));
0c1d50bd
EB
616 /* We care about NBD_INFO_NAME and NBD_INFO_BLOCK_SIZE;
617 * everything else is either a request we don't know or
618 * something we send regardless of request */
619 switch (request) {
620 case NBD_INFO_NAME:
f37708f6 621 sendname = true;
0c1d50bd
EB
622 break;
623 case NBD_INFO_BLOCK_SIZE:
624 blocksize = true;
625 break;
f37708f6
EB
626 }
627 }
894e0280
EB
628 if (client->optlen) {
629 return nbd_reject_length(client, false, errp);
630 }
f37708f6
EB
631
632 exp = nbd_export_find(name);
633 if (!exp) {
5c4fe018
EB
634 g_autofree char *sane_name = nbd_sanitize_name(name);
635
0cfae925
VSO
636 return nbd_negotiate_send_rep_err(client, NBD_REP_ERR_UNKNOWN,
637 errp, "export '%s' not present",
5c4fe018 638 sane_name);
f37708f6
EB
639 }
640
641 /* Don't bother sending NBD_INFO_NAME unless client requested it */
642 if (sendname) {
0cfae925 643 rc = nbd_negotiate_send_info(client, NBD_INFO_NAME, namelen, name,
f37708f6
EB
644 errp);
645 if (rc < 0) {
646 return rc;
647 }
648 }
649
650 /* Send NBD_INFO_DESCRIPTION only if available, regardless of
651 * client request */
652 if (exp->description) {
653 size_t len = strlen(exp->description);
654
93676c88 655 assert(len <= NBD_MAX_STRING_SIZE);
0cfae925 656 rc = nbd_negotiate_send_info(client, NBD_INFO_DESCRIPTION,
f37708f6
EB
657 len, exp->description, errp);
658 if (rc < 0) {
659 return rc;
660 }
661 }
662
0c1d50bd
EB
663 /* Send NBD_INFO_BLOCK_SIZE always, but tweak the minimum size
664 * according to whether the client requested it, and according to
665 * whether this is OPT_INFO or OPT_GO. */
b0245d64
EB
666 /* minimum - 1 for back-compat, or actual if client will obey it. */
667 if (client->opt == NBD_OPT_INFO || blocksize) {
37a4f70c 668 check_align = sizes[0] = blk_get_request_alignment(exp->common.blk);
b0245d64
EB
669 } else {
670 sizes[0] = 1;
671 }
672 assert(sizes[0] <= NBD_MAX_BUFFER_SIZE);
0c1d50bd
EB
673 /* preferred - Hard-code to 4096 for now.
674 * TODO: is blk_bs(blk)->bl.opt_transfer appropriate? */
b0245d64 675 sizes[1] = MAX(4096, sizes[0]);
0c1d50bd 676 /* maximum - At most 32M, but smaller as appropriate. */
37a4f70c 677 sizes[2] = MIN(blk_get_max_transfer(exp->common.blk), NBD_MAX_BUFFER_SIZE);
0c1d50bd 678 trace_nbd_negotiate_handle_info_block_size(sizes[0], sizes[1], sizes[2]);
80c7c2b0
PM
679 sizes[0] = cpu_to_be32(sizes[0]);
680 sizes[1] = cpu_to_be32(sizes[1]);
681 sizes[2] = cpu_to_be32(sizes[2]);
0cfae925 682 rc = nbd_negotiate_send_info(client, NBD_INFO_BLOCK_SIZE,
0c1d50bd
EB
683 sizeof(sizes), sizes, errp);
684 if (rc < 0) {
685 return rc;
686 }
687
f37708f6 688 /* Send NBD_INFO_EXPORT always */
dbb38caa 689 myflags = exp->nbdflags;
ac132d05 690 if (client->mode >= NBD_MODE_STRUCTURED) {
dbb38caa
EB
691 myflags |= NBD_FLAG_SEND_DF;
692 }
693 trace_nbd_negotiate_new_style_size_flags(exp->size, myflags);
f37708f6 694 stq_be_p(buf, exp->size);
dbb38caa 695 stw_be_p(buf + 8, myflags);
0cfae925 696 rc = nbd_negotiate_send_info(client, NBD_INFO_EXPORT,
f37708f6
EB
697 sizeof(buf), buf, errp);
698 if (rc < 0) {
699 return rc;
700 }
701
099fbcd6
EB
702 /*
703 * If the client is just asking for NBD_OPT_INFO, but forgot to
704 * request block sizes in a situation that would impact
705 * performance, then return an error. But for NBD_OPT_GO, we
706 * tolerate all clients, regardless of alignments.
707 */
708 if (client->opt == NBD_OPT_INFO && !blocksize &&
37a4f70c 709 blk_get_request_alignment(exp->common.blk) > 1) {
0cfae925
VSO
710 return nbd_negotiate_send_rep_err(client,
711 NBD_REP_ERR_BLOCK_SIZE_REQD,
0c1d50bd
EB
712 errp,
713 "request NBD_INFO_BLOCK_SIZE to "
714 "use this export");
715 }
716
f37708f6 717 /* Final reply */
0cfae925 718 rc = nbd_negotiate_send_rep(client, NBD_REP_ACK, errp);
f37708f6
EB
719 if (rc < 0) {
720 return rc;
721 }
722
0cfae925 723 if (client->opt == NBD_OPT_GO) {
f37708f6 724 client->exp = exp;
6e280648 725 client->check_align = check_align;
f37708f6 726 QTAILQ_INSERT_TAIL(&client->exp->clients, client, next);
c69de1be 727 blk_exp_ref(&client->exp->common);
af736e54 728 nbd_check_meta_export(client);
f37708f6
EB
729 rc = 1;
730 }
731 return rc;
f37708f6
EB
732}
733
734
36683283
EB
735/* Handle NBD_OPT_STARTTLS. Return NULL to drop connection, or else the
736 * new channel for all further (now-encrypted) communication. */
f95910fe 737static QIOChannel *nbd_negotiate_handle_starttls(NBDClient *client,
2fd2c840 738 Error **errp)
f95910fe
DB
739{
740 QIOChannel *ioc;
741 QIOChannelTLS *tioc;
742 struct NBDTLSHandshakeData data = { 0 };
743
0cfae925
VSO
744 assert(client->opt == NBD_OPT_STARTTLS);
745
9588463e 746 trace_nbd_negotiate_handle_starttls();
f95910fe 747 ioc = client->ioc;
f95910fe 748
0cfae925 749 if (nbd_negotiate_send_rep(client, NBD_REP_ACK, errp) < 0) {
63d5ef86
EB
750 return NULL;
751 }
f95910fe
DB
752
753 tioc = qio_channel_tls_new_server(ioc,
754 client->tlscreds,
b25e12da 755 client->tlsauthz,
2fd2c840 756 errp);
f95910fe
DB
757 if (!tioc) {
758 return NULL;
759 }
760
0d73f725 761 qio_channel_set_name(QIO_CHANNEL(tioc), "nbd-server-tls");
9588463e 762 trace_nbd_negotiate_handle_starttls_handshake();
f95910fe
DB
763 data.loop = g_main_loop_new(g_main_context_default(), FALSE);
764 qio_channel_tls_handshake(tioc,
765 nbd_tls_handshake,
766 &data,
1939ccda 767 NULL,
f95910fe
DB
768 NULL);
769
770 if (!data.complete) {
771 g_main_loop_run(data.loop);
772 }
773 g_main_loop_unref(data.loop);
774 if (data.error) {
775 object_unref(OBJECT(tioc));
2fd2c840 776 error_propagate(errp, data.error);
f95910fe
DB
777 return NULL;
778 }
779
780 return QIO_CHANNEL(tioc);
781}
782
e7b1948d
VSO
783/* nbd_negotiate_send_meta_context
784 *
785 * Send one chunk of reply to NBD_OPT_{LIST,SET}_META_CONTEXT
786 *
787 * For NBD_OPT_LIST_META_CONTEXT @context_id is ignored, 0 is used instead.
788 */
789static int nbd_negotiate_send_meta_context(NBDClient *client,
790 const char *context,
791 uint32_t context_id,
792 Error **errp)
793{
794 NBDOptionReplyMetaContext opt;
795 struct iovec iov[] = {
796 {.iov_base = &opt, .iov_len = sizeof(opt)},
797 {.iov_base = (void *)context, .iov_len = strlen(context)}
798 };
799
93676c88 800 assert(iov[1].iov_len <= NBD_MAX_STRING_SIZE);
e7b1948d
VSO
801 if (client->opt == NBD_OPT_LIST_META_CONTEXT) {
802 context_id = 0;
803 }
804
2b53af25 805 trace_nbd_negotiate_meta_query_reply(context, context_id);
e7b1948d
VSO
806 set_be_option_rep(&opt.h, client->opt, NBD_REP_META_CONTEXT,
807 sizeof(opt) - sizeof(opt.h) + iov[1].iov_len);
808 stl_be_p(&opt.context_id, context_id);
809
810 return qio_channel_writev_all(client->ioc, iov, 2, errp) < 0 ? -EIO : 0;
811}
812
ebd57062
EB
813/*
814 * Return true if @query matches @pattern, or if @query is empty when
815 * the @client is performing _LIST_.
dbb8b396 816 */
ebd57062
EB
817static bool nbd_meta_empty_or_pattern(NBDClient *client, const char *pattern,
818 const char *query)
e7b1948d 819{
ebd57062
EB
820 if (!*query) {
821 trace_nbd_negotiate_meta_query_parse("empty");
822 return client->opt == NBD_OPT_LIST_META_CONTEXT;
e7b1948d 823 }
ebd57062 824 if (strcmp(query, pattern) == 0) {
b0769d8f 825 trace_nbd_negotiate_meta_query_parse(pattern);
ebd57062 826 return true;
e7b1948d 827 }
ebd57062
EB
828 trace_nbd_negotiate_meta_query_skip("pattern not matched");
829 return false;
e7b1948d
VSO
830}
831
b0769d8f 832/*
ebd57062 833 * Return true and adjust @str in place if it begins with @prefix.
b0769d8f 834 */
ebd57062 835static bool nbd_strshift(const char **str, const char *prefix)
b0769d8f 836{
ebd57062 837 size_t len = strlen(prefix);
b0769d8f 838
ebd57062
EB
839 if (strncmp(*str, prefix, len) == 0) {
840 *str += len;
841 return true;
b0769d8f 842 }
ebd57062 843 return false;
b0769d8f
VSO
844}
845
846/* nbd_meta_base_query
847 *
848 * Handle queries to 'base' namespace. For now, only the base:allocation
ebd57062 849 * context is available. Return true if @query has been handled.
b0769d8f 850 */
ebd57062
EB
851static bool nbd_meta_base_query(NBDClient *client, NBDExportMetaContexts *meta,
852 const char *query)
b0769d8f 853{
ebd57062
EB
854 if (!nbd_strshift(&query, "base:")) {
855 return false;
856 }
857 trace_nbd_negotiate_meta_query_parse("base:");
858
859 if (nbd_meta_empty_or_pattern(client, "allocation", query)) {
860 meta->base_allocation = true;
861 }
862 return true;
b0769d8f
VSO
863}
864
ebd57062 865/* nbd_meta_qemu_query
3d068aff 866 *
ebd57062 867 * Handle queries to 'qemu' namespace. For now, only the qemu:dirty-bitmap:
71719cd5
EB
868 * and qemu:allocation-depth contexts are available. Return true if @query
869 * has been handled.
ebd57062
EB
870 */
871static bool nbd_meta_qemu_query(NBDClient *client, NBDExportMetaContexts *meta,
872 const char *query)
3d068aff 873{
3b1f244c
EB
874 size_t i;
875
ebd57062
EB
876 if (!nbd_strshift(&query, "qemu:")) {
877 return false;
3d068aff 878 }
ebd57062 879 trace_nbd_negotiate_meta_query_parse("qemu:");
3d068aff 880
ebd57062 881 if (!*query) {
3d068aff 882 if (client->opt == NBD_OPT_LIST_META_CONTEXT) {
71719cd5 883 meta->allocation_depth = meta->exp->allocation_depth;
76df2b8d
EB
884 if (meta->exp->nr_export_bitmaps) {
885 memset(meta->bitmaps, 1, meta->exp->nr_export_bitmaps);
886 }
3d068aff
VSO
887 }
888 trace_nbd_negotiate_meta_query_parse("empty");
ebd57062 889 return true;
3d068aff
VSO
890 }
891
71719cd5
EB
892 if (strcmp(query, "allocation-depth") == 0) {
893 trace_nbd_negotiate_meta_query_parse("allocation-depth");
894 meta->allocation_depth = meta->exp->allocation_depth;
895 return true;
896 }
897
ebd57062
EB
898 if (nbd_strshift(&query, "dirty-bitmap:")) {
899 trace_nbd_negotiate_meta_query_parse("dirty-bitmap:");
3b1f244c 900 if (!*query) {
76df2b8d
EB
901 if (client->opt == NBD_OPT_LIST_META_CONTEXT &&
902 meta->exp->nr_export_bitmaps) {
3b1f244c
EB
903 memset(meta->bitmaps, 1, meta->exp->nr_export_bitmaps);
904 }
905 trace_nbd_negotiate_meta_query_parse("empty");
ebd57062
EB
906 return true;
907 }
3b1f244c
EB
908
909 for (i = 0; i < meta->exp->nr_export_bitmaps; i++) {
910 const char *bm_name;
911
912 bm_name = bdrv_dirty_bitmap_name(meta->exp->export_bitmaps[i]);
913 if (strcmp(bm_name, query) == 0) {
914 meta->bitmaps[i] = true;
915 trace_nbd_negotiate_meta_query_parse(query);
916 return true;
917 }
ebd57062 918 }
3b1f244c 919 trace_nbd_negotiate_meta_query_skip("no dirty-bitmap match");
ebd57062 920 return true;
3d068aff
VSO
921 }
922
71719cd5 923 trace_nbd_negotiate_meta_query_skip("unknown qemu context");
ebd57062 924 return true;
3d068aff
VSO
925}
926
e7b1948d
VSO
927/* nbd_negotiate_meta_query
928 *
929 * Parse namespace name and call corresponding function to parse body of the
930 * query.
931 *
93676c88 932 * The only supported namespaces are 'base' and 'qemu'.
e7b1948d 933 *
e7b1948d
VSO
934 * Return -errno on I/O error, 0 if option was completely handled by
935 * sending a reply about inconsistent lengths, or 1 on success. */
936static int nbd_negotiate_meta_query(NBDClient *client,
937 NBDExportMetaContexts *meta, Error **errp)
938{
939 int ret;
ebd57062 940 g_autofree char *query = NULL;
e7b1948d
VSO
941 uint32_t len;
942
d1e2c3e7 943 ret = nbd_opt_read(client, &len, sizeof(len), false, errp);
e7b1948d
VSO
944 if (ret <= 0) {
945 return ret;
946 }
80c7c2b0 947 len = cpu_to_be32(len);
e7b1948d 948
93676c88
EB
949 if (len > NBD_MAX_STRING_SIZE) {
950 trace_nbd_negotiate_meta_query_skip("length too long");
951 return nbd_opt_skip(client, len, errp);
952 }
e7b1948d 953
ebd57062
EB
954 query = g_malloc(len + 1);
955 ret = nbd_opt_read(client, query, len, true, errp);
e7b1948d
VSO
956 if (ret <= 0) {
957 return ret;
958 }
ebd57062 959 query[len] = '\0';
3d068aff 960
ebd57062
EB
961 if (nbd_meta_base_query(client, meta, query)) {
962 return 1;
963 }
964 if (nbd_meta_qemu_query(client, meta, query)) {
965 return 1;
e7b1948d
VSO
966 }
967
3d068aff 968 trace_nbd_negotiate_meta_query_skip("unknown namespace");
ebd57062 969 return 1;
e7b1948d
VSO
970}
971
972/* nbd_negotiate_meta_queries
973 * Handle NBD_OPT_LIST_META_CONTEXT and NBD_OPT_SET_META_CONTEXT
974 *
975 * Return -errno on I/O error, or 0 if option was completely handled. */
976static int nbd_negotiate_meta_queries(NBDClient *client,
977 NBDExportMetaContexts *meta, Error **errp)
978{
979 int ret;
9d7ab222 980 g_autofree char *export_name = NULL;
cd1675f8
RH
981 /* Mark unused to work around https://bugs.llvm.org/show_bug.cgi?id=3888 */
982 g_autofree G_GNUC_UNUSED bool *bitmaps = NULL;
3b1f244c 983 NBDExportMetaContexts local_meta = {0};
e7b1948d 984 uint32_t nb_queries;
3b1f244c 985 size_t i;
47ec485e 986 size_t count = 0;
e7b1948d 987
ac132d05
EB
988 if (client->opt == NBD_OPT_SET_META_CONTEXT &&
989 client->mode < NBD_MODE_STRUCTURED) {
e7b1948d
VSO
990 return nbd_opt_invalid(client, errp,
991 "request option '%s' when structured reply "
992 "is not negotiated",
993 nbd_opt_lookup(client->opt));
994 }
995
996 if (client->opt == NBD_OPT_LIST_META_CONTEXT) {
997 /* Only change the caller's meta on SET. */
998 meta = &local_meta;
999 }
1000
3b1f244c 1001 g_free(meta->bitmaps);
e7b1948d
VSO
1002 memset(meta, 0, sizeof(*meta));
1003
9d7ab222 1004 ret = nbd_opt_read_name(client, &export_name, NULL, errp);
e7b1948d
VSO
1005 if (ret <= 0) {
1006 return ret;
1007 }
1008
af736e54
VSO
1009 meta->exp = nbd_export_find(export_name);
1010 if (meta->exp == NULL) {
5c4fe018
EB
1011 g_autofree char *sane_name = nbd_sanitize_name(export_name);
1012
e7b1948d 1013 return nbd_opt_drop(client, NBD_REP_ERR_UNKNOWN, errp,
5c4fe018 1014 "export '%s' not present", sane_name);
e7b1948d 1015 }
3b1f244c
EB
1016 meta->bitmaps = g_new0(bool, meta->exp->nr_export_bitmaps);
1017 if (client->opt == NBD_OPT_LIST_META_CONTEXT) {
1018 bitmaps = meta->bitmaps;
1019 }
e7b1948d 1020
d1e2c3e7 1021 ret = nbd_opt_read(client, &nb_queries, sizeof(nb_queries), false, errp);
e7b1948d
VSO
1022 if (ret <= 0) {
1023 return ret;
1024 }
80c7c2b0 1025 nb_queries = cpu_to_be32(nb_queries);
2b53af25 1026 trace_nbd_negotiate_meta_context(nbd_opt_lookup(client->opt),
af736e54 1027 export_name, nb_queries);
e7b1948d
VSO
1028
1029 if (client->opt == NBD_OPT_LIST_META_CONTEXT && !nb_queries) {
1030 /* enable all known contexts */
1031 meta->base_allocation = true;
71719cd5 1032 meta->allocation_depth = meta->exp->allocation_depth;
76df2b8d
EB
1033 if (meta->exp->nr_export_bitmaps) {
1034 memset(meta->bitmaps, 1, meta->exp->nr_export_bitmaps);
1035 }
e7b1948d
VSO
1036 } else {
1037 for (i = 0; i < nb_queries; ++i) {
1038 ret = nbd_negotiate_meta_query(client, meta, errp);
1039 if (ret <= 0) {
1040 return ret;
1041 }
1042 }
1043 }
1044
1045 if (meta->base_allocation) {
1046 ret = nbd_negotiate_send_meta_context(client, "base:allocation",
1047 NBD_META_ID_BASE_ALLOCATION,
1048 errp);
1049 if (ret < 0) {
1050 return ret;
1051 }
47ec485e 1052 count++;
e7b1948d
VSO
1053 }
1054
71719cd5
EB
1055 if (meta->allocation_depth) {
1056 ret = nbd_negotiate_send_meta_context(client, "qemu:allocation-depth",
1057 NBD_META_ID_ALLOCATION_DEPTH,
1058 errp);
1059 if (ret < 0) {
1060 return ret;
1061 }
1062 count++;
1063 }
1064
3b1f244c
EB
1065 for (i = 0; i < meta->exp->nr_export_bitmaps; i++) {
1066 const char *bm_name;
1067 g_autofree char *context = NULL;
1068
1069 if (!meta->bitmaps[i]) {
1070 continue;
1071 }
1072
1073 bm_name = bdrv_dirty_bitmap_name(meta->exp->export_bitmaps[i]);
1074 context = g_strdup_printf("qemu:dirty-bitmap:%s", bm_name);
02e87e3b
EB
1075
1076 ret = nbd_negotiate_send_meta_context(client, context,
3b1f244c 1077 NBD_META_ID_DIRTY_BITMAP + i,
3d068aff
VSO
1078 errp);
1079 if (ret < 0) {
1080 return ret;
1081 }
47ec485e 1082 count++;
3d068aff
VSO
1083 }
1084
e7b1948d
VSO
1085 ret = nbd_negotiate_send_rep(client, NBD_REP_ACK, errp);
1086 if (ret == 0) {
47ec485e 1087 meta->count = count;
e7b1948d
VSO
1088 }
1089
1090 return ret;
1091}
1092
1e120ffe 1093/* nbd_negotiate_options
f37708f6
EB
1094 * Process all NBD_OPT_* client option commands, during fixed newstyle
1095 * negotiation.
1e120ffe 1096 * Return:
2fd2c840
VSO
1097 * -errno on error, errp is set
1098 * 0 on successful negotiation, errp is not set
1099 * 1 if client sent NBD_OPT_ABORT, i.e. on valid disconnect,
1100 * errp is not set
1e120ffe 1101 */
dbb38caa 1102static int nbd_negotiate_options(NBDClient *client, Error **errp)
f5076b5a 1103{
9c122ada 1104 uint32_t flags;
26afa868 1105 bool fixedNewstyle = false;
23e099c3 1106 bool no_zeroes = false;
9c122ada
HR
1107
1108 /* Client sends:
1109 [ 0 .. 3] client flags
1110
f37708f6 1111 Then we loop until NBD_OPT_EXPORT_NAME or NBD_OPT_GO:
9c122ada
HR
1112 [ 0 .. 7] NBD_OPTS_MAGIC
1113 [ 8 .. 11] NBD option
1114 [12 .. 15] Data length
1115 ... Rest of request
1116
1117 [ 0 .. 7] NBD_OPTS_MAGIC
1118 [ 8 .. 11] Second NBD option
1119 [12 .. 15] Data length
1120 ... Rest of request
1121 */
1122
e6798f06 1123 if (nbd_read32(client->ioc, &flags, "flags", errp) < 0) {
9c122ada
HR
1124 return -EIO;
1125 }
ac132d05 1126 client->mode = NBD_MODE_EXPORT_NAME;
621c4f4e 1127 trace_nbd_negotiate_options_flags(flags);
26afa868 1128 if (flags & NBD_FLAG_C_FIXED_NEWSTYLE) {
26afa868
DB
1129 fixedNewstyle = true;
1130 flags &= ~NBD_FLAG_C_FIXED_NEWSTYLE;
ac132d05 1131 client->mode = NBD_MODE_SIMPLE;
26afa868 1132 }
c203c59a 1133 if (flags & NBD_FLAG_C_NO_ZEROES) {
23e099c3 1134 no_zeroes = true;
c203c59a
EB
1135 flags &= ~NBD_FLAG_C_NO_ZEROES;
1136 }
26afa868 1137 if (flags != 0) {
2fd2c840 1138 error_setg(errp, "Unknown client flags 0x%" PRIx32 " received", flags);
621c4f4e 1139 return -EINVAL;
9c122ada
HR
1140 }
1141
f5076b5a 1142 while (1) {
9c122ada 1143 int ret;
7f9039cd 1144 uint32_t option, length;
f5076b5a
HB
1145 uint64_t magic;
1146
e6798f06 1147 if (nbd_read64(client->ioc, &magic, "opts magic", errp) < 0) {
f5076b5a
HB
1148 return -EINVAL;
1149 }
9588463e
VSO
1150 trace_nbd_negotiate_options_check_magic(magic);
1151 if (magic != NBD_OPTS_MAGIC) {
2fd2c840 1152 error_setg(errp, "Bad magic received");
f5076b5a
HB
1153 return -EINVAL;
1154 }
1155
e6798f06 1156 if (nbd_read32(client->ioc, &option, "option", errp) < 0) {
f5076b5a
HB
1157 return -EINVAL;
1158 }
0cfae925 1159 client->opt = option;
f5076b5a 1160
e6798f06 1161 if (nbd_read32(client->ioc, &length, "option length", errp) < 0) {
f5076b5a
HB
1162 return -EINVAL;
1163 }
894e0280 1164 assert(!client->optlen);
0cfae925 1165 client->optlen = length;
f5076b5a 1166
fdad35ef 1167 if (length > NBD_MAX_BUFFER_SIZE) {
b2578459 1168 error_setg(errp, "len (%" PRIu32 ") is larger than max len (%u)",
fdad35ef
EB
1169 length, NBD_MAX_BUFFER_SIZE);
1170 return -EINVAL;
1171 }
1172
3736cc5b
EB
1173 trace_nbd_negotiate_options_check_option(option,
1174 nbd_opt_lookup(option));
f95910fe
DB
1175 if (client->tlscreds &&
1176 client->ioc == (QIOChannel *)client->sioc) {
1177 QIOChannel *tioc;
1178 if (!fixedNewstyle) {
7f9039cd 1179 error_setg(errp, "Unsupported option 0x%" PRIx32, option);
f95910fe
DB
1180 return -EINVAL;
1181 }
7f9039cd 1182 switch (option) {
f95910fe 1183 case NBD_OPT_STARTTLS:
e68c35cf
EB
1184 if (length) {
1185 /* Unconditionally drop the connection if the client
1186 * can't start a TLS negotiation correctly */
0cfae925 1187 return nbd_reject_length(client, true, errp);
e68c35cf
EB
1188 }
1189 tioc = nbd_negotiate_handle_starttls(client, errp);
f95910fe
DB
1190 if (!tioc) {
1191 return -EIO;
1192 }
8cbee49e 1193 ret = 0;
f95910fe 1194 object_unref(OBJECT(client->ioc));
7d5b0d68 1195 client->ioc = tioc;
f95910fe
DB
1196 break;
1197
d1129a8a
EB
1198 case NBD_OPT_EXPORT_NAME:
1199 /* No way to return an error to client, so drop connection */
2fd2c840 1200 error_setg(errp, "Option 0x%x not permitted before TLS",
7f9039cd 1201 option);
d1129a8a
EB
1202 return -EINVAL;
1203
f95910fe 1204 default:
3e99ebb9
EB
1205 /* Let the client keep trying, unless they asked to
1206 * quit. Always try to give an error back to the
1207 * client; but when replying to OPT_ABORT, be aware
1208 * that the client may hang up before receiving the
1209 * error, in which case we are fine ignoring the
1210 * resulting EPIPE. */
1211 ret = nbd_opt_drop(client, NBD_REP_ERR_TLS_REQD,
1212 option == NBD_OPT_ABORT ? NULL : errp,
894e0280 1213 "Option 0x%" PRIx32
0b0bb124 1214 " not permitted before TLS", option);
7f9039cd 1215 if (option == NBD_OPT_ABORT) {
1e120ffe 1216 return 1;
b6f5d3b5 1217 }
d1129a8a 1218 break;
f95910fe
DB
1219 }
1220 } else if (fixedNewstyle) {
7f9039cd 1221 switch (option) {
26afa868 1222 case NBD_OPT_LIST:
e68c35cf 1223 if (length) {
0cfae925 1224 ret = nbd_reject_length(client, false, errp);
e68c35cf
EB
1225 } else {
1226 ret = nbd_negotiate_handle_list(client, errp);
1227 }
26afa868
DB
1228 break;
1229
1230 case NBD_OPT_ABORT:
b6f5d3b5
EB
1231 /* NBD spec says we must try to reply before
1232 * disconnecting, but that we must also tolerate
1233 * guests that don't wait for our reply. */
0cfae925 1234 nbd_negotiate_send_rep(client, NBD_REP_ACK, NULL);
1e120ffe 1235 return 1;
26afa868
DB
1236
1237 case NBD_OPT_EXPORT_NAME:
dbb38caa 1238 return nbd_negotiate_handle_export_name(client, no_zeroes,
23e099c3 1239 errp);
26afa868 1240
f37708f6
EB
1241 case NBD_OPT_INFO:
1242 case NBD_OPT_GO:
dbb38caa 1243 ret = nbd_negotiate_handle_info(client, errp);
f37708f6
EB
1244 if (ret == 1) {
1245 assert(option == NBD_OPT_GO);
1246 return 0;
1247 }
f37708f6
EB
1248 break;
1249
f95910fe 1250 case NBD_OPT_STARTTLS:
e68c35cf 1251 if (length) {
0cfae925 1252 ret = nbd_reject_length(client, false, errp);
e68c35cf 1253 } else if (client->tlscreds) {
0cfae925
VSO
1254 ret = nbd_negotiate_send_rep_err(client,
1255 NBD_REP_ERR_INVALID, errp,
36683283 1256 "TLS already enabled");
f95910fe 1257 } else {
0cfae925
VSO
1258 ret = nbd_negotiate_send_rep_err(client,
1259 NBD_REP_ERR_POLICY, errp,
36683283 1260 "TLS not configured");
63d5ef86 1261 }
d1129a8a 1262 break;
5c54e7fa
VSO
1263
1264 case NBD_OPT_STRUCTURED_REPLY:
1265 if (length) {
0cfae925 1266 ret = nbd_reject_length(client, false, errp);
ac132d05 1267 } else if (client->mode >= NBD_MODE_STRUCTURED) {
5c54e7fa 1268 ret = nbd_negotiate_send_rep_err(
0cfae925 1269 client, NBD_REP_ERR_INVALID, errp,
5c54e7fa
VSO
1270 "structured reply already negotiated");
1271 } else {
0cfae925 1272 ret = nbd_negotiate_send_rep(client, NBD_REP_ACK, errp);
ac132d05 1273 client->mode = NBD_MODE_STRUCTURED;
5c54e7fa
VSO
1274 }
1275 break;
1276
e7b1948d
VSO
1277 case NBD_OPT_LIST_META_CONTEXT:
1278 case NBD_OPT_SET_META_CONTEXT:
1279 ret = nbd_negotiate_meta_queries(client, &client->export_meta,
1280 errp);
1281 break;
1282
26afa868 1283 default:
894e0280 1284 ret = nbd_opt_drop(client, NBD_REP_ERR_UNSUP, errp,
28fb494f 1285 "Unsupported option %" PRIu32 " (%s)",
894e0280 1286 option, nbd_opt_lookup(option));
156f6a10 1287 break;
26afa868
DB
1288 }
1289 } else {
1290 /*
1291 * If broken new-style we should drop the connection
1292 * for anything except NBD_OPT_EXPORT_NAME
1293 */
7f9039cd 1294 switch (option) {
26afa868 1295 case NBD_OPT_EXPORT_NAME:
dbb38caa 1296 return nbd_negotiate_handle_export_name(client, no_zeroes,
23e099c3 1297 errp);
26afa868
DB
1298
1299 default:
28fb494f 1300 error_setg(errp, "Unsupported option %" PRIu32 " (%s)",
3736cc5b 1301 option, nbd_opt_lookup(option));
26afa868 1302 return -EINVAL;
32d7d2e0 1303 }
f5076b5a 1304 }
8cbee49e
EB
1305 if (ret < 0) {
1306 return ret;
1307 }
f5076b5a
HB
1308 }
1309}
1310
1e120ffe
VSO
1311/* nbd_negotiate
1312 * Return:
2fd2c840
VSO
1313 * -errno on error, errp is set
1314 * 0 on successful negotiation, errp is not set
1315 * 1 if client sent NBD_OPT_ABORT, i.e. on valid disconnect,
1316 * errp is not set
1e120ffe 1317 */
2fd2c840 1318static coroutine_fn int nbd_negotiate(NBDClient *client, Error **errp)
7a5ca864 1319{
795d946d 1320 ERRP_GUARD();
5f66d060 1321 char buf[NBD_OLDSTYLE_NEGOTIATE_SIZE] = "";
2e5c9ad6 1322 int ret;
b2e3d87f 1323
5f66d060 1324 /* Old style negotiation header, no room for options
6b8c01e7
PB
1325 [ 0 .. 7] passwd ("NBDMAGIC")
1326 [ 8 .. 15] magic (NBD_CLIENT_MAGIC)
b2e3d87f 1327 [16 .. 23] size
5f66d060 1328 [24 .. 27] export flags (zero-extended)
6b8c01e7
PB
1329 [28 .. 151] reserved (0)
1330
5f66d060 1331 New style negotiation header, client can send options
6b8c01e7
PB
1332 [ 0 .. 7] passwd ("NBDMAGIC")
1333 [ 8 .. 15] magic (NBD_OPTS_MAGIC)
1334 [16 .. 17] server flags (0)
f37708f6 1335 ....options sent, ending in NBD_OPT_EXPORT_NAME or NBD_OPT_GO....
b2e3d87f
NT
1336 */
1337
1c778ef7 1338 qio_channel_set_blocking(client->ioc, false, NULL);
06e0f098 1339 qio_channel_set_follow_coroutine_ctx(client->ioc, true);
185b4338 1340
9588463e 1341 trace_nbd_negotiate_begin();
b2e3d87f 1342 memcpy(buf, "NBDMAGIC", 8);
f95910fe 1343
7f7dfe2a
VSO
1344 stq_be_p(buf + 8, NBD_OPTS_MAGIC);
1345 stw_be_p(buf + 16, NBD_FLAG_FIXED_NEWSTYLE | NBD_FLAG_NO_ZEROES);
b2e3d87f 1346
7f7dfe2a
VSO
1347 if (nbd_write(client->ioc, buf, 18, errp) < 0) {
1348 error_prepend(errp, "write failed: ");
1349 return -EINVAL;
1350 }
dbb38caa 1351 ret = nbd_negotiate_options(client, errp);
7f7dfe2a
VSO
1352 if (ret != 0) {
1353 if (ret < 0) {
1354 error_prepend(errp, "option negotiation failed: ");
6b8c01e7 1355 }
7f7dfe2a 1356 return ret;
b2e3d87f
NT
1357 }
1358
0cfae925 1359 assert(!client->optlen);
9588463e 1360 trace_nbd_negotiate_success();
d9faeed8
VSO
1361
1362 return 0;
7a5ca864
FB
1363}
1364
f148ae7d
SL
1365/* nbd_read_eof
1366 * Tries to read @size bytes from @ioc. This is a local implementation of
1367 * qio_channel_readv_all_eof. We have it here because we need it to be
1368 * interruptible and to know when the coroutine is yielding.
1369 * Returns 1 on success
1370 * 0 on eof, when no data was read (errp is not set)
1371 * negative errno on failure (errp is set)
1372 */
1373static inline int coroutine_fn
1374nbd_read_eof(NBDClient *client, void *buffer, size_t size, Error **errp)
1375{
1376 bool partial = false;
1377
1378 assert(size);
1379 while (size > 0) {
1380 struct iovec iov = { .iov_base = buffer, .iov_len = size };
1381 ssize_t len;
1382
1383 len = qio_channel_readv(client->ioc, &iov, 1, errp);
1384 if (len == QIO_CHANNEL_ERR_BLOCK) {
1385 client->read_yielding = true;
1386 qio_channel_yield(client->ioc, G_IO_IN);
1387 client->read_yielding = false;
1388 if (client->quiescing) {
1389 return -EAGAIN;
1390 }
1391 continue;
1392 } else if (len < 0) {
1393 return -EIO;
1394 } else if (len == 0) {
1395 if (partial) {
1396 error_setg(errp,
1397 "Unexpected end-of-file before all bytes were read");
1398 return -EIO;
1399 } else {
1400 return 0;
1401 }
1402 }
1403
1404 partial = true;
1405 size -= len;
1406 buffer = (uint8_t *) buffer + len;
1407 }
1408 return 1;
1409}
1410
d2223cdd
PB
1411static int coroutine_fn nbd_receive_request(NBDClient *client, NBDRequest *request,
1412 Error **errp)
75818250 1413{
c8720ca0
EB
1414 uint8_t buf[NBD_EXTENDED_REQUEST_SIZE];
1415 uint32_t magic, expect;
a0dc63a6 1416 int ret;
c8720ca0
EB
1417 size_t size = client->mode >= NBD_MODE_EXTENDED ?
1418 NBD_EXTENDED_REQUEST_SIZE : NBD_REQUEST_SIZE;
b2e3d87f 1419
c8720ca0 1420 ret = nbd_read_eof(client, buf, size, errp);
185b4338
PB
1421 if (ret < 0) {
1422 return ret;
1423 }
1644ccce
EB
1424 if (ret == 0) {
1425 return -EIO;
1426 }
185b4338 1427
c8720ca0
EB
1428 /*
1429 * Compact request
1430 * [ 0 .. 3] magic (NBD_REQUEST_MAGIC)
1431 * [ 4 .. 5] flags (NBD_CMD_FLAG_FUA, ...)
1432 * [ 6 .. 7] type (NBD_CMD_READ, ...)
1433 * [ 8 .. 15] cookie
1434 * [16 .. 23] from
1435 * [24 .. 27] len
1436 * Extended request
1437 * [ 0 .. 3] magic (NBD_EXTENDED_REQUEST_MAGIC)
1438 * [ 4 .. 5] flags (NBD_CMD_FLAG_FUA, NBD_CMD_FLAG_PAYLOAD_LEN, ...)
1439 * [ 6 .. 7] type (NBD_CMD_READ, ...)
1440 * [ 8 .. 15] cookie
1441 * [16 .. 23] from
1442 * [24 .. 31] len
b2e3d87f
NT
1443 */
1444
773dce3c 1445 magic = ldl_be_p(buf);
b626b51a
EB
1446 request->flags = lduw_be_p(buf + 4);
1447 request->type = lduw_be_p(buf + 6);
22efd811 1448 request->cookie = ldq_be_p(buf + 8);
773dce3c 1449 request->from = ldq_be_p(buf + 16);
c8720ca0
EB
1450 if (client->mode >= NBD_MODE_EXTENDED) {
1451 request->len = ldq_be_p(buf + 24);
1452 expect = NBD_EXTENDED_REQUEST_MAGIC;
1453 } else {
1454 request->len = (uint32_t)ldl_be_p(buf + 24); /* widen 32 to 64 bits */
1455 expect = NBD_REQUEST_MAGIC;
1456 }
b2e3d87f 1457
9588463e
VSO
1458 trace_nbd_receive_request(magic, request->flags, request->type,
1459 request->from, request->len);
b2e3d87f 1460
c8720ca0
EB
1461 if (magic != expect) {
1462 error_setg(errp, "invalid magic (got 0x%" PRIx32 ", expected 0x%"
1463 PRIx32 ")", magic, expect);
185b4338 1464 return -EINVAL;
b2e3d87f
NT
1465 }
1466 return 0;
75818250
TS
1467}
1468
41996e38
PB
1469#define MAX_NBD_REQUESTS 16
1470
ce33967a 1471void nbd_client_get(NBDClient *client)
1743b515
PB
1472{
1473 client->refcount++;
1474}
1475
ce33967a 1476void nbd_client_put(NBDClient *client)
1743b515
PB
1477{
1478 if (--client->refcount == 0) {
ff2b68aa 1479 /* The last reference should be dropped by client->close,
f53a829b 1480 * which is called by client_close.
ff2b68aa
PB
1481 */
1482 assert(client->closing);
1483
1c778ef7
DB
1484 object_unref(OBJECT(client->sioc));
1485 object_unref(OBJECT(client->ioc));
f95910fe
DB
1486 if (client->tlscreds) {
1487 object_unref(OBJECT(client->tlscreds));
1488 }
b25e12da 1489 g_free(client->tlsauthz);
6b8c01e7
PB
1490 if (client->exp) {
1491 QTAILQ_REMOVE(&client->exp->clients, client, next);
c69de1be 1492 blk_exp_unref(&client->exp->common);
6b8c01e7 1493 }
3b1f244c 1494 g_free(client->export_meta.bitmaps);
1743b515
PB
1495 g_free(client);
1496 }
1497}
1498
0c9390d9 1499static void client_close(NBDClient *client, bool negotiated)
1743b515 1500{
ff2b68aa
PB
1501 if (client->closing) {
1502 return;
1503 }
1504
1505 client->closing = true;
1506
1507 /* Force requests to finish. They will drop their own references,
1508 * then we'll close the socket and free the NBDClient.
1509 */
1c778ef7
DB
1510 qio_channel_shutdown(client->ioc, QIO_CHANNEL_SHUTDOWN_BOTH,
1511 NULL);
ff2b68aa
PB
1512
1513 /* Also tell the client, so that they release their reference. */
0c9390d9
EB
1514 if (client->close_fn) {
1515 client->close_fn(client, negotiated);
1743b515 1516 }
1743b515
PB
1517}
1518
315f78ab 1519static NBDRequestData *nbd_request_get(NBDClient *client)
d9a73806 1520{
315f78ab 1521 NBDRequestData *req;
72deddc5 1522
41996e38
PB
1523 assert(client->nb_requests <= MAX_NBD_REQUESTS - 1);
1524 client->nb_requests++;
1525
315f78ab 1526 req = g_new0(NBDRequestData, 1);
72deddc5
PB
1527 nbd_client_get(client);
1528 req->client = client;
d9a73806
PB
1529 return req;
1530}
1531
315f78ab 1532static void nbd_request_put(NBDRequestData *req)
d9a73806 1533{
72deddc5 1534 NBDClient *client = req->client;
e1adb27a 1535
2d821488
SH
1536 if (req->data) {
1537 qemu_vfree(req->data);
1538 }
1729404c 1539 g_free(req);
e1adb27a 1540
958c717d 1541 client->nb_requests--;
fd6afc50
SL
1542
1543 if (client->quiescing && client->nb_requests == 0) {
1544 aio_wait_kick();
1545 }
1546
ff82911c
PB
1547 nbd_client_receive_next_request(client);
1548
72deddc5 1549 nbd_client_put(client);
d9a73806
PB
1550}
1551
aadf99a7 1552static void blk_aio_attached(AioContext *ctx, void *opaque)
f2149281
HR
1553{
1554 NBDExport *exp = opaque;
1555 NBDClient *client;
1556
9588463e 1557 trace_nbd_blk_aio_attached(exp->name, ctx);
f2149281 1558
8612c686 1559 exp->common.ctx = ctx;
f2149281
HR
1560
1561 QTAILQ_FOREACH(client, &exp->clients, next) {
fd6afc50 1562 assert(client->nb_requests == 0);
f148ae7d
SL
1563 assert(client->recv_coroutine == NULL);
1564 assert(client->send_coroutine == NULL);
f148ae7d
SL
1565 }
1566}
1567
fd6afc50 1568static void blk_aio_detach(void *opaque)
f148ae7d
SL
1569{
1570 NBDExport *exp = opaque;
f148ae7d 1571
fd6afc50
SL
1572 trace_nbd_blk_aio_detach(exp->name, exp->common.ctx);
1573
fd6afc50
SL
1574 exp->common.ctx = NULL;
1575}
1576
1577static void nbd_drained_begin(void *opaque)
1578{
1579 NBDExport *exp = opaque;
1580 NBDClient *client;
1581
1582 QTAILQ_FOREACH(client, &exp->clients, next) {
f148ae7d 1583 client->quiescing = true;
fd6afc50
SL
1584 }
1585}
f148ae7d 1586
fd6afc50
SL
1587static void nbd_drained_end(void *opaque)
1588{
1589 NBDExport *exp = opaque;
1590 NBDClient *client;
f148ae7d 1591
fd6afc50
SL
1592 QTAILQ_FOREACH(client, &exp->clients, next) {
1593 client->quiescing = false;
1594 nbd_client_receive_next_request(client);
f2149281
HR
1595 }
1596}
1597
fd6afc50 1598static bool nbd_drained_poll(void *opaque)
f2149281
HR
1599{
1600 NBDExport *exp = opaque;
fd6afc50 1601 NBDClient *client;
f2149281 1602
fd6afc50
SL
1603 QTAILQ_FOREACH(client, &exp->clients, next) {
1604 if (client->nb_requests != 0) {
1605 /*
1606 * If there's a coroutine waiting for a request on nbd_read_eof()
1607 * enter it here so we don't depend on the client to wake it up.
1608 */
1609 if (client->recv_coroutine != NULL && client->read_yielding) {
7c1f51bf 1610 qio_channel_wake_read(client->ioc);
fd6afc50 1611 }
f2149281 1612
fd6afc50
SL
1613 return true;
1614 }
1615 }
f2149281 1616
fd6afc50 1617 return false;
f2149281
HR
1618}
1619
741cc431
HR
1620static void nbd_eject_notifier(Notifier *n, void *data)
1621{
1622 NBDExport *exp = container_of(n, NBDExport, eject_notifier);
61bc846d 1623
bc4ee65b 1624 blk_exp_request_shutdown(&exp->common);
741cc431
HR
1625}
1626
9b562c64
KW
1627void nbd_export_set_on_eject_blk(BlockExport *exp, BlockBackend *blk)
1628{
1629 NBDExport *nbd_exp = container_of(exp, NBDExport, common);
1630 assert(exp->drv == &blk_exp_nbd);
1631 assert(nbd_exp->eject_notifier_blk == NULL);
1632
1633 blk_ref(blk);
1634 nbd_exp->eject_notifier_blk = blk;
1635 nbd_exp->eject_notifier.notify = nbd_eject_notifier;
1636 blk_add_remove_bs_notifier(blk, &nbd_exp->eject_notifier);
1637}
1638
fd6afc50
SL
1639static const BlockDevOps nbd_block_ops = {
1640 .drained_begin = nbd_drained_begin,
1641 .drained_end = nbd_drained_end,
1642 .drained_poll = nbd_drained_poll,
1643};
1644
5b1cb497
KW
1645static int nbd_export_create(BlockExport *blk_exp, BlockExportOptions *exp_args,
1646 Error **errp)
af49bbbe 1647{
a6ff7989 1648 NBDExport *exp = container_of(blk_exp, NBDExport, common);
5b1cb497 1649 BlockExportOptionsNbd *arg = &exp_args->u.nbd;
8461b4d6 1650 const char *name = arg->name ?: exp_args->node_name;
331170e0 1651 BlockBackend *blk = blk_exp->blk;
b57e4de0 1652 int64_t size;
331170e0 1653 uint64_t perm, shared_perm;
5b1cb497 1654 bool readonly = !exp_args->writable;
e5fb29d5 1655 BlockDirtyBitmapOrStrList *bitmaps;
3b1f244c 1656 size_t i;
d7086422 1657 int ret;
cd7fca95 1658
5b1cb497
KW
1659 assert(exp_args->type == BLOCK_EXPORT_TYPE_NBD);
1660
1661 if (!nbd_server_is_running()) {
1662 error_setg(errp, "NBD server not running");
1663 return -EINVAL;
1664 }
1665
8461b4d6
MA
1666 if (strlen(name) > NBD_MAX_STRING_SIZE) {
1667 error_setg(errp, "export name '%s' too long", name);
5b1cb497
KW
1668 return -EINVAL;
1669 }
1670
1671 if (arg->description && strlen(arg->description) > NBD_MAX_STRING_SIZE) {
1672 error_setg(errp, "description '%s' too long", arg->description);
1673 return -EINVAL;
1674 }
1675
8461b4d6
MA
1676 if (nbd_export_find(name)) {
1677 error_setg(errp, "NBD server already has export named '%s'", name);
5b1cb497
KW
1678 return -EEXIST;
1679 }
1680
331170e0 1681 size = blk_getlength(blk);
b57e4de0
KW
1682 if (size < 0) {
1683 error_setg_errno(errp, -size,
1684 "Failed to determine the NBD export's length");
a6ff7989 1685 return size;
b57e4de0
KW
1686 }
1687
8a7ce4f9
KW
1688 /* Don't allow resize while the NBD server is running, otherwise we don't
1689 * care what happens with the node. */
331170e0 1690 blk_get_perm(blk, &perm, &shared_perm);
331170e0 1691 ret = blk_set_perm(blk, perm, shared_perm & ~BLK_PERM_RESIZE, errp);
d7086422 1692 if (ret < 0) {
331170e0 1693 return ret;
d7086422 1694 }
331170e0 1695
4b9441f6 1696 QTAILQ_INIT(&exp->clients);
8461b4d6 1697 exp->name = g_strdup(name);
5b1cb497 1698 exp->description = g_strdup(arg->description);
dbb38caa
EB
1699 exp->nbdflags = (NBD_FLAG_HAS_FLAGS | NBD_FLAG_SEND_FLUSH |
1700 NBD_FLAG_SEND_FUA | NBD_FLAG_SEND_CACHE);
58a6fdcc
EB
1701
1702 if (nbd_server_max_connections() != 1) {
1703 exp->nbdflags |= NBD_FLAG_CAN_MULTI_CONN;
1704 }
dbb38caa
EB
1705 if (readonly) {
1706 exp->nbdflags |= NBD_FLAG_READ_ONLY;
dbb38caa 1707 } else {
b491dbb7
EB
1708 exp->nbdflags |= (NBD_FLAG_SEND_TRIM | NBD_FLAG_SEND_WRITE_ZEROES |
1709 NBD_FLAG_SEND_FAST_ZERO);
dbb38caa 1710 }
7596bbb3 1711 exp->size = QEMU_ALIGN_DOWN(size, BDRV_SECTOR_SIZE);
98f44bbe 1712
cbad81ce 1713 for (bitmaps = arg->bitmaps; bitmaps; bitmaps = bitmaps->next) {
3b1f244c
EB
1714 exp->nr_export_bitmaps++;
1715 }
1716 exp->export_bitmaps = g_new0(BdrvDirtyBitmap *, exp->nr_export_bitmaps);
1717 for (i = 0, bitmaps = arg->bitmaps; bitmaps;
e5fb29d5
VSO
1718 i++, bitmaps = bitmaps->next)
1719 {
1720 const char *bitmap;
331170e0 1721 BlockDriverState *bs = blk_bs(blk);
678ba275 1722 BdrvDirtyBitmap *bm = NULL;
678ba275 1723
e5fb29d5
VSO
1724 switch (bitmaps->value->type) {
1725 case QTYPE_QSTRING:
1726 bitmap = bitmaps->value->u.local;
1727 while (bs) {
1728 bm = bdrv_find_dirty_bitmap(bs, bitmap);
1729 if (bm != NULL) {
1730 break;
1731 }
1732
1733 bs = bdrv_filter_or_cow_bs(bs);
678ba275
EB
1734 }
1735
e5fb29d5
VSO
1736 if (bm == NULL) {
1737 ret = -ENOENT;
1738 error_setg(errp, "Bitmap '%s' is not found",
1739 bitmaps->value->u.local);
1740 goto fail;
1741 }
678ba275 1742
e5fb29d5
VSO
1743 if (readonly && bdrv_is_writable(bs) &&
1744 bdrv_dirty_bitmap_enabled(bm)) {
1745 ret = -EINVAL;
1746 error_setg(errp, "Enabled bitmap '%s' incompatible with "
1747 "readonly export", bitmap);
1748 goto fail;
1749 }
1750 break;
1751 case QTYPE_QDICT:
1752 bitmap = bitmaps->value->u.external.name;
1753 bm = block_dirty_bitmap_lookup(bitmaps->value->u.external.node,
1754 bitmap, NULL, errp);
1755 if (!bm) {
1756 ret = -ENOENT;
1757 goto fail;
1758 }
1759 break;
1760 default:
1761 abort();
678ba275
EB
1762 }
1763
e5fb29d5 1764 assert(bm);
3b78a927 1765
e5fb29d5 1766 if (bdrv_dirty_bitmap_check(bm, BDRV_BITMAP_ALLOW_RO, errp)) {
a6ff7989 1767 ret = -EINVAL;
678ba275
EB
1768 goto fail;
1769 }
1770
3b1f244c 1771 exp->export_bitmaps[i] = bm;
cbad81ce 1772 assert(strlen(bitmap) <= BDRV_BITMAP_MAX_NAME_SIZE);
678ba275
EB
1773 }
1774
3b1f244c
EB
1775 /* Mark bitmaps busy in a separate loop, to simplify roll-back concerns. */
1776 for (i = 0; i < exp->nr_export_bitmaps; i++) {
1777 bdrv_dirty_bitmap_set_busy(exp->export_bitmaps[i], true);
1778 }
1779
dbc7b014
EB
1780 exp->allocation_depth = arg->allocation_depth;
1781
fd6afc50
SL
1782 /*
1783 * We need to inhibit request queuing in the block layer to ensure we can
1784 * be properly quiesced when entering a drained section, as our coroutines
1785 * servicing pending requests might enter blk_pread().
1786 */
1787 blk_set_disable_request_queuing(blk, true);
1788
aadf99a7 1789 blk_add_aio_context_notifier(blk, blk_aio_attached, blk_aio_detach, exp);
741cc431 1790
fd6afc50
SL
1791 blk_set_dev_ops(blk, &nbd_block_ops, exp);
1792
3fa4c765 1793 QTAILQ_INSERT_TAIL(&exports, exp, next);
c69de1be 1794
a6ff7989 1795 return 0;
98f44bbe
HR
1796
1797fail:
3b1f244c 1798 g_free(exp->export_bitmaps);
3fa4c765
EB
1799 g_free(exp->name);
1800 g_free(exp->description);
a6ff7989 1801 return ret;
af49bbbe
PB
1802}
1803
ee0a19ec
PB
1804NBDExport *nbd_export_find(const char *name)
1805{
1806 NBDExport *exp;
1807 QTAILQ_FOREACH(exp, &exports, next) {
1808 if (strcmp(name, exp->name) == 0) {
1809 return exp;
1810 }
1811 }
1812
1813 return NULL;
1814}
1815
61bc846d
EB
1816AioContext *
1817nbd_export_aio_context(NBDExport *exp)
1818{
8612c686 1819 return exp->common.ctx;
61bc846d
EB
1820}
1821
bc4ee65b 1822static void nbd_export_request_shutdown(BlockExport *blk_exp)
af49bbbe 1823{
bc4ee65b 1824 NBDExport *exp = container_of(blk_exp, NBDExport, common);
4b9441f6 1825 NBDClient *client, *next;
2c8d9f06 1826
c69de1be 1827 blk_exp_ref(&exp->common);
3fa4c765
EB
1828 /*
1829 * TODO: Should we expand QMP NbdServerRemoveNode enum to allow a
1830 * close mode that stops advertising the export to new clients but
1831 * still permits existing clients to run to completion? Because of
1832 * that possibility, nbd_export_close() can be called more than
1833 * once on an export.
1834 */
4b9441f6 1835 QTAILQ_FOREACH_SAFE(client, &exp->clients, next, next) {
0c9390d9 1836 client_close(client, true);
4b9441f6 1837 }
3fa4c765 1838 if (exp->name) {
3fa4c765
EB
1839 g_free(exp->name);
1840 exp->name = NULL;
1841 QTAILQ_REMOVE(&exports, exp, next);
1842 }
c69de1be 1843 blk_exp_unref(&exp->common);
2c8d9f06
PB
1844}
1845
c69de1be 1846static void nbd_export_delete(BlockExport *blk_exp)
2c8d9f06 1847{
3b1f244c 1848 size_t i;
c69de1be 1849 NBDExport *exp = container_of(blk_exp, NBDExport, common);
2c8d9f06 1850
c69de1be
KW
1851 assert(exp->name == NULL);
1852 assert(QTAILQ_EMPTY(&exp->clients));
d6268348 1853
c69de1be
KW
1854 g_free(exp->description);
1855 exp->description = NULL;
1856
dd5b6780
PB
1857 if (exp->eject_notifier_blk) {
1858 notifier_remove(&exp->eject_notifier);
1859 blk_unref(exp->eject_notifier_blk);
c69de1be 1860 }
dd5b6780
PB
1861 blk_remove_aio_context_notifier(exp->common.blk, blk_aio_attached,
1862 blk_aio_detach, exp);
1863 blk_set_disable_request_queuing(exp->common.blk, false);
3d068aff 1864
3b1f244c
EB
1865 for (i = 0; i < exp->nr_export_bitmaps; i++) {
1866 bdrv_dirty_bitmap_set_busy(exp->export_bitmaps[i], false);
2c8d9f06 1867 }
af49bbbe
PB
1868}
1869
56ee8626
KW
1870const BlockExportDriver blk_exp_nbd = {
1871 .type = BLOCK_EXPORT_TYPE_NBD,
a6ff7989 1872 .instance_size = sizeof(NBDExport),
56ee8626 1873 .create = nbd_export_create,
c69de1be 1874 .delete = nbd_export_delete,
bc4ee65b 1875 .request_shutdown = nbd_export_request_shutdown,
56ee8626
KW
1876};
1877
de79bfc3
VSO
1878static int coroutine_fn nbd_co_send_iov(NBDClient *client, struct iovec *iov,
1879 unsigned niov, Error **errp)
1880{
1881 int ret;
1882
1883 g_assert(qemu_in_coroutine());
1884 qemu_co_mutex_lock(&client->send_lock);
1885 client->send_coroutine = qemu_coroutine_self();
1886
1887 ret = qio_channel_writev_all(client->ioc, iov, niov, errp) < 0 ? -EIO : 0;
1888
1889 client->send_coroutine = NULL;
1890 qemu_co_mutex_unlock(&client->send_lock);
1891
1892 return ret;
1893}
1894
caad5384 1895static inline void set_be_simple_reply(NBDSimpleReply *reply, uint64_t error,
22efd811 1896 uint64_t cookie)
caad5384
VSO
1897{
1898 stl_be_p(&reply->magic, NBD_SIMPLE_REPLY_MAGIC);
1899 stl_be_p(&reply->error, error);
22efd811 1900 stq_be_p(&reply->cookie, cookie);
caad5384
VSO
1901}
1902
d2223cdd 1903static int coroutine_fn nbd_co_send_simple_reply(NBDClient *client,
66d4f4fe 1904 NBDRequest *request,
d2223cdd
PB
1905 uint32_t error,
1906 void *data,
b2578459 1907 uint64_t len,
d2223cdd 1908 Error **errp)
22045592 1909{
de79bfc3 1910 NBDSimpleReply reply;
14cea41d 1911 int nbd_err = system_errno_to_nbd_errno(error);
de79bfc3
VSO
1912 struct iovec iov[] = {
1913 {.iov_base = &reply, .iov_len = sizeof(reply)},
1914 {.iov_base = data, .iov_len = len}
1915 };
6fb2b972 1916
a7c8ed36 1917 assert(!len || !nbd_err);
b2578459 1918 assert(len <= NBD_MAX_BUFFER_SIZE);
ac132d05
EB
1919 assert(client->mode < NBD_MODE_STRUCTURED ||
1920 (client->mode == NBD_MODE_STRUCTURED &&
1921 request->type != NBD_CMD_READ));
22efd811 1922 trace_nbd_co_send_simple_reply(request->cookie, nbd_err,
66d4f4fe 1923 nbd_err_lookup(nbd_err), len);
22efd811 1924 set_be_simple_reply(&reply, nbd_err, request->cookie);
262db388 1925
a7c8ed36 1926 return nbd_co_send_iov(client, iov, 2, errp);
22045592
PB
1927}
1928
a7c8ed36
EB
1929/*
1930 * Prepare the header of a reply chunk for network transmission.
1931 *
1932 * On input, @iov is partially initialized: iov[0].iov_base must point
1933 * to an uninitialized NBDReply, while the remaining @niov elements
1934 * (if any) must be ready for transmission. This function then
1935 * populates iov[0] for transmission.
1936 */
1937static inline void set_be_chunk(NBDClient *client, struct iovec *iov,
1938 size_t niov, uint16_t flags, uint16_t type,
66d4f4fe 1939 NBDRequest *request)
5c54e7fa 1940{
a7c8ed36
EB
1941 size_t i, length = 0;
1942
1943 for (i = 1; i < niov; i++) {
1944 length += iov[i].iov_len;
1945 }
1946 assert(length <= NBD_MAX_BUFFER_SIZE + sizeof(NBDStructuredReadData));
1947
11d3355f
EB
1948 if (client->mode >= NBD_MODE_EXTENDED) {
1949 NBDExtendedReplyChunk *chunk = iov->iov_base;
1950
1951 iov[0].iov_len = sizeof(*chunk);
1952 stl_be_p(&chunk->magic, NBD_EXTENDED_REPLY_MAGIC);
1953 stw_be_p(&chunk->flags, flags);
1954 stw_be_p(&chunk->type, type);
1955 stq_be_p(&chunk->cookie, request->cookie);
1956 stq_be_p(&chunk->offset, request->from);
1957 stq_be_p(&chunk->length, length);
1958 } else {
1959 NBDStructuredReplyChunk *chunk = iov->iov_base;
1960
1961 iov[0].iov_len = sizeof(*chunk);
1962 stl_be_p(&chunk->magic, NBD_STRUCTURED_REPLY_MAGIC);
1963 stw_be_p(&chunk->flags, flags);
1964 stw_be_p(&chunk->type, type);
1965 stq_be_p(&chunk->cookie, request->cookie);
1966 stl_be_p(&chunk->length, length);
1967 }
5c54e7fa
VSO
1968}
1969
a7c8ed36 1970static int coroutine_fn nbd_co_send_chunk_done(NBDClient *client,
66d4f4fe 1971 NBDRequest *request,
a7c8ed36 1972 Error **errp)
ef8c887e 1973{
a7c8ed36 1974 NBDReply hdr;
ef8c887e 1975 struct iovec iov[] = {
a7c8ed36 1976 {.iov_base = &hdr},
ef8c887e
EB
1977 };
1978
22efd811 1979 trace_nbd_co_send_chunk_done(request->cookie);
a7c8ed36 1980 set_be_chunk(client, iov, 1, NBD_REPLY_FLAG_DONE,
66d4f4fe 1981 NBD_REPLY_TYPE_NONE, request);
ef8c887e
EB
1982 return nbd_co_send_iov(client, iov, 1, errp);
1983}
1984
a7c8ed36 1985static int coroutine_fn nbd_co_send_chunk_read(NBDClient *client,
66d4f4fe 1986 NBDRequest *request,
a7c8ed36
EB
1987 uint64_t offset,
1988 void *data,
b2578459 1989 uint64_t size,
a7c8ed36
EB
1990 bool final,
1991 Error **errp)
5c54e7fa 1992{
a7c8ed36 1993 NBDReply hdr;
efdc0c10 1994 NBDStructuredReadData chunk;
5c54e7fa 1995 struct iovec iov[] = {
a7c8ed36 1996 {.iov_base = &hdr},
5c54e7fa
VSO
1997 {.iov_base = &chunk, .iov_len = sizeof(chunk)},
1998 {.iov_base = data, .iov_len = size}
1999 };
2000
b2578459 2001 assert(size && size <= NBD_MAX_BUFFER_SIZE);
22efd811 2002 trace_nbd_co_send_chunk_read(request->cookie, offset, data, size);
a7c8ed36 2003 set_be_chunk(client, iov, 3, final ? NBD_REPLY_FLAG_DONE : 0,
66d4f4fe 2004 NBD_REPLY_TYPE_OFFSET_DATA, request);
5c54e7fa
VSO
2005 stq_be_p(&chunk.offset, offset);
2006
a7c8ed36 2007 return nbd_co_send_iov(client, iov, 3, errp);
5c54e7fa 2008}
ac132d05 2009
a7c8ed36 2010static int coroutine_fn nbd_co_send_chunk_error(NBDClient *client,
66d4f4fe 2011 NBDRequest *request,
a7c8ed36
EB
2012 uint32_t error,
2013 const char *msg,
2014 Error **errp)
60ace2ba 2015{
a7c8ed36 2016 NBDReply hdr;
60ace2ba
VSO
2017 NBDStructuredError chunk;
2018 int nbd_err = system_errno_to_nbd_errno(error);
2019 struct iovec iov[] = {
a7c8ed36 2020 {.iov_base = &hdr},
60ace2ba
VSO
2021 {.iov_base = &chunk, .iov_len = sizeof(chunk)},
2022 {.iov_base = (char *)msg, .iov_len = msg ? strlen(msg) : 0},
2023 };
2024
2025 assert(nbd_err);
22efd811 2026 trace_nbd_co_send_chunk_error(request->cookie, nbd_err,
a7c8ed36
EB
2027 nbd_err_lookup(nbd_err), msg ? msg : "");
2028 set_be_chunk(client, iov, 3, NBD_REPLY_FLAG_DONE,
66d4f4fe 2029 NBD_REPLY_TYPE_ERROR, request);
60ace2ba 2030 stl_be_p(&chunk.error, nbd_err);
a7c8ed36 2031 stw_be_p(&chunk.message_length, iov[2].iov_len);
60ace2ba 2032
a7c8ed36 2033 return nbd_co_send_iov(client, iov, 3, errp);
60ace2ba
VSO
2034}
2035
37e02aeb 2036/* Do a sparse read and send the structured reply to the client.
ff7e261b 2037 * Returns -errno if sending fails. blk_co_block_status_above() failure is
37e02aeb
VSO
2038 * reported to the client, at which point this function succeeds.
2039 */
418638d3 2040static int coroutine_fn nbd_co_send_sparse_read(NBDClient *client,
66d4f4fe 2041 NBDRequest *request,
418638d3
EB
2042 uint64_t offset,
2043 uint8_t *data,
b2578459 2044 uint64_t size,
418638d3
EB
2045 Error **errp)
2046{
2047 int ret = 0;
2048 NBDExport *exp = client->exp;
2049 size_t progress = 0;
2050
b2578459 2051 assert(size <= NBD_MAX_BUFFER_SIZE);
418638d3
EB
2052 while (progress < size) {
2053 int64_t pnum;
ff7e261b
EGE
2054 int status = blk_co_block_status_above(exp->common.blk, NULL,
2055 offset + progress,
2056 size - progress, &pnum, NULL,
2057 NULL);
e2de3256 2058 bool final;
418638d3
EB
2059
2060 if (status < 0) {
37e02aeb
VSO
2061 char *msg = g_strdup_printf("unable to check for holes: %s",
2062 strerror(-status));
2063
66d4f4fe 2064 ret = nbd_co_send_chunk_error(client, request, -status, msg, errp);
37e02aeb
VSO
2065 g_free(msg);
2066 return ret;
418638d3
EB
2067 }
2068 assert(pnum && pnum <= size - progress);
e2de3256 2069 final = progress + pnum == size;
418638d3 2070 if (status & BDRV_BLOCK_ZERO) {
a7c8ed36 2071 NBDReply hdr;
418638d3
EB
2072 NBDStructuredReadHole chunk;
2073 struct iovec iov[] = {
a7c8ed36 2074 {.iov_base = &hdr},
418638d3
EB
2075 {.iov_base = &chunk, .iov_len = sizeof(chunk)},
2076 };
2077
22efd811 2078 trace_nbd_co_send_chunk_read_hole(request->cookie,
66d4f4fe 2079 offset + progress, pnum);
a7c8ed36
EB
2080 set_be_chunk(client, iov, 2,
2081 final ? NBD_REPLY_FLAG_DONE : 0,
66d4f4fe 2082 NBD_REPLY_TYPE_OFFSET_HOLE, request);
418638d3
EB
2083 stq_be_p(&chunk.offset, offset + progress);
2084 stl_be_p(&chunk.length, pnum);
a7c8ed36 2085 ret = nbd_co_send_iov(client, iov, 2, errp);
418638d3 2086 } else {
d2223cdd
PB
2087 ret = blk_co_pread(exp->common.blk, offset + progress, pnum,
2088 data + progress, 0);
418638d3
EB
2089 if (ret < 0) {
2090 error_setg_errno(errp, -ret, "reading from file failed");
2091 break;
2092 }
66d4f4fe 2093 ret = nbd_co_send_chunk_read(client, request, offset + progress,
a7c8ed36 2094 data + progress, pnum, final, errp);
418638d3
EB
2095 }
2096
2097 if (ret < 0) {
2098 break;
2099 }
2100 progress += pnum;
2101 }
418638d3
EB
2102 return ret;
2103}
2104
89cbc7e3 2105typedef struct NBDExtentArray {
bcc16cc1 2106 NBDExtent64 *extents;
89cbc7e3
VSO
2107 unsigned int nb_alloc;
2108 unsigned int count;
2109 uint64_t total_length;
bcc16cc1 2110 bool extended;
89cbc7e3
VSO
2111 bool can_add;
2112 bool converted_to_be;
2113} NBDExtentArray;
2114
bcc16cc1
EB
2115static NBDExtentArray *nbd_extent_array_new(unsigned int nb_alloc,
2116 NBDMode mode)
89cbc7e3
VSO
2117{
2118 NBDExtentArray *ea = g_new0(NBDExtentArray, 1);
2119
bcc16cc1 2120 assert(mode >= NBD_MODE_STRUCTURED);
89cbc7e3 2121 ea->nb_alloc = nb_alloc;
bcc16cc1
EB
2122 ea->extents = g_new(NBDExtent64, nb_alloc);
2123 ea->extended = mode >= NBD_MODE_EXTENDED;
89cbc7e3
VSO
2124 ea->can_add = true;
2125
2126 return ea;
2127}
2128
2129static void nbd_extent_array_free(NBDExtentArray *ea)
2130{
2131 g_free(ea->extents);
2132 g_free(ea);
2133}
e0e7fe07 2134G_DEFINE_AUTOPTR_CLEANUP_FUNC(NBDExtentArray, nbd_extent_array_free)
89cbc7e3
VSO
2135
2136/* Further modifications of the array after conversion are abandoned */
2137static void nbd_extent_array_convert_to_be(NBDExtentArray *ea)
2138{
2139 int i;
2140
2141 assert(!ea->converted_to_be);
bcc16cc1 2142 assert(ea->extended);
89cbc7e3
VSO
2143 ea->can_add = false;
2144 ea->converted_to_be = true;
2145
2146 for (i = 0; i < ea->count; i++) {
bcc16cc1
EB
2147 ea->extents[i].length = cpu_to_be64(ea->extents[i].length);
2148 ea->extents[i].flags = cpu_to_be64(ea->extents[i].flags);
89cbc7e3
VSO
2149 }
2150}
2151
bcc16cc1
EB
2152/* Further modifications of the array after conversion are abandoned */
2153static NBDExtent32 *nbd_extent_array_convert_to_narrow(NBDExtentArray *ea)
2154{
2155 int i;
2156 NBDExtent32 *extents = g_new(NBDExtent32, ea->count);
2157
2158 assert(!ea->converted_to_be);
2159 assert(!ea->extended);
2160 ea->can_add = false;
2161 ea->converted_to_be = true;
2162
2163 for (i = 0; i < ea->count; i++) {
2164 assert((ea->extents[i].length | ea->extents[i].flags) <= UINT32_MAX);
2165 extents[i].length = cpu_to_be32(ea->extents[i].length);
2166 extents[i].flags = cpu_to_be32(ea->extents[i].flags);
2167 }
2168
2169 return extents;
2170}
2171
fb7afc79 2172/*
89cbc7e3
VSO
2173 * Add extent to NBDExtentArray. If extent can't be added (no available space),
2174 * return -1.
2175 * For safety, when returning -1 for the first time, .can_add is set to false,
314b9026
EB
2176 * and further calls to nbd_extent_array_add() will crash.
2177 * (this avoids the situation where a caller ignores failure to add one extent,
2178 * where adding another extent that would squash into the last array entry
2179 * would result in an incorrect range reported to the client)
fb7afc79 2180 */
89cbc7e3 2181static int nbd_extent_array_add(NBDExtentArray *ea,
bcc16cc1 2182 uint64_t length, uint32_t flags)
e7b1948d 2183{
89cbc7e3
VSO
2184 assert(ea->can_add);
2185
2186 if (!length) {
2187 return 0;
2188 }
bcc16cc1
EB
2189 if (!ea->extended) {
2190 assert(length <= UINT32_MAX);
2191 }
89cbc7e3
VSO
2192
2193 /* Extend previous extent if flags are the same */
2194 if (ea->count > 0 && flags == ea->extents[ea->count - 1].flags) {
bcc16cc1 2195 uint64_t sum = length + ea->extents[ea->count - 1].length;
89cbc7e3 2196
bcc16cc1
EB
2197 /*
2198 * sum cannot overflow: the block layer bounds image size at
2199 * 2^63, and ea->extents[].length comes from the block layer.
2200 */
2201 assert(sum >= length);
2202 if (sum <= UINT32_MAX || ea->extended) {
89cbc7e3
VSO
2203 ea->extents[ea->count - 1].length = sum;
2204 ea->total_length += length;
2205 return 0;
2206 }
2207 }
2208
2209 if (ea->count >= ea->nb_alloc) {
2210 ea->can_add = false;
2211 return -1;
2212 }
2213
2214 ea->total_length += length;
bcc16cc1 2215 ea->extents[ea->count] = (NBDExtent64) {.length = length, .flags = flags};
89cbc7e3 2216 ea->count++;
e7b1948d 2217
89cbc7e3
VSO
2218 return 0;
2219}
2220
ff7e261b 2221static int coroutine_fn blockstatus_to_extents(BlockBackend *blk,
6f58ac55
EGE
2222 uint64_t offset, uint64_t bytes,
2223 NBDExtentArray *ea)
89cbc7e3
VSO
2224{
2225 while (bytes) {
e7b1948d
VSO
2226 uint32_t flags;
2227 int64_t num;
ff7e261b
EGE
2228 int ret = blk_co_block_status_above(blk, NULL, offset, bytes, &num,
2229 NULL, NULL);
fb7afc79 2230
e7b1948d
VSO
2231 if (ret < 0) {
2232 return ret;
2233 }
2234
0da98568
NS
2235 flags = (ret & BDRV_BLOCK_DATA ? 0 : NBD_STATE_HOLE) |
2236 (ret & BDRV_BLOCK_ZERO ? NBD_STATE_ZERO : 0);
e7b1948d 2237
89cbc7e3
VSO
2238 if (nbd_extent_array_add(ea, num, flags) < 0) {
2239 return 0;
e7b1948d 2240 }
fb7afc79 2241
89cbc7e3
VSO
2242 offset += num;
2243 bytes -= num;
e7b1948d
VSO
2244 }
2245
e7b1948d
VSO
2246 return 0;
2247}
2248
ff7e261b 2249static int coroutine_fn blockalloc_to_extents(BlockBackend *blk,
6f58ac55
EGE
2250 uint64_t offset, uint64_t bytes,
2251 NBDExtentArray *ea)
71719cd5
EB
2252{
2253 while (bytes) {
2254 int64_t num;
ff7e261b
EGE
2255 int ret = blk_co_is_allocated_above(blk, NULL, false, offset, bytes,
2256 &num);
71719cd5
EB
2257
2258 if (ret < 0) {
2259 return ret;
2260 }
2261
2262 if (nbd_extent_array_add(ea, num, ret) < 0) {
2263 return 0;
2264 }
2265
2266 offset += num;
2267 bytes -= num;
2268 }
2269
2270 return 0;
2271}
2272
89cbc7e3
VSO
2273/*
2274 * nbd_co_send_extents
3d068aff 2275 *
89cbc7e3
VSO
2276 * @ea is converted to BE by the function
2277 * @last controls whether NBD_REPLY_FLAG_DONE is sent.
3d068aff 2278 */
d2223cdd 2279static int coroutine_fn
66d4f4fe 2280nbd_co_send_extents(NBDClient *client, NBDRequest *request, NBDExtentArray *ea,
d2223cdd 2281 bool last, uint32_t context_id, Error **errp)
e7b1948d 2282{
a7c8ed36 2283 NBDReply hdr;
bcc16cc1
EB
2284 NBDStructuredMeta meta;
2285 NBDExtendedMeta meta_ext;
2286 g_autofree NBDExtent32 *extents = NULL;
2287 uint16_t type;
2288 struct iovec iov[] = { {.iov_base = &hdr}, {0}, {0} };
e7b1948d 2289
bcc16cc1
EB
2290 if (client->mode >= NBD_MODE_EXTENDED) {
2291 type = NBD_REPLY_TYPE_BLOCK_STATUS_EXT;
2292
2293 iov[1].iov_base = &meta_ext;
2294 iov[1].iov_len = sizeof(meta_ext);
2295 stl_be_p(&meta_ext.context_id, context_id);
2296 stl_be_p(&meta_ext.count, ea->count);
2297
2298 nbd_extent_array_convert_to_be(ea);
2299 iov[2].iov_base = ea->extents;
2300 iov[2].iov_len = ea->count * sizeof(ea->extents[0]);
2301 } else {
2302 type = NBD_REPLY_TYPE_BLOCK_STATUS;
2303
2304 iov[1].iov_base = &meta;
2305 iov[1].iov_len = sizeof(meta);
2306 stl_be_p(&meta.context_id, context_id);
2307
2308 extents = nbd_extent_array_convert_to_narrow(ea);
2309 iov[2].iov_base = extents;
2310 iov[2].iov_len = ea->count * sizeof(extents[0]);
2311 }
89cbc7e3 2312
22efd811 2313 trace_nbd_co_send_extents(request->cookie, ea->count, context_id,
66d4f4fe 2314 ea->total_length, last);
bcc16cc1
EB
2315 set_be_chunk(client, iov, 3, last ? NBD_REPLY_FLAG_DONE : 0, type,
2316 request);
e7b1948d 2317
a7c8ed36 2318 return nbd_co_send_iov(client, iov, 3, errp);
e7b1948d
VSO
2319}
2320
2321/* Get block status from the exported device and send it to the client */
6f58ac55 2322static int
66d4f4fe 2323coroutine_fn nbd_co_send_block_status(NBDClient *client, NBDRequest *request,
ff7e261b 2324 BlockBackend *blk, uint64_t offset,
bcc16cc1 2325 uint64_t length, bool dont_fragment,
6f58ac55
EGE
2326 bool last, uint32_t context_id,
2327 Error **errp)
e7b1948d
VSO
2328{
2329 int ret;
416e34bd 2330 unsigned int nb_extents = dont_fragment ? 1 : NBD_MAX_BLOCK_STATUS_EXTENTS;
bcc16cc1
EB
2331 g_autoptr(NBDExtentArray) ea =
2332 nbd_extent_array_new(nb_extents, client->mode);
e7b1948d 2333
71719cd5 2334 if (context_id == NBD_META_ID_BASE_ALLOCATION) {
ff7e261b 2335 ret = blockstatus_to_extents(blk, offset, length, ea);
71719cd5 2336 } else {
ff7e261b 2337 ret = blockalloc_to_extents(blk, offset, length, ea);
71719cd5 2338 }
e7b1948d 2339 if (ret < 0) {
66d4f4fe 2340 return nbd_co_send_chunk_error(client, request, -ret,
a7c8ed36 2341 "can't get block status", errp);
e7b1948d
VSO
2342 }
2343
66d4f4fe 2344 return nbd_co_send_extents(client, request, ea, last, context_id, errp);
3d068aff
VSO
2345}
2346
dacbb6eb 2347/* Populate @ea from a dirty bitmap. */
89cbc7e3
VSO
2348static void bitmap_to_extents(BdrvDirtyBitmap *bitmap,
2349 uint64_t offset, uint64_t length,
dacbb6eb 2350 NBDExtentArray *es)
3d068aff 2351{
dacbb6eb
VSO
2352 int64_t start, dirty_start, dirty_count;
2353 int64_t end = offset + length;
2354 bool full = false;
bcc16cc1 2355 int64_t bound = es->extended ? INT64_MAX : INT32_MAX;
3d068aff
VSO
2356
2357 bdrv_dirty_bitmap_lock(bitmap);
2358
dacbb6eb 2359 for (start = offset;
bcc16cc1 2360 bdrv_dirty_bitmap_next_dirty_area(bitmap, start, end, bound,
dacbb6eb
VSO
2361 &dirty_start, &dirty_count);
2362 start = dirty_start + dirty_count)
2363 {
2364 if ((nbd_extent_array_add(es, dirty_start - start, 0) < 0) ||
2365 (nbd_extent_array_add(es, dirty_count, NBD_STATE_DIRTY) < 0))
2366 {
2367 full = true;
89cbc7e3
VSO
2368 break;
2369 }
3d068aff
VSO
2370 }
2371
dacbb6eb 2372 if (!full) {
c0b21f2e
EB
2373 /* last non dirty extent, nothing to do if array is now full */
2374 (void) nbd_extent_array_add(es, end - start, 0);
dacbb6eb 2375 }
3d068aff
VSO
2376
2377 bdrv_dirty_bitmap_unlock(bitmap);
3d068aff
VSO
2378}
2379
66d4f4fe
EB
2380static int coroutine_fn nbd_co_send_bitmap(NBDClient *client,
2381 NBDRequest *request,
2382 BdrvDirtyBitmap *bitmap,
2383 uint64_t offset,
bcc16cc1 2384 uint64_t length, bool dont_fragment,
66d4f4fe
EB
2385 bool last, uint32_t context_id,
2386 Error **errp)
3d068aff 2387{
416e34bd 2388 unsigned int nb_extents = dont_fragment ? 1 : NBD_MAX_BLOCK_STATUS_EXTENTS;
bcc16cc1
EB
2389 g_autoptr(NBDExtentArray) ea =
2390 nbd_extent_array_new(nb_extents, client->mode);
3d068aff 2391
dacbb6eb 2392 bitmap_to_extents(bitmap, offset, length, ea);
3d068aff 2393
66d4f4fe 2394 return nbd_co_send_extents(client, request, ea, last, context_id, errp);
e7b1948d
VSO
2395}
2396
2a6e128b
VSO
2397/* nbd_co_receive_request
2398 * Collect a client request. Return 0 if request looks valid, -EIO to drop
f148ae7d
SL
2399 * connection right away, -EAGAIN to indicate we were interrupted and the
2400 * channel should be quiesced, and any other negative value to report an error
2401 * to the client (although the caller may still need to disconnect after
2402 * reporting the error).
2a6e128b 2403 */
8db7e2d6
EB
2404static int coroutine_fn nbd_co_receive_request(NBDRequestData *req,
2405 NBDRequest *request,
d2223cdd 2406 Error **errp)
a030b347 2407{
72deddc5 2408 NBDClient *client = req->client;
009cd866 2409 bool extended_with_payload;
8db7e2d6
EB
2410 bool check_length = false;
2411 bool check_rofs = false;
2412 bool allocate_buffer = false;
009cd866
EB
2413 bool payload_okay = false;
2414 uint64_t payload_len = 0;
8db7e2d6 2415 int valid_flags = NBD_CMD_FLAG_FUA;
f148ae7d 2416 int ret;
a030b347 2417
1c778ef7 2418 g_assert(qemu_in_coroutine());
ff82911c 2419 assert(client->recv_coroutine == qemu_coroutine_self());
f148ae7d
SL
2420 ret = nbd_receive_request(client, request, errp);
2421 if (ret < 0) {
314b9026 2422 return ret;
a030b347
PB
2423 }
2424
22efd811 2425 trace_nbd_co_receive_request_decode_type(request->cookie, request->type,
3736cc5b 2426 nbd_cmd_lookup(request->type));
009cd866
EB
2427 extended_with_payload = client->mode >= NBD_MODE_EXTENDED &&
2428 request->flags & NBD_CMD_FLAG_PAYLOAD_LEN;
2429 if (extended_with_payload) {
2430 payload_len = request->len;
2431 check_length = true;
2432 }
2433
8db7e2d6
EB
2434 switch (request->type) {
2435 case NBD_CMD_DISC:
29b6c3b3
EB
2436 /* Special case: we're going to disconnect without a reply,
2437 * whether or not flags, from, or len are bogus */
8db7e2d6 2438 req->complete = true;
ee898b87 2439 return -EIO;
29b6c3b3 2440
8db7e2d6
EB
2441 case NBD_CMD_READ:
2442 if (client->mode >= NBD_MODE_STRUCTURED) {
2443 valid_flags |= NBD_CMD_FLAG_DF;
eb38c3b6 2444 }
8db7e2d6
EB
2445 check_length = true;
2446 allocate_buffer = true;
2447 break;
eb38c3b6 2448
8db7e2d6 2449 case NBD_CMD_WRITE:
009cd866
EB
2450 if (client->mode >= NBD_MODE_EXTENDED) {
2451 if (!extended_with_payload) {
2452 /* The client is noncompliant. Trace it, but proceed. */
2453 trace_nbd_co_receive_ext_payload_compliance(request->from,
2454 request->len);
2455 }
2456 valid_flags |= NBD_CMD_FLAG_PAYLOAD_LEN;
2457 }
2458 payload_okay = true;
8db7e2d6
EB
2459 payload_len = request->len;
2460 check_length = true;
2461 allocate_buffer = true;
2462 check_rofs = true;
2463 break;
2464
2465 case NBD_CMD_FLUSH:
2466 break;
2467
2468 case NBD_CMD_TRIM:
2469 check_rofs = true;
2470 break;
2471
2472 case NBD_CMD_CACHE:
2473 check_length = true;
2474 break;
2475
2476 case NBD_CMD_WRITE_ZEROES:
2477 valid_flags |= NBD_CMD_FLAG_NO_HOLE | NBD_CMD_FLAG_FAST_ZERO;
2478 check_rofs = true;
2479 break;
2480
2481 case NBD_CMD_BLOCK_STATUS:
2482 valid_flags |= NBD_CMD_FLAG_REQ_ONE;
2483 break;
2484
2485 default:
2486 /* Unrecognized, will fail later */
2487 ;
2d821488 2488 }
7fa5c565 2489
8db7e2d6
EB
2490 /* Payload and buffer handling. */
2491 if (!payload_len) {
2492 req->complete = true;
2493 }
2494 if (check_length && request->len > NBD_MAX_BUFFER_SIZE) {
2495 /* READ, WRITE, CACHE */
2496 error_setg(errp, "len (%" PRIu64 ") is larger than max len (%u)",
2497 request->len, NBD_MAX_BUFFER_SIZE);
2498 return -EINVAL;
2499 }
009cd866
EB
2500 if (payload_len && !payload_okay) {
2501 /*
2502 * For now, we don't support payloads on other commands; but
2503 * we can keep the connection alive by ignoring the payload.
2504 * We will fail the command later with NBD_EINVAL for the use
2505 * of an unsupported flag (and not for access beyond bounds).
2506 */
2507 assert(request->type != NBD_CMD_WRITE);
2508 request->len = 0;
2509 }
8db7e2d6
EB
2510 if (allocate_buffer) {
2511 /* READ, WRITE */
2512 req->data = blk_try_blockalign(client->exp->common.blk,
2513 request->len);
2514 if (req->data == NULL) {
2515 error_setg(errp, "No memory");
2516 return -ENOMEM;
2517 }
2518 }
2519 if (payload_len) {
009cd866
EB
2520 if (payload_okay) {
2521 /* WRITE */
2522 assert(req->data);
2523 ret = nbd_read(client->ioc, req->data, payload_len,
2524 "CMD_WRITE data", errp);
2525 } else {
2526 ret = nbd_drop(client->ioc, payload_len, errp);
2527 }
8db7e2d6 2528 if (ret < 0) {
ee898b87 2529 return -EIO;
a030b347 2530 }
29b6c3b3 2531 req->complete = true;
22efd811 2532 trace_nbd_co_receive_request_payload_received(request->cookie,
8db7e2d6 2533 payload_len);
a030b347 2534 }
29b6c3b3 2535
fed5f8f8 2536 /* Sanity checks. */
8db7e2d6
EB
2537 if (client->exp->nbdflags & NBD_FLAG_READ_ONLY && check_rofs) {
2538 /* WRITE, TRIM, WRITE_ZEROES */
fed5f8f8
EB
2539 error_setg(errp, "Export is read-only");
2540 return -EROFS;
2541 }
2542 if (request->from > client->exp->size ||
9d26dfcb 2543 request->len > client->exp->size - request->from) {
b2578459 2544 error_setg(errp, "operation past EOF; From: %" PRIu64 ", Len: %" PRIu64
2fd2c840 2545 ", Size: %" PRIu64, request->from, request->len,
9d26dfcb 2546 client->exp->size);
fed5f8f8
EB
2547 return (request->type == NBD_CMD_WRITE ||
2548 request->type == NBD_CMD_WRITE_ZEROES) ? -ENOSPC : -EINVAL;
29b6c3b3 2549 }
6e280648
EB
2550 if (client->check_align && !QEMU_IS_ALIGNED(request->from | request->len,
2551 client->check_align)) {
2552 /*
2553 * The block layer gracefully handles unaligned requests, but
2554 * it's still worth tracing client non-compliance
2555 */
2556 trace_nbd_co_receive_align_compliance(nbd_cmd_lookup(request->type),
2557 request->from,
2558 request->len,
2559 client->check_align);
2560 }
5c54e7fa
VSO
2561 if (request->flags & ~valid_flags) {
2562 error_setg(errp, "unsupported flags for command %s (got 0x%x)",
2563 nbd_cmd_lookup(request->type), request->flags);
ee898b87 2564 return -EINVAL;
1f4d6d18 2565 }
29b6c3b3 2566
ee898b87 2567 return 0;
a030b347
PB
2568}
2569
6a417599
VSO
2570/* Send simple reply without a payload, or a structured error
2571 * @error_msg is ignored if @ret >= 0
2572 * Returns 0 if connection is still live, -errno on failure to talk to client
2573 */
2574static coroutine_fn int nbd_send_generic_reply(NBDClient *client,
66d4f4fe 2575 NBDRequest *request,
6a417599
VSO
2576 int ret,
2577 const char *error_msg,
2578 Error **errp)
2579{
ac132d05 2580 if (client->mode >= NBD_MODE_STRUCTURED && ret < 0) {
66d4f4fe 2581 return nbd_co_send_chunk_error(client, request, -ret, error_msg, errp);
11d3355f
EB
2582 } else if (client->mode >= NBD_MODE_EXTENDED) {
2583 return nbd_co_send_chunk_done(client, request, errp);
6a417599 2584 } else {
66d4f4fe 2585 return nbd_co_send_simple_reply(client, request, ret < 0 ? -ret : 0,
6a417599
VSO
2586 NULL, 0, errp);
2587 }
2588}
2589
2590/* Handle NBD_CMD_READ request.
2591 * Return -errno if sending fails. Other errors are reported directly to the
2592 * client as an error reply. */
2593static coroutine_fn int nbd_do_cmd_read(NBDClient *client, NBDRequest *request,
2594 uint8_t *data, Error **errp)
2595{
2596 int ret;
2597 NBDExport *exp = client->exp;
2598
7fa5c565 2599 assert(request->type == NBD_CMD_READ);
b2578459 2600 assert(request->len <= NBD_MAX_BUFFER_SIZE);
6a417599
VSO
2601
2602 /* XXX: NBD Protocol only documents use of FUA with WRITE */
2603 if (request->flags & NBD_CMD_FLAG_FUA) {
37a4f70c 2604 ret = blk_co_flush(exp->common.blk);
6a417599 2605 if (ret < 0) {
66d4f4fe 2606 return nbd_send_generic_reply(client, request, ret,
6a417599
VSO
2607 "flush failed", errp);
2608 }
2609 }
2610
ac132d05
EB
2611 if (client->mode >= NBD_MODE_STRUCTURED &&
2612 !(request->flags & NBD_CMD_FLAG_DF) && request->len)
2f454def 2613 {
66d4f4fe 2614 return nbd_co_send_sparse_read(client, request, request->from,
6a417599
VSO
2615 data, request->len, errp);
2616 }
2617
d2223cdd 2618 ret = blk_co_pread(exp->common.blk, request->from, request->len, data, 0);
7fa5c565 2619 if (ret < 0) {
66d4f4fe 2620 return nbd_send_generic_reply(client, request, ret,
6a417599
VSO
2621 "reading from file failed", errp);
2622 }
2623
ac132d05 2624 if (client->mode >= NBD_MODE_STRUCTURED) {
6a417599 2625 if (request->len) {
66d4f4fe 2626 return nbd_co_send_chunk_read(client, request, request->from, data,
a7c8ed36 2627 request->len, true, errp);
6a417599 2628 } else {
66d4f4fe 2629 return nbd_co_send_chunk_done(client, request, errp);
6a417599
VSO
2630 }
2631 } else {
66d4f4fe 2632 return nbd_co_send_simple_reply(client, request, 0,
6a417599
VSO
2633 data, request->len, errp);
2634 }
2635}
2636
7fa5c565
VSO
2637/*
2638 * nbd_do_cmd_cache
2639 *
2640 * Handle NBD_CMD_CACHE request.
2641 * Return -errno if sending fails. Other errors are reported directly to the
2642 * client as an error reply.
2643 */
2644static coroutine_fn int nbd_do_cmd_cache(NBDClient *client, NBDRequest *request,
2645 Error **errp)
2646{
2647 int ret;
2648 NBDExport *exp = client->exp;
2649
2650 assert(request->type == NBD_CMD_CACHE);
b2578459 2651 assert(request->len <= NBD_MAX_BUFFER_SIZE);
7fa5c565 2652
37a4f70c 2653 ret = blk_co_preadv(exp->common.blk, request->from, request->len,
7fa5c565
VSO
2654 NULL, BDRV_REQ_COPY_ON_READ | BDRV_REQ_PREFETCH);
2655
66d4f4fe 2656 return nbd_send_generic_reply(client, request, ret,
7fa5c565
VSO
2657 "caching data failed", errp);
2658}
2659
6f302e60
VSO
2660/* Handle NBD request.
2661 * Return -errno if sending fails. Other errors are reported directly to the
2662 * client as an error reply. */
2663static coroutine_fn int nbd_handle_request(NBDClient *client,
2664 NBDRequest *request,
2665 uint8_t *data, Error **errp)
2666{
2667 int ret;
2668 int flags;
2669 NBDExport *exp = client->exp;
2670 char *msg;
3b1f244c 2671 size_t i;
6f302e60
VSO
2672
2673 switch (request->type) {
bc37b06a 2674 case NBD_CMD_CACHE:
7fa5c565
VSO
2675 return nbd_do_cmd_cache(client, request, errp);
2676
2677 case NBD_CMD_READ:
6f302e60
VSO
2678 return nbd_do_cmd_read(client, request, data, errp);
2679
2680 case NBD_CMD_WRITE:
2681 flags = 0;
2682 if (request->flags & NBD_CMD_FLAG_FUA) {
2683 flags |= BDRV_REQ_FUA;
2684 }
b2578459 2685 assert(request->len <= NBD_MAX_BUFFER_SIZE);
d2223cdd
PB
2686 ret = blk_co_pwrite(exp->common.blk, request->from, request->len, data,
2687 flags);
66d4f4fe 2688 return nbd_send_generic_reply(client, request, ret,
6f302e60
VSO
2689 "writing to file failed", errp);
2690
2691 case NBD_CMD_WRITE_ZEROES:
2692 flags = 0;
2693 if (request->flags & NBD_CMD_FLAG_FUA) {
2694 flags |= BDRV_REQ_FUA;
2695 }
2696 if (!(request->flags & NBD_CMD_FLAG_NO_HOLE)) {
2697 flags |= BDRV_REQ_MAY_UNMAP;
2698 }
b491dbb7
EB
2699 if (request->flags & NBD_CMD_FLAG_FAST_ZERO) {
2700 flags |= BDRV_REQ_NO_FALLBACK;
2701 }
d2223cdd
PB
2702 ret = blk_co_pwrite_zeroes(exp->common.blk, request->from, request->len,
2703 flags);
66d4f4fe 2704 return nbd_send_generic_reply(client, request, ret,
6f302e60
VSO
2705 "writing to file failed", errp);
2706
2707 case NBD_CMD_DISC:
2708 /* unreachable, thanks to special case in nbd_co_receive_request() */
2709 abort();
2710
2711 case NBD_CMD_FLUSH:
37a4f70c 2712 ret = blk_co_flush(exp->common.blk);
66d4f4fe 2713 return nbd_send_generic_reply(client, request, ret,
6f302e60
VSO
2714 "flush failed", errp);
2715
2716 case NBD_CMD_TRIM:
e3557422 2717 ret = blk_co_pdiscard(exp->common.blk, request->from, request->len);
890cbccb 2718 if (ret >= 0 && request->flags & NBD_CMD_FLAG_FUA) {
37a4f70c 2719 ret = blk_co_flush(exp->common.blk);
65529782 2720 }
66d4f4fe 2721 return nbd_send_generic_reply(client, request, ret,
6f302e60
VSO
2722 "discard failed", errp);
2723
e7b1948d 2724 case NBD_CMD_BLOCK_STATUS:
d8b20291 2725 if (!request->len) {
66d4f4fe 2726 return nbd_send_generic_reply(client, request, -EINVAL,
d8b20291
EB
2727 "need non-zero length", errp);
2728 }
bcc16cc1
EB
2729 assert(client->mode >= NBD_MODE_EXTENDED ||
2730 request->len <= UINT32_MAX);
47ec485e 2731 if (client->export_meta.count) {
fb7afc79 2732 bool dont_fragment = request->flags & NBD_CMD_FLAG_REQ_ONE;
47ec485e 2733 int contexts_remaining = client->export_meta.count;
fb7afc79 2734
3d068aff 2735 if (client->export_meta.base_allocation) {
66d4f4fe 2736 ret = nbd_co_send_block_status(client, request,
ff7e261b 2737 exp->common.blk,
37a4f70c 2738 request->from,
fb7afc79 2739 request->len, dont_fragment,
47ec485e 2740 !--contexts_remaining,
3d068aff
VSO
2741 NBD_META_ID_BASE_ALLOCATION,
2742 errp);
73e064cc
EB
2743 if (ret < 0) {
2744 return ret;
2745 }
2746 }
2747
71719cd5 2748 if (client->export_meta.allocation_depth) {
66d4f4fe 2749 ret = nbd_co_send_block_status(client, request,
ff7e261b 2750 exp->common.blk,
71719cd5
EB
2751 request->from, request->len,
2752 dont_fragment,
2753 !--contexts_remaining,
2754 NBD_META_ID_ALLOCATION_DEPTH,
2755 errp);
2756 if (ret < 0) {
2757 return ret;
2758 }
2759 }
2760
3b1f244c
EB
2761 for (i = 0; i < client->exp->nr_export_bitmaps; i++) {
2762 if (!client->export_meta.bitmaps[i]) {
2763 continue;
2764 }
66d4f4fe 2765 ret = nbd_co_send_bitmap(client, request,
3b1f244c 2766 client->exp->export_bitmaps[i],
3d068aff 2767 request->from, request->len,
47ec485e 2768 dont_fragment, !--contexts_remaining,
3b1f244c 2769 NBD_META_ID_DIRTY_BITMAP + i, errp);
73e064cc
EB
2770 if (ret < 0) {
2771 return ret;
2772 }
3d068aff
VSO
2773 }
2774
47ec485e
EB
2775 assert(!contexts_remaining);
2776
73e064cc 2777 return 0;
e7b1948d 2778 } else {
66d4f4fe 2779 return nbd_send_generic_reply(client, request, -EINVAL,
e7b1948d
VSO
2780 "CMD_BLOCK_STATUS not negotiated",
2781 errp);
2782 }
2783
6f302e60
VSO
2784 default:
2785 msg = g_strdup_printf("invalid request type (%" PRIu32 ") received",
2786 request->type);
66d4f4fe 2787 ret = nbd_send_generic_reply(client, request, -EINVAL, msg,
6f302e60
VSO
2788 errp);
2789 g_free(msg);
2790 return ret;
2791 }
2792}
2793
ff82911c
PB
2794/* Owns a reference to the NBDClient passed as opaque. */
2795static coroutine_fn void nbd_trip(void *opaque)
75818250 2796{
262db388 2797 NBDClient *client = opaque;
315f78ab 2798 NBDRequestData *req;
ff82911c 2799 NBDRequest request = { 0 }; /* GCC thinks it can be used uninitialized */
a0dc63a6 2800 int ret;
2fd2c840 2801 Error *local_err = NULL;
b2e3d87f 2802
9588463e 2803 trace_nbd_trip();
ff2b68aa 2804 if (client->closing) {
ff82911c 2805 nbd_client_put(client);
ff2b68aa
PB
2806 return;
2807 }
b2e3d87f 2808
f148ae7d
SL
2809 if (client->quiescing) {
2810 /*
2811 * We're switching between AIO contexts. Don't attempt to receive a new
2812 * request and kick the main context which may be waiting for us.
2813 */
2814 nbd_client_put(client);
2815 client->recv_coroutine = NULL;
2816 aio_wait_kick();
2817 return;
2818 }
2819
ff2b68aa 2820 req = nbd_request_get(client);
2fd2c840 2821 ret = nbd_co_receive_request(req, &request, &local_err);
ee898b87 2822 client->recv_coroutine = NULL;
b2e3d87f 2823
d6268348
WC
2824 if (client->closing) {
2825 /*
2826 * The client may be closed when we are blocked in
2827 * nbd_co_receive_request()
2828 */
2829 goto done;
2830 }
2831
f148ae7d
SL
2832 if (ret == -EAGAIN) {
2833 assert(client->quiescing);
2834 goto done;
2835 }
2836
a0d7ce20
VSO
2837 nbd_client_receive_next_request(client);
2838 if (ret == -EIO) {
2839 goto disconnect;
2840 }
2841
bd2cd4a4
FW
2842 qio_channel_set_cork(client->ioc, true);
2843
a0d7ce20 2844 if (ret < 0) {
314b9026 2845 /* It wasn't -EIO, so, according to nbd_co_receive_request()
6a417599
VSO
2846 * semantics, we should return the error to the client. */
2847 Error *export_err = local_err;
2848
2849 local_err = NULL;
66d4f4fe 2850 ret = nbd_send_generic_reply(client, &request, -EINVAL,
6a417599
VSO
2851 error_get_pretty(export_err), &local_err);
2852 error_free(export_err);
6f302e60
VSO
2853 } else {
2854 ret = nbd_handle_request(client, &request, req->data, &local_err);
5c54e7fa
VSO
2855 }
2856 if (ret < 0) {
c7b97282 2857 error_prepend(&local_err, "Failed to send reply: ");
2fd2c840
VSO
2858 goto disconnect;
2859 }
2860
8c372a02
VSO
2861 /* We must disconnect after NBD_CMD_WRITE if we did not
2862 * read the payload.
2863 */
2fd2c840
VSO
2864 if (!req->complete) {
2865 error_setg(&local_err, "Request handling failed in intermediate state");
8c372a02 2866 goto disconnect;
b2e3d87f
NT
2867 }
2868
bd2cd4a4 2869 qio_channel_set_cork(client->ioc, false);
7fe7b68b 2870done:
262db388 2871 nbd_request_put(req);
ff82911c 2872 nbd_client_put(client);
262db388
PB
2873 return;
2874
8c372a02 2875disconnect:
2fd2c840
VSO
2876 if (local_err) {
2877 error_reportf_err(local_err, "Disconnect client, due to: ");
2878 }
72deddc5 2879 nbd_request_put(req);
0c9390d9 2880 client_close(client, true);
ff82911c 2881 nbd_client_put(client);
7a5ca864 2882}
af49bbbe 2883
ff82911c 2884static void nbd_client_receive_next_request(NBDClient *client)
958c717d 2885{
f148ae7d
SL
2886 if (!client->recv_coroutine && client->nb_requests < MAX_NBD_REQUESTS &&
2887 !client->quiescing) {
ff82911c
PB
2888 nbd_client_get(client);
2889 client->recv_coroutine = qemu_coroutine_create(nbd_trip, client);
8612c686 2890 aio_co_schedule(client->exp->common.ctx, client->recv_coroutine);
958c717d
HR
2891 }
2892}
2893
1a6245a5
FZ
2894static coroutine_fn void nbd_co_client_start(void *opaque)
2895{
c84087f2 2896 NBDClient *client = opaque;
2fd2c840 2897 Error *local_err = NULL;
1a6245a5 2898
df8ad9f1
EB
2899 qemu_co_mutex_init(&client->send_lock);
2900
2fd2c840
VSO
2901 if (nbd_negotiate(client, &local_err)) {
2902 if (local_err) {
2903 error_report_err(local_err);
2904 }
0c9390d9 2905 client_close(client, false);
c84087f2 2906 return;
1a6245a5 2907 }
ff82911c
PB
2908
2909 nbd_client_receive_next_request(client);
1a6245a5
FZ
2910}
2911
0c9390d9 2912/*
7f7dfe2a
VSO
2913 * Create a new client listener using the given channel @sioc.
2914 * Begin servicing it in a coroutine. When the connection closes, call
2915 * @close_fn with an indication of whether the client completed negotiation.
0c9390d9 2916 */
7f7dfe2a 2917void nbd_client_new(QIOChannelSocket *sioc,
f95910fe 2918 QCryptoTLSCreds *tlscreds,
b25e12da 2919 const char *tlsauthz,
0c9390d9 2920 void (*close_fn)(NBDClient *, bool))
af49bbbe 2921{
1743b515 2922 NBDClient *client;
c84087f2 2923 Coroutine *co;
1a6245a5 2924
e8d3eb74 2925 client = g_new0(NBDClient, 1);
1743b515 2926 client->refcount = 1;
f95910fe
DB
2927 client->tlscreds = tlscreds;
2928 if (tlscreds) {
2929 object_ref(OBJECT(client->tlscreds));
2930 }
b25e12da 2931 client->tlsauthz = g_strdup(tlsauthz);
1c778ef7 2932 client->sioc = sioc;
f1426881 2933 qio_channel_set_delay(QIO_CHANNEL(sioc), false);
1c778ef7
DB
2934 object_ref(OBJECT(client->sioc));
2935 client->ioc = QIO_CHANNEL(sioc);
2936 object_ref(OBJECT(client->ioc));
0c9390d9 2937 client->close_fn = close_fn;
2c8d9f06 2938
c84087f2
VSO
2939 co = qemu_coroutine_create(nbd_co_client_start, client);
2940 qemu_coroutine_enter(co);
af49bbbe 2941}