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