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