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