]> Git Repo - qemu.git/blame - nbd/server.c
target/arm: Introduce PREDDESC field definitions
[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 <[email protected]>
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
dbc7b014
EB
1644 exp->allocation_depth = arg->allocation_depth;
1645
aadf99a7 1646 blk_add_aio_context_notifier(blk, blk_aio_attached, blk_aio_detach, exp);
741cc431 1647
3fa4c765 1648 QTAILQ_INSERT_TAIL(&exports, exp, next);
c69de1be 1649
a6ff7989 1650 return 0;
98f44bbe
HR
1651
1652fail:
3b1f244c 1653 g_free(exp->export_bitmaps);
3fa4c765
EB
1654 g_free(exp->name);
1655 g_free(exp->description);
a6ff7989 1656 return ret;
af49bbbe
PB
1657}
1658
ee0a19ec
PB
1659NBDExport *nbd_export_find(const char *name)
1660{
1661 NBDExport *exp;
1662 QTAILQ_FOREACH(exp, &exports, next) {
1663 if (strcmp(name, exp->name) == 0) {
1664 return exp;
1665 }
1666 }
1667
1668 return NULL;
1669}
1670
61bc846d
EB
1671AioContext *
1672nbd_export_aio_context(NBDExport *exp)
1673{
8612c686 1674 return exp->common.ctx;
61bc846d
EB
1675}
1676
bc4ee65b 1677static void nbd_export_request_shutdown(BlockExport *blk_exp)
af49bbbe 1678{
bc4ee65b 1679 NBDExport *exp = container_of(blk_exp, NBDExport, common);
4b9441f6 1680 NBDClient *client, *next;
2c8d9f06 1681
c69de1be 1682 blk_exp_ref(&exp->common);
3fa4c765
EB
1683 /*
1684 * TODO: Should we expand QMP NbdServerRemoveNode enum to allow a
1685 * close mode that stops advertising the export to new clients but
1686 * still permits existing clients to run to completion? Because of
1687 * that possibility, nbd_export_close() can be called more than
1688 * once on an export.
1689 */
4b9441f6 1690 QTAILQ_FOREACH_SAFE(client, &exp->clients, next, next) {
0c9390d9 1691 client_close(client, true);
4b9441f6 1692 }
3fa4c765 1693 if (exp->name) {
3fa4c765
EB
1694 g_free(exp->name);
1695 exp->name = NULL;
1696 QTAILQ_REMOVE(&exports, exp, next);
1697 }
c69de1be 1698 blk_exp_unref(&exp->common);
2c8d9f06
PB
1699}
1700
c69de1be 1701static void nbd_export_delete(BlockExport *blk_exp)
2c8d9f06 1702{
3b1f244c 1703 size_t i;
c69de1be 1704 NBDExport *exp = container_of(blk_exp, NBDExport, common);
2c8d9f06 1705
c69de1be
KW
1706 assert(exp->name == NULL);
1707 assert(QTAILQ_EMPTY(&exp->clients));
d6268348 1708
c69de1be
KW
1709 g_free(exp->description);
1710 exp->description = NULL;
1711
37a4f70c 1712 if (exp->common.blk) {
c69de1be
KW
1713 if (exp->eject_notifier_blk) {
1714 notifier_remove(&exp->eject_notifier);
1715 blk_unref(exp->eject_notifier_blk);
3d068aff 1716 }
37a4f70c 1717 blk_remove_aio_context_notifier(exp->common.blk, blk_aio_attached,
c69de1be 1718 blk_aio_detach, exp);
c69de1be 1719 }
3d068aff 1720
3b1f244c
EB
1721 for (i = 0; i < exp->nr_export_bitmaps; i++) {
1722 bdrv_dirty_bitmap_set_busy(exp->export_bitmaps[i], false);
2c8d9f06 1723 }
af49bbbe
PB
1724}
1725
56ee8626
KW
1726const BlockExportDriver blk_exp_nbd = {
1727 .type = BLOCK_EXPORT_TYPE_NBD,
a6ff7989 1728 .instance_size = sizeof(NBDExport),
56ee8626 1729 .create = nbd_export_create,
c69de1be 1730 .delete = nbd_export_delete,
bc4ee65b 1731 .request_shutdown = nbd_export_request_shutdown,
56ee8626
KW
1732};
1733
de79bfc3
VSO
1734static int coroutine_fn nbd_co_send_iov(NBDClient *client, struct iovec *iov,
1735 unsigned niov, Error **errp)
1736{
1737 int ret;
1738
1739 g_assert(qemu_in_coroutine());
1740 qemu_co_mutex_lock(&client->send_lock);
1741 client->send_coroutine = qemu_coroutine_self();
1742
1743 ret = qio_channel_writev_all(client->ioc, iov, niov, errp) < 0 ? -EIO : 0;
1744
1745 client->send_coroutine = NULL;
1746 qemu_co_mutex_unlock(&client->send_lock);
1747
1748 return ret;
1749}
1750
caad5384
VSO
1751static inline void set_be_simple_reply(NBDSimpleReply *reply, uint64_t error,
1752 uint64_t handle)
1753{
1754 stl_be_p(&reply->magic, NBD_SIMPLE_REPLY_MAGIC);
1755 stl_be_p(&reply->error, error);
1756 stq_be_p(&reply->handle, handle);
1757}
1758
978df1b6 1759static int nbd_co_send_simple_reply(NBDClient *client,
14cea41d
VSO
1760 uint64_t handle,
1761 uint32_t error,
978df1b6
VSO
1762 void *data,
1763 size_t len,
1764 Error **errp)
22045592 1765{
de79bfc3 1766 NBDSimpleReply reply;
14cea41d 1767 int nbd_err = system_errno_to_nbd_errno(error);
de79bfc3
VSO
1768 struct iovec iov[] = {
1769 {.iov_base = &reply, .iov_len = sizeof(reply)},
1770 {.iov_base = data, .iov_len = len}
1771 };
6fb2b972 1772
e7a78d0e
EB
1773 trace_nbd_co_send_simple_reply(handle, nbd_err, nbd_err_lookup(nbd_err),
1774 len);
de79bfc3 1775 set_be_simple_reply(&reply, nbd_err, handle);
262db388 1776
de79bfc3 1777 return nbd_co_send_iov(client, iov, len ? 2 : 1, errp);
22045592
PB
1778}
1779
5c54e7fa
VSO
1780static inline void set_be_chunk(NBDStructuredReplyChunk *chunk, uint16_t flags,
1781 uint16_t type, uint64_t handle, uint32_t length)
1782{
1783 stl_be_p(&chunk->magic, NBD_STRUCTURED_REPLY_MAGIC);
1784 stw_be_p(&chunk->flags, flags);
1785 stw_be_p(&chunk->type, type);
1786 stq_be_p(&chunk->handle, handle);
1787 stl_be_p(&chunk->length, length);
1788}
1789
ef8c887e
EB
1790static int coroutine_fn nbd_co_send_structured_done(NBDClient *client,
1791 uint64_t handle,
1792 Error **errp)
1793{
1794 NBDStructuredReplyChunk chunk;
1795 struct iovec iov[] = {
1796 {.iov_base = &chunk, .iov_len = sizeof(chunk)},
1797 };
1798
1799 trace_nbd_co_send_structured_done(handle);
1800 set_be_chunk(&chunk, NBD_REPLY_FLAG_DONE, NBD_REPLY_TYPE_NONE, handle, 0);
1801
1802 return nbd_co_send_iov(client, iov, 1, errp);
1803}
1804
5c54e7fa
VSO
1805static int coroutine_fn nbd_co_send_structured_read(NBDClient *client,
1806 uint64_t handle,
1807 uint64_t offset,
1808 void *data,
1809 size_t size,
418638d3 1810 bool final,
5c54e7fa
VSO
1811 Error **errp)
1812{
efdc0c10 1813 NBDStructuredReadData chunk;
5c54e7fa
VSO
1814 struct iovec iov[] = {
1815 {.iov_base = &chunk, .iov_len = sizeof(chunk)},
1816 {.iov_base = data, .iov_len = size}
1817 };
1818
ef8c887e 1819 assert(size);
5c54e7fa 1820 trace_nbd_co_send_structured_read(handle, offset, data, size);
418638d3
EB
1821 set_be_chunk(&chunk.h, final ? NBD_REPLY_FLAG_DONE : 0,
1822 NBD_REPLY_TYPE_OFFSET_DATA, handle,
1823 sizeof(chunk) - sizeof(chunk.h) + size);
5c54e7fa
VSO
1824 stq_be_p(&chunk.offset, offset);
1825
1826 return nbd_co_send_iov(client, iov, 2, errp);
1827}
1828
60ace2ba
VSO
1829static int coroutine_fn nbd_co_send_structured_error(NBDClient *client,
1830 uint64_t handle,
1831 uint32_t error,
1832 const char *msg,
1833 Error **errp)
1834{
1835 NBDStructuredError chunk;
1836 int nbd_err = system_errno_to_nbd_errno(error);
1837 struct iovec iov[] = {
1838 {.iov_base = &chunk, .iov_len = sizeof(chunk)},
1839 {.iov_base = (char *)msg, .iov_len = msg ? strlen(msg) : 0},
1840 };
1841
1842 assert(nbd_err);
1843 trace_nbd_co_send_structured_error(handle, nbd_err,
1844 nbd_err_lookup(nbd_err), msg ? msg : "");
1845 set_be_chunk(&chunk.h, NBD_REPLY_FLAG_DONE, NBD_REPLY_TYPE_ERROR, handle,
1846 sizeof(chunk) - sizeof(chunk.h) + iov[1].iov_len);
1847 stl_be_p(&chunk.error, nbd_err);
1848 stw_be_p(&chunk.message_length, iov[1].iov_len);
1849
1850 return nbd_co_send_iov(client, iov, 1 + !!iov[1].iov_len, errp);
1851}
1852
37e02aeb
VSO
1853/* Do a sparse read and send the structured reply to the client.
1854 * Returns -errno if sending fails. bdrv_block_status_above() failure is
1855 * reported to the client, at which point this function succeeds.
1856 */
418638d3
EB
1857static int coroutine_fn nbd_co_send_sparse_read(NBDClient *client,
1858 uint64_t handle,
1859 uint64_t offset,
1860 uint8_t *data,
1861 size_t size,
1862 Error **errp)
1863{
1864 int ret = 0;
1865 NBDExport *exp = client->exp;
1866 size_t progress = 0;
1867
1868 while (progress < size) {
1869 int64_t pnum;
37a4f70c 1870 int status = bdrv_block_status_above(blk_bs(exp->common.blk), NULL,
418638d3
EB
1871 offset + progress,
1872 size - progress, &pnum, NULL,
1873 NULL);
e2de3256 1874 bool final;
418638d3
EB
1875
1876 if (status < 0) {
37e02aeb
VSO
1877 char *msg = g_strdup_printf("unable to check for holes: %s",
1878 strerror(-status));
1879
1880 ret = nbd_co_send_structured_error(client, handle, -status, msg,
1881 errp);
1882 g_free(msg);
1883 return ret;
418638d3
EB
1884 }
1885 assert(pnum && pnum <= size - progress);
e2de3256 1886 final = progress + pnum == size;
418638d3
EB
1887 if (status & BDRV_BLOCK_ZERO) {
1888 NBDStructuredReadHole chunk;
1889 struct iovec iov[] = {
1890 {.iov_base = &chunk, .iov_len = sizeof(chunk)},
1891 };
1892
1893 trace_nbd_co_send_structured_read_hole(handle, offset + progress,
1894 pnum);
e2de3256
EB
1895 set_be_chunk(&chunk.h, final ? NBD_REPLY_FLAG_DONE : 0,
1896 NBD_REPLY_TYPE_OFFSET_HOLE,
418638d3
EB
1897 handle, sizeof(chunk) - sizeof(chunk.h));
1898 stq_be_p(&chunk.offset, offset + progress);
1899 stl_be_p(&chunk.length, pnum);
1900 ret = nbd_co_send_iov(client, iov, 1, errp);
1901 } else {
37a4f70c
KW
1902 ret = blk_pread(exp->common.blk, offset + progress,
1903 data + progress, pnum);
418638d3
EB
1904 if (ret < 0) {
1905 error_setg_errno(errp, -ret, "reading from file failed");
1906 break;
1907 }
1908 ret = nbd_co_send_structured_read(client, handle, offset + progress,
e2de3256 1909 data + progress, pnum, final,
418638d3
EB
1910 errp);
1911 }
1912
1913 if (ret < 0) {
1914 break;
1915 }
1916 progress += pnum;
1917 }
418638d3
EB
1918 return ret;
1919}
1920
89cbc7e3
VSO
1921typedef struct NBDExtentArray {
1922 NBDExtent *extents;
1923 unsigned int nb_alloc;
1924 unsigned int count;
1925 uint64_t total_length;
1926 bool can_add;
1927 bool converted_to_be;
1928} NBDExtentArray;
1929
1930static NBDExtentArray *nbd_extent_array_new(unsigned int nb_alloc)
1931{
1932 NBDExtentArray *ea = g_new0(NBDExtentArray, 1);
1933
1934 ea->nb_alloc = nb_alloc;
1935 ea->extents = g_new(NBDExtent, nb_alloc);
1936 ea->can_add = true;
1937
1938 return ea;
1939}
1940
1941static void nbd_extent_array_free(NBDExtentArray *ea)
1942{
1943 g_free(ea->extents);
1944 g_free(ea);
1945}
1946G_DEFINE_AUTOPTR_CLEANUP_FUNC(NBDExtentArray, nbd_extent_array_free);
1947
1948/* Further modifications of the array after conversion are abandoned */
1949static void nbd_extent_array_convert_to_be(NBDExtentArray *ea)
1950{
1951 int i;
1952
1953 assert(!ea->converted_to_be);
1954 ea->can_add = false;
1955 ea->converted_to_be = true;
1956
1957 for (i = 0; i < ea->count; i++) {
1958 ea->extents[i].flags = cpu_to_be32(ea->extents[i].flags);
1959 ea->extents[i].length = cpu_to_be32(ea->extents[i].length);
1960 }
1961}
1962
fb7afc79 1963/*
89cbc7e3
VSO
1964 * Add extent to NBDExtentArray. If extent can't be added (no available space),
1965 * return -1.
1966 * For safety, when returning -1 for the first time, .can_add is set to false,
1967 * further call to nbd_extent_array_add() will crash.
1968 * (to avoid the situation, when after failing to add an extent (returned -1),
1969 * user miss this failure and add another extent, which is successfully added
1970 * (array is full, but new extent may be squashed into the last one), then we
1971 * have invalid array with skipped extent)
fb7afc79 1972 */
89cbc7e3
VSO
1973static int nbd_extent_array_add(NBDExtentArray *ea,
1974 uint32_t length, uint32_t flags)
e7b1948d 1975{
89cbc7e3
VSO
1976 assert(ea->can_add);
1977
1978 if (!length) {
1979 return 0;
1980 }
1981
1982 /* Extend previous extent if flags are the same */
1983 if (ea->count > 0 && flags == ea->extents[ea->count - 1].flags) {
1984 uint64_t sum = (uint64_t)length + ea->extents[ea->count - 1].length;
1985
1986 if (sum <= UINT32_MAX) {
1987 ea->extents[ea->count - 1].length = sum;
1988 ea->total_length += length;
1989 return 0;
1990 }
1991 }
1992
1993 if (ea->count >= ea->nb_alloc) {
1994 ea->can_add = false;
1995 return -1;
1996 }
1997
1998 ea->total_length += length;
1999 ea->extents[ea->count] = (NBDExtent) {.length = length, .flags = flags};
2000 ea->count++;
e7b1948d 2001
89cbc7e3
VSO
2002 return 0;
2003}
2004
2005static int blockstatus_to_extents(BlockDriverState *bs, uint64_t offset,
2006 uint64_t bytes, NBDExtentArray *ea)
2007{
2008 while (bytes) {
e7b1948d
VSO
2009 uint32_t flags;
2010 int64_t num;
89cbc7e3
VSO
2011 int ret = bdrv_block_status_above(bs, NULL, offset, bytes, &num,
2012 NULL, NULL);
fb7afc79 2013
e7b1948d
VSO
2014 if (ret < 0) {
2015 return ret;
2016 }
2017
2018 flags = (ret & BDRV_BLOCK_ALLOCATED ? 0 : NBD_STATE_HOLE) |
2019 (ret & BDRV_BLOCK_ZERO ? NBD_STATE_ZERO : 0);
2020
89cbc7e3
VSO
2021 if (nbd_extent_array_add(ea, num, flags) < 0) {
2022 return 0;
e7b1948d 2023 }
fb7afc79 2024
89cbc7e3
VSO
2025 offset += num;
2026 bytes -= num;
e7b1948d
VSO
2027 }
2028
e7b1948d
VSO
2029 return 0;
2030}
2031
71719cd5
EB
2032static int blockalloc_to_extents(BlockDriverState *bs, uint64_t offset,
2033 uint64_t bytes, NBDExtentArray *ea)
2034{
2035 while (bytes) {
2036 int64_t num;
2037 int ret = bdrv_is_allocated_above(bs, NULL, false, offset, bytes,
2038 &num);
2039
2040 if (ret < 0) {
2041 return ret;
2042 }
2043
2044 if (nbd_extent_array_add(ea, num, ret) < 0) {
2045 return 0;
2046 }
2047
2048 offset += num;
2049 bytes -= num;
2050 }
2051
2052 return 0;
2053}
2054
89cbc7e3
VSO
2055/*
2056 * nbd_co_send_extents
3d068aff 2057 *
89cbc7e3
VSO
2058 * @ea is converted to BE by the function
2059 * @last controls whether NBD_REPLY_FLAG_DONE is sent.
3d068aff 2060 */
e7b1948d 2061static int nbd_co_send_extents(NBDClient *client, uint64_t handle,
89cbc7e3
VSO
2062 NBDExtentArray *ea,
2063 bool last, uint32_t context_id, Error **errp)
e7b1948d
VSO
2064{
2065 NBDStructuredMeta chunk;
e7b1948d
VSO
2066 struct iovec iov[] = {
2067 {.iov_base = &chunk, .iov_len = sizeof(chunk)},
89cbc7e3 2068 {.iov_base = ea->extents, .iov_len = ea->count * sizeof(ea->extents[0])}
e7b1948d
VSO
2069 };
2070
89cbc7e3
VSO
2071 nbd_extent_array_convert_to_be(ea);
2072
2073 trace_nbd_co_send_extents(handle, ea->count, context_id, ea->total_length,
2074 last);
3d068aff
VSO
2075 set_be_chunk(&chunk.h, last ? NBD_REPLY_FLAG_DONE : 0,
2076 NBD_REPLY_TYPE_BLOCK_STATUS,
e7b1948d
VSO
2077 handle, sizeof(chunk) - sizeof(chunk.h) + iov[1].iov_len);
2078 stl_be_p(&chunk.context_id, context_id);
2079
2080 return nbd_co_send_iov(client, iov, 2, errp);
2081}
2082
2083/* Get block status from the exported device and send it to the client */
2084static int nbd_co_send_block_status(NBDClient *client, uint64_t handle,
2085 BlockDriverState *bs, uint64_t offset,
fb7afc79
VSO
2086 uint32_t length, bool dont_fragment,
2087 bool last, uint32_t context_id,
2088 Error **errp)
e7b1948d
VSO
2089{
2090 int ret;
416e34bd 2091 unsigned int nb_extents = dont_fragment ? 1 : NBD_MAX_BLOCK_STATUS_EXTENTS;
89cbc7e3 2092 g_autoptr(NBDExtentArray) ea = nbd_extent_array_new(nb_extents);
e7b1948d 2093
71719cd5
EB
2094 if (context_id == NBD_META_ID_BASE_ALLOCATION) {
2095 ret = blockstatus_to_extents(bs, offset, length, ea);
2096 } else {
2097 ret = blockalloc_to_extents(bs, offset, length, ea);
2098 }
e7b1948d
VSO
2099 if (ret < 0) {
2100 return nbd_co_send_structured_error(
2101 client, handle, -ret, "can't get block status", errp);
2102 }
2103
89cbc7e3 2104 return nbd_co_send_extents(client, handle, ea, last, context_id, errp);
3d068aff
VSO
2105}
2106
dacbb6eb 2107/* Populate @ea from a dirty bitmap. */
89cbc7e3
VSO
2108static void bitmap_to_extents(BdrvDirtyBitmap *bitmap,
2109 uint64_t offset, uint64_t length,
dacbb6eb 2110 NBDExtentArray *es)
3d068aff 2111{
dacbb6eb
VSO
2112 int64_t start, dirty_start, dirty_count;
2113 int64_t end = offset + length;
2114 bool full = false;
3d068aff
VSO
2115
2116 bdrv_dirty_bitmap_lock(bitmap);
2117
dacbb6eb
VSO
2118 for (start = offset;
2119 bdrv_dirty_bitmap_next_dirty_area(bitmap, start, end, INT32_MAX,
2120 &dirty_start, &dirty_count);
2121 start = dirty_start + dirty_count)
2122 {
2123 if ((nbd_extent_array_add(es, dirty_start - start, 0) < 0) ||
2124 (nbd_extent_array_add(es, dirty_count, NBD_STATE_DIRTY) < 0))
2125 {
2126 full = true;
89cbc7e3
VSO
2127 break;
2128 }
3d068aff
VSO
2129 }
2130
dacbb6eb 2131 if (!full) {
c0b21f2e
EB
2132 /* last non dirty extent, nothing to do if array is now full */
2133 (void) nbd_extent_array_add(es, end - start, 0);
dacbb6eb 2134 }
3d068aff
VSO
2135
2136 bdrv_dirty_bitmap_unlock(bitmap);
3d068aff
VSO
2137}
2138
2139static int nbd_co_send_bitmap(NBDClient *client, uint64_t handle,
2140 BdrvDirtyBitmap *bitmap, uint64_t offset,
2141 uint32_t length, bool dont_fragment, bool last,
2142 uint32_t context_id, Error **errp)
2143{
416e34bd 2144 unsigned int nb_extents = dont_fragment ? 1 : NBD_MAX_BLOCK_STATUS_EXTENTS;
89cbc7e3 2145 g_autoptr(NBDExtentArray) ea = nbd_extent_array_new(nb_extents);
3d068aff 2146
dacbb6eb 2147 bitmap_to_extents(bitmap, offset, length, ea);
3d068aff 2148
89cbc7e3 2149 return nbd_co_send_extents(client, handle, ea, last, context_id, errp);
e7b1948d
VSO
2150}
2151
2a6e128b
VSO
2152/* nbd_co_receive_request
2153 * Collect a client request. Return 0 if request looks valid, -EIO to drop
2154 * connection right away, and any other negative value to report an error to
2155 * the client (although the caller may still need to disconnect after reporting
2156 * the error).
2157 */
2fd2c840
VSO
2158static int nbd_co_receive_request(NBDRequestData *req, NBDRequest *request,
2159 Error **errp)
a030b347 2160{
72deddc5 2161 NBDClient *client = req->client;
5c54e7fa 2162 int valid_flags;
a030b347 2163
1c778ef7 2164 g_assert(qemu_in_coroutine());
ff82911c 2165 assert(client->recv_coroutine == qemu_coroutine_self());
2fd2c840 2166 if (nbd_receive_request(client->ioc, request, errp) < 0) {
ee898b87 2167 return -EIO;
a030b347
PB
2168 }
2169
3736cc5b
EB
2170 trace_nbd_co_receive_request_decode_type(request->handle, request->type,
2171 nbd_cmd_lookup(request->type));
29b6c3b3 2172
b626b51a 2173 if (request->type != NBD_CMD_WRITE) {
29b6c3b3
EB
2174 /* No payload, we are ready to read the next request. */
2175 req->complete = true;
2176 }
2177
b626b51a 2178 if (request->type == NBD_CMD_DISC) {
29b6c3b3
EB
2179 /* Special case: we're going to disconnect without a reply,
2180 * whether or not flags, from, or len are bogus */
ee898b87 2181 return -EIO;
29b6c3b3
EB
2182 }
2183
bc37b06a
VSO
2184 if (request->type == NBD_CMD_READ || request->type == NBD_CMD_WRITE ||
2185 request->type == NBD_CMD_CACHE)
2186 {
eb38c3b6 2187 if (request->len > NBD_MAX_BUFFER_SIZE) {
2fd2c840
VSO
2188 error_setg(errp, "len (%" PRIu32" ) is larger than max len (%u)",
2189 request->len, NBD_MAX_BUFFER_SIZE);
ee898b87 2190 return -EINVAL;
eb38c3b6
PB
2191 }
2192
7fa5c565 2193 if (request->type != NBD_CMD_CACHE) {
37a4f70c
KW
2194 req->data = blk_try_blockalign(client->exp->common.blk,
2195 request->len);
7fa5c565
VSO
2196 if (req->data == NULL) {
2197 error_setg(errp, "No memory");
2198 return -ENOMEM;
2199 }
f1c17521 2200 }
2d821488 2201 }
7fa5c565 2202
b626b51a 2203 if (request->type == NBD_CMD_WRITE) {
e6798f06
VSO
2204 if (nbd_read(client->ioc, req->data, request->len, "CMD_WRITE data",
2205 errp) < 0)
2206 {
ee898b87 2207 return -EIO;
a030b347 2208 }
29b6c3b3 2209 req->complete = true;
6fb2b972 2210
9588463e
VSO
2211 trace_nbd_co_receive_request_payload_received(request->handle,
2212 request->len);
a030b347 2213 }
29b6c3b3 2214
fed5f8f8
EB
2215 /* Sanity checks. */
2216 if (client->exp->nbdflags & NBD_FLAG_READ_ONLY &&
2217 (request->type == NBD_CMD_WRITE ||
2218 request->type == NBD_CMD_WRITE_ZEROES ||
2219 request->type == NBD_CMD_TRIM)) {
2220 error_setg(errp, "Export is read-only");
2221 return -EROFS;
2222 }
2223 if (request->from > client->exp->size ||
9d26dfcb 2224 request->len > client->exp->size - request->from) {
2fd2c840
VSO
2225 error_setg(errp, "operation past EOF; From: %" PRIu64 ", Len: %" PRIu32
2226 ", Size: %" PRIu64, request->from, request->len,
9d26dfcb 2227 client->exp->size);
fed5f8f8
EB
2228 return (request->type == NBD_CMD_WRITE ||
2229 request->type == NBD_CMD_WRITE_ZEROES) ? -ENOSPC : -EINVAL;
29b6c3b3 2230 }
6e280648
EB
2231 if (client->check_align && !QEMU_IS_ALIGNED(request->from | request->len,
2232 client->check_align)) {
2233 /*
2234 * The block layer gracefully handles unaligned requests, but
2235 * it's still worth tracing client non-compliance
2236 */
2237 trace_nbd_co_receive_align_compliance(nbd_cmd_lookup(request->type),
2238 request->from,
2239 request->len,
2240 client->check_align);
2241 }
5c54e7fa
VSO
2242 valid_flags = NBD_CMD_FLAG_FUA;
2243 if (request->type == NBD_CMD_READ && client->structured_reply) {
2244 valid_flags |= NBD_CMD_FLAG_DF;
2245 } else if (request->type == NBD_CMD_WRITE_ZEROES) {
b491dbb7 2246 valid_flags |= NBD_CMD_FLAG_NO_HOLE | NBD_CMD_FLAG_FAST_ZERO;
e7b1948d
VSO
2247 } else if (request->type == NBD_CMD_BLOCK_STATUS) {
2248 valid_flags |= NBD_CMD_FLAG_REQ_ONE;
ab7c548e 2249 }
5c54e7fa
VSO
2250 if (request->flags & ~valid_flags) {
2251 error_setg(errp, "unsupported flags for command %s (got 0x%x)",
2252 nbd_cmd_lookup(request->type), request->flags);
ee898b87 2253 return -EINVAL;
1f4d6d18 2254 }
29b6c3b3 2255
ee898b87 2256 return 0;
a030b347
PB
2257}
2258
6a417599
VSO
2259/* Send simple reply without a payload, or a structured error
2260 * @error_msg is ignored if @ret >= 0
2261 * Returns 0 if connection is still live, -errno on failure to talk to client
2262 */
2263static coroutine_fn int nbd_send_generic_reply(NBDClient *client,
2264 uint64_t handle,
2265 int ret,
2266 const char *error_msg,
2267 Error **errp)
2268{
2269 if (client->structured_reply && ret < 0) {
2270 return nbd_co_send_structured_error(client, handle, -ret, error_msg,
2271 errp);
2272 } else {
2273 return nbd_co_send_simple_reply(client, handle, ret < 0 ? -ret : 0,
2274 NULL, 0, errp);
2275 }
2276}
2277
2278/* Handle NBD_CMD_READ request.
2279 * Return -errno if sending fails. Other errors are reported directly to the
2280 * client as an error reply. */
2281static coroutine_fn int nbd_do_cmd_read(NBDClient *client, NBDRequest *request,
2282 uint8_t *data, Error **errp)
2283{
2284 int ret;
2285 NBDExport *exp = client->exp;
2286
7fa5c565 2287 assert(request->type == NBD_CMD_READ);
6a417599
VSO
2288
2289 /* XXX: NBD Protocol only documents use of FUA with WRITE */
2290 if (request->flags & NBD_CMD_FLAG_FUA) {
37a4f70c 2291 ret = blk_co_flush(exp->common.blk);
6a417599
VSO
2292 if (ret < 0) {
2293 return nbd_send_generic_reply(client, request->handle, ret,
2294 "flush failed", errp);
2295 }
2296 }
2297
2298 if (client->structured_reply && !(request->flags & NBD_CMD_FLAG_DF) &&
7fa5c565 2299 request->len)
2f454def 2300 {
6a417599
VSO
2301 return nbd_co_send_sparse_read(client, request->handle, request->from,
2302 data, request->len, errp);
2303 }
2304
37a4f70c 2305 ret = blk_pread(exp->common.blk, request->from, data, request->len);
7fa5c565 2306 if (ret < 0) {
6a417599
VSO
2307 return nbd_send_generic_reply(client, request->handle, ret,
2308 "reading from file failed", errp);
2309 }
2310
2311 if (client->structured_reply) {
2312 if (request->len) {
2313 return nbd_co_send_structured_read(client, request->handle,
2314 request->from, data,
2315 request->len, true, errp);
2316 } else {
2317 return nbd_co_send_structured_done(client, request->handle, errp);
2318 }
2319 } else {
2320 return nbd_co_send_simple_reply(client, request->handle, 0,
2321 data, request->len, errp);
2322 }
2323}
2324
7fa5c565
VSO
2325/*
2326 * nbd_do_cmd_cache
2327 *
2328 * Handle NBD_CMD_CACHE request.
2329 * Return -errno if sending fails. Other errors are reported directly to the
2330 * client as an error reply.
2331 */
2332static coroutine_fn int nbd_do_cmd_cache(NBDClient *client, NBDRequest *request,
2333 Error **errp)
2334{
2335 int ret;
2336 NBDExport *exp = client->exp;
2337
2338 assert(request->type == NBD_CMD_CACHE);
2339
37a4f70c 2340 ret = blk_co_preadv(exp->common.blk, request->from, request->len,
7fa5c565
VSO
2341 NULL, BDRV_REQ_COPY_ON_READ | BDRV_REQ_PREFETCH);
2342
2343 return nbd_send_generic_reply(client, request->handle, ret,
2344 "caching data failed", errp);
2345}
2346
6f302e60
VSO
2347/* Handle NBD request.
2348 * Return -errno if sending fails. Other errors are reported directly to the
2349 * client as an error reply. */
2350static coroutine_fn int nbd_handle_request(NBDClient *client,
2351 NBDRequest *request,
2352 uint8_t *data, Error **errp)
2353{
2354 int ret;
2355 int flags;
2356 NBDExport *exp = client->exp;
2357 char *msg;
3b1f244c 2358 size_t i;
6f302e60
VSO
2359
2360 switch (request->type) {
bc37b06a 2361 case NBD_CMD_CACHE:
7fa5c565
VSO
2362 return nbd_do_cmd_cache(client, request, errp);
2363
2364 case NBD_CMD_READ:
6f302e60
VSO
2365 return nbd_do_cmd_read(client, request, data, errp);
2366
2367 case NBD_CMD_WRITE:
2368 flags = 0;
2369 if (request->flags & NBD_CMD_FLAG_FUA) {
2370 flags |= BDRV_REQ_FUA;
2371 }
37a4f70c
KW
2372 ret = blk_pwrite(exp->common.blk, request->from, data, request->len,
2373 flags);
6f302e60
VSO
2374 return nbd_send_generic_reply(client, request->handle, ret,
2375 "writing to file failed", errp);
2376
2377 case NBD_CMD_WRITE_ZEROES:
2378 flags = 0;
2379 if (request->flags & NBD_CMD_FLAG_FUA) {
2380 flags |= BDRV_REQ_FUA;
2381 }
2382 if (!(request->flags & NBD_CMD_FLAG_NO_HOLE)) {
2383 flags |= BDRV_REQ_MAY_UNMAP;
2384 }
b491dbb7
EB
2385 if (request->flags & NBD_CMD_FLAG_FAST_ZERO) {
2386 flags |= BDRV_REQ_NO_FALLBACK;
2387 }
890cbccb
EB
2388 ret = 0;
2389 /* FIXME simplify this when blk_pwrite_zeroes switches to 64-bit */
2390 while (ret >= 0 && request->len) {
2391 int align = client->check_align ?: 1;
2392 int len = MIN(request->len, QEMU_ALIGN_DOWN(BDRV_REQUEST_MAX_BYTES,
2393 align));
37a4f70c 2394 ret = blk_pwrite_zeroes(exp->common.blk, request->from, len, flags);
890cbccb
EB
2395 request->len -= len;
2396 request->from += len;
2397 }
6f302e60
VSO
2398 return nbd_send_generic_reply(client, request->handle, ret,
2399 "writing to file failed", errp);
2400
2401 case NBD_CMD_DISC:
2402 /* unreachable, thanks to special case in nbd_co_receive_request() */
2403 abort();
2404
2405 case NBD_CMD_FLUSH:
37a4f70c 2406 ret = blk_co_flush(exp->common.blk);
6f302e60
VSO
2407 return nbd_send_generic_reply(client, request->handle, ret,
2408 "flush failed", errp);
2409
2410 case NBD_CMD_TRIM:
890cbccb
EB
2411 ret = 0;
2412 /* FIXME simplify this when blk_co_pdiscard switches to 64-bit */
2413 while (ret >= 0 && request->len) {
2414 int align = client->check_align ?: 1;
2415 int len = MIN(request->len, QEMU_ALIGN_DOWN(BDRV_REQUEST_MAX_BYTES,
2416 align));
37a4f70c 2417 ret = blk_co_pdiscard(exp->common.blk, request->from, len);
890cbccb
EB
2418 request->len -= len;
2419 request->from += len;
2420 }
2421 if (ret >= 0 && request->flags & NBD_CMD_FLAG_FUA) {
37a4f70c 2422 ret = blk_co_flush(exp->common.blk);
65529782 2423 }
6f302e60
VSO
2424 return nbd_send_generic_reply(client, request->handle, ret,
2425 "discard failed", errp);
2426
e7b1948d 2427 case NBD_CMD_BLOCK_STATUS:
d8b20291
EB
2428 if (!request->len) {
2429 return nbd_send_generic_reply(client, request->handle, -EINVAL,
2430 "need non-zero length", errp);
2431 }
47ec485e 2432 if (client->export_meta.count) {
fb7afc79 2433 bool dont_fragment = request->flags & NBD_CMD_FLAG_REQ_ONE;
47ec485e 2434 int contexts_remaining = client->export_meta.count;
fb7afc79 2435
3d068aff
VSO
2436 if (client->export_meta.base_allocation) {
2437 ret = nbd_co_send_block_status(client, request->handle,
37a4f70c
KW
2438 blk_bs(exp->common.blk),
2439 request->from,
fb7afc79 2440 request->len, dont_fragment,
47ec485e 2441 !--contexts_remaining,
3d068aff
VSO
2442 NBD_META_ID_BASE_ALLOCATION,
2443 errp);
73e064cc
EB
2444 if (ret < 0) {
2445 return ret;
2446 }
2447 }
2448
71719cd5
EB
2449 if (client->export_meta.allocation_depth) {
2450 ret = nbd_co_send_block_status(client, request->handle,
2451 blk_bs(exp->common.blk),
2452 request->from, request->len,
2453 dont_fragment,
2454 !--contexts_remaining,
2455 NBD_META_ID_ALLOCATION_DEPTH,
2456 errp);
2457 if (ret < 0) {
2458 return ret;
2459 }
2460 }
2461
3b1f244c
EB
2462 for (i = 0; i < client->exp->nr_export_bitmaps; i++) {
2463 if (!client->export_meta.bitmaps[i]) {
2464 continue;
2465 }
3d068aff 2466 ret = nbd_co_send_bitmap(client, request->handle,
3b1f244c 2467 client->exp->export_bitmaps[i],
3d068aff 2468 request->from, request->len,
47ec485e 2469 dont_fragment, !--contexts_remaining,
3b1f244c 2470 NBD_META_ID_DIRTY_BITMAP + i, errp);
73e064cc
EB
2471 if (ret < 0) {
2472 return ret;
2473 }
3d068aff
VSO
2474 }
2475
47ec485e
EB
2476 assert(!contexts_remaining);
2477
73e064cc 2478 return 0;
e7b1948d
VSO
2479 } else {
2480 return nbd_send_generic_reply(client, request->handle, -EINVAL,
2481 "CMD_BLOCK_STATUS not negotiated",
2482 errp);
2483 }
2484
6f302e60
VSO
2485 default:
2486 msg = g_strdup_printf("invalid request type (%" PRIu32 ") received",
2487 request->type);
2488 ret = nbd_send_generic_reply(client, request->handle, -EINVAL, msg,
2489 errp);
2490 g_free(msg);
2491 return ret;
2492 }
2493}
2494
ff82911c
PB
2495/* Owns a reference to the NBDClient passed as opaque. */
2496static coroutine_fn void nbd_trip(void *opaque)
75818250 2497{
262db388 2498 NBDClient *client = opaque;
315f78ab 2499 NBDRequestData *req;
ff82911c 2500 NBDRequest request = { 0 }; /* GCC thinks it can be used uninitialized */
a0dc63a6 2501 int ret;
2fd2c840 2502 Error *local_err = NULL;
b2e3d87f 2503
9588463e 2504 trace_nbd_trip();
ff2b68aa 2505 if (client->closing) {
ff82911c 2506 nbd_client_put(client);
ff2b68aa
PB
2507 return;
2508 }
b2e3d87f 2509
ff2b68aa 2510 req = nbd_request_get(client);
2fd2c840 2511 ret = nbd_co_receive_request(req, &request, &local_err);
ee898b87 2512 client->recv_coroutine = NULL;
b2e3d87f 2513
d6268348
WC
2514 if (client->closing) {
2515 /*
2516 * The client may be closed when we are blocked in
2517 * nbd_co_receive_request()
2518 */
2519 goto done;
2520 }
2521
a0d7ce20
VSO
2522 nbd_client_receive_next_request(client);
2523 if (ret == -EIO) {
2524 goto disconnect;
2525 }
2526
2527 if (ret < 0) {
6a417599
VSO
2528 /* It wans't -EIO, so, according to nbd_co_receive_request()
2529 * semantics, we should return the error to the client. */
2530 Error *export_err = local_err;
2531
2532 local_err = NULL;
2533 ret = nbd_send_generic_reply(client, request.handle, -EINVAL,
2534 error_get_pretty(export_err), &local_err);
2535 error_free(export_err);
6f302e60
VSO
2536 } else {
2537 ret = nbd_handle_request(client, &request, req->data, &local_err);
5c54e7fa
VSO
2538 }
2539 if (ret < 0) {
c7b97282 2540 error_prepend(&local_err, "Failed to send reply: ");
2fd2c840
VSO
2541 goto disconnect;
2542 }
2543
8c372a02
VSO
2544 /* We must disconnect after NBD_CMD_WRITE if we did not
2545 * read the payload.
2546 */
2fd2c840
VSO
2547 if (!req->complete) {
2548 error_setg(&local_err, "Request handling failed in intermediate state");
8c372a02 2549 goto disconnect;
b2e3d87f
NT
2550 }
2551
7fe7b68b 2552done:
262db388 2553 nbd_request_put(req);
ff82911c 2554 nbd_client_put(client);
262db388
PB
2555 return;
2556
8c372a02 2557disconnect:
2fd2c840
VSO
2558 if (local_err) {
2559 error_reportf_err(local_err, "Disconnect client, due to: ");
2560 }
72deddc5 2561 nbd_request_put(req);
0c9390d9 2562 client_close(client, true);
ff82911c 2563 nbd_client_put(client);
7a5ca864 2564}
af49bbbe 2565
ff82911c 2566static void nbd_client_receive_next_request(NBDClient *client)
958c717d 2567{
ff82911c
PB
2568 if (!client->recv_coroutine && client->nb_requests < MAX_NBD_REQUESTS) {
2569 nbd_client_get(client);
2570 client->recv_coroutine = qemu_coroutine_create(nbd_trip, client);
8612c686 2571 aio_co_schedule(client->exp->common.ctx, client->recv_coroutine);
958c717d
HR
2572 }
2573}
2574
1a6245a5
FZ
2575static coroutine_fn void nbd_co_client_start(void *opaque)
2576{
c84087f2 2577 NBDClient *client = opaque;
2fd2c840 2578 Error *local_err = NULL;
1a6245a5 2579
df8ad9f1
EB
2580 qemu_co_mutex_init(&client->send_lock);
2581
2fd2c840
VSO
2582 if (nbd_negotiate(client, &local_err)) {
2583 if (local_err) {
2584 error_report_err(local_err);
2585 }
0c9390d9 2586 client_close(client, false);
c84087f2 2587 return;
1a6245a5 2588 }
ff82911c
PB
2589
2590 nbd_client_receive_next_request(client);
1a6245a5
FZ
2591}
2592
0c9390d9 2593/*
7f7dfe2a
VSO
2594 * Create a new client listener using the given channel @sioc.
2595 * Begin servicing it in a coroutine. When the connection closes, call
2596 * @close_fn with an indication of whether the client completed negotiation.
0c9390d9 2597 */
7f7dfe2a 2598void nbd_client_new(QIOChannelSocket *sioc,
f95910fe 2599 QCryptoTLSCreds *tlscreds,
b25e12da 2600 const char *tlsauthz,
0c9390d9 2601 void (*close_fn)(NBDClient *, bool))
af49bbbe 2602{
1743b515 2603 NBDClient *client;
c84087f2 2604 Coroutine *co;
1a6245a5 2605
e8d3eb74 2606 client = g_new0(NBDClient, 1);
1743b515 2607 client->refcount = 1;
f95910fe
DB
2608 client->tlscreds = tlscreds;
2609 if (tlscreds) {
2610 object_ref(OBJECT(client->tlscreds));
2611 }
b25e12da 2612 client->tlsauthz = g_strdup(tlsauthz);
1c778ef7
DB
2613 client->sioc = sioc;
2614 object_ref(OBJECT(client->sioc));
2615 client->ioc = QIO_CHANNEL(sioc);
2616 object_ref(OBJECT(client->ioc));
0c9390d9 2617 client->close_fn = close_fn;
2c8d9f06 2618
c84087f2
VSO
2619 co = qemu_coroutine_create(nbd_co_client_start, client);
2620 qemu_coroutine_enter(co);
af49bbbe 2621}
This page took 1.251361 seconds and 4 git commands to generate.