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