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