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