master
c 3,312 lines 103 KB
Raw
1 /*
2 * Copyright Red Hat
3 * Copyright (C) 2005 Anthony Liguori <anthony@codemonkey.ws>
4 *
5 * Network Block Device Server Side
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
17 * along with this program; if not, see <http://www.gnu.org/licenses/>.
18 */
19
20 #include "qemu/osdep.h"
21
22 #include "block/block_int.h"
23 #include "block/export.h"
24 #include "block/dirty-bitmap.h"
25 #include "qapi/error.h"
26 #include "qemu/queue.h"
27 #include "trace.h"
28 #include "nbd-internal.h"
29 #include "qemu/units.h"
30 #include "qemu/memalign.h"
31
32 #define NBD_META_ID_BASE_ALLOCATION 0
33 #define NBD_META_ID_ALLOCATION_DEPTH 1
34 /* Dirty bitmaps use 'NBD_META_ID_DIRTY_BITMAP + i', so keep this id last. */
35 #define NBD_META_ID_DIRTY_BITMAP 2
36
37 /*
38 * NBD_MAX_BLOCK_STATUS_EXTENTS: 1 MiB of extents data. An empirical
39 * constant. If an increase is needed, note that the NBD protocol
40 * recommends no larger than 32 mb, so that the client won't consider
41 * the reply as a denial of service attack.
42 */
43 #define NBD_MAX_BLOCK_STATUS_EXTENTS (1 * MiB / 8)
44
45 static int system_errno_to_nbd_errno(int err)
46 {
47 switch (err) {
48 case 0:
49 return NBD_SUCCESS;
50 case EPERM:
51 case EROFS:
52 return NBD_EPERM;
53 case EIO:
54 return NBD_EIO;
55 case ENOMEM:
56 return NBD_ENOMEM;
57 #ifdef EDQUOT
58 case EDQUOT:
59 #endif
60 case EFBIG:
61 case ENOSPC:
62 return NBD_ENOSPC;
63 case EOVERFLOW:
64 return NBD_EOVERFLOW;
65 case ENOTSUP:
66 #if ENOTSUP != EOPNOTSUPP
67 case EOPNOTSUPP:
68 #endif
69 return NBD_ENOTSUP;
70 case ESHUTDOWN:
71 return NBD_ESHUTDOWN;
72 case EINVAL:
73 default:
74 return NBD_EINVAL;
75 }
76 }
77
78 /* Definitions for opaque data types */
79
80 typedef struct NBDRequestData NBDRequestData;
81
82 struct NBDRequestData {
83 NBDClient *client;
84 uint8_t *data;
85 bool complete;
86 };
87
88 struct NBDExport {
89 BlockExport common;
90
91 char *name;
92 char *description;
93 uint64_t size;
94 uint16_t nbdflags;
95 QTAILQ_HEAD(, NBDClient) clients;
96 QTAILQ_ENTRY(NBDExport) next;
97
98 BlockBackend *eject_notifier_blk;
99 Notifier eject_notifier;
100
101 bool allocation_depth;
102 BdrvDirtyBitmap **export_bitmaps;
103 size_t nr_export_bitmaps;
104 };
105
106 static QTAILQ_HEAD(, NBDExport) exports = QTAILQ_HEAD_INITIALIZER(exports);
107
108 /*
109 * NBDMetaContexts represents a list of meta contexts in use,
110 * as selected by NBD_OPT_SET_META_CONTEXT. Also used for
111 * NBD_OPT_LIST_META_CONTEXT.
112 */
113 struct NBDMetaContexts {
114 const NBDExport *exp; /* associated export */
115 size_t count; /* number of negotiated contexts */
116 bool base_allocation; /* export base:allocation context (block status) */
117 bool allocation_depth; /* export qemu:allocation-depth */
118 bool *bitmaps; /*
119 * export qemu:dirty-bitmap:<export bitmap name>,
120 * sized by exp->nr_export_bitmaps
121 */
122 };
123
124 struct NBDClient {
125 int refcount; /* atomic */
126 void (*close_fn)(NBDClient *client, bool negotiated);
127 void *owner;
128
129 QemuMutex lock;
130
131 NBDExport *exp;
132 QCryptoTLSCreds *tlscreds;
133 char *tlsauthz;
134 uint32_t handshake_max_secs;
135 QIOChannelSocket *sioc; /* The underlying data channel */
136 QIOChannel *ioc; /* The current I/O channel which may differ (eg TLS) */
137
138 Coroutine *recv_coroutine; /* protected by lock */
139
140 CoMutex send_lock;
141 Coroutine *send_coroutine;
142
143 bool read_yielding; /* protected by lock */
144 bool quiescing; /* protected by lock */
145
146 QTAILQ_ENTRY(NBDClient) next;
147 int nb_requests; /* protected by lock */
148 bool closing; /* protected by lock */
149
150 uint32_t check_align; /* If non-zero, check for aligned client requests */
151
152 NBDMode mode;
153 NBDMetaContexts contexts; /* Negotiated meta contexts */
154
155 uint32_t opt; /* Current option being negotiated */
156 uint32_t optlen; /* remaining length of data in ioc for the option being
157 negotiated now */
158 };
159
160 static void nbd_client_receive_next_request(NBDClient *client);
161
162 /* Basic flow for negotiation
163
164 Server Client
165 Negotiate
166
167 or
168
169 Server Client
170 Negotiate #1
171 Option
172 Negotiate #2
173
174 ----
175
176 followed by
177
178 Server Client
179 Request
180 Response
181 Request
182 Response
183 ...
184 ...
185 Request (type == 2)
186
187 */
188
189 static inline void set_be_option_rep(NBDOptionReply *rep, uint32_t option,
190 uint32_t type, uint32_t length)
191 {
192 stq_be_p(&rep->magic, NBD_REP_MAGIC);
193 stl_be_p(&rep->option, option);
194 stl_be_p(&rep->type, type);
195 stl_be_p(&rep->length, length);
196 }
197
198 /* Send a reply header, including length, but no payload.
199 * Return -errno on error, 0 on success. */
200 static coroutine_fn int
201 nbd_negotiate_send_rep_len(NBDClient *client, uint32_t type,
202 uint32_t len, Error **errp)
203 {
204 NBDOptionReply rep;
205
206 trace_nbd_negotiate_send_rep_len(client->opt, nbd_opt_lookup(client->opt),
207 type, nbd_rep_lookup(type), len);
208
209 assert(len < NBD_MAX_BUFFER_SIZE);
210
211 set_be_option_rep(&rep, client->opt, type, len);
212 return nbd_write(client->ioc, &rep, sizeof(rep), errp);
213 }
214
215 /* Send a reply header with default 0 length.
216 * Return -errno on error, 0 on success. */
217 static coroutine_fn int
218 nbd_negotiate_send_rep(NBDClient *client, uint32_t type, Error **errp)
219 {
220 return nbd_negotiate_send_rep_len(client, type, 0, errp);
221 }
222
223 /* Send an error reply.
224 * Return -errno on error, 0 on success. */
225 static coroutine_fn int G_GNUC_PRINTF(4, 0)
226 nbd_negotiate_send_rep_verr(NBDClient *client, uint32_t type,
227 Error **errp, const char *fmt, va_list va)
228 {
229 ERRP_GUARD();
230 g_autofree char *msg = NULL;
231 int ret;
232 size_t len;
233
234 msg = g_strdup_vprintf(fmt, va);
235 len = strlen(msg);
236 assert(len < NBD_MAX_STRING_SIZE);
237 trace_nbd_negotiate_send_rep_err(msg);
238 ret = nbd_negotiate_send_rep_len(client, type, len, errp);
239 if (ret < 0) {
240 return ret;
241 }
242 if (nbd_write(client->ioc, msg, len, errp) < 0) {
243 error_prepend(errp, "write failed (error message): ");
244 return -EIO;
245 }
246
247 return 0;
248 }
249
250 /*
251 * Return a malloc'd copy of @name suitable for use in an error reply.
252 */
253 static char *
254 nbd_sanitize_name(const char *name)
255 {
256 if (strnlen(name, 80) < 80) {
257 return g_strdup(name);
258 }
259 /* XXX Should we also try to sanitize any control characters? */
260 return g_strdup_printf("%.80s...", name);
261 }
262
263 /* Send an error reply.
264 * Return -errno on error, 0 on success. */
265 static coroutine_fn int G_GNUC_PRINTF(4, 5)
266 nbd_negotiate_send_rep_err(NBDClient *client, uint32_t type,
267 Error **errp, const char *fmt, ...)
268 {
269 va_list va;
270 int ret;
271
272 va_start(va, fmt);
273 ret = nbd_negotiate_send_rep_verr(client, type, errp, fmt, va);
274 va_end(va);
275 return ret;
276 }
277
278 /* Drop remainder of the current option, and send a reply with the
279 * given error type and message. Return -errno on read or write
280 * failure; or 0 if connection is still live. */
281 static coroutine_fn int G_GNUC_PRINTF(4, 0)
282 nbd_opt_vdrop(NBDClient *client, uint32_t type, Error **errp,
283 const char *fmt, va_list va)
284 {
285 int ret = nbd_drop(client->ioc, client->optlen, errp);
286
287 client->optlen = 0;
288 if (!ret) {
289 ret = nbd_negotiate_send_rep_verr(client, type, errp, fmt, va);
290 }
291 return ret;
292 }
293
294 static coroutine_fn int G_GNUC_PRINTF(4, 5)
295 nbd_opt_drop(NBDClient *client, uint32_t type, Error **errp,
296 const char *fmt, ...)
297 {
298 int ret;
299 va_list va;
300
301 va_start(va, fmt);
302 ret = nbd_opt_vdrop(client, type, errp, fmt, va);
303 va_end(va);
304
305 return ret;
306 }
307
308 static coroutine_fn int G_GNUC_PRINTF(3, 4)
309 nbd_opt_invalid(NBDClient *client, Error **errp, const char *fmt, ...)
310 {
311 int ret;
312 va_list va;
313
314 va_start(va, fmt);
315 ret = nbd_opt_vdrop(client, NBD_REP_ERR_INVALID, errp, fmt, va);
316 va_end(va);
317
318 return ret;
319 }
320
321 /* Read size bytes from the unparsed payload of the current option.
322 * If @check_nul, require that no NUL bytes appear in buffer.
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 static coroutine_fn int
326 nbd_opt_read(NBDClient *client, void *buffer, size_t size,
327 bool check_nul, Error **errp)
328 {
329 if (size > client->optlen) {
330 return nbd_opt_invalid(client, errp,
331 "Inconsistent lengths in option %s",
332 nbd_opt_lookup(client->opt));
333 }
334 client->optlen -= size;
335 if (qio_channel_read_all(client->ioc, buffer, size, errp) < 0) {
336 return -EIO;
337 }
338
339 if (check_nul && strnlen(buffer, size) != size) {
340 return nbd_opt_invalid(client, errp,
341 "Unexpected embedded NUL in option %s",
342 nbd_opt_lookup(client->opt));
343 }
344 return 1;
345 }
346
347 /* Drop size bytes from the unparsed payload of the current option.
348 * Return -errno on I/O error, 0 if option was completely handled by
349 * sending a reply about inconsistent lengths, or 1 on success. */
350 static coroutine_fn int
351 nbd_opt_skip(NBDClient *client, size_t size, Error **errp)
352 {
353 if (size > client->optlen) {
354 return nbd_opt_invalid(client, errp,
355 "Inconsistent lengths in option %s",
356 nbd_opt_lookup(client->opt));
357 }
358 client->optlen -= size;
359 return nbd_drop(client->ioc, size, errp) < 0 ? -EIO : 1;
360 }
361
362 /* nbd_opt_read_name
363 *
364 * Read a string with the format:
365 * uint32_t len (<= NBD_MAX_STRING_SIZE)
366 * len bytes string (not 0-terminated)
367 *
368 * On success, @name will be allocated.
369 * If @length is non-null, it will be set to the actual string length.
370 *
371 * Return -errno on I/O error, 0 if option was completely handled by
372 * sending a reply about inconsistent lengths, or 1 on success.
373 */
374 static coroutine_fn int
375 nbd_opt_read_name(NBDClient *client, char **name, uint32_t *length,
376 Error **errp)
377 {
378 int ret;
379 uint32_t len;
380 g_autofree char *local_name = NULL;
381
382 *name = NULL;
383 ret = nbd_opt_read(client, &len, sizeof(len), false, errp);
384 if (ret <= 0) {
385 return ret;
386 }
387 len = cpu_to_be32(len);
388
389 if (len > NBD_MAX_STRING_SIZE) {
390 return nbd_opt_invalid(client, errp,
391 "Invalid name length: %" PRIu32, len);
392 }
393
394 local_name = g_malloc(len + 1);
395 ret = nbd_opt_read(client, local_name, len, true, errp);
396 if (ret <= 0) {
397 return ret;
398 }
399 local_name[len] = '\0';
400
401 if (length) {
402 *length = len;
403 }
404 *name = g_steal_pointer(&local_name);
405
406 return 1;
407 }
408
409 /* Send a single NBD_REP_SERVER reply to NBD_OPT_LIST, including payload.
410 * Return -errno on error, 0 on success. */
411 static coroutine_fn int
412 nbd_negotiate_send_rep_list(NBDClient *client, NBDExport *exp, Error **errp)
413 {
414 ERRP_GUARD();
415 size_t name_len, desc_len;
416 uint32_t len;
417 const char *name = exp->name ? exp->name : "";
418 const char *desc = exp->description ? exp->description : "";
419 QIOChannel *ioc = client->ioc;
420 int ret;
421
422 trace_nbd_negotiate_send_rep_list(name, desc);
423 name_len = strlen(name);
424 desc_len = strlen(desc);
425 assert(name_len <= NBD_MAX_STRING_SIZE && desc_len <= NBD_MAX_STRING_SIZE);
426 len = name_len + desc_len + sizeof(len);
427 ret = nbd_negotiate_send_rep_len(client, NBD_REP_SERVER, len, errp);
428 if (ret < 0) {
429 return ret;
430 }
431
432 len = cpu_to_be32(name_len);
433 if (nbd_write(ioc, &len, sizeof(len), errp) < 0) {
434 error_prepend(errp, "write failed (name length): ");
435 return -EINVAL;
436 }
437
438 if (nbd_write(ioc, name, name_len, errp) < 0) {
439 error_prepend(errp, "write failed (name buffer): ");
440 return -EINVAL;
441 }
442
443 if (nbd_write(ioc, desc, desc_len, errp) < 0) {
444 error_prepend(errp, "write failed (description buffer): ");
445 return -EINVAL;
446 }
447
448 return 0;
449 }
450
451 /* Process the NBD_OPT_LIST command, with a potential series of replies.
452 * Return -errno on error, 0 on success. */
453 static coroutine_fn int
454 nbd_negotiate_handle_list(NBDClient *client, Error **errp)
455 {
456 NBDExport *exp;
457 assert(client->opt == NBD_OPT_LIST);
458
459 /* For each export, send a NBD_REP_SERVER reply. */
460 QTAILQ_FOREACH(exp, &exports, next) {
461 if (nbd_negotiate_send_rep_list(client, exp, errp)) {
462 return -EINVAL;
463 }
464 }
465 /* Finish with a NBD_REP_ACK. */
466 return nbd_negotiate_send_rep(client, NBD_REP_ACK, errp);
467 }
468
469 static coroutine_fn void
470 nbd_check_meta_export(NBDClient *client, NBDExport *exp)
471 {
472 if (exp != client->contexts.exp) {
473 client->contexts.count = 0;
474 }
475 }
476
477 /* Send a reply to NBD_OPT_EXPORT_NAME.
478 * Return -errno on error, 0 on success. */
479 static coroutine_fn int
480 nbd_negotiate_handle_export_name(NBDClient *client, bool no_zeroes,
481 Error **errp)
482 {
483 ERRP_GUARD();
484 g_autofree char *name = NULL;
485 char buf[NBD_REPLY_EXPORT_NAME_SIZE] = "";
486 size_t len;
487 int ret;
488 uint16_t myflags;
489
490 /* Client sends:
491 [20 .. xx] export name (length bytes)
492 Server replies:
493 [ 0 .. 7] size
494 [ 8 .. 9] export flags
495 [10 .. 133] reserved (0) [unless no_zeroes]
496 */
497 trace_nbd_negotiate_handle_export_name();
498 if (client->mode >= NBD_MODE_EXTENDED) {
499 error_setg(errp, "Extended headers already negotiated");
500 return -EINVAL;
501 }
502 if (client->optlen > NBD_MAX_STRING_SIZE) {
503 error_setg(errp, "Bad length received");
504 return -EINVAL;
505 }
506 name = g_malloc(client->optlen + 1);
507 if (nbd_read(client->ioc, name, client->optlen, "export name", errp) < 0) {
508 return -EIO;
509 }
510 name[client->optlen] = '\0';
511 client->optlen = 0;
512
513 trace_nbd_negotiate_handle_export_name_request(name);
514
515 client->exp = nbd_export_find(name);
516 if (!client->exp) {
517 error_setg(errp, "export not found");
518 return -EINVAL;
519 }
520 nbd_check_meta_export(client, client->exp);
521
522 myflags = client->exp->nbdflags;
523 if (client->mode >= NBD_MODE_STRUCTURED) {
524 myflags |= NBD_FLAG_SEND_DF;
525 }
526 if (client->mode >= NBD_MODE_EXTENDED && client->contexts.count) {
527 myflags |= NBD_FLAG_BLOCK_STAT_PAYLOAD;
528 }
529 trace_nbd_negotiate_new_style_size_flags(client->exp->size, myflags);
530 stq_be_p(buf, client->exp->size);
531 stw_be_p(buf + 8, myflags);
532 len = no_zeroes ? 10 : sizeof(buf);
533 ret = nbd_write(client->ioc, buf, len, errp);
534 if (ret < 0) {
535 error_prepend(errp, "write failed: ");
536 return ret;
537 }
538
539 QTAILQ_INSERT_TAIL(&client->exp->clients, client, next);
540 blk_exp_ref(&client->exp->common);
541
542 return 0;
543 }
544
545 /* Send a single NBD_REP_INFO, with a buffer @buf of @length bytes.
546 * The buffer does NOT include the info type prefix.
547 * Return -errno on error, 0 if ready to send more. */
548 static coroutine_fn int
549 nbd_negotiate_send_info(NBDClient *client, uint16_t info, uint32_t length,
550 void *buf, Error **errp)
551 {
552 int rc;
553
554 trace_nbd_negotiate_send_info(info, nbd_info_lookup(info), length);
555 rc = nbd_negotiate_send_rep_len(client, NBD_REP_INFO,
556 sizeof(info) + length, errp);
557 if (rc < 0) {
558 return rc;
559 }
560 info = cpu_to_be16(info);
561 if (nbd_write(client->ioc, &info, sizeof(info), errp) < 0) {
562 return -EIO;
563 }
564 if (nbd_write(client->ioc, buf, length, errp) < 0) {
565 return -EIO;
566 }
567 return 0;
568 }
569
570 /* nbd_reject_length: Handle any unexpected payload.
571 * @fatal requests that we quit talking to the client, even if we are able
572 * to successfully send an error reply.
573 * Return:
574 * -errno transmission error occurred or @fatal was requested, errp is set
575 * 0 error message successfully sent to client, errp is not set
576 */
577 static coroutine_fn int
578 nbd_reject_length(NBDClient *client, bool fatal, Error **errp)
579 {
580 int ret;
581
582 assert(client->optlen);
583 ret = nbd_opt_invalid(client, errp, "option '%s' has unexpected length",
584 nbd_opt_lookup(client->opt));
585 if (fatal && !ret) {
586 error_setg(errp, "option '%s' has unexpected length",
587 nbd_opt_lookup(client->opt));
588 return -EINVAL;
589 }
590 return ret;
591 }
592
593 /* Handle NBD_OPT_INFO and NBD_OPT_GO.
594 * Return -errno on error, 0 if ready for next option, and 1 to move
595 * into transmission phase. */
596 static coroutine_fn int
597 nbd_negotiate_handle_info(NBDClient *client, Error **errp)
598 {
599 int rc;
600 g_autofree char *name = NULL;
601 NBDExport *exp;
602 uint16_t requests;
603 uint16_t request;
604 uint32_t namelen = 0;
605 bool sendname = false;
606 bool blocksize = false;
607 uint32_t sizes[3];
608 char buf[sizeof(uint64_t) + sizeof(uint16_t)];
609 uint32_t check_align = 0;
610 uint16_t myflags;
611
612 /* Client sends:
613 4 bytes: L, name length (can be 0)
614 L bytes: export name
615 2 bytes: N, number of requests (can be 0)
616 N * 2 bytes: N requests
617 */
618 rc = nbd_opt_read_name(client, &name, &namelen, errp);
619 if (rc <= 0) {
620 return rc;
621 }
622 trace_nbd_negotiate_handle_export_name_request(name);
623
624 rc = nbd_opt_read(client, &requests, sizeof(requests), false, errp);
625 if (rc <= 0) {
626 return rc;
627 }
628 requests = be16_to_cpu(requests);
629 trace_nbd_negotiate_handle_info_requests(requests);
630 while (requests--) {
631 rc = nbd_opt_read(client, &request, sizeof(request), false, errp);
632 if (rc <= 0) {
633 return rc;
634 }
635 request = be16_to_cpu(request);
636 trace_nbd_negotiate_handle_info_request(request,
637 nbd_info_lookup(request));
638 /* We care about NBD_INFO_NAME and NBD_INFO_BLOCK_SIZE;
639 * everything else is either a request we don't know or
640 * something we send regardless of request */
641 switch (request) {
642 case NBD_INFO_NAME:
643 sendname = true;
644 break;
645 case NBD_INFO_BLOCK_SIZE:
646 blocksize = true;
647 break;
648 }
649 }
650 if (client->optlen) {
651 return nbd_reject_length(client, false, errp);
652 }
653
654 exp = nbd_export_find(name);
655 if (!exp) {
656 g_autofree char *sane_name = nbd_sanitize_name(name);
657
658 return nbd_negotiate_send_rep_err(client, NBD_REP_ERR_UNKNOWN,
659 errp, "export '%s' not present",
660 sane_name);
661 }
662 if (client->opt == NBD_OPT_GO) {
663 nbd_check_meta_export(client, exp);
664 }
665
666 /* Don't bother sending NBD_INFO_NAME unless client requested it */
667 if (sendname) {
668 rc = nbd_negotiate_send_info(client, NBD_INFO_NAME, namelen, name,
669 errp);
670 if (rc < 0) {
671 return rc;
672 }
673 }
674
675 /* Send NBD_INFO_DESCRIPTION only if available, regardless of
676 * client request */
677 if (exp->description) {
678 size_t len = strlen(exp->description);
679
680 assert(len <= NBD_MAX_STRING_SIZE);
681 rc = nbd_negotiate_send_info(client, NBD_INFO_DESCRIPTION,
682 len, exp->description, errp);
683 if (rc < 0) {
684 return rc;
685 }
686 }
687
688 /* Send NBD_INFO_BLOCK_SIZE always, but tweak the minimum size
689 * according to whether the client requested it, and according to
690 * whether this is OPT_INFO or OPT_GO. */
691 /* minimum - 1 for back-compat, or actual if client will obey it. */
692 if (client->opt == NBD_OPT_INFO || blocksize) {
693 check_align = sizes[0] = blk_get_request_alignment(exp->common.blk);
694 } else {
695 sizes[0] = 1;
696 }
697 assert(sizes[0] <= NBD_MAX_BUFFER_SIZE);
698 /* preferred - Hard-code to 4096 for now.
699 * TODO: is blk_bs(blk)->bl.opt_transfer appropriate? */
700 sizes[1] = MAX(4096, sizes[0]);
701 /* maximum - At most 32M, but smaller as appropriate. */
702 sizes[2] = MIN(blk_get_max_transfer(exp->common.blk), NBD_MAX_BUFFER_SIZE);
703 trace_nbd_negotiate_handle_info_block_size(sizes[0], sizes[1], sizes[2]);
704 sizes[0] = cpu_to_be32(sizes[0]);
705 sizes[1] = cpu_to_be32(sizes[1]);
706 sizes[2] = cpu_to_be32(sizes[2]);
707 rc = nbd_negotiate_send_info(client, NBD_INFO_BLOCK_SIZE,
708 sizeof(sizes), sizes, errp);
709 if (rc < 0) {
710 return rc;
711 }
712
713 /* Send NBD_INFO_EXPORT always */
714 myflags = exp->nbdflags;
715 if (client->mode >= NBD_MODE_STRUCTURED) {
716 myflags |= NBD_FLAG_SEND_DF;
717 }
718 if (client->mode >= NBD_MODE_EXTENDED &&
719 (client->contexts.count || client->opt == NBD_OPT_INFO)) {
720 myflags |= NBD_FLAG_BLOCK_STAT_PAYLOAD;
721 }
722 trace_nbd_negotiate_new_style_size_flags(exp->size, myflags);
723 stq_be_p(buf, exp->size);
724 stw_be_p(buf + 8, myflags);
725 rc = nbd_negotiate_send_info(client, NBD_INFO_EXPORT,
726 sizeof(buf), buf, errp);
727 if (rc < 0) {
728 return rc;
729 }
730
731 /*
732 * If the client is just asking for NBD_OPT_INFO, but forgot to
733 * request block sizes in a situation that would impact
734 * performance, then return an error. But for NBD_OPT_GO, we
735 * tolerate all clients, regardless of alignments.
736 */
737 if (client->opt == NBD_OPT_INFO && !blocksize &&
738 blk_get_request_alignment(exp->common.blk) > 1) {
739 return nbd_negotiate_send_rep_err(client,
740 NBD_REP_ERR_BLOCK_SIZE_REQD,
741 errp,
742 "request NBD_INFO_BLOCK_SIZE to "
743 "use this export");
744 }
745
746 /* Final reply */
747 rc = nbd_negotiate_send_rep(client, NBD_REP_ACK, errp);
748 if (rc < 0) {
749 return rc;
750 }
751
752 if (client->opt == NBD_OPT_GO) {
753 client->exp = exp;
754 client->check_align = check_align;
755 QTAILQ_INSERT_TAIL(&client->exp->clients, client, next);
756 blk_exp_ref(&client->exp->common);
757 rc = 1;
758 }
759 return rc;
760 }
761
762 /* Callback to learn when QIO TLS upgrade is complete */
763 struct NBDTLSServerHandshakeData {
764 bool complete;
765 Error *error;
766 Coroutine *co;
767 };
768
769 static void
770 nbd_server_tls_handshake(QIOTask *task, void *opaque)
771 {
772 struct NBDTLSServerHandshakeData *data = opaque;
773
774 qio_task_propagate_error(task, &data->error);
775 data->complete = true;
776 if (!qemu_coroutine_entered(data->co)) {
777 aio_co_wake(data->co);
778 }
779 }
780
781 /* Handle NBD_OPT_STARTTLS. Return NULL to drop connection, or else the
782 * new channel for all further (now-encrypted) communication. */
783 static coroutine_fn QIOChannel *
784 nbd_negotiate_handle_starttls(NBDClient *client, Error **errp)
785 {
786 QIOChannel *ioc;
787 QIOChannelTLS *tioc;
788 struct NBDTLSServerHandshakeData data = { 0 };
789
790 assert(client->opt == NBD_OPT_STARTTLS);
791
792 trace_nbd_negotiate_handle_starttls();
793 ioc = client->ioc;
794
795 if (nbd_negotiate_send_rep(client, NBD_REP_ACK, errp) < 0) {
796 return NULL;
797 }
798
799 tioc = qio_channel_tls_new_server(ioc,
800 client->tlscreds,
801 client->tlsauthz,
802 errp);
803 if (!tioc) {
804 return NULL;
805 }
806
807 qio_channel_set_name(QIO_CHANNEL(tioc), "nbd-server-tls");
808 trace_nbd_negotiate_handle_starttls_handshake();
809 data.co = qemu_coroutine_self();
810 qio_channel_tls_handshake(tioc,
811 nbd_server_tls_handshake,
812 &data,
813 NULL,
814 NULL);
815
816 if (!data.complete) {
817 qemu_coroutine_yield();
818 assert(data.complete);
819 }
820
821 if (data.error) {
822 object_unref(OBJECT(tioc));
823 error_propagate(errp, data.error);
824 return NULL;
825 }
826
827 return QIO_CHANNEL(tioc);
828 }
829
830 /* nbd_negotiate_send_meta_context
831 *
832 * Send one chunk of reply to NBD_OPT_{LIST,SET}_META_CONTEXT
833 *
834 * For NBD_OPT_LIST_META_CONTEXT @context_id is ignored, 0 is used instead.
835 */
836 static coroutine_fn int
837 nbd_negotiate_send_meta_context(NBDClient *client, const char *context,
838 uint32_t context_id, Error **errp)
839 {
840 NBDOptionReplyMetaContext opt;
841 struct iovec iov[] = {
842 {.iov_base = &opt, .iov_len = sizeof(opt)},
843 {.iov_base = (void *)context, .iov_len = strlen(context)}
844 };
845
846 assert(iov[1].iov_len <= NBD_MAX_STRING_SIZE);
847 if (client->opt == NBD_OPT_LIST_META_CONTEXT) {
848 context_id = 0;
849 }
850
851 trace_nbd_negotiate_meta_query_reply(context, context_id);
852 set_be_option_rep(&opt.h, client->opt, NBD_REP_META_CONTEXT,
853 sizeof(opt) - sizeof(opt.h) + iov[1].iov_len);
854 stl_be_p(&opt.context_id, context_id);
855
856 return qio_channel_writev_all(client->ioc, iov, 2, errp) < 0 ? -EIO : 0;
857 }
858
859 /*
860 * Return true if @query matches @pattern, or if @query is empty when
861 * the @client is performing _LIST_.
862 */
863 static coroutine_fn bool
864 nbd_meta_empty_or_pattern(NBDClient *client, const char *pattern,
865 const char *query)
866 {
867 if (!*query) {
868 trace_nbd_negotiate_meta_query_parse("empty");
869 return client->opt == NBD_OPT_LIST_META_CONTEXT;
870 }
871 if (strcmp(query, pattern) == 0) {
872 trace_nbd_negotiate_meta_query_parse(pattern);
873 return true;
874 }
875 trace_nbd_negotiate_meta_query_skip("pattern not matched");
876 return false;
877 }
878
879 /*
880 * Return true and adjust @str in place if it begins with @prefix.
881 */
882 static coroutine_fn bool
883 nbd_strshift(const char **str, const char *prefix)
884 {
885 size_t len = strlen(prefix);
886
887 if (strncmp(*str, prefix, len) == 0) {
888 *str += len;
889 return true;
890 }
891 return false;
892 }
893
894 /* nbd_meta_base_query
895 *
896 * Handle queries to 'base' namespace. For now, only the base:allocation
897 * context is available. Return true if @query has been handled.
898 */
899 static coroutine_fn bool
900 nbd_meta_base_query(NBDClient *client, NBDMetaContexts *meta,
901 const char *query)
902 {
903 if (!nbd_strshift(&query, "base:")) {
904 return false;
905 }
906 trace_nbd_negotiate_meta_query_parse("base:");
907
908 if (nbd_meta_empty_or_pattern(client, "allocation", query)) {
909 meta->base_allocation = true;
910 }
911 return true;
912 }
913
914 /* nbd_meta_qemu_query
915 *
916 * Handle queries to 'qemu' namespace. For now, only the qemu:dirty-bitmap:
917 * and qemu:allocation-depth contexts are available. Return true if @query
918 * has been handled.
919 */
920 static coroutine_fn bool
921 nbd_meta_qemu_query(NBDClient *client, NBDMetaContexts *meta,
922 const char *query)
923 {
924 size_t i;
925
926 if (!nbd_strshift(&query, "qemu:")) {
927 return false;
928 }
929 trace_nbd_negotiate_meta_query_parse("qemu:");
930
931 if (!*query) {
932 if (client->opt == NBD_OPT_LIST_META_CONTEXT) {
933 meta->allocation_depth = meta->exp->allocation_depth;
934 if (meta->exp->nr_export_bitmaps) {
935 memset(meta->bitmaps, 1, meta->exp->nr_export_bitmaps);
936 }
937 }
938 trace_nbd_negotiate_meta_query_parse("empty");
939 return true;
940 }
941
942 if (strcmp(query, "allocation-depth") == 0) {
943 trace_nbd_negotiate_meta_query_parse("allocation-depth");
944 meta->allocation_depth = meta->exp->allocation_depth;
945 return true;
946 }
947
948 if (nbd_strshift(&query, "dirty-bitmap:")) {
949 trace_nbd_negotiate_meta_query_parse("dirty-bitmap:");
950 if (!*query) {
951 if (client->opt == NBD_OPT_LIST_META_CONTEXT &&
952 meta->exp->nr_export_bitmaps) {
953 memset(meta->bitmaps, 1, meta->exp->nr_export_bitmaps);
954 }
955 trace_nbd_negotiate_meta_query_parse("empty");
956 return true;
957 }
958
959 for (i = 0; i < meta->exp->nr_export_bitmaps; i++) {
960 const char *bm_name;
961
962 bm_name = bdrv_dirty_bitmap_name(meta->exp->export_bitmaps[i]);
963 if (strcmp(bm_name, query) == 0) {
964 meta->bitmaps[i] = true;
965 trace_nbd_negotiate_meta_query_parse(query);
966 return true;
967 }
968 }
969 trace_nbd_negotiate_meta_query_skip("no dirty-bitmap match");
970 return true;
971 }
972
973 trace_nbd_negotiate_meta_query_skip("unknown qemu context");
974 return true;
975 }
976
977 /* nbd_negotiate_meta_query
978 *
979 * Parse namespace name and call corresponding function to parse body of the
980 * query.
981 *
982 * The only supported namespaces are 'base' and 'qemu'.
983 *
984 * Return -errno on I/O error, 0 if option was completely handled by
985 * sending a reply about inconsistent lengths, or 1 on success. */
986 static coroutine_fn int
987 nbd_negotiate_meta_query(NBDClient *client,
988 NBDMetaContexts *meta, Error **errp)
989 {
990 int ret;
991 g_autofree char *query = NULL;
992 uint32_t len;
993
994 ret = nbd_opt_read(client, &len, sizeof(len), false, errp);
995 if (ret <= 0) {
996 return ret;
997 }
998 len = cpu_to_be32(len);
999
1000 if (len > NBD_MAX_STRING_SIZE) {
1001 trace_nbd_negotiate_meta_query_skip("length too long");
1002 return nbd_opt_skip(client, len, errp);
1003 }
1004
1005 query = g_malloc(len + 1);
1006 ret = nbd_opt_read(client, query, len, true, errp);
1007 if (ret <= 0) {
1008 return ret;
1009 }
1010 query[len] = '\0';
1011
1012 if (nbd_meta_base_query(client, meta, query)) {
1013 return 1;
1014 }
1015 if (nbd_meta_qemu_query(client, meta, query)) {
1016 return 1;
1017 }
1018
1019 trace_nbd_negotiate_meta_query_skip("unknown namespace");
1020 return 1;
1021 }
1022
1023 /* nbd_negotiate_meta_queries
1024 * Handle NBD_OPT_LIST_META_CONTEXT and NBD_OPT_SET_META_CONTEXT
1025 *
1026 * Return -errno on I/O error, or 0 if option was completely handled. */
1027 static coroutine_fn int
1028 nbd_negotiate_meta_queries(NBDClient *client, Error **errp)
1029 {
1030 int ret;
1031 g_autofree char *export_name = NULL;
1032 /* Mark unused to work around https://bugs.llvm.org/show_bug.cgi?id=3888 */
1033 g_autofree G_GNUC_UNUSED bool *bitmaps = NULL;
1034 NBDMetaContexts local_meta = {0};
1035 NBDMetaContexts *meta;
1036 uint32_t nb_queries;
1037 size_t i;
1038 size_t count = 0;
1039
1040 if (client->opt == NBD_OPT_SET_META_CONTEXT &&
1041 client->mode < NBD_MODE_STRUCTURED) {
1042 return nbd_opt_invalid(client, errp,
1043 "request option '%s' when structured reply "
1044 "is not negotiated",
1045 nbd_opt_lookup(client->opt));
1046 }
1047
1048 if (client->opt == NBD_OPT_LIST_META_CONTEXT) {
1049 /* Only change the caller's meta on SET. */
1050 meta = &local_meta;
1051 } else {
1052 meta = &client->contexts;
1053 }
1054
1055 g_free(meta->bitmaps);
1056 memset(meta, 0, sizeof(*meta));
1057
1058 ret = nbd_opt_read_name(client, &export_name, NULL, errp);
1059 if (ret <= 0) {
1060 return ret;
1061 }
1062
1063 meta->exp = nbd_export_find(export_name);
1064 if (meta->exp == NULL) {
1065 g_autofree char *sane_name = nbd_sanitize_name(export_name);
1066
1067 return nbd_opt_drop(client, NBD_REP_ERR_UNKNOWN, errp,
1068 "export '%s' not present", sane_name);
1069 }
1070 meta->bitmaps = g_new0(bool, meta->exp->nr_export_bitmaps);
1071 if (client->opt == NBD_OPT_LIST_META_CONTEXT) {
1072 bitmaps = meta->bitmaps;
1073 }
1074
1075 ret = nbd_opt_read(client, &nb_queries, sizeof(nb_queries), false, errp);
1076 if (ret <= 0) {
1077 return ret;
1078 }
1079 nb_queries = cpu_to_be32(nb_queries);
1080 trace_nbd_negotiate_meta_context(nbd_opt_lookup(client->opt),
1081 export_name, nb_queries);
1082
1083 if (client->opt == NBD_OPT_LIST_META_CONTEXT && !nb_queries) {
1084 /* enable all known contexts */
1085 meta->base_allocation = true;
1086 meta->allocation_depth = meta->exp->allocation_depth;
1087 if (meta->exp->nr_export_bitmaps) {
1088 memset(meta->bitmaps, 1, meta->exp->nr_export_bitmaps);
1089 }
1090 } else {
1091 for (i = 0; i < nb_queries; ++i) {
1092 ret = nbd_negotiate_meta_query(client, meta, errp);
1093 if (ret <= 0) {
1094 return ret;
1095 }
1096 }
1097 }
1098
1099 if (meta->base_allocation) {
1100 ret = nbd_negotiate_send_meta_context(client, "base:allocation",
1101 NBD_META_ID_BASE_ALLOCATION,
1102 errp);
1103 if (ret < 0) {
1104 return ret;
1105 }
1106 count++;
1107 }
1108
1109 if (meta->allocation_depth) {
1110 ret = nbd_negotiate_send_meta_context(client, "qemu:allocation-depth",
1111 NBD_META_ID_ALLOCATION_DEPTH,
1112 errp);
1113 if (ret < 0) {
1114 return ret;
1115 }
1116 count++;
1117 }
1118
1119 for (i = 0; i < meta->exp->nr_export_bitmaps; i++) {
1120 const char *bm_name;
1121 g_autofree char *context = NULL;
1122
1123 if (!meta->bitmaps[i]) {
1124 continue;
1125 }
1126
1127 bm_name = bdrv_dirty_bitmap_name(meta->exp->export_bitmaps[i]);
1128 context = g_strdup_printf("qemu:dirty-bitmap:%s", bm_name);
1129
1130 ret = nbd_negotiate_send_meta_context(client, context,
1131 NBD_META_ID_DIRTY_BITMAP + i,
1132 errp);
1133 if (ret < 0) {
1134 return ret;
1135 }
1136 count++;
1137 }
1138
1139 ret = nbd_negotiate_send_rep(client, NBD_REP_ACK, errp);
1140 if (ret == 0) {
1141 meta->count = count;
1142 }
1143
1144 return ret;
1145 }
1146
1147 /* nbd_negotiate_options
1148 * Process all NBD_OPT_* client option commands, during fixed newstyle
1149 * negotiation.
1150 * Return:
1151 * -errno on error, errp is set
1152 * 0 on successful negotiation, errp is not set
1153 * 1 if client sent NBD_OPT_ABORT (i.e. on valid disconnect) or never
1154 * wrote anything (i.e. port probe); errp is not set
1155 */
1156 static coroutine_fn int
1157 nbd_negotiate_options(NBDClient *client, Error **errp)
1158 {
1159 uint32_t flags;
1160 bool fixedNewstyle = false;
1161 bool no_zeroes = false;
1162
1163 /* Client sends:
1164 [ 0 .. 3] client flags
1165
1166 Then we loop until NBD_OPT_EXPORT_NAME or NBD_OPT_GO:
1167 [ 0 .. 7] NBD_OPTS_MAGIC
1168 [ 8 .. 11] NBD option
1169 [12 .. 15] Data length
1170 ... Rest of request
1171
1172 [ 0 .. 7] NBD_OPTS_MAGIC
1173 [ 8 .. 11] Second NBD option
1174 [12 .. 15] Data length
1175 ... Rest of request
1176 */
1177
1178 /*
1179 * Intentionally ignore errors on this first read - we do not want
1180 * to be noisy about a mere port probe, but only for clients that
1181 * start talking the protocol and then quit abruptly.
1182 */
1183 if (nbd_read32(client->ioc, &flags, "flags", NULL) < 0) {
1184 return 1;
1185 }
1186 client->mode = NBD_MODE_EXPORT_NAME;
1187 trace_nbd_negotiate_options_flags(flags);
1188 if (flags & NBD_FLAG_C_FIXED_NEWSTYLE) {
1189 fixedNewstyle = true;
1190 flags &= ~NBD_FLAG_C_FIXED_NEWSTYLE;
1191 client->mode = NBD_MODE_SIMPLE;
1192 }
1193 if (flags & NBD_FLAG_C_NO_ZEROES) {
1194 no_zeroes = true;
1195 flags &= ~NBD_FLAG_C_NO_ZEROES;
1196 }
1197 if (flags != 0) {
1198 error_setg(errp, "Unknown client flags 0x%" PRIx32 " received", flags);
1199 return -EINVAL;
1200 }
1201
1202 while (1) {
1203 int ret;
1204 uint32_t option, length;
1205 uint64_t magic;
1206
1207 if (nbd_read64(client->ioc, &magic, "opts magic", errp) < 0) {
1208 return -EINVAL;
1209 }
1210 trace_nbd_negotiate_options_check_magic(magic);
1211 if (magic != NBD_OPTS_MAGIC) {
1212 error_setg(errp, "Bad magic received");
1213 return -EINVAL;
1214 }
1215
1216 if (nbd_read32(client->ioc, &option, "option", errp) < 0) {
1217 return -EINVAL;
1218 }
1219 client->opt = option;
1220
1221 if (nbd_read32(client->ioc, &length, "option length", errp) < 0) {
1222 return -EINVAL;
1223 }
1224 assert(!client->optlen);
1225 client->optlen = length;
1226
1227 if (length > NBD_MAX_BUFFER_SIZE) {
1228 error_setg(errp, "len (%" PRIu32 ") is larger than max len (%u)",
1229 length, NBD_MAX_BUFFER_SIZE);
1230 return -EINVAL;
1231 }
1232
1233 trace_nbd_negotiate_options_check_option(option,
1234 nbd_opt_lookup(option));
1235 if (client->tlscreds &&
1236 client->ioc == (QIOChannel *)client->sioc) {
1237 QIOChannel *tioc;
1238 if (!fixedNewstyle) {
1239 error_setg(errp, "Unsupported option 0x%" PRIx32, option);
1240 return -EINVAL;
1241 }
1242 switch (option) {
1243 case NBD_OPT_STARTTLS:
1244 if (length) {
1245 /* Unconditionally drop the connection if the client
1246 * can't start a TLS negotiation correctly */
1247 return nbd_reject_length(client, true, errp);
1248 }
1249 tioc = nbd_negotiate_handle_starttls(client, errp);
1250 if (!tioc) {
1251 return -EIO;
1252 }
1253 ret = 0;
1254 object_unref(OBJECT(client->ioc));
1255 client->ioc = tioc;
1256 break;
1257
1258 case NBD_OPT_EXPORT_NAME:
1259 /* No way to return an error to client, so drop connection */
1260 error_setg(errp, "Option 0x%x not permitted before TLS",
1261 option);
1262 return -EINVAL;
1263
1264 default:
1265 /* Let the client keep trying, unless they asked to
1266 * quit. Always try to give an error back to the
1267 * client; but when replying to OPT_ABORT, be aware
1268 * that the client may hang up before receiving the
1269 * error, in which case we are fine ignoring the
1270 * resulting EPIPE. */
1271 ret = nbd_opt_drop(client, NBD_REP_ERR_TLS_REQD,
1272 option == NBD_OPT_ABORT ? NULL : errp,
1273 "Option 0x%" PRIx32
1274 " not permitted before TLS", option);
1275 if (option == NBD_OPT_ABORT) {
1276 return 1;
1277 }
1278 break;
1279 }
1280 } else if (fixedNewstyle) {
1281 switch (option) {
1282 case NBD_OPT_LIST:
1283 if (length) {
1284 ret = nbd_reject_length(client, false, errp);
1285 } else {
1286 ret = nbd_negotiate_handle_list(client, errp);
1287 }
1288 break;
1289
1290 case NBD_OPT_ABORT:
1291 /* NBD spec says we must try to reply before
1292 * disconnecting, but that we must also tolerate
1293 * guests that don't wait for our reply. */
1294 nbd_negotiate_send_rep(client, NBD_REP_ACK, NULL);
1295 return 1;
1296
1297 case NBD_OPT_EXPORT_NAME:
1298 return nbd_negotiate_handle_export_name(client, no_zeroes,
1299 errp);
1300
1301 case NBD_OPT_INFO:
1302 case NBD_OPT_GO:
1303 ret = nbd_negotiate_handle_info(client, errp);
1304 if (ret == 1) {
1305 assert(option == NBD_OPT_GO);
1306 return 0;
1307 }
1308 break;
1309
1310 case NBD_OPT_STARTTLS:
1311 if (length) {
1312 ret = nbd_reject_length(client, false, errp);
1313 } else if (client->tlscreds) {
1314 ret = nbd_negotiate_send_rep_err(client,
1315 NBD_REP_ERR_INVALID, errp,
1316 "TLS already enabled");
1317 } else {
1318 ret = nbd_negotiate_send_rep_err(client,
1319 NBD_REP_ERR_POLICY, errp,
1320 "TLS not configured");
1321 }
1322 break;
1323
1324 case NBD_OPT_STRUCTURED_REPLY:
1325 if (length) {
1326 ret = nbd_reject_length(client, false, errp);
1327 } else if (client->mode >= NBD_MODE_EXTENDED) {
1328 ret = nbd_negotiate_send_rep_err(
1329 client, NBD_REP_ERR_EXT_HEADER_REQD, errp,
1330 "extended headers already negotiated");
1331 } else if (client->mode >= NBD_MODE_STRUCTURED) {
1332 ret = nbd_negotiate_send_rep_err(
1333 client, NBD_REP_ERR_INVALID, errp,
1334 "structured reply already negotiated");
1335 } else {
1336 ret = nbd_negotiate_send_rep(client, NBD_REP_ACK, errp);
1337 client->mode = NBD_MODE_STRUCTURED;
1338 }
1339 break;
1340
1341 case NBD_OPT_LIST_META_CONTEXT:
1342 case NBD_OPT_SET_META_CONTEXT:
1343 ret = nbd_negotiate_meta_queries(client, errp);
1344 break;
1345
1346 case NBD_OPT_EXTENDED_HEADERS:
1347 if (length) {
1348 ret = nbd_reject_length(client, false, errp);
1349 } else if (client->mode >= NBD_MODE_EXTENDED) {
1350 ret = nbd_negotiate_send_rep_err(
1351 client, NBD_REP_ERR_INVALID, errp,
1352 "extended headers already negotiated");
1353 } else {
1354 ret = nbd_negotiate_send_rep(client, NBD_REP_ACK, errp);
1355 client->mode = NBD_MODE_EXTENDED;
1356 }
1357 break;
1358
1359 default:
1360 ret = nbd_opt_drop(client, NBD_REP_ERR_UNSUP, errp,
1361 "Unsupported option %" PRIu32 " (%s)",
1362 option, nbd_opt_lookup(option));
1363 break;
1364 }
1365 } else {
1366 /*
1367 * If broken new-style we should drop the connection
1368 * for anything except NBD_OPT_EXPORT_NAME
1369 */
1370 switch (option) {
1371 case NBD_OPT_EXPORT_NAME:
1372 return nbd_negotiate_handle_export_name(client, no_zeroes,
1373 errp);
1374
1375 default:
1376 error_setg(errp, "Unsupported option %" PRIu32 " (%s)",
1377 option, nbd_opt_lookup(option));
1378 return -EINVAL;
1379 }
1380 }
1381 if (ret < 0) {
1382 return ret;
1383 }
1384 }
1385 }
1386
1387 /* nbd_negotiate
1388 * Return:
1389 * -errno on error, errp is set
1390 * 0 on successful negotiation, errp is not set
1391 * 1 if client sent NBD_OPT_ABORT (i.e. on valid disconnect) or never
1392 * wrote anything (i.e. port probe); errp is not set
1393 */
1394 static coroutine_fn int nbd_negotiate(NBDClient *client, Error **errp)
1395 {
1396 ERRP_GUARD();
1397 char buf[NBD_OLDSTYLE_NEGOTIATE_SIZE] = "";
1398 int ret;
1399
1400 /* Old style negotiation header, no room for options
1401 [ 0 .. 7] passwd ("NBDMAGIC")
1402 [ 8 .. 15] magic (NBD_CLIENT_MAGIC)
1403 [16 .. 23] size
1404 [24 .. 27] export flags (zero-extended)
1405 [28 .. 151] reserved (0)
1406
1407 New style negotiation header, client can send options
1408 [ 0 .. 7] passwd ("NBDMAGIC")
1409 [ 8 .. 15] magic (NBD_OPTS_MAGIC)
1410 [16 .. 17] server flags (0)
1411 ....options sent, ending in NBD_OPT_EXPORT_NAME or NBD_OPT_GO....
1412 */
1413
1414 if (!qio_channel_set_blocking(client->ioc, false, errp)) {
1415 return -EINVAL;
1416 }
1417 qio_channel_set_follow_coroutine_ctx(client->ioc, true);
1418
1419 trace_nbd_negotiate_begin();
1420 memcpy(buf, "NBDMAGIC", 8);
1421
1422 stq_be_p(buf + 8, NBD_OPTS_MAGIC);
1423 stw_be_p(buf + 16, NBD_FLAG_FIXED_NEWSTYLE | NBD_FLAG_NO_ZEROES);
1424
1425 /*
1426 * Be silent about failure to write our greeting: there is nothing
1427 * wrong with a client testing if our port is alive.
1428 */
1429 if (nbd_write(client->ioc, buf, 18, NULL) < 0) {
1430 return 1;
1431 }
1432 ret = nbd_negotiate_options(client, errp);
1433 if (ret != 0) {
1434 if (ret < 0) {
1435 error_prepend(errp, "option negotiation failed: ");
1436 }
1437 return ret;
1438 }
1439
1440 assert(!client->optlen);
1441 trace_nbd_negotiate_success();
1442
1443 return 0;
1444 }
1445
1446 /* nbd_read_eof
1447 * Tries to read @size bytes from @ioc. This is a local implementation of
1448 * qio_channel_readv_all_eof. We have it here because we need it to be
1449 * interruptible and to know when the coroutine is yielding.
1450 * Returns 1 on success
1451 * 0 on eof, when no data was read (errp is not set)
1452 * negative errno on failure (errp is set)
1453 */
1454 static inline int coroutine_fn
1455 nbd_read_eof(NBDClient *client, void *buffer, size_t size, Error **errp)
1456 {
1457 bool partial = false;
1458
1459 assert(size);
1460 while (size > 0) {
1461 struct iovec iov = { .iov_base = buffer, .iov_len = size };
1462 ssize_t len;
1463
1464 len = qio_channel_readv(client->ioc, &iov, 1, errp);
1465 if (len == QIO_CHANNEL_ERR_BLOCK) {
1466 WITH_QEMU_LOCK_GUARD(&client->lock) {
1467 client->read_yielding = true;
1468
1469 /* Prompt main loop thread to re-run nbd_drained_poll() */
1470 aio_wait_kick();
1471 }
1472 qio_channel_yield(client->ioc, G_IO_IN);
1473 WITH_QEMU_LOCK_GUARD(&client->lock) {
1474 client->read_yielding = false;
1475 if (client->quiescing) {
1476 return -EAGAIN;
1477 }
1478 }
1479 continue;
1480 } else if (len < 0) {
1481 return -EIO;
1482 } else if (len == 0) {
1483 if (partial) {
1484 error_setg(errp,
1485 "Unexpected end-of-file before all bytes were read");
1486 return -EIO;
1487 } else {
1488 return 0;
1489 }
1490 }
1491
1492 partial = true;
1493 size -= len;
1494 buffer = (uint8_t *) buffer + len;
1495 }
1496 return 1;
1497 }
1498
1499 static int coroutine_fn nbd_receive_request(NBDClient *client, NBDRequest *request,
1500 Error **errp)
1501 {
1502 uint8_t buf[NBD_EXTENDED_REQUEST_SIZE];
1503 uint32_t magic, expect;
1504 int ret;
1505 size_t size = client->mode >= NBD_MODE_EXTENDED ?
1506 NBD_EXTENDED_REQUEST_SIZE : NBD_REQUEST_SIZE;
1507
1508 ret = nbd_read_eof(client, buf, size, errp);
1509 if (ret < 0) {
1510 return ret;
1511 }
1512 if (ret == 0) {
1513 return -EIO;
1514 }
1515
1516 /*
1517 * Compact request
1518 * [ 0 .. 3] magic (NBD_REQUEST_MAGIC)
1519 * [ 4 .. 5] flags (NBD_CMD_FLAG_FUA, ...)
1520 * [ 6 .. 7] type (NBD_CMD_READ, ...)
1521 * [ 8 .. 15] cookie
1522 * [16 .. 23] from
1523 * [24 .. 27] len
1524 * Extended request
1525 * [ 0 .. 3] magic (NBD_EXTENDED_REQUEST_MAGIC)
1526 * [ 4 .. 5] flags (NBD_CMD_FLAG_FUA, NBD_CMD_FLAG_PAYLOAD_LEN, ...)
1527 * [ 6 .. 7] type (NBD_CMD_READ, ...)
1528 * [ 8 .. 15] cookie
1529 * [16 .. 23] from
1530 * [24 .. 31] len
1531 */
1532
1533 magic = ldl_be_p(buf);
1534 request->flags = lduw_be_p(buf + 4);
1535 request->type = lduw_be_p(buf + 6);
1536 request->cookie = ldq_be_p(buf + 8);
1537 request->from = ldq_be_p(buf + 16);
1538 if (client->mode >= NBD_MODE_EXTENDED) {
1539 request->len = ldq_be_p(buf + 24);
1540 expect = NBD_EXTENDED_REQUEST_MAGIC;
1541 } else {
1542 request->len = (uint32_t)ldl_be_p(buf + 24); /* widen 32 to 64 bits */
1543 expect = NBD_REQUEST_MAGIC;
1544 }
1545
1546 trace_nbd_receive_request(magic, request->flags, request->type,
1547 request->from, request->len);
1548
1549 if (magic != expect) {
1550 error_setg(errp, "invalid magic (got 0x%" PRIx32 ", expected 0x%"
1551 PRIx32 ")", magic, expect);
1552 return -EINVAL;
1553 }
1554 return 0;
1555 }
1556
1557 #define MAX_NBD_REQUESTS 16
1558
1559 /* Runs in export AioContext and main loop thread */
1560 void nbd_client_get(NBDClient *client)
1561 {
1562 qatomic_inc(&client->refcount);
1563 }
1564
1565 void nbd_client_put(NBDClient *client)
1566 {
1567 assert(qemu_in_main_thread());
1568
1569 if (qatomic_fetch_dec(&client->refcount) == 1) {
1570 /* The last reference should be dropped by client->close,
1571 * which is called by client_close.
1572 */
1573 assert(client->closing);
1574
1575 object_unref(OBJECT(client->sioc));
1576 object_unref(OBJECT(client->ioc));
1577 if (client->tlscreds) {
1578 object_unref(OBJECT(client->tlscreds));
1579 }
1580 g_free(client->tlsauthz);
1581 if (client->exp) {
1582 QTAILQ_REMOVE(&client->exp->clients, client, next);
1583 blk_exp_unref(&client->exp->common);
1584 }
1585 g_free(client->contexts.bitmaps);
1586 qemu_mutex_destroy(&client->lock);
1587 g_free(client);
1588 }
1589 }
1590
1591 /*
1592 * Tries to release the reference to @client, but only if other references
1593 * remain. This is an optimization for the common case where we want to avoid
1594 * the expense of scheduling nbd_client_put() in the main loop thread.
1595 *
1596 * Returns true upon success or false if the reference was not released because
1597 * it is the last reference.
1598 */
1599 static bool nbd_client_put_nonzero(NBDClient *client)
1600 {
1601 int old = qatomic_read(&client->refcount);
1602 int expected;
1603
1604 do {
1605 if (old == 1) {
1606 return false;
1607 }
1608
1609 expected = old;
1610 old = qatomic_cmpxchg(&client->refcount, expected, expected - 1);
1611 } while (old != expected);
1612
1613 return true;
1614 }
1615
1616 static void client_close(NBDClient *client, bool negotiated)
1617 {
1618 assert(qemu_in_main_thread());
1619
1620 WITH_QEMU_LOCK_GUARD(&client->lock) {
1621 if (client->closing) {
1622 return;
1623 }
1624
1625 client->closing = true;
1626 }
1627
1628 /* Force requests to finish. They will drop their own references,
1629 * then we'll close the socket and free the NBDClient.
1630 */
1631 qio_channel_shutdown(client->ioc, QIO_CHANNEL_SHUTDOWN_BOTH,
1632 NULL);
1633
1634 /* Also tell the client, so that they release their reference. */
1635 if (client->close_fn) {
1636 client->close_fn(client, negotiated);
1637 }
1638 }
1639
1640 /* Runs in export AioContext with client->lock held */
1641 static NBDRequestData *nbd_request_get(NBDClient *client)
1642 {
1643 NBDRequestData *req;
1644
1645 assert(client->nb_requests <= MAX_NBD_REQUESTS - 1);
1646 client->nb_requests++;
1647
1648 req = g_new0(NBDRequestData, 1);
1649 req->client = client;
1650 return req;
1651 }
1652
1653 /* Runs in export AioContext with client->lock held */
1654 static void nbd_request_put(NBDRequestData *req)
1655 {
1656 NBDClient *client = req->client;
1657
1658 if (req->data) {
1659 qemu_vfree(req->data);
1660 }
1661 g_free(req);
1662
1663 client->nb_requests--;
1664
1665 if (client->quiescing && client->nb_requests == 0) {
1666 aio_wait_kick();
1667 }
1668
1669 nbd_client_receive_next_request(client);
1670 }
1671
1672 static void blk_aio_attached(AioContext *ctx, void *opaque)
1673 {
1674 NBDExport *exp = opaque;
1675 NBDClient *client;
1676
1677 assert(qemu_in_main_thread());
1678
1679 trace_nbd_blk_aio_attached(exp->name, ctx);
1680
1681 exp->common.ctx = ctx;
1682
1683 QTAILQ_FOREACH(client, &exp->clients, next) {
1684 WITH_QEMU_LOCK_GUARD(&client->lock) {
1685 assert(client->nb_requests == 0);
1686 assert(client->recv_coroutine == NULL);
1687 assert(client->send_coroutine == NULL);
1688 }
1689 }
1690 }
1691
1692 static void blk_aio_detach(void *opaque)
1693 {
1694 NBDExport *exp = opaque;
1695
1696 assert(qemu_in_main_thread());
1697
1698 trace_nbd_blk_aio_detach(exp->name, exp->common.ctx);
1699
1700 exp->common.ctx = NULL;
1701 }
1702
1703 static void nbd_drained_begin(void *opaque)
1704 {
1705 NBDExport *exp = opaque;
1706 NBDClient *client;
1707
1708 assert(qemu_in_main_thread());
1709
1710 QTAILQ_FOREACH(client, &exp->clients, next) {
1711 WITH_QEMU_LOCK_GUARD(&client->lock) {
1712 client->quiescing = true;
1713 }
1714 }
1715 }
1716
1717 static void nbd_drained_end(void *opaque)
1718 {
1719 NBDExport *exp = opaque;
1720 NBDClient *client;
1721
1722 assert(qemu_in_main_thread());
1723
1724 QTAILQ_FOREACH(client, &exp->clients, next) {
1725 WITH_QEMU_LOCK_GUARD(&client->lock) {
1726 client->quiescing = false;
1727 nbd_client_receive_next_request(client);
1728 }
1729 }
1730 }
1731
1732 /* Runs in export AioContext */
1733 static void nbd_wake_read_bh(void *opaque)
1734 {
1735 NBDClient *client = opaque;
1736 qio_channel_wake_read(client->ioc);
1737 }
1738
1739 static bool nbd_drained_poll(void *opaque)
1740 {
1741 NBDExport *exp = opaque;
1742 NBDClient *client;
1743
1744 assert(qemu_in_main_thread());
1745
1746 QTAILQ_FOREACH(client, &exp->clients, next) {
1747 WITH_QEMU_LOCK_GUARD(&client->lock) {
1748 if (client->nb_requests != 0) {
1749 /*
1750 * If there's a coroutine waiting for a request on nbd_read_eof()
1751 * enter it here so we don't depend on the client to wake it up.
1752 *
1753 * Schedule a BH in the export AioContext to avoid missing the
1754 * wake up due to the race between qio_channel_wake_read() and
1755 * qio_channel_yield().
1756 */
1757 if (client->recv_coroutine != NULL && client->read_yielding) {
1758 aio_bh_schedule_oneshot(nbd_export_aio_context(client->exp),
1759 nbd_wake_read_bh, client);
1760 }
1761
1762 return true;
1763 }
1764 }
1765 }
1766
1767 return false;
1768 }
1769
1770 static void nbd_eject_notifier(Notifier *n, void *data)
1771 {
1772 NBDExport *exp = container_of(n, NBDExport, eject_notifier);
1773
1774 assert(qemu_in_main_thread());
1775
1776 blk_exp_request_shutdown(&exp->common);
1777 }
1778
1779 void nbd_export_set_on_eject_blk(BlockExport *exp, BlockBackend *blk)
1780 {
1781 NBDExport *nbd_exp = container_of(exp, NBDExport, common);
1782 assert(exp->drv == &blk_exp_nbd);
1783 assert(nbd_exp->eject_notifier_blk == NULL);
1784
1785 blk_ref(blk);
1786 nbd_exp->eject_notifier_blk = blk;
1787 nbd_exp->eject_notifier.notify = nbd_eject_notifier;
1788 blk_add_remove_bs_notifier(blk, &nbd_exp->eject_notifier);
1789 }
1790
1791 static const BlockDevOps nbd_block_ops = {
1792 .drained_begin = nbd_drained_begin,
1793 .drained_end = nbd_drained_end,
1794 .drained_poll = nbd_drained_poll,
1795 };
1796
1797 static int nbd_export_create(BlockExport *blk_exp, BlockExportOptions *exp_args,
1798 AioContext *const *multithread, size_t mt_count,
1799 Error **errp)
1800 {
1801 NBDExport *exp = container_of(blk_exp, NBDExport, common);
1802 BlockExportOptionsNbd *arg = &exp_args->u.nbd;
1803 const char *name = arg->name ?: exp_args->node_name;
1804 BlockBackend *blk = blk_exp->blk;
1805 int64_t size;
1806 uint64_t perm, shared_perm;
1807 bool readonly = !exp_args->writable;
1808 BlockDirtyBitmapOrStrList *bitmaps;
1809 size_t i;
1810 int ret;
1811
1812 GLOBAL_STATE_CODE();
1813 assert(exp_args->type == BLOCK_EXPORT_TYPE_NBD);
1814
1815 if (!nbd_server_is_running()) {
1816 error_setg(errp, "NBD server not running");
1817 return -EINVAL;
1818 }
1819
1820 if (strlen(name) > NBD_MAX_STRING_SIZE) {
1821 error_setg(errp, "export name '%s' too long", name);
1822 return -EINVAL;
1823 }
1824
1825 if (arg->description && strlen(arg->description) > NBD_MAX_STRING_SIZE) {
1826 error_setg(errp, "description '%s' too long", arg->description);
1827 return -EINVAL;
1828 }
1829
1830 if (nbd_export_find(name)) {
1831 error_setg(errp, "NBD server already has export named '%s'", name);
1832 return -EEXIST;
1833 }
1834
1835 if (multithread) {
1836 error_setg(errp, "NBD export does not support multi-threading");
1837 return -EINVAL;
1838 }
1839
1840 size = blk_getlength(blk);
1841 if (size < 0) {
1842 error_setg_errno(errp, -size,
1843 "Failed to determine the NBD export's length");
1844 return size;
1845 }
1846
1847 /* Don't allow resize while the NBD server is running, otherwise we don't
1848 * care what happens with the node. */
1849 blk_get_perm(blk, &perm, &shared_perm);
1850 ret = blk_set_perm(blk, perm, shared_perm & ~BLK_PERM_RESIZE, errp);
1851 if (ret < 0) {
1852 return ret;
1853 }
1854
1855 QTAILQ_INIT(&exp->clients);
1856 exp->name = g_strdup(name);
1857 exp->description = g_strdup(arg->description);
1858 exp->nbdflags = (NBD_FLAG_HAS_FLAGS | NBD_FLAG_SEND_FLUSH |
1859 NBD_FLAG_SEND_FUA | NBD_FLAG_SEND_CACHE);
1860
1861 if (nbd_server_max_connections() != 1) {
1862 exp->nbdflags |= NBD_FLAG_CAN_MULTI_CONN;
1863 }
1864 if (readonly) {
1865 exp->nbdflags |= NBD_FLAG_READ_ONLY;
1866 } else {
1867 exp->nbdflags |= (NBD_FLAG_SEND_TRIM | NBD_FLAG_SEND_WRITE_ZEROES |
1868 NBD_FLAG_SEND_FAST_ZERO);
1869 }
1870 exp->size = QEMU_ALIGN_DOWN(size, BDRV_SECTOR_SIZE);
1871
1872 bdrv_graph_rdlock_main_loop();
1873
1874 for (bitmaps = arg->bitmaps; bitmaps; bitmaps = bitmaps->next) {
1875 exp->nr_export_bitmaps++;
1876 }
1877 exp->export_bitmaps = g_new0(BdrvDirtyBitmap *, exp->nr_export_bitmaps);
1878 for (i = 0, bitmaps = arg->bitmaps; bitmaps;
1879 i++, bitmaps = bitmaps->next)
1880 {
1881 const char *bitmap;
1882 BlockDriverState *bs = blk_bs(blk);
1883 BdrvDirtyBitmap *bm = NULL;
1884
1885 switch (bitmaps->value->type) {
1886 case QTYPE_QSTRING:
1887 bitmap = bitmaps->value->u.local;
1888 while (bs) {
1889 bm = bdrv_find_dirty_bitmap(bs, bitmap);
1890 if (bm != NULL) {
1891 break;
1892 }
1893
1894 bs = bdrv_filter_or_cow_bs(bs);
1895 }
1896
1897 if (bm == NULL) {
1898 ret = -ENOENT;
1899 error_setg(errp, "Bitmap '%s' is not found",
1900 bitmaps->value->u.local);
1901 goto fail;
1902 }
1903
1904 if (readonly && bdrv_is_writable(bs) &&
1905 bdrv_dirty_bitmap_enabled(bm)) {
1906 ret = -EINVAL;
1907 error_setg(errp, "Enabled bitmap '%s' incompatible with "
1908 "readonly export", bitmap);
1909 goto fail;
1910 }
1911 break;
1912 case QTYPE_QDICT:
1913 bitmap = bitmaps->value->u.external.name;
1914 bm = block_dirty_bitmap_lookup(bitmaps->value->u.external.node,
1915 bitmap, NULL, errp);
1916 if (!bm) {
1917 ret = -ENOENT;
1918 goto fail;
1919 }
1920 break;
1921 default:
1922 abort();
1923 }
1924
1925 assert(bm);
1926
1927 if (bdrv_dirty_bitmap_check(bm, BDRV_BITMAP_ALLOW_RO, errp)) {
1928 ret = -EINVAL;
1929 goto fail;
1930 }
1931
1932 exp->export_bitmaps[i] = bm;
1933 assert(strlen(bitmap) <= BDRV_BITMAP_MAX_NAME_SIZE);
1934 }
1935
1936 /* Mark bitmaps busy in a separate loop, to simplify roll-back concerns. */
1937 for (i = 0; i < exp->nr_export_bitmaps; i++) {
1938 bdrv_dirty_bitmap_set_busy(exp->export_bitmaps[i], true);
1939 }
1940
1941 exp->allocation_depth = arg->allocation_depth;
1942
1943 /*
1944 * We need to inhibit request queuing in the block layer to ensure we can
1945 * be properly quiesced when entering a drained section, as our coroutines
1946 * servicing pending requests might enter blk_pread().
1947 */
1948 blk_set_disable_request_queuing(blk, true);
1949
1950 blk_add_aio_context_notifier(blk, blk_aio_attached, blk_aio_detach, exp);
1951
1952 blk_set_dev_ops(blk, &nbd_block_ops, exp);
1953
1954 QTAILQ_INSERT_TAIL(&exports, exp, next);
1955
1956 bdrv_graph_rdunlock_main_loop();
1957
1958 return 0;
1959
1960 fail:
1961 bdrv_graph_rdunlock_main_loop();
1962 g_free(exp->export_bitmaps);
1963 g_free(exp->name);
1964 g_free(exp->description);
1965 return ret;
1966 }
1967
1968 NBDExport *nbd_export_find(const char *name)
1969 {
1970 NBDExport *exp;
1971 QTAILQ_FOREACH(exp, &exports, next) {
1972 if (strcmp(name, exp->name) == 0) {
1973 return exp;
1974 }
1975 }
1976
1977 return NULL;
1978 }
1979
1980 AioContext *
1981 nbd_export_aio_context(NBDExport *exp)
1982 {
1983 return exp->common.ctx;
1984 }
1985
1986 static void nbd_export_request_shutdown(BlockExport *blk_exp)
1987 {
1988 NBDExport *exp = container_of(blk_exp, NBDExport, common);
1989 NBDClient *client, *next;
1990
1991 blk_exp_ref(&exp->common);
1992 /*
1993 * TODO: Should we expand QMP BlockExportRemoveMode enum to allow a
1994 * close mode that stops advertising the export to new clients but
1995 * still permits existing clients to run to completion? Because of
1996 * that possibility, nbd_export_close() can be called more than
1997 * once on an export.
1998 */
1999 QTAILQ_FOREACH_SAFE(client, &exp->clients, next, next) {
2000 client_close(client, true);
2001 }
2002 if (exp->name) {
2003 g_free(exp->name);
2004 exp->name = NULL;
2005 QTAILQ_REMOVE(&exports, exp, next);
2006 }
2007 blk_exp_unref(&exp->common);
2008 }
2009
2010 static void nbd_export_delete(BlockExport *blk_exp)
2011 {
2012 size_t i;
2013 NBDExport *exp = container_of(blk_exp, NBDExport, common);
2014
2015 assert(exp->name == NULL);
2016 assert(QTAILQ_EMPTY(&exp->clients));
2017
2018 g_free(exp->description);
2019 exp->description = NULL;
2020
2021 if (exp->eject_notifier_blk) {
2022 notifier_remove(&exp->eject_notifier);
2023 blk_unref(exp->eject_notifier_blk);
2024 }
2025 blk_remove_aio_context_notifier(exp->common.blk, blk_aio_attached,
2026 blk_aio_detach, exp);
2027 blk_set_disable_request_queuing(exp->common.blk, false);
2028
2029 for (i = 0; i < exp->nr_export_bitmaps; i++) {
2030 bdrv_dirty_bitmap_set_busy(exp->export_bitmaps[i], false);
2031 }
2032 }
2033
2034 const BlockExportDriver blk_exp_nbd = {
2035 .type = BLOCK_EXPORT_TYPE_NBD,
2036 .instance_size = sizeof(NBDExport),
2037 .supports_inactive = true,
2038 .create = nbd_export_create,
2039 .delete = nbd_export_delete,
2040 .request_shutdown = nbd_export_request_shutdown,
2041 };
2042
2043 static int coroutine_fn nbd_co_send_iov(NBDClient *client, struct iovec *iov,
2044 unsigned niov, Error **errp)
2045 {
2046 int ret;
2047
2048 g_assert(qemu_in_coroutine());
2049 qemu_co_mutex_lock(&client->send_lock);
2050 client->send_coroutine = qemu_coroutine_self();
2051
2052 ret = qio_channel_writev_all(client->ioc, iov, niov, errp) < 0 ? -EIO : 0;
2053
2054 client->send_coroutine = NULL;
2055 qemu_co_mutex_unlock(&client->send_lock);
2056
2057 return ret;
2058 }
2059
2060 static inline void set_be_simple_reply(NBDSimpleReply *reply, uint64_t error,
2061 uint64_t cookie)
2062 {
2063 stl_be_p(&reply->magic, NBD_SIMPLE_REPLY_MAGIC);
2064 stl_be_p(&reply->error, error);
2065 stq_be_p(&reply->cookie, cookie);
2066 }
2067
2068 static int coroutine_fn nbd_co_send_simple_reply(NBDClient *client,
2069 NBDRequest *request,
2070 uint32_t error,
2071 void *data,
2072 uint64_t len,
2073 Error **errp)
2074 {
2075 NBDSimpleReply reply;
2076 int nbd_err = system_errno_to_nbd_errno(error);
2077 struct iovec iov[] = {
2078 {.iov_base = &reply, .iov_len = sizeof(reply)},
2079 {.iov_base = data, .iov_len = len}
2080 };
2081
2082 assert(!len || !nbd_err);
2083 assert(len <= NBD_MAX_BUFFER_SIZE);
2084 assert(client->mode < NBD_MODE_STRUCTURED ||
2085 (client->mode == NBD_MODE_STRUCTURED &&
2086 request->type != NBD_CMD_READ));
2087 trace_nbd_co_send_simple_reply(request->cookie, nbd_err,
2088 nbd_err_lookup(nbd_err), len);
2089 set_be_simple_reply(&reply, nbd_err, request->cookie);
2090
2091 return nbd_co_send_iov(client, iov, 2, errp);
2092 }
2093
2094 /*
2095 * Prepare the header of a reply chunk for network transmission.
2096 *
2097 * On input, @iov is partially initialized: iov[0].iov_base must point
2098 * to an uninitialized NBDReply, while the remaining @niov elements
2099 * (if any) must be ready for transmission. This function then
2100 * populates iov[0] for transmission.
2101 */
2102 static inline void set_be_chunk(NBDClient *client, struct iovec *iov,
2103 size_t niov, uint16_t flags, uint16_t type,
2104 NBDRequest *request)
2105 {
2106 size_t i, length = 0;
2107
2108 for (i = 1; i < niov; i++) {
2109 length += iov[i].iov_len;
2110 }
2111 assert(length <= NBD_MAX_BUFFER_SIZE + sizeof(NBDStructuredReadData));
2112
2113 if (client->mode >= NBD_MODE_EXTENDED) {
2114 NBDExtendedReplyChunk *chunk = iov->iov_base;
2115
2116 iov[0].iov_len = sizeof(*chunk);
2117 stl_be_p(&chunk->magic, NBD_EXTENDED_REPLY_MAGIC);
2118 stw_be_p(&chunk->flags, flags);
2119 stw_be_p(&chunk->type, type);
2120 stq_be_p(&chunk->cookie, request->cookie);
2121 stq_be_p(&chunk->offset, request->from);
2122 stq_be_p(&chunk->length, length);
2123 } else {
2124 NBDStructuredReplyChunk *chunk = iov->iov_base;
2125
2126 iov[0].iov_len = sizeof(*chunk);
2127 stl_be_p(&chunk->magic, NBD_STRUCTURED_REPLY_MAGIC);
2128 stw_be_p(&chunk->flags, flags);
2129 stw_be_p(&chunk->type, type);
2130 stq_be_p(&chunk->cookie, request->cookie);
2131 stl_be_p(&chunk->length, length);
2132 }
2133 }
2134
2135 static int coroutine_fn nbd_co_send_chunk_done(NBDClient *client,
2136 NBDRequest *request,
2137 Error **errp)
2138 {
2139 NBDReply hdr;
2140 struct iovec iov[] = {
2141 {.iov_base = &hdr},
2142 };
2143
2144 trace_nbd_co_send_chunk_done(request->cookie);
2145 set_be_chunk(client, iov, 1, NBD_REPLY_FLAG_DONE,
2146 NBD_REPLY_TYPE_NONE, request);
2147 return nbd_co_send_iov(client, iov, 1, errp);
2148 }
2149
2150 static int coroutine_fn nbd_co_send_chunk_read(NBDClient *client,
2151 NBDRequest *request,
2152 uint64_t offset,
2153 void *data,
2154 uint64_t size,
2155 bool final,
2156 Error **errp)
2157 {
2158 NBDReply hdr;
2159 NBDStructuredReadData chunk;
2160 struct iovec iov[] = {
2161 {.iov_base = &hdr},
2162 {.iov_base = &chunk, .iov_len = sizeof(chunk)},
2163 {.iov_base = data, .iov_len = size}
2164 };
2165
2166 assert(size && size <= NBD_MAX_BUFFER_SIZE);
2167 trace_nbd_co_send_chunk_read(request->cookie, offset, data, size);
2168 set_be_chunk(client, iov, 3, final ? NBD_REPLY_FLAG_DONE : 0,
2169 NBD_REPLY_TYPE_OFFSET_DATA, request);
2170 stq_be_p(&chunk.offset, offset);
2171
2172 return nbd_co_send_iov(client, iov, 3, errp);
2173 }
2174
2175 static int coroutine_fn nbd_co_send_chunk_error(NBDClient *client,
2176 NBDRequest *request,
2177 uint32_t error,
2178 const char *msg,
2179 Error **errp)
2180 {
2181 NBDReply hdr;
2182 NBDStructuredError chunk;
2183 int nbd_err = system_errno_to_nbd_errno(error);
2184 struct iovec iov[] = {
2185 {.iov_base = &hdr},
2186 {.iov_base = &chunk, .iov_len = sizeof(chunk)},
2187 {.iov_base = (char *)msg, .iov_len = msg ? strlen(msg) : 0},
2188 };
2189
2190 assert(nbd_err);
2191 trace_nbd_co_send_chunk_error(request->cookie, nbd_err,
2192 nbd_err_lookup(nbd_err), msg ? msg : "");
2193 set_be_chunk(client, iov, 3, NBD_REPLY_FLAG_DONE,
2194 NBD_REPLY_TYPE_ERROR, request);
2195 stl_be_p(&chunk.error, nbd_err);
2196 stw_be_p(&chunk.message_length, iov[2].iov_len);
2197
2198 return nbd_co_send_iov(client, iov, 3, errp);
2199 }
2200
2201 /* Do a sparse read and send the structured reply to the client.
2202 * Returns -errno if sending fails. blk_co_block_status_above() failure is
2203 * reported to the client, at which point this function succeeds.
2204 */
2205 static int coroutine_fn nbd_co_send_sparse_read(NBDClient *client,
2206 NBDRequest *request,
2207 uint64_t offset,
2208 uint8_t *data,
2209 uint64_t size,
2210 Error **errp)
2211 {
2212 int ret = 0;
2213 NBDExport *exp = client->exp;
2214 size_t progress = 0;
2215
2216 assert(size <= NBD_MAX_BUFFER_SIZE);
2217 while (progress < size) {
2218 int64_t pnum;
2219 int status = blk_co_block_status_above(exp->common.blk, NULL,
2220 offset + progress,
2221 size - progress, &pnum, NULL,
2222 NULL);
2223 bool final;
2224
2225 if (status < 0) {
2226 char *msg = g_strdup_printf("unable to check for holes: %s",
2227 strerror(-status));
2228
2229 ret = nbd_co_send_chunk_error(client, request, -status, msg, errp);
2230 g_free(msg);
2231 return ret;
2232 }
2233 assert(pnum && pnum <= size - progress);
2234 final = progress + pnum == size;
2235 if (status & BDRV_BLOCK_ZERO) {
2236 NBDReply hdr;
2237 NBDStructuredReadHole chunk;
2238 struct iovec iov[] = {
2239 {.iov_base = &hdr},
2240 {.iov_base = &chunk, .iov_len = sizeof(chunk)},
2241 };
2242
2243 trace_nbd_co_send_chunk_read_hole(request->cookie,
2244 offset + progress, pnum);
2245 set_be_chunk(client, iov, 2,
2246 final ? NBD_REPLY_FLAG_DONE : 0,
2247 NBD_REPLY_TYPE_OFFSET_HOLE, request);
2248 stq_be_p(&chunk.offset, offset + progress);
2249 stl_be_p(&chunk.length, pnum);
2250 ret = nbd_co_send_iov(client, iov, 2, errp);
2251 } else {
2252 ret = blk_co_pread(exp->common.blk, offset + progress, pnum,
2253 data + progress, 0);
2254 if (ret < 0) {
2255 error_setg_errno(errp, -ret, "reading from file failed");
2256 break;
2257 }
2258 ret = nbd_co_send_chunk_read(client, request, offset + progress,
2259 data + progress, pnum, final, errp);
2260 }
2261
2262 if (ret < 0) {
2263 break;
2264 }
2265 progress += pnum;
2266 }
2267 return ret;
2268 }
2269
2270 typedef struct NBDExtentArray {
2271 NBDExtent64 *extents;
2272 unsigned int nb_alloc;
2273 unsigned int count;
2274 uint64_t total_length;
2275 bool extended;
2276 bool can_add;
2277 bool converted_to_be;
2278 } NBDExtentArray;
2279
2280 static NBDExtentArray *nbd_extent_array_new(unsigned int nb_alloc,
2281 NBDMode mode)
2282 {
2283 NBDExtentArray *ea = g_new0(NBDExtentArray, 1);
2284
2285 assert(mode >= NBD_MODE_STRUCTURED);
2286 ea->nb_alloc = nb_alloc;
2287 ea->extents = g_new(NBDExtent64, nb_alloc);
2288 ea->extended = mode >= NBD_MODE_EXTENDED;
2289 ea->can_add = true;
2290
2291 return ea;
2292 }
2293
2294 static void nbd_extent_array_free(NBDExtentArray *ea)
2295 {
2296 g_free(ea->extents);
2297 g_free(ea);
2298 }
2299 G_DEFINE_AUTOPTR_CLEANUP_FUNC(NBDExtentArray, nbd_extent_array_free)
2300
2301 /* Further modifications of the array after conversion are abandoned */
2302 static void nbd_extent_array_convert_to_be(NBDExtentArray *ea)
2303 {
2304 int i;
2305
2306 assert(!ea->converted_to_be);
2307 assert(ea->extended);
2308 ea->can_add = false;
2309 ea->converted_to_be = true;
2310
2311 for (i = 0; i < ea->count; i++) {
2312 ea->extents[i].length = cpu_to_be64(ea->extents[i].length);
2313 ea->extents[i].flags = cpu_to_be64(ea->extents[i].flags);
2314 }
2315 }
2316
2317 /* Further modifications of the array after conversion are abandoned */
2318 static NBDExtent32 *nbd_extent_array_convert_to_narrow(NBDExtentArray *ea)
2319 {
2320 int i;
2321 NBDExtent32 *extents = g_new(NBDExtent32, ea->count);
2322
2323 assert(!ea->converted_to_be);
2324 assert(!ea->extended);
2325 ea->can_add = false;
2326 ea->converted_to_be = true;
2327
2328 for (i = 0; i < ea->count; i++) {
2329 assert((ea->extents[i].length | ea->extents[i].flags) <= UINT32_MAX);
2330 extents[i].length = cpu_to_be32(ea->extents[i].length);
2331 extents[i].flags = cpu_to_be32(ea->extents[i].flags);
2332 }
2333
2334 return extents;
2335 }
2336
2337 /*
2338 * Add extent to NBDExtentArray. If extent can't be added (no available space),
2339 * return -1.
2340 * For safety, when returning -1 for the first time, .can_add is set to false,
2341 * and further calls to nbd_extent_array_add() will crash.
2342 * (this avoids the situation where a caller ignores failure to add one extent,
2343 * where adding another extent that would squash into the last array entry
2344 * would result in an incorrect range reported to the client)
2345 */
2346 static int nbd_extent_array_add(NBDExtentArray *ea,
2347 uint64_t length, uint32_t flags)
2348 {
2349 assert(ea->can_add);
2350
2351 if (!length) {
2352 return 0;
2353 }
2354 if (!ea->extended) {
2355 assert(length <= UINT32_MAX);
2356 }
2357
2358 /* Extend previous extent if flags are the same */
2359 if (ea->count > 0 && flags == ea->extents[ea->count - 1].flags) {
2360 uint64_t sum = length + ea->extents[ea->count - 1].length;
2361
2362 /*
2363 * sum cannot overflow: the block layer bounds image size at
2364 * 2^63, and ea->extents[].length comes from the block layer.
2365 */
2366 assert(sum >= length);
2367 if (sum <= UINT32_MAX || ea->extended) {
2368 ea->extents[ea->count - 1].length = sum;
2369 ea->total_length += length;
2370 return 0;
2371 }
2372 }
2373
2374 if (ea->count >= ea->nb_alloc) {
2375 ea->can_add = false;
2376 return -1;
2377 }
2378
2379 ea->total_length += length;
2380 ea->extents[ea->count] = (NBDExtent64) {.length = length, .flags = flags};
2381 ea->count++;
2382
2383 return 0;
2384 }
2385
2386 static int coroutine_fn blockstatus_to_extents(BlockBackend *blk,
2387 uint64_t offset, uint64_t bytes,
2388 NBDExtentArray *ea)
2389 {
2390 while (bytes) {
2391 uint32_t flags;
2392 int64_t num;
2393 int ret = blk_co_block_status_above(blk, NULL, offset, bytes, &num,
2394 NULL, NULL);
2395
2396 if (ret < 0) {
2397 return ret;
2398 }
2399
2400 flags = (ret & BDRV_BLOCK_DATA ? 0 : NBD_STATE_HOLE) |
2401 (ret & BDRV_BLOCK_ZERO ? NBD_STATE_ZERO : 0);
2402
2403 if (nbd_extent_array_add(ea, num, flags) < 0) {
2404 return 0;
2405 }
2406
2407 offset += num;
2408 bytes -= num;
2409 }
2410
2411 return 0;
2412 }
2413
2414 static int coroutine_fn blockalloc_to_extents(BlockBackend *blk,
2415 uint64_t offset, uint64_t bytes,
2416 NBDExtentArray *ea)
2417 {
2418 while (bytes) {
2419 int64_t num;
2420 int ret = blk_co_is_allocated_above(blk, NULL, false, offset, bytes,
2421 &num);
2422
2423 if (ret < 0) {
2424 return ret;
2425 }
2426
2427 if (nbd_extent_array_add(ea, num, ret) < 0) {
2428 return 0;
2429 }
2430
2431 offset += num;
2432 bytes -= num;
2433 }
2434
2435 return 0;
2436 }
2437
2438 /*
2439 * nbd_co_send_extents
2440 *
2441 * @ea is converted to BE by the function
2442 * @last controls whether NBD_REPLY_FLAG_DONE is sent.
2443 */
2444 static int coroutine_fn
2445 nbd_co_send_extents(NBDClient *client, NBDRequest *request, NBDExtentArray *ea,
2446 bool last, uint32_t context_id, Error **errp)
2447 {
2448 NBDReply hdr;
2449 NBDStructuredMeta meta;
2450 NBDExtendedMeta meta_ext;
2451 g_autofree NBDExtent32 *extents = NULL;
2452 uint16_t type;
2453 struct iovec iov[] = { {.iov_base = &hdr}, {0}, {0} };
2454
2455 if (client->mode >= NBD_MODE_EXTENDED) {
2456 type = NBD_REPLY_TYPE_BLOCK_STATUS_EXT;
2457
2458 iov[1].iov_base = &meta_ext;
2459 iov[1].iov_len = sizeof(meta_ext);
2460 stl_be_p(&meta_ext.context_id, context_id);
2461 stl_be_p(&meta_ext.count, ea->count);
2462
2463 nbd_extent_array_convert_to_be(ea);
2464 iov[2].iov_base = ea->extents;
2465 iov[2].iov_len = ea->count * sizeof(ea->extents[0]);
2466 } else {
2467 type = NBD_REPLY_TYPE_BLOCK_STATUS;
2468
2469 iov[1].iov_base = &meta;
2470 iov[1].iov_len = sizeof(meta);
2471 stl_be_p(&meta.context_id, context_id);
2472
2473 extents = nbd_extent_array_convert_to_narrow(ea);
2474 iov[2].iov_base = extents;
2475 iov[2].iov_len = ea->count * sizeof(extents[0]);
2476 }
2477
2478 trace_nbd_co_send_extents(request->cookie, ea->count, context_id,
2479 ea->total_length, last);
2480 set_be_chunk(client, iov, 3, last ? NBD_REPLY_FLAG_DONE : 0, type,
2481 request);
2482
2483 return nbd_co_send_iov(client, iov, 3, errp);
2484 }
2485
2486 /* Get block status from the exported device and send it to the client */
2487 static int
2488 coroutine_fn nbd_co_send_block_status(NBDClient *client, NBDRequest *request,
2489 BlockBackend *blk, uint64_t offset,
2490 uint64_t length, bool dont_fragment,
2491 bool last, uint32_t context_id,
2492 Error **errp)
2493 {
2494 int ret;
2495 unsigned int nb_extents = dont_fragment ? 1 : NBD_MAX_BLOCK_STATUS_EXTENTS;
2496 g_autoptr(NBDExtentArray) ea =
2497 nbd_extent_array_new(nb_extents, client->mode);
2498
2499 if (context_id == NBD_META_ID_BASE_ALLOCATION) {
2500 ret = blockstatus_to_extents(blk, offset, length, ea);
2501 } else {
2502 ret = blockalloc_to_extents(blk, offset, length, ea);
2503 }
2504 if (ret < 0) {
2505 return nbd_co_send_chunk_error(client, request, -ret,
2506 "can't get block status", errp);
2507 }
2508
2509 return nbd_co_send_extents(client, request, ea, last, context_id, errp);
2510 }
2511
2512 /* Populate @ea from a dirty bitmap. */
2513 static void bitmap_to_extents(BdrvDirtyBitmap *bitmap,
2514 uint64_t offset, uint64_t length,
2515 NBDExtentArray *es)
2516 {
2517 int64_t start, dirty_start, dirty_count;
2518 int64_t end = offset + length;
2519 bool full = false;
2520 int64_t bound = es->extended ? INT64_MAX : INT32_MAX;
2521
2522 bdrv_dirty_bitmap_lock(bitmap);
2523
2524 for (start = offset;
2525 bdrv_dirty_bitmap_next_dirty_area(bitmap, start, end, bound,
2526 &dirty_start, &dirty_count);
2527 start = dirty_start + dirty_count)
2528 {
2529 if ((nbd_extent_array_add(es, dirty_start - start, 0) < 0) ||
2530 (nbd_extent_array_add(es, dirty_count, NBD_STATE_DIRTY) < 0))
2531 {
2532 full = true;
2533 break;
2534 }
2535 }
2536
2537 if (!full) {
2538 /* last non dirty extent, nothing to do if array is now full */
2539 (void) nbd_extent_array_add(es, end - start, 0);
2540 }
2541
2542 bdrv_dirty_bitmap_unlock(bitmap);
2543 }
2544
2545 static int coroutine_fn nbd_co_send_bitmap(NBDClient *client,
2546 NBDRequest *request,
2547 BdrvDirtyBitmap *bitmap,
2548 uint64_t offset,
2549 uint64_t length, bool dont_fragment,
2550 bool last, uint32_t context_id,
2551 Error **errp)
2552 {
2553 unsigned int nb_extents = dont_fragment ? 1 : NBD_MAX_BLOCK_STATUS_EXTENTS;
2554 g_autoptr(NBDExtentArray) ea =
2555 nbd_extent_array_new(nb_extents, client->mode);
2556
2557 bitmap_to_extents(bitmap, offset, length, ea);
2558
2559 return nbd_co_send_extents(client, request, ea, last, context_id, errp);
2560 }
2561
2562 /*
2563 * nbd_co_block_status_payload_read
2564 * Called when a client wants a subset of negotiated contexts via a
2565 * BLOCK_STATUS payload. Check the payload for valid length and
2566 * contents. On success, return 0 with request updated to effective
2567 * length. If request was invalid but all payload consumed, return 0
2568 * with request->len and request->contexts->count set to 0 (which will
2569 * trigger an appropriate NBD_EINVAL response later on). Return
2570 * negative errno if the payload was not fully consumed.
2571 */
2572 static int
2573 nbd_co_block_status_payload_read(NBDClient *client, NBDRequest *request,
2574 Error **errp)
2575 {
2576 uint64_t payload_len = request->len;
2577 g_autofree char *buf = NULL;
2578 size_t count, i, nr_bitmaps;
2579 uint32_t id;
2580
2581 if (payload_len > NBD_MAX_BUFFER_SIZE) {
2582 error_setg(errp, "len (%" PRIu64 ") is larger than max len (%u)",
2583 request->len, NBD_MAX_BUFFER_SIZE);
2584 return -EINVAL;
2585 }
2586
2587 assert(client->contexts.exp == client->exp);
2588 nr_bitmaps = client->exp->nr_export_bitmaps;
2589 request->contexts = g_new0(NBDMetaContexts, 1);
2590 request->contexts->exp = client->exp;
2591
2592 if (payload_len % sizeof(uint32_t) ||
2593 payload_len < sizeof(NBDBlockStatusPayload) ||
2594 payload_len > (sizeof(NBDBlockStatusPayload) +
2595 sizeof(id) * client->contexts.count)) {
2596 goto skip;
2597 }
2598
2599 buf = g_malloc(payload_len);
2600 if (nbd_read(client->ioc, buf, payload_len,
2601 "CMD_BLOCK_STATUS data", errp) < 0) {
2602 return -EIO;
2603 }
2604 trace_nbd_co_receive_request_payload_received(request->cookie,
2605 payload_len);
2606 request->contexts->bitmaps = g_new0(bool, nr_bitmaps);
2607 count = (payload_len - sizeof(NBDBlockStatusPayload)) / sizeof(id);
2608 payload_len = 0;
2609
2610 for (i = 0; i < count; i++) {
2611 id = ldl_be_p(buf + sizeof(NBDBlockStatusPayload) + sizeof(id) * i);
2612 if (id == NBD_META_ID_BASE_ALLOCATION) {
2613 if (!client->contexts.base_allocation ||
2614 request->contexts->base_allocation) {
2615 goto skip;
2616 }
2617 request->contexts->base_allocation = true;
2618 } else if (id == NBD_META_ID_ALLOCATION_DEPTH) {
2619 if (!client->contexts.allocation_depth ||
2620 request->contexts->allocation_depth) {
2621 goto skip;
2622 }
2623 request->contexts->allocation_depth = true;
2624 } else {
2625 unsigned idx = id - NBD_META_ID_DIRTY_BITMAP;
2626
2627 if (idx >= nr_bitmaps || !client->contexts.bitmaps[idx] ||
2628 request->contexts->bitmaps[idx]) {
2629 goto skip;
2630 }
2631 request->contexts->bitmaps[idx] = true;
2632 }
2633 }
2634
2635 request->len = ldq_be_p(buf);
2636 request->contexts->count = count;
2637 return 0;
2638
2639 skip:
2640 trace_nbd_co_receive_block_status_payload_compliance(request->from,
2641 request->len);
2642 request->len = request->contexts->count = 0;
2643 return nbd_drop(client->ioc, payload_len, errp);
2644 }
2645
2646 /* nbd_co_receive_request
2647 * Collect a client request. Return 0 if request looks valid, -EIO to drop
2648 * connection right away, -EAGAIN to indicate we were interrupted and the
2649 * channel should be quiesced, and any other negative value to report an error
2650 * to the client (although the caller may still need to disconnect after
2651 * reporting the error).
2652 */
2653 static int coroutine_fn nbd_co_receive_request(NBDRequestData *req,
2654 NBDRequest *request,
2655 Error **errp)
2656 {
2657 NBDClient *client = req->client;
2658 bool extended_with_payload;
2659 bool check_length = false;
2660 bool check_rofs = false;
2661 bool allocate_buffer = false;
2662 bool payload_okay = false;
2663 uint64_t payload_len = 0;
2664 int valid_flags = NBD_CMD_FLAG_FUA;
2665 int ret;
2666
2667 g_assert(qemu_in_coroutine());
2668 ret = nbd_receive_request(client, request, errp);
2669 if (ret < 0) {
2670 return ret;
2671 }
2672
2673 trace_nbd_co_receive_request_decode_type(request->cookie, request->type,
2674 nbd_cmd_lookup(request->type));
2675 extended_with_payload = client->mode >= NBD_MODE_EXTENDED &&
2676 request->flags & NBD_CMD_FLAG_PAYLOAD_LEN;
2677 if (extended_with_payload) {
2678 payload_len = request->len;
2679 check_length = true;
2680 }
2681
2682 switch (request->type) {
2683 case NBD_CMD_DISC:
2684 /* Special case: we're going to disconnect without a reply,
2685 * whether or not flags, from, or len are bogus */
2686 req->complete = true;
2687 return -EIO;
2688
2689 case NBD_CMD_READ:
2690 if (client->mode >= NBD_MODE_STRUCTURED) {
2691 valid_flags |= NBD_CMD_FLAG_DF;
2692 }
2693 check_length = true;
2694 allocate_buffer = true;
2695 break;
2696
2697 case NBD_CMD_WRITE:
2698 if (client->mode >= NBD_MODE_EXTENDED) {
2699 if (!extended_with_payload) {
2700 /* The client is noncompliant. Trace it, but proceed. */
2701 trace_nbd_co_receive_ext_payload_compliance(request->from,
2702 request->len);
2703 }
2704 valid_flags |= NBD_CMD_FLAG_PAYLOAD_LEN;
2705 }
2706 payload_okay = true;
2707 payload_len = request->len;
2708 check_length = true;
2709 allocate_buffer = true;
2710 check_rofs = true;
2711 break;
2712
2713 case NBD_CMD_FLUSH:
2714 break;
2715
2716 case NBD_CMD_TRIM:
2717 check_rofs = true;
2718 break;
2719
2720 case NBD_CMD_CACHE:
2721 check_length = true;
2722 break;
2723
2724 case NBD_CMD_WRITE_ZEROES:
2725 valid_flags |= NBD_CMD_FLAG_NO_HOLE | NBD_CMD_FLAG_FAST_ZERO;
2726 check_rofs = true;
2727 break;
2728
2729 case NBD_CMD_BLOCK_STATUS:
2730 if (extended_with_payload) {
2731 ret = nbd_co_block_status_payload_read(client, request, errp);
2732 if (ret < 0) {
2733 return ret;
2734 }
2735 /* payload now consumed */
2736 check_length = false;
2737 payload_len = 0;
2738 valid_flags |= NBD_CMD_FLAG_PAYLOAD_LEN;
2739 } else {
2740 request->contexts = &client->contexts;
2741 }
2742 valid_flags |= NBD_CMD_FLAG_REQ_ONE;
2743 break;
2744
2745 default:
2746 /* Unrecognized, will fail later */
2747 ;
2748 }
2749
2750 /* Payload and buffer handling. */
2751 if (!payload_len) {
2752 req->complete = true;
2753 }
2754 if (check_length && request->len > NBD_MAX_BUFFER_SIZE) {
2755 /* READ, WRITE, CACHE */
2756 error_setg(errp, "len (%" PRIu64 ") is larger than max len (%u)",
2757 request->len, NBD_MAX_BUFFER_SIZE);
2758 return -EINVAL;
2759 }
2760 if (payload_len && !payload_okay) {
2761 /*
2762 * For now, we don't support payloads on other commands; but
2763 * we can keep the connection alive by ignoring the payload.
2764 * We will fail the command later with NBD_EINVAL for the use
2765 * of an unsupported flag (and not for access beyond bounds).
2766 */
2767 assert(request->type != NBD_CMD_WRITE);
2768 request->len = 0;
2769 }
2770 if (allocate_buffer) {
2771 /* READ, WRITE */
2772 req->data = blk_try_blockalign(client->exp->common.blk,
2773 request->len);
2774 if (req->data == NULL) {
2775 error_setg(errp, "No memory");
2776 return -ENOMEM;
2777 }
2778 }
2779 if (payload_len) {
2780 if (payload_okay) {
2781 /* WRITE */
2782 assert(req->data);
2783 ret = nbd_read(client->ioc, req->data, payload_len,
2784 "CMD_WRITE data", errp);
2785 } else {
2786 ret = nbd_drop(client->ioc, payload_len, errp);
2787 }
2788 if (ret < 0) {
2789 return -EIO;
2790 }
2791 req->complete = true;
2792 trace_nbd_co_receive_request_payload_received(request->cookie,
2793 payload_len);
2794 }
2795
2796 /* Sanity checks. */
2797 if (client->exp->nbdflags & NBD_FLAG_READ_ONLY && check_rofs) {
2798 /* WRITE, TRIM, WRITE_ZEROES */
2799 error_setg(errp, "Export is read-only");
2800 return -EROFS;
2801 }
2802 if (request->from > client->exp->size ||
2803 request->len > client->exp->size - request->from) {
2804 error_setg(errp, "operation past EOF; From: %" PRIu64 ", Len: %" PRIu64
2805 ", Size: %" PRIu64, request->from, request->len,
2806 client->exp->size);
2807 return (request->type == NBD_CMD_WRITE ||
2808 request->type == NBD_CMD_WRITE_ZEROES) ? -ENOSPC : -EINVAL;
2809 }
2810 if (client->check_align && !QEMU_IS_ALIGNED(request->from | request->len,
2811 client->check_align)) {
2812 /*
2813 * The block layer gracefully handles unaligned requests, but
2814 * it's still worth tracing client non-compliance
2815 */
2816 trace_nbd_co_receive_align_compliance(nbd_cmd_lookup(request->type),
2817 request->from,
2818 request->len,
2819 client->check_align);
2820 }
2821 if (request->flags & ~valid_flags) {
2822 error_setg(errp, "unsupported flags for command %s (got 0x%x)",
2823 nbd_cmd_lookup(request->type), request->flags);
2824 return -EINVAL;
2825 }
2826
2827 return 0;
2828 }
2829
2830 /* Send simple reply without a payload, or a structured error
2831 * @error_msg is ignored if @ret >= 0
2832 * Returns 0 if connection is still live, -errno on failure to talk to client
2833 */
2834 static coroutine_fn int nbd_send_generic_reply(NBDClient *client,
2835 NBDRequest *request,
2836 int ret,
2837 const char *error_msg,
2838 Error **errp)
2839 {
2840 if (client->mode >= NBD_MODE_STRUCTURED && ret < 0) {
2841 return nbd_co_send_chunk_error(client, request, -ret, error_msg, errp);
2842 } else if (client->mode >= NBD_MODE_EXTENDED) {
2843 return nbd_co_send_chunk_done(client, request, errp);
2844 } else {
2845 return nbd_co_send_simple_reply(client, request, ret < 0 ? -ret : 0,
2846 NULL, 0, errp);
2847 }
2848 }
2849
2850 /* Handle NBD_CMD_READ request.
2851 * Return -errno if sending fails. Other errors are reported directly to the
2852 * client as an error reply. */
2853 static coroutine_fn int nbd_do_cmd_read(NBDClient *client, NBDRequest *request,
2854 uint8_t *data, Error **errp)
2855 {
2856 int ret;
2857 NBDExport *exp = client->exp;
2858
2859 assert(request->type == NBD_CMD_READ);
2860 assert(request->len <= NBD_MAX_BUFFER_SIZE);
2861
2862 /* XXX: NBD Protocol only documents use of FUA with WRITE */
2863 if (request->flags & NBD_CMD_FLAG_FUA) {
2864 ret = blk_co_flush(exp->common.blk);
2865 if (ret < 0) {
2866 return nbd_send_generic_reply(client, request, ret,
2867 "flush failed", errp);
2868 }
2869 }
2870
2871 if (client->mode >= NBD_MODE_STRUCTURED &&
2872 !(request->flags & NBD_CMD_FLAG_DF) && request->len)
2873 {
2874 return nbd_co_send_sparse_read(client, request, request->from,
2875 data, request->len, errp);
2876 }
2877
2878 ret = blk_co_pread(exp->common.blk, request->from, request->len, data, 0);
2879 if (ret < 0) {
2880 return nbd_send_generic_reply(client, request, ret,
2881 "reading from file failed", errp);
2882 }
2883
2884 if (client->mode >= NBD_MODE_STRUCTURED) {
2885 if (request->len) {
2886 return nbd_co_send_chunk_read(client, request, request->from, data,
2887 request->len, true, errp);
2888 } else {
2889 return nbd_co_send_chunk_done(client, request, errp);
2890 }
2891 } else {
2892 return nbd_co_send_simple_reply(client, request, 0,
2893 data, request->len, errp);
2894 }
2895 }
2896
2897 /*
2898 * nbd_do_cmd_cache
2899 *
2900 * Handle NBD_CMD_CACHE request.
2901 * Return -errno if sending fails. Other errors are reported directly to the
2902 * client as an error reply.
2903 */
2904 static coroutine_fn int nbd_do_cmd_cache(NBDClient *client, NBDRequest *request,
2905 Error **errp)
2906 {
2907 int ret;
2908 NBDExport *exp = client->exp;
2909
2910 assert(request->type == NBD_CMD_CACHE);
2911 assert(request->len <= NBD_MAX_BUFFER_SIZE);
2912
2913 ret = blk_co_preadv(exp->common.blk, request->from, request->len,
2914 NULL, BDRV_REQ_COPY_ON_READ | BDRV_REQ_PREFETCH);
2915
2916 return nbd_send_generic_reply(client, request, ret,
2917 "caching data failed", errp);
2918 }
2919
2920 /* Handle NBD request.
2921 * Return -errno if sending fails. Other errors are reported directly to the
2922 * client as an error reply. */
2923 static coroutine_fn int nbd_handle_request(NBDClient *client,
2924 NBDRequest *request,
2925 uint8_t *data, Error **errp)
2926 {
2927 int ret;
2928 int flags;
2929 NBDExport *exp = client->exp;
2930 char *msg;
2931 size_t i;
2932 bool inactive;
2933
2934 WITH_GRAPH_RDLOCK_GUARD() {
2935 inactive = bdrv_is_inactive(blk_bs(exp->common.blk));
2936 if (inactive) {
2937 switch (request->type) {
2938 case NBD_CMD_READ:
2939 /* These commands are allowed on inactive nodes */
2940 break;
2941 default:
2942 /* Return an error for the rest */
2943 return nbd_send_generic_reply(client, request, -EPERM,
2944 "export is inactive", errp);
2945 }
2946 }
2947 }
2948
2949 switch (request->type) {
2950 case NBD_CMD_CACHE:
2951 return nbd_do_cmd_cache(client, request, errp);
2952
2953 case NBD_CMD_READ:
2954 return nbd_do_cmd_read(client, request, data, errp);
2955
2956 case NBD_CMD_WRITE:
2957 flags = 0;
2958 if (request->flags & NBD_CMD_FLAG_FUA) {
2959 flags |= BDRV_REQ_FUA;
2960 }
2961 assert(request->len <= NBD_MAX_BUFFER_SIZE);
2962 ret = blk_co_pwrite(exp->common.blk, request->from, request->len, data,
2963 flags);
2964 return nbd_send_generic_reply(client, request, ret,
2965 "writing to file failed", errp);
2966
2967 case NBD_CMD_WRITE_ZEROES:
2968 flags = 0;
2969 if (request->flags & NBD_CMD_FLAG_FUA) {
2970 flags |= BDRV_REQ_FUA;
2971 }
2972 if (!(request->flags & NBD_CMD_FLAG_NO_HOLE)) {
2973 flags |= BDRV_REQ_MAY_UNMAP;
2974 }
2975 if (request->flags & NBD_CMD_FLAG_FAST_ZERO) {
2976 flags |= BDRV_REQ_NO_FALLBACK;
2977 }
2978 ret = blk_co_pwrite_zeroes(exp->common.blk, request->from, request->len,
2979 flags);
2980 return nbd_send_generic_reply(client, request, ret,
2981 "writing to file failed", errp);
2982
2983 case NBD_CMD_DISC:
2984 /* unreachable, thanks to special case in nbd_co_receive_request() */
2985 abort();
2986
2987 case NBD_CMD_FLUSH:
2988 ret = blk_co_flush(exp->common.blk);
2989 return nbd_send_generic_reply(client, request, ret,
2990 "flush failed", errp);
2991
2992 case NBD_CMD_TRIM:
2993 ret = blk_co_pdiscard(exp->common.blk, request->from, request->len, 0);
2994 if (ret >= 0 && request->flags & NBD_CMD_FLAG_FUA) {
2995 ret = blk_co_flush(exp->common.blk);
2996 }
2997 return nbd_send_generic_reply(client, request, ret,
2998 "discard failed", errp);
2999
3000 case NBD_CMD_BLOCK_STATUS:
3001 assert(request->contexts);
3002 assert(client->mode >= NBD_MODE_EXTENDED ||
3003 request->len <= UINT32_MAX);
3004 if (request->contexts->count) {
3005 bool dont_fragment = request->flags & NBD_CMD_FLAG_REQ_ONE;
3006 int contexts_remaining = request->contexts->count;
3007
3008 if (!request->len) {
3009 return nbd_send_generic_reply(client, request, -EINVAL,
3010 "need non-zero length", errp);
3011 }
3012 if (request->contexts->base_allocation) {
3013 ret = nbd_co_send_block_status(client, request,
3014 exp->common.blk,
3015 request->from,
3016 request->len, dont_fragment,
3017 !--contexts_remaining,
3018 NBD_META_ID_BASE_ALLOCATION,
3019 errp);
3020 if (ret < 0) {
3021 return ret;
3022 }
3023 }
3024
3025 if (request->contexts->allocation_depth) {
3026 ret = nbd_co_send_block_status(client, request,
3027 exp->common.blk,
3028 request->from, request->len,
3029 dont_fragment,
3030 !--contexts_remaining,
3031 NBD_META_ID_ALLOCATION_DEPTH,
3032 errp);
3033 if (ret < 0) {
3034 return ret;
3035 }
3036 }
3037
3038 assert(request->contexts->exp == client->exp);
3039 for (i = 0; i < client->exp->nr_export_bitmaps; i++) {
3040 if (!request->contexts->bitmaps[i]) {
3041 continue;
3042 }
3043 ret = nbd_co_send_bitmap(client, request,
3044 client->exp->export_bitmaps[i],
3045 request->from, request->len,
3046 dont_fragment, !--contexts_remaining,
3047 NBD_META_ID_DIRTY_BITMAP + i, errp);
3048 if (ret < 0) {
3049 return ret;
3050 }
3051 }
3052
3053 assert(!contexts_remaining);
3054
3055 return 0;
3056 } else if (client->contexts.count) {
3057 return nbd_send_generic_reply(client, request, -EINVAL,
3058 "CMD_BLOCK_STATUS payload not valid",
3059 errp);
3060 } else {
3061 return nbd_send_generic_reply(client, request, -EINVAL,
3062 "CMD_BLOCK_STATUS not negotiated",
3063 errp);
3064 }
3065
3066 default:
3067 msg = g_strdup_printf("invalid request type (%" PRIu32 ") received",
3068 request->type);
3069 ret = nbd_send_generic_reply(client, request, -EINVAL, msg,
3070 errp);
3071 g_free(msg);
3072 return ret;
3073 }
3074 }
3075
3076 /* Owns a reference to the NBDClient passed as opaque. */
3077 static coroutine_fn void nbd_trip(void *opaque)
3078 {
3079 NBDRequestData *req = opaque;
3080 NBDClient *client = req->client;
3081 NBDRequest request = { 0 }; /* GCC thinks it can be used uninitialized */
3082 int ret;
3083 Error *local_err = NULL;
3084
3085 /*
3086 * Note that nbd_client_put() and client_close() must be called from the
3087 * main loop thread. Use aio_co_reschedule_self() to switch AioContext
3088 * before calling these functions.
3089 */
3090
3091 trace_nbd_trip();
3092
3093 qemu_mutex_lock(&client->lock);
3094
3095 if (client->closing) {
3096 goto done;
3097 }
3098
3099 if (client->quiescing) {
3100 /*
3101 * We're switching between AIO contexts. Don't attempt to receive a new
3102 * request and kick the main context which may be waiting for us.
3103 */
3104 client->recv_coroutine = NULL;
3105 aio_wait_kick();
3106 goto done;
3107 }
3108
3109 /*
3110 * nbd_co_receive_request() returns -EAGAIN when nbd_drained_begin() has
3111 * set client->quiescing but by the time we get back nbd_drained_end() may
3112 * have already cleared client->quiescing. In that case we try again
3113 * because nothing else will spawn an nbd_trip() coroutine until we set
3114 * client->recv_coroutine = NULL further down.
3115 */
3116 do {
3117 assert(client->recv_coroutine == qemu_coroutine_self());
3118 qemu_mutex_unlock(&client->lock);
3119 ret = nbd_co_receive_request(req, &request, &local_err);
3120 qemu_mutex_lock(&client->lock);
3121 } while (ret == -EAGAIN && !client->quiescing);
3122
3123 client->recv_coroutine = NULL;
3124
3125 if (client->closing) {
3126 /*
3127 * The client may be closed when we are blocked in
3128 * nbd_co_receive_request()
3129 */
3130 goto done;
3131 }
3132
3133 if (ret == -EAGAIN) {
3134 goto done;
3135 }
3136
3137 nbd_client_receive_next_request(client);
3138
3139 if (ret == -EIO) {
3140 goto disconnect;
3141 }
3142
3143 qemu_mutex_unlock(&client->lock);
3144 qio_channel_set_cork(client->ioc, true);
3145
3146 if (ret < 0) {
3147 /* It wasn't -EIO, so, according to nbd_co_receive_request()
3148 * semantics, we should return the error to the client. */
3149 Error *export_err = local_err;
3150
3151 local_err = NULL;
3152 ret = nbd_send_generic_reply(client, &request, -EINVAL,
3153 error_get_pretty(export_err), &local_err);
3154 error_free(export_err);
3155 } else {
3156 ret = nbd_handle_request(client, &request, req->data, &local_err);
3157 }
3158 if (request.contexts && request.contexts != &client->contexts) {
3159 assert(request.type == NBD_CMD_BLOCK_STATUS);
3160 g_free(request.contexts->bitmaps);
3161 g_free(request.contexts);
3162 }
3163
3164 qio_channel_set_cork(client->ioc, false);
3165 qemu_mutex_lock(&client->lock);
3166
3167 if (ret < 0) {
3168 error_prepend(&local_err, "Failed to send reply: ");
3169 goto disconnect;
3170 }
3171
3172 /*
3173 * We must disconnect after NBD_CMD_WRITE or BLOCK_STATUS with
3174 * payload if we did not read the payload.
3175 */
3176 if (!req->complete) {
3177 error_setg(&local_err, "Request handling failed in intermediate state");
3178 goto disconnect;
3179 }
3180
3181 done:
3182 nbd_request_put(req);
3183
3184 qemu_mutex_unlock(&client->lock);
3185
3186 if (!nbd_client_put_nonzero(client)) {
3187 aio_co_reschedule_self(qemu_get_aio_context());
3188 nbd_client_put(client);
3189 }
3190 return;
3191
3192 disconnect:
3193 if (local_err) {
3194 error_reportf_err(local_err, "Disconnect client, due to: ");
3195 }
3196
3197 nbd_request_put(req);
3198 qemu_mutex_unlock(&client->lock);
3199
3200 aio_co_reschedule_self(qemu_get_aio_context());
3201 client_close(client, true);
3202 nbd_client_put(client);
3203 }
3204
3205 /*
3206 * Runs in export AioContext and main loop thread. Caller must hold
3207 * client->lock.
3208 */
3209 static void nbd_client_receive_next_request(NBDClient *client)
3210 {
3211 NBDRequestData *req;
3212
3213 if (!client->recv_coroutine && client->nb_requests < MAX_NBD_REQUESTS &&
3214 !client->quiescing) {
3215 nbd_client_get(client);
3216 req = nbd_request_get(client);
3217 client->recv_coroutine = qemu_coroutine_create(nbd_trip, req);
3218 aio_co_schedule(client->exp->common.ctx, client->recv_coroutine);
3219 }
3220 }
3221
3222 static void nbd_handshake_timer_cb(void *opaque)
3223 {
3224 QIOChannel *ioc = opaque;
3225
3226 trace_nbd_handshake_timer_cb();
3227 qio_channel_shutdown(ioc, QIO_CHANNEL_SHUTDOWN_BOTH, NULL);
3228 }
3229
3230 static coroutine_fn void nbd_co_client_start(void *opaque)
3231 {
3232 NBDClient *client = opaque;
3233 Error *local_err = NULL;
3234 QEMUTimer *handshake_timer = NULL;
3235
3236 qemu_co_mutex_init(&client->send_lock);
3237
3238 /*
3239 * Create a timer to bound the time spent in negotiation. If the
3240 * timer expires, it is likely nbd_negotiate will fail because the
3241 * socket was shutdown.
3242 */
3243 if (client->handshake_max_secs > 0) {
3244 handshake_timer = aio_timer_new(qemu_get_aio_context(),
3245 QEMU_CLOCK_REALTIME,
3246 SCALE_NS,
3247 nbd_handshake_timer_cb,
3248 client->sioc);
3249 timer_mod(handshake_timer,
3250 qemu_clock_get_ns(QEMU_CLOCK_REALTIME) +
3251 client->handshake_max_secs * NANOSECONDS_PER_SECOND);
3252 }
3253
3254 if (nbd_negotiate(client, &local_err)) {
3255 if (local_err) {
3256 error_report_err(local_err);
3257 }
3258 timer_free(handshake_timer);
3259 client_close(client, false);
3260 return;
3261 }
3262
3263 timer_free(handshake_timer);
3264 WITH_QEMU_LOCK_GUARD(&client->lock) {
3265 nbd_client_receive_next_request(client);
3266 }
3267 }
3268
3269 /*
3270 * Create a new client listener using the given channel @sioc and @owner.
3271 * Begin servicing it in a coroutine. When the connection closes, call
3272 * @close_fn with an indication of whether the client completed negotiation
3273 * within @handshake_max_secs seconds (0 for unbounded).
3274 */
3275 void nbd_client_new(QIOChannelSocket *sioc,
3276 uint32_t handshake_max_secs,
3277 QCryptoTLSCreds *tlscreds,
3278 const char *tlsauthz,
3279 void (*close_fn)(NBDClient *, bool),
3280 void *owner)
3281 {
3282 NBDClient *client;
3283 Coroutine *co;
3284
3285 client = g_new0(NBDClient, 1);
3286 qemu_mutex_init(&client->lock);
3287 client->refcount = 1;
3288 client->tlscreds = tlscreds;
3289 if (tlscreds) {
3290 object_ref(OBJECT(client->tlscreds));
3291 }
3292 client->tlsauthz = g_strdup(tlsauthz);
3293 client->handshake_max_secs = handshake_max_secs;
3294 client->sioc = sioc;
3295 qio_channel_set_delay(QIO_CHANNEL(sioc), false);
3296 object_ref(OBJECT(client->sioc));
3297 client->ioc = QIO_CHANNEL(sioc);
3298 object_ref(OBJECT(client->ioc));
3299 client->close_fn = close_fn;
3300 client->owner = owner;
3301
3302 nbd_set_socket_send_buffer(sioc);
3303
3304 co = qemu_coroutine_create(nbd_co_client_start, client);
3305 qemu_coroutine_enter(co);
3306 }
3307
3308 void *
3309 nbd_client_owner(NBDClient *client)
3310 {
3311 return client->owner;
3312 }