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