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