1 /* 2 * Block driver for the QCOW version 2 format 3 * 4 * Copyright (c) 2004-2006 Fabrice Bellard 5 * 6 * Permission is hereby granted, free of charge, to any person obtaining a copy 7 * of this software and associated documentation files (the "Software"), to deal 8 * in the Software without restriction, including without limitation the rights 9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 10 * copies of the Software, and to permit persons to whom the Software is 11 * furnished to do so, subject to the following conditions: 12 * 13 * The above copyright notice and this permission notice shall be included in 14 * all copies or substantial portions of the Software. 15 * 16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 19 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 22 * THE SOFTWARE. 23 */ 24 #include "qemu-common.h" 25 #include "block/block_int.h" 26 #include "qemu/module.h" 27 #include <zlib.h> 28 #include "qemu/aes.h" 29 #include "block/qcow2.h" 30 #include "qemu/error-report.h" 31 #include "qapi/qmp/qerror.h" 32 #include "qapi/qmp/qbool.h" 33 #include "trace.h" 34 #include "qemu/option_int.h" 35 36 /* 37 Differences with QCOW: 38 39 - Support for multiple incremental snapshots. 40 - Memory management by reference counts. 41 - Clusters which have a reference count of one have the bit 42 QCOW_OFLAG_COPIED to optimize write performance. 43 - Size of compressed clusters is stored in sectors to reduce bit usage 44 in the cluster offsets. 45 - Support for storing additional data (such as the VM state) in the 46 snapshots. 47 - If a backing store is used, the cluster size is not constrained 48 (could be backported to QCOW). 49 - L2 tables have always a size of one cluster. 50 */ 51 52 53 typedef struct { 54 uint32_t magic; 55 uint32_t len; 56 } QEMU_PACKED QCowExtension; 57 58 #define QCOW2_EXT_MAGIC_END 0 59 #define QCOW2_EXT_MAGIC_BACKING_FORMAT 0xE2792ACA 60 #define QCOW2_EXT_MAGIC_FEATURE_TABLE 0x6803f857 61 62 static int qcow2_probe(const uint8_t *buf, int buf_size, const char *filename) 63 { 64 const QCowHeader *cow_header = (const void *)buf; 65 66 if (buf_size >= sizeof(QCowHeader) && 67 be32_to_cpu(cow_header->magic) == QCOW_MAGIC && 68 be32_to_cpu(cow_header->version) >= 2) 69 return 100; 70 else 71 return 0; 72 } 73 74 75 /* 76 * read qcow2 extension and fill bs 77 * start reading from start_offset 78 * finish reading upon magic of value 0 or when end_offset reached 79 * unknown magic is skipped (future extension this version knows nothing about) 80 * return 0 upon success, non-0 otherwise 81 */ 82 static int qcow2_read_extensions(BlockDriverState *bs, uint64_t start_offset, 83 uint64_t end_offset, void **p_feature_table, 84 Error **errp) 85 { 86 BDRVQcowState *s = bs->opaque; 87 QCowExtension ext; 88 uint64_t offset; 89 int ret; 90 91 #ifdef DEBUG_EXT 92 printf("qcow2_read_extensions: start=%ld end=%ld\n", start_offset, end_offset); 93 #endif 94 offset = start_offset; 95 while (offset < end_offset) { 96 97 #ifdef DEBUG_EXT 98 /* Sanity check */ 99 if (offset > s->cluster_size) 100 printf("qcow2_read_extension: suspicious offset %lu\n", offset); 101 102 printf("attempting to read extended header in offset %lu\n", offset); 103 #endif 104 105 ret = bdrv_pread(bs->file, offset, &ext, sizeof(ext)); 106 if (ret < 0) { 107 error_setg_errno(errp, -ret, "qcow2_read_extension: ERROR: " 108 "pread fail from offset %" PRIu64, offset); 109 return 1; 110 } 111 be32_to_cpus(&ext.magic); 112 be32_to_cpus(&ext.len); 113 offset += sizeof(ext); 114 #ifdef DEBUG_EXT 115 printf("ext.magic = 0x%x\n", ext.magic); 116 #endif 117 if (ext.len > end_offset - offset) { 118 error_setg(errp, "Header extension too large"); 119 return -EINVAL; 120 } 121 122 switch (ext.magic) { 123 case QCOW2_EXT_MAGIC_END: 124 return 0; 125 126 case QCOW2_EXT_MAGIC_BACKING_FORMAT: 127 if (ext.len >= sizeof(bs->backing_format)) { 128 error_setg(errp, "ERROR: ext_backing_format: len=%" PRIu32 129 " too large (>=%zu)", ext.len, 130 sizeof(bs->backing_format)); 131 return 2; 132 } 133 ret = bdrv_pread(bs->file, offset, bs->backing_format, ext.len); 134 if (ret < 0) { 135 error_setg_errno(errp, -ret, "ERROR: ext_backing_format: " 136 "Could not read format name"); 137 return 3; 138 } 139 bs->backing_format[ext.len] = '\0'; 140 #ifdef DEBUG_EXT 141 printf("Qcow2: Got format extension %s\n", bs->backing_format); 142 #endif 143 break; 144 145 case QCOW2_EXT_MAGIC_FEATURE_TABLE: 146 if (p_feature_table != NULL) { 147 void* feature_table = g_malloc0(ext.len + 2 * sizeof(Qcow2Feature)); 148 ret = bdrv_pread(bs->file, offset , feature_table, ext.len); 149 if (ret < 0) { 150 error_setg_errno(errp, -ret, "ERROR: ext_feature_table: " 151 "Could not read table"); 152 return ret; 153 } 154 155 *p_feature_table = feature_table; 156 } 157 break; 158 159 default: 160 /* unknown magic - save it in case we need to rewrite the header */ 161 { 162 Qcow2UnknownHeaderExtension *uext; 163 164 uext = g_malloc0(sizeof(*uext) + ext.len); 165 uext->magic = ext.magic; 166 uext->len = ext.len; 167 QLIST_INSERT_HEAD(&s->unknown_header_ext, uext, next); 168 169 ret = bdrv_pread(bs->file, offset , uext->data, uext->len); 170 if (ret < 0) { 171 error_setg_errno(errp, -ret, "ERROR: unknown extension: " 172 "Could not read data"); 173 return ret; 174 } 175 } 176 break; 177 } 178 179 offset += ((ext.len + 7) & ~7); 180 } 181 182 return 0; 183 } 184 185 static void cleanup_unknown_header_ext(BlockDriverState *bs) 186 { 187 BDRVQcowState *s = bs->opaque; 188 Qcow2UnknownHeaderExtension *uext, *next; 189 190 QLIST_FOREACH_SAFE(uext, &s->unknown_header_ext, next, next) { 191 QLIST_REMOVE(uext, next); 192 g_free(uext); 193 } 194 } 195 196 static void GCC_FMT_ATTR(3, 4) report_unsupported(BlockDriverState *bs, 197 Error **errp, const char *fmt, ...) 198 { 199 char msg[64]; 200 va_list ap; 201 202 va_start(ap, fmt); 203 vsnprintf(msg, sizeof(msg), fmt, ap); 204 va_end(ap); 205 206 error_set(errp, QERR_UNKNOWN_BLOCK_FORMAT_FEATURE, bs->device_name, "qcow2", 207 msg); 208 } 209 210 static void report_unsupported_feature(BlockDriverState *bs, 211 Error **errp, Qcow2Feature *table, uint64_t mask) 212 { 213 while (table && table->name[0] != '\0') { 214 if (table->type == QCOW2_FEAT_TYPE_INCOMPATIBLE) { 215 if (mask & (1 << table->bit)) { 216 report_unsupported(bs, errp, "%.46s", table->name); 217 mask &= ~(1 << table->bit); 218 } 219 } 220 table++; 221 } 222 223 if (mask) { 224 report_unsupported(bs, errp, "Unknown incompatible feature: %" PRIx64, 225 mask); 226 } 227 } 228 229 /* 230 * Sets the dirty bit and flushes afterwards if necessary. 231 * 232 * The incompatible_features bit is only set if the image file header was 233 * updated successfully. Therefore it is not required to check the return 234 * value of this function. 235 */ 236 int qcow2_mark_dirty(BlockDriverState *bs) 237 { 238 BDRVQcowState *s = bs->opaque; 239 uint64_t val; 240 int ret; 241 242 assert(s->qcow_version >= 3); 243 244 if (s->incompatible_features & QCOW2_INCOMPAT_DIRTY) { 245 return 0; /* already dirty */ 246 } 247 248 val = cpu_to_be64(s->incompatible_features | QCOW2_INCOMPAT_DIRTY); 249 ret = bdrv_pwrite(bs->file, offsetof(QCowHeader, incompatible_features), 250 &val, sizeof(val)); 251 if (ret < 0) { 252 return ret; 253 } 254 ret = bdrv_flush(bs->file); 255 if (ret < 0) { 256 return ret; 257 } 258 259 /* Only treat image as dirty if the header was updated successfully */ 260 s->incompatible_features |= QCOW2_INCOMPAT_DIRTY; 261 return 0; 262 } 263 264 /* 265 * Clears the dirty bit and flushes before if necessary. Only call this 266 * function when there are no pending requests, it does not guard against 267 * concurrent requests dirtying the image. 268 */ 269 static int qcow2_mark_clean(BlockDriverState *bs) 270 { 271 BDRVQcowState *s = bs->opaque; 272 273 if (s->incompatible_features & QCOW2_INCOMPAT_DIRTY) { 274 int ret; 275 276 s->incompatible_features &= ~QCOW2_INCOMPAT_DIRTY; 277 278 ret = bdrv_flush(bs); 279 if (ret < 0) { 280 return ret; 281 } 282 283 return qcow2_update_header(bs); 284 } 285 return 0; 286 } 287 288 /* 289 * Marks the image as corrupt. 290 */ 291 int qcow2_mark_corrupt(BlockDriverState *bs) 292 { 293 BDRVQcowState *s = bs->opaque; 294 295 s->incompatible_features |= QCOW2_INCOMPAT_CORRUPT; 296 return qcow2_update_header(bs); 297 } 298 299 /* 300 * Marks the image as consistent, i.e., unsets the corrupt bit, and flushes 301 * before if necessary. 302 */ 303 int qcow2_mark_consistent(BlockDriverState *bs) 304 { 305 BDRVQcowState *s = bs->opaque; 306 307 if (s->incompatible_features & QCOW2_INCOMPAT_CORRUPT) { 308 int ret = bdrv_flush(bs); 309 if (ret < 0) { 310 return ret; 311 } 312 313 s->incompatible_features &= ~QCOW2_INCOMPAT_CORRUPT; 314 return qcow2_update_header(bs); 315 } 316 return 0; 317 } 318 319 static int qcow2_check(BlockDriverState *bs, BdrvCheckResult *result, 320 BdrvCheckMode fix) 321 { 322 int ret = qcow2_check_refcounts(bs, result, fix); 323 if (ret < 0) { 324 return ret; 325 } 326 327 if (fix && result->check_errors == 0 && result->corruptions == 0) { 328 ret = qcow2_mark_clean(bs); 329 if (ret < 0) { 330 return ret; 331 } 332 return qcow2_mark_consistent(bs); 333 } 334 return ret; 335 } 336 337 static int validate_table_offset(BlockDriverState *bs, uint64_t offset, 338 uint64_t entries, size_t entry_len) 339 { 340 BDRVQcowState *s = bs->opaque; 341 uint64_t size; 342 343 /* Use signed INT64_MAX as the maximum even for uint64_t header fields, 344 * because values will be passed to qemu functions taking int64_t. */ 345 if (entries > INT64_MAX / entry_len) { 346 return -EINVAL; 347 } 348 349 size = entries * entry_len; 350 351 if (INT64_MAX - size < offset) { 352 return -EINVAL; 353 } 354 355 /* Tables must be cluster aligned */ 356 if (offset & (s->cluster_size - 1)) { 357 return -EINVAL; 358 } 359 360 return 0; 361 } 362 363 static QemuOptsList qcow2_runtime_opts = { 364 .name = "qcow2", 365 .head = QTAILQ_HEAD_INITIALIZER(qcow2_runtime_opts.head), 366 .desc = { 367 { 368 .name = QCOW2_OPT_LAZY_REFCOUNTS, 369 .type = QEMU_OPT_BOOL, 370 .help = "Postpone refcount updates", 371 }, 372 { 373 .name = QCOW2_OPT_DISCARD_REQUEST, 374 .type = QEMU_OPT_BOOL, 375 .help = "Pass guest discard requests to the layer below", 376 }, 377 { 378 .name = QCOW2_OPT_DISCARD_SNAPSHOT, 379 .type = QEMU_OPT_BOOL, 380 .help = "Generate discard requests when snapshot related space " 381 "is freed", 382 }, 383 { 384 .name = QCOW2_OPT_DISCARD_OTHER, 385 .type = QEMU_OPT_BOOL, 386 .help = "Generate discard requests when other clusters are freed", 387 }, 388 { 389 .name = QCOW2_OPT_OVERLAP, 390 .type = QEMU_OPT_STRING, 391 .help = "Selects which overlap checks to perform from a range of " 392 "templates (none, constant, cached, all)", 393 }, 394 { 395 .name = QCOW2_OPT_OVERLAP_MAIN_HEADER, 396 .type = QEMU_OPT_BOOL, 397 .help = "Check for unintended writes into the main qcow2 header", 398 }, 399 { 400 .name = QCOW2_OPT_OVERLAP_ACTIVE_L1, 401 .type = QEMU_OPT_BOOL, 402 .help = "Check for unintended writes into the active L1 table", 403 }, 404 { 405 .name = QCOW2_OPT_OVERLAP_ACTIVE_L2, 406 .type = QEMU_OPT_BOOL, 407 .help = "Check for unintended writes into an active L2 table", 408 }, 409 { 410 .name = QCOW2_OPT_OVERLAP_REFCOUNT_TABLE, 411 .type = QEMU_OPT_BOOL, 412 .help = "Check for unintended writes into the refcount table", 413 }, 414 { 415 .name = QCOW2_OPT_OVERLAP_REFCOUNT_BLOCK, 416 .type = QEMU_OPT_BOOL, 417 .help = "Check for unintended writes into a refcount block", 418 }, 419 { 420 .name = QCOW2_OPT_OVERLAP_SNAPSHOT_TABLE, 421 .type = QEMU_OPT_BOOL, 422 .help = "Check for unintended writes into the snapshot table", 423 }, 424 { 425 .name = QCOW2_OPT_OVERLAP_INACTIVE_L1, 426 .type = QEMU_OPT_BOOL, 427 .help = "Check for unintended writes into an inactive L1 table", 428 }, 429 { 430 .name = QCOW2_OPT_OVERLAP_INACTIVE_L2, 431 .type = QEMU_OPT_BOOL, 432 .help = "Check for unintended writes into an inactive L2 table", 433 }, 434 { /* end of list */ } 435 }, 436 }; 437 438 static const char *overlap_bool_option_names[QCOW2_OL_MAX_BITNR] = { 439 [QCOW2_OL_MAIN_HEADER_BITNR] = QCOW2_OPT_OVERLAP_MAIN_HEADER, 440 [QCOW2_OL_ACTIVE_L1_BITNR] = QCOW2_OPT_OVERLAP_ACTIVE_L1, 441 [QCOW2_OL_ACTIVE_L2_BITNR] = QCOW2_OPT_OVERLAP_ACTIVE_L2, 442 [QCOW2_OL_REFCOUNT_TABLE_BITNR] = QCOW2_OPT_OVERLAP_REFCOUNT_TABLE, 443 [QCOW2_OL_REFCOUNT_BLOCK_BITNR] = QCOW2_OPT_OVERLAP_REFCOUNT_BLOCK, 444 [QCOW2_OL_SNAPSHOT_TABLE_BITNR] = QCOW2_OPT_OVERLAP_SNAPSHOT_TABLE, 445 [QCOW2_OL_INACTIVE_L1_BITNR] = QCOW2_OPT_OVERLAP_INACTIVE_L1, 446 [QCOW2_OL_INACTIVE_L2_BITNR] = QCOW2_OPT_OVERLAP_INACTIVE_L2, 447 }; 448 449 static int qcow2_open(BlockDriverState *bs, QDict *options, int flags, 450 Error **errp) 451 { 452 BDRVQcowState *s = bs->opaque; 453 unsigned int len, i; 454 int ret = 0; 455 QCowHeader header; 456 QemuOpts *opts; 457 Error *local_err = NULL; 458 uint64_t ext_end; 459 uint64_t l1_vm_state_index; 460 const char *opt_overlap_check; 461 int overlap_check_template = 0; 462 463 ret = bdrv_pread(bs->file, 0, &header, sizeof(header)); 464 if (ret < 0) { 465 error_setg_errno(errp, -ret, "Could not read qcow2 header"); 466 goto fail; 467 } 468 be32_to_cpus(&header.magic); 469 be32_to_cpus(&header.version); 470 be64_to_cpus(&header.backing_file_offset); 471 be32_to_cpus(&header.backing_file_size); 472 be64_to_cpus(&header.size); 473 be32_to_cpus(&header.cluster_bits); 474 be32_to_cpus(&header.crypt_method); 475 be64_to_cpus(&header.l1_table_offset); 476 be32_to_cpus(&header.l1_size); 477 be64_to_cpus(&header.refcount_table_offset); 478 be32_to_cpus(&header.refcount_table_clusters); 479 be64_to_cpus(&header.snapshots_offset); 480 be32_to_cpus(&header.nb_snapshots); 481 482 if (header.magic != QCOW_MAGIC) { 483 error_setg(errp, "Image is not in qcow2 format"); 484 ret = -EINVAL; 485 goto fail; 486 } 487 if (header.version < 2 || header.version > 3) { 488 report_unsupported(bs, errp, "QCOW version %" PRIu32, header.version); 489 ret = -ENOTSUP; 490 goto fail; 491 } 492 493 s->qcow_version = header.version; 494 495 /* Initialise cluster size */ 496 if (header.cluster_bits < MIN_CLUSTER_BITS || 497 header.cluster_bits > MAX_CLUSTER_BITS) { 498 error_setg(errp, "Unsupported cluster size: 2^%" PRIu32, 499 header.cluster_bits); 500 ret = -EINVAL; 501 goto fail; 502 } 503 504 s->cluster_bits = header.cluster_bits; 505 s->cluster_size = 1 << s->cluster_bits; 506 s->cluster_sectors = 1 << (s->cluster_bits - 9); 507 508 /* Initialise version 3 header fields */ 509 if (header.version == 2) { 510 header.incompatible_features = 0; 511 header.compatible_features = 0; 512 header.autoclear_features = 0; 513 header.refcount_order = 4; 514 header.header_length = 72; 515 } else { 516 be64_to_cpus(&header.incompatible_features); 517 be64_to_cpus(&header.compatible_features); 518 be64_to_cpus(&header.autoclear_features); 519 be32_to_cpus(&header.refcount_order); 520 be32_to_cpus(&header.header_length); 521 522 if (header.header_length < 104) { 523 error_setg(errp, "qcow2 header too short"); 524 ret = -EINVAL; 525 goto fail; 526 } 527 } 528 529 if (header.header_length > s->cluster_size) { 530 error_setg(errp, "qcow2 header exceeds cluster size"); 531 ret = -EINVAL; 532 goto fail; 533 } 534 535 if (header.header_length > sizeof(header)) { 536 s->unknown_header_fields_size = header.header_length - sizeof(header); 537 s->unknown_header_fields = g_malloc(s->unknown_header_fields_size); 538 ret = bdrv_pread(bs->file, sizeof(header), s->unknown_header_fields, 539 s->unknown_header_fields_size); 540 if (ret < 0) { 541 error_setg_errno(errp, -ret, "Could not read unknown qcow2 header " 542 "fields"); 543 goto fail; 544 } 545 } 546 547 if (header.backing_file_offset > s->cluster_size) { 548 error_setg(errp, "Invalid backing file offset"); 549 ret = -EINVAL; 550 goto fail; 551 } 552 553 if (header.backing_file_offset) { 554 ext_end = header.backing_file_offset; 555 } else { 556 ext_end = 1 << header.cluster_bits; 557 } 558 559 /* Handle feature bits */ 560 s->incompatible_features = header.incompatible_features; 561 s->compatible_features = header.compatible_features; 562 s->autoclear_features = header.autoclear_features; 563 564 if (s->incompatible_features & ~QCOW2_INCOMPAT_MASK) { 565 void *feature_table = NULL; 566 qcow2_read_extensions(bs, header.header_length, ext_end, 567 &feature_table, NULL); 568 report_unsupported_feature(bs, errp, feature_table, 569 s->incompatible_features & 570 ~QCOW2_INCOMPAT_MASK); 571 ret = -ENOTSUP; 572 g_free(feature_table); 573 goto fail; 574 } 575 576 if (s->incompatible_features & QCOW2_INCOMPAT_CORRUPT) { 577 /* Corrupt images may not be written to unless they are being repaired 578 */ 579 if ((flags & BDRV_O_RDWR) && !(flags & BDRV_O_CHECK)) { 580 error_setg(errp, "qcow2: Image is corrupt; cannot be opened " 581 "read/write"); 582 ret = -EACCES; 583 goto fail; 584 } 585 } 586 587 /* Check support for various header values */ 588 if (header.refcount_order != 4) { 589 report_unsupported(bs, errp, "%d bit reference counts", 590 1 << header.refcount_order); 591 ret = -ENOTSUP; 592 goto fail; 593 } 594 s->refcount_order = header.refcount_order; 595 596 if (header.crypt_method > QCOW_CRYPT_AES) { 597 error_setg(errp, "Unsupported encryption method: %" PRIu32, 598 header.crypt_method); 599 ret = -EINVAL; 600 goto fail; 601 } 602 s->crypt_method_header = header.crypt_method; 603 if (s->crypt_method_header) { 604 bs->encrypted = 1; 605 } 606 607 s->l2_bits = s->cluster_bits - 3; /* L2 is always one cluster */ 608 s->l2_size = 1 << s->l2_bits; 609 bs->total_sectors = header.size / 512; 610 s->csize_shift = (62 - (s->cluster_bits - 8)); 611 s->csize_mask = (1 << (s->cluster_bits - 8)) - 1; 612 s->cluster_offset_mask = (1LL << s->csize_shift) - 1; 613 614 s->refcount_table_offset = header.refcount_table_offset; 615 s->refcount_table_size = 616 header.refcount_table_clusters << (s->cluster_bits - 3); 617 618 if (header.refcount_table_clusters > qcow2_max_refcount_clusters(s)) { 619 error_setg(errp, "Reference count table too large"); 620 ret = -EINVAL; 621 goto fail; 622 } 623 624 ret = validate_table_offset(bs, s->refcount_table_offset, 625 s->refcount_table_size, sizeof(uint64_t)); 626 if (ret < 0) { 627 error_setg(errp, "Invalid reference count table offset"); 628 goto fail; 629 } 630 631 /* Snapshot table offset/length */ 632 if (header.nb_snapshots > QCOW_MAX_SNAPSHOTS) { 633 error_setg(errp, "Too many snapshots"); 634 ret = -EINVAL; 635 goto fail; 636 } 637 638 ret = validate_table_offset(bs, header.snapshots_offset, 639 header.nb_snapshots, 640 sizeof(QCowSnapshotHeader)); 641 if (ret < 0) { 642 error_setg(errp, "Invalid snapshot table offset"); 643 goto fail; 644 } 645 646 /* read the level 1 table */ 647 if (header.l1_size > QCOW_MAX_L1_SIZE) { 648 error_setg(errp, "Active L1 table too large"); 649 ret = -EFBIG; 650 goto fail; 651 } 652 s->l1_size = header.l1_size; 653 654 l1_vm_state_index = size_to_l1(s, header.size); 655 if (l1_vm_state_index > INT_MAX) { 656 error_setg(errp, "Image is too big"); 657 ret = -EFBIG; 658 goto fail; 659 } 660 s->l1_vm_state_index = l1_vm_state_index; 661 662 /* the L1 table must contain at least enough entries to put 663 header.size bytes */ 664 if (s->l1_size < s->l1_vm_state_index) { 665 error_setg(errp, "L1 table is too small"); 666 ret = -EINVAL; 667 goto fail; 668 } 669 670 ret = validate_table_offset(bs, header.l1_table_offset, 671 header.l1_size, sizeof(uint64_t)); 672 if (ret < 0) { 673 error_setg(errp, "Invalid L1 table offset"); 674 goto fail; 675 } 676 s->l1_table_offset = header.l1_table_offset; 677 678 679 if (s->l1_size > 0) { 680 s->l1_table = g_malloc0( 681 align_offset(s->l1_size * sizeof(uint64_t), 512)); 682 ret = bdrv_pread(bs->file, s->l1_table_offset, s->l1_table, 683 s->l1_size * sizeof(uint64_t)); 684 if (ret < 0) { 685 error_setg_errno(errp, -ret, "Could not read L1 table"); 686 goto fail; 687 } 688 for(i = 0;i < s->l1_size; i++) { 689 be64_to_cpus(&s->l1_table[i]); 690 } 691 } 692 693 /* alloc L2 table/refcount block cache */ 694 s->l2_table_cache = qcow2_cache_create(bs, L2_CACHE_SIZE); 695 s->refcount_block_cache = qcow2_cache_create(bs, REFCOUNT_CACHE_SIZE); 696 697 s->cluster_cache = g_malloc(s->cluster_size); 698 /* one more sector for decompressed data alignment */ 699 s->cluster_data = qemu_blockalign(bs, QCOW_MAX_CRYPT_CLUSTERS * s->cluster_size 700 + 512); 701 s->cluster_cache_offset = -1; 702 s->flags = flags; 703 704 ret = qcow2_refcount_init(bs); 705 if (ret != 0) { 706 error_setg_errno(errp, -ret, "Could not initialize refcount handling"); 707 goto fail; 708 } 709 710 QLIST_INIT(&s->cluster_allocs); 711 QTAILQ_INIT(&s->discards); 712 713 /* read qcow2 extensions */ 714 if (qcow2_read_extensions(bs, header.header_length, ext_end, NULL, 715 &local_err)) { 716 error_propagate(errp, local_err); 717 ret = -EINVAL; 718 goto fail; 719 } 720 721 /* read the backing file name */ 722 if (header.backing_file_offset != 0) { 723 len = header.backing_file_size; 724 if (len > MIN(1023, s->cluster_size - header.backing_file_offset)) { 725 error_setg(errp, "Backing file name too long"); 726 ret = -EINVAL; 727 goto fail; 728 } 729 ret = bdrv_pread(bs->file, header.backing_file_offset, 730 bs->backing_file, len); 731 if (ret < 0) { 732 error_setg_errno(errp, -ret, "Could not read backing file name"); 733 goto fail; 734 } 735 bs->backing_file[len] = '\0'; 736 } 737 738 /* Internal snapshots */ 739 s->snapshots_offset = header.snapshots_offset; 740 s->nb_snapshots = header.nb_snapshots; 741 742 ret = qcow2_read_snapshots(bs); 743 if (ret < 0) { 744 error_setg_errno(errp, -ret, "Could not read snapshots"); 745 goto fail; 746 } 747 748 /* Clear unknown autoclear feature bits */ 749 if (!bs->read_only && !(flags & BDRV_O_INCOMING) && s->autoclear_features) { 750 s->autoclear_features = 0; 751 ret = qcow2_update_header(bs); 752 if (ret < 0) { 753 error_setg_errno(errp, -ret, "Could not update qcow2 header"); 754 goto fail; 755 } 756 } 757 758 /* Initialise locks */ 759 qemu_co_mutex_init(&s->lock); 760 761 /* Repair image if dirty */ 762 if (!(flags & (BDRV_O_CHECK | BDRV_O_INCOMING)) && !bs->read_only && 763 (s->incompatible_features & QCOW2_INCOMPAT_DIRTY)) { 764 BdrvCheckResult result = {0}; 765 766 ret = qcow2_check(bs, &result, BDRV_FIX_ERRORS); 767 if (ret < 0) { 768 error_setg_errno(errp, -ret, "Could not repair dirty image"); 769 goto fail; 770 } 771 } 772 773 /* Enable lazy_refcounts according to image and command line options */ 774 opts = qemu_opts_create(&qcow2_runtime_opts, NULL, 0, &error_abort); 775 qemu_opts_absorb_qdict(opts, options, &local_err); 776 if (local_err) { 777 error_propagate(errp, local_err); 778 ret = -EINVAL; 779 goto fail; 780 } 781 782 s->use_lazy_refcounts = qemu_opt_get_bool(opts, QCOW2_OPT_LAZY_REFCOUNTS, 783 (s->compatible_features & QCOW2_COMPAT_LAZY_REFCOUNTS)); 784 785 s->discard_passthrough[QCOW2_DISCARD_NEVER] = false; 786 s->discard_passthrough[QCOW2_DISCARD_ALWAYS] = true; 787 s->discard_passthrough[QCOW2_DISCARD_REQUEST] = 788 qemu_opt_get_bool(opts, QCOW2_OPT_DISCARD_REQUEST, 789 flags & BDRV_O_UNMAP); 790 s->discard_passthrough[QCOW2_DISCARD_SNAPSHOT] = 791 qemu_opt_get_bool(opts, QCOW2_OPT_DISCARD_SNAPSHOT, true); 792 s->discard_passthrough[QCOW2_DISCARD_OTHER] = 793 qemu_opt_get_bool(opts, QCOW2_OPT_DISCARD_OTHER, false); 794 795 opt_overlap_check = qemu_opt_get(opts, "overlap-check") ?: "cached"; 796 if (!strcmp(opt_overlap_check, "none")) { 797 overlap_check_template = 0; 798 } else if (!strcmp(opt_overlap_check, "constant")) { 799 overlap_check_template = QCOW2_OL_CONSTANT; 800 } else if (!strcmp(opt_overlap_check, "cached")) { 801 overlap_check_template = QCOW2_OL_CACHED; 802 } else if (!strcmp(opt_overlap_check, "all")) { 803 overlap_check_template = QCOW2_OL_ALL; 804 } else { 805 error_setg(errp, "Unsupported value '%s' for qcow2 option " 806 "'overlap-check'. Allowed are either of the following: " 807 "none, constant, cached, all", opt_overlap_check); 808 qemu_opts_del(opts); 809 ret = -EINVAL; 810 goto fail; 811 } 812 813 s->overlap_check = 0; 814 for (i = 0; i < QCOW2_OL_MAX_BITNR; i++) { 815 /* overlap-check defines a template bitmask, but every flag may be 816 * overwritten through the associated boolean option */ 817 s->overlap_check |= 818 qemu_opt_get_bool(opts, overlap_bool_option_names[i], 819 overlap_check_template & (1 << i)) << i; 820 } 821 822 qemu_opts_del(opts); 823 824 if (s->use_lazy_refcounts && s->qcow_version < 3) { 825 error_setg(errp, "Lazy refcounts require a qcow2 image with at least " 826 "qemu 1.1 compatibility level"); 827 ret = -EINVAL; 828 goto fail; 829 } 830 831 #ifdef DEBUG_ALLOC 832 { 833 BdrvCheckResult result = {0}; 834 qcow2_check_refcounts(bs, &result, 0); 835 } 836 #endif 837 return ret; 838 839 fail: 840 g_free(s->unknown_header_fields); 841 cleanup_unknown_header_ext(bs); 842 qcow2_free_snapshots(bs); 843 qcow2_refcount_close(bs); 844 g_free(s->l1_table); 845 /* else pre-write overlap checks in cache_destroy may crash */ 846 s->l1_table = NULL; 847 if (s->l2_table_cache) { 848 qcow2_cache_destroy(bs, s->l2_table_cache); 849 } 850 if (s->refcount_block_cache) { 851 qcow2_cache_destroy(bs, s->refcount_block_cache); 852 } 853 g_free(s->cluster_cache); 854 qemu_vfree(s->cluster_data); 855 return ret; 856 } 857 858 static int qcow2_refresh_limits(BlockDriverState *bs) 859 { 860 BDRVQcowState *s = bs->opaque; 861 862 bs->bl.write_zeroes_alignment = s->cluster_sectors; 863 864 return 0; 865 } 866 867 static int qcow2_set_key(BlockDriverState *bs, const char *key) 868 { 869 BDRVQcowState *s = bs->opaque; 870 uint8_t keybuf[16]; 871 int len, i; 872 873 memset(keybuf, 0, 16); 874 len = strlen(key); 875 if (len > 16) 876 len = 16; 877 /* XXX: we could compress the chars to 7 bits to increase 878 entropy */ 879 for(i = 0;i < len;i++) { 880 keybuf[i] = key[i]; 881 } 882 s->crypt_method = s->crypt_method_header; 883 884 if (AES_set_encrypt_key(keybuf, 128, &s->aes_encrypt_key) != 0) 885 return -1; 886 if (AES_set_decrypt_key(keybuf, 128, &s->aes_decrypt_key) != 0) 887 return -1; 888 #if 0 889 /* test */ 890 { 891 uint8_t in[16]; 892 uint8_t out[16]; 893 uint8_t tmp[16]; 894 for(i=0;i<16;i++) 895 in[i] = i; 896 AES_encrypt(in, tmp, &s->aes_encrypt_key); 897 AES_decrypt(tmp, out, &s->aes_decrypt_key); 898 for(i = 0; i < 16; i++) 899 printf(" %02x", tmp[i]); 900 printf("\n"); 901 for(i = 0; i < 16; i++) 902 printf(" %02x", out[i]); 903 printf("\n"); 904 } 905 #endif 906 return 0; 907 } 908 909 /* We have no actual commit/abort logic for qcow2, but we need to write out any 910 * unwritten data if we reopen read-only. */ 911 static int qcow2_reopen_prepare(BDRVReopenState *state, 912 BlockReopenQueue *queue, Error **errp) 913 { 914 int ret; 915 916 if ((state->flags & BDRV_O_RDWR) == 0) { 917 ret = bdrv_flush(state->bs); 918 if (ret < 0) { 919 return ret; 920 } 921 922 ret = qcow2_mark_clean(state->bs); 923 if (ret < 0) { 924 return ret; 925 } 926 } 927 928 return 0; 929 } 930 931 static int64_t coroutine_fn qcow2_co_get_block_status(BlockDriverState *bs, 932 int64_t sector_num, int nb_sectors, int *pnum) 933 { 934 BDRVQcowState *s = bs->opaque; 935 uint64_t cluster_offset; 936 int index_in_cluster, ret; 937 int64_t status = 0; 938 939 *pnum = nb_sectors; 940 qemu_co_mutex_lock(&s->lock); 941 ret = qcow2_get_cluster_offset(bs, sector_num << 9, pnum, &cluster_offset); 942 qemu_co_mutex_unlock(&s->lock); 943 if (ret < 0) { 944 return ret; 945 } 946 947 if (cluster_offset != 0 && ret != QCOW2_CLUSTER_COMPRESSED && 948 !s->crypt_method) { 949 index_in_cluster = sector_num & (s->cluster_sectors - 1); 950 cluster_offset |= (index_in_cluster << BDRV_SECTOR_BITS); 951 status |= BDRV_BLOCK_OFFSET_VALID | cluster_offset; 952 } 953 if (ret == QCOW2_CLUSTER_ZERO) { 954 status |= BDRV_BLOCK_ZERO; 955 } else if (ret != QCOW2_CLUSTER_UNALLOCATED) { 956 status |= BDRV_BLOCK_DATA; 957 } 958 return status; 959 } 960 961 /* handle reading after the end of the backing file */ 962 int qcow2_backing_read1(BlockDriverState *bs, QEMUIOVector *qiov, 963 int64_t sector_num, int nb_sectors) 964 { 965 int n1; 966 if ((sector_num + nb_sectors) <= bs->total_sectors) 967 return nb_sectors; 968 if (sector_num >= bs->total_sectors) 969 n1 = 0; 970 else 971 n1 = bs->total_sectors - sector_num; 972 973 qemu_iovec_memset(qiov, 512 * n1, 0, 512 * (nb_sectors - n1)); 974 975 return n1; 976 } 977 978 static coroutine_fn int qcow2_co_readv(BlockDriverState *bs, int64_t sector_num, 979 int remaining_sectors, QEMUIOVector *qiov) 980 { 981 BDRVQcowState *s = bs->opaque; 982 int index_in_cluster, n1; 983 int ret; 984 int cur_nr_sectors; /* number of sectors in current iteration */ 985 uint64_t cluster_offset = 0; 986 uint64_t bytes_done = 0; 987 QEMUIOVector hd_qiov; 988 uint8_t *cluster_data = NULL; 989 990 qemu_iovec_init(&hd_qiov, qiov->niov); 991 992 qemu_co_mutex_lock(&s->lock); 993 994 while (remaining_sectors != 0) { 995 996 /* prepare next request */ 997 cur_nr_sectors = remaining_sectors; 998 if (s->crypt_method) { 999 cur_nr_sectors = MIN(cur_nr_sectors, 1000 QCOW_MAX_CRYPT_CLUSTERS * s->cluster_sectors); 1001 } 1002 1003 ret = qcow2_get_cluster_offset(bs, sector_num << 9, 1004 &cur_nr_sectors, &cluster_offset); 1005 if (ret < 0) { 1006 goto fail; 1007 } 1008 1009 index_in_cluster = sector_num & (s->cluster_sectors - 1); 1010 1011 qemu_iovec_reset(&hd_qiov); 1012 qemu_iovec_concat(&hd_qiov, qiov, bytes_done, 1013 cur_nr_sectors * 512); 1014 1015 switch (ret) { 1016 case QCOW2_CLUSTER_UNALLOCATED: 1017 1018 if (bs->backing_hd) { 1019 /* read from the base image */ 1020 n1 = qcow2_backing_read1(bs->backing_hd, &hd_qiov, 1021 sector_num, cur_nr_sectors); 1022 if (n1 > 0) { 1023 QEMUIOVector local_qiov; 1024 1025 qemu_iovec_init(&local_qiov, hd_qiov.niov); 1026 qemu_iovec_concat(&local_qiov, &hd_qiov, 0, 1027 n1 * BDRV_SECTOR_SIZE); 1028 1029 BLKDBG_EVENT(bs->file, BLKDBG_READ_BACKING_AIO); 1030 qemu_co_mutex_unlock(&s->lock); 1031 ret = bdrv_co_readv(bs->backing_hd, sector_num, 1032 n1, &local_qiov); 1033 qemu_co_mutex_lock(&s->lock); 1034 1035 qemu_iovec_destroy(&local_qiov); 1036 1037 if (ret < 0) { 1038 goto fail; 1039 } 1040 } 1041 } else { 1042 /* Note: in this case, no need to wait */ 1043 qemu_iovec_memset(&hd_qiov, 0, 0, 512 * cur_nr_sectors); 1044 } 1045 break; 1046 1047 case QCOW2_CLUSTER_ZERO: 1048 qemu_iovec_memset(&hd_qiov, 0, 0, 512 * cur_nr_sectors); 1049 break; 1050 1051 case QCOW2_CLUSTER_COMPRESSED: 1052 /* add AIO support for compressed blocks ? */ 1053 ret = qcow2_decompress_cluster(bs, cluster_offset); 1054 if (ret < 0) { 1055 goto fail; 1056 } 1057 1058 qemu_iovec_from_buf(&hd_qiov, 0, 1059 s->cluster_cache + index_in_cluster * 512, 1060 512 * cur_nr_sectors); 1061 break; 1062 1063 case QCOW2_CLUSTER_NORMAL: 1064 if ((cluster_offset & 511) != 0) { 1065 ret = -EIO; 1066 goto fail; 1067 } 1068 1069 if (s->crypt_method) { 1070 /* 1071 * For encrypted images, read everything into a temporary 1072 * contiguous buffer on which the AES functions can work. 1073 */ 1074 if (!cluster_data) { 1075 cluster_data = 1076 qemu_blockalign(bs, QCOW_MAX_CRYPT_CLUSTERS * s->cluster_size); 1077 } 1078 1079 assert(cur_nr_sectors <= 1080 QCOW_MAX_CRYPT_CLUSTERS * s->cluster_sectors); 1081 qemu_iovec_reset(&hd_qiov); 1082 qemu_iovec_add(&hd_qiov, cluster_data, 1083 512 * cur_nr_sectors); 1084 } 1085 1086 BLKDBG_EVENT(bs->file, BLKDBG_READ_AIO); 1087 qemu_co_mutex_unlock(&s->lock); 1088 ret = bdrv_co_readv(bs->file, 1089 (cluster_offset >> 9) + index_in_cluster, 1090 cur_nr_sectors, &hd_qiov); 1091 qemu_co_mutex_lock(&s->lock); 1092 if (ret < 0) { 1093 goto fail; 1094 } 1095 if (s->crypt_method) { 1096 qcow2_encrypt_sectors(s, sector_num, cluster_data, 1097 cluster_data, cur_nr_sectors, 0, &s->aes_decrypt_key); 1098 qemu_iovec_from_buf(qiov, bytes_done, 1099 cluster_data, 512 * cur_nr_sectors); 1100 } 1101 break; 1102 1103 default: 1104 g_assert_not_reached(); 1105 ret = -EIO; 1106 goto fail; 1107 } 1108 1109 remaining_sectors -= cur_nr_sectors; 1110 sector_num += cur_nr_sectors; 1111 bytes_done += cur_nr_sectors * 512; 1112 } 1113 ret = 0; 1114 1115 fail: 1116 qemu_co_mutex_unlock(&s->lock); 1117 1118 qemu_iovec_destroy(&hd_qiov); 1119 qemu_vfree(cluster_data); 1120 1121 return ret; 1122 } 1123 1124 static coroutine_fn int qcow2_co_writev(BlockDriverState *bs, 1125 int64_t sector_num, 1126 int remaining_sectors, 1127 QEMUIOVector *qiov) 1128 { 1129 BDRVQcowState *s = bs->opaque; 1130 int index_in_cluster; 1131 int ret; 1132 int cur_nr_sectors; /* number of sectors in current iteration */ 1133 uint64_t cluster_offset; 1134 QEMUIOVector hd_qiov; 1135 uint64_t bytes_done = 0; 1136 uint8_t *cluster_data = NULL; 1137 QCowL2Meta *l2meta = NULL; 1138 1139 trace_qcow2_writev_start_req(qemu_coroutine_self(), sector_num, 1140 remaining_sectors); 1141 1142 qemu_iovec_init(&hd_qiov, qiov->niov); 1143 1144 s->cluster_cache_offset = -1; /* disable compressed cache */ 1145 1146 qemu_co_mutex_lock(&s->lock); 1147 1148 while (remaining_sectors != 0) { 1149 1150 l2meta = NULL; 1151 1152 trace_qcow2_writev_start_part(qemu_coroutine_self()); 1153 index_in_cluster = sector_num & (s->cluster_sectors - 1); 1154 cur_nr_sectors = remaining_sectors; 1155 if (s->crypt_method && 1156 cur_nr_sectors > 1157 QCOW_MAX_CRYPT_CLUSTERS * s->cluster_sectors - index_in_cluster) { 1158 cur_nr_sectors = 1159 QCOW_MAX_CRYPT_CLUSTERS * s->cluster_sectors - index_in_cluster; 1160 } 1161 1162 ret = qcow2_alloc_cluster_offset(bs, sector_num << 9, 1163 &cur_nr_sectors, &cluster_offset, &l2meta); 1164 if (ret < 0) { 1165 goto fail; 1166 } 1167 1168 assert((cluster_offset & 511) == 0); 1169 1170 qemu_iovec_reset(&hd_qiov); 1171 qemu_iovec_concat(&hd_qiov, qiov, bytes_done, 1172 cur_nr_sectors * 512); 1173 1174 if (s->crypt_method) { 1175 if (!cluster_data) { 1176 cluster_data = qemu_blockalign(bs, QCOW_MAX_CRYPT_CLUSTERS * 1177 s->cluster_size); 1178 } 1179 1180 assert(hd_qiov.size <= 1181 QCOW_MAX_CRYPT_CLUSTERS * s->cluster_size); 1182 qemu_iovec_to_buf(&hd_qiov, 0, cluster_data, hd_qiov.size); 1183 1184 qcow2_encrypt_sectors(s, sector_num, cluster_data, 1185 cluster_data, cur_nr_sectors, 1, &s->aes_encrypt_key); 1186 1187 qemu_iovec_reset(&hd_qiov); 1188 qemu_iovec_add(&hd_qiov, cluster_data, 1189 cur_nr_sectors * 512); 1190 } 1191 1192 ret = qcow2_pre_write_overlap_check(bs, 0, 1193 cluster_offset + index_in_cluster * BDRV_SECTOR_SIZE, 1194 cur_nr_sectors * BDRV_SECTOR_SIZE); 1195 if (ret < 0) { 1196 goto fail; 1197 } 1198 1199 qemu_co_mutex_unlock(&s->lock); 1200 BLKDBG_EVENT(bs->file, BLKDBG_WRITE_AIO); 1201 trace_qcow2_writev_data(qemu_coroutine_self(), 1202 (cluster_offset >> 9) + index_in_cluster); 1203 ret = bdrv_co_writev(bs->file, 1204 (cluster_offset >> 9) + index_in_cluster, 1205 cur_nr_sectors, &hd_qiov); 1206 qemu_co_mutex_lock(&s->lock); 1207 if (ret < 0) { 1208 goto fail; 1209 } 1210 1211 while (l2meta != NULL) { 1212 QCowL2Meta *next; 1213 1214 ret = qcow2_alloc_cluster_link_l2(bs, l2meta); 1215 if (ret < 0) { 1216 goto fail; 1217 } 1218 1219 /* Take the request off the list of running requests */ 1220 if (l2meta->nb_clusters != 0) { 1221 QLIST_REMOVE(l2meta, next_in_flight); 1222 } 1223 1224 qemu_co_queue_restart_all(&l2meta->dependent_requests); 1225 1226 next = l2meta->next; 1227 g_free(l2meta); 1228 l2meta = next; 1229 } 1230 1231 remaining_sectors -= cur_nr_sectors; 1232 sector_num += cur_nr_sectors; 1233 bytes_done += cur_nr_sectors * 512; 1234 trace_qcow2_writev_done_part(qemu_coroutine_self(), cur_nr_sectors); 1235 } 1236 ret = 0; 1237 1238 fail: 1239 qemu_co_mutex_unlock(&s->lock); 1240 1241 while (l2meta != NULL) { 1242 QCowL2Meta *next; 1243 1244 if (l2meta->nb_clusters != 0) { 1245 QLIST_REMOVE(l2meta, next_in_flight); 1246 } 1247 qemu_co_queue_restart_all(&l2meta->dependent_requests); 1248 1249 next = l2meta->next; 1250 g_free(l2meta); 1251 l2meta = next; 1252 } 1253 1254 qemu_iovec_destroy(&hd_qiov); 1255 qemu_vfree(cluster_data); 1256 trace_qcow2_writev_done_req(qemu_coroutine_self(), ret); 1257 1258 return ret; 1259 } 1260 1261 static void qcow2_close(BlockDriverState *bs) 1262 { 1263 BDRVQcowState *s = bs->opaque; 1264 g_free(s->l1_table); 1265 /* else pre-write overlap checks in cache_destroy may crash */ 1266 s->l1_table = NULL; 1267 1268 if (!(bs->open_flags & BDRV_O_INCOMING)) { 1269 qcow2_cache_flush(bs, s->l2_table_cache); 1270 qcow2_cache_flush(bs, s->refcount_block_cache); 1271 1272 qcow2_mark_clean(bs); 1273 } 1274 1275 qcow2_cache_destroy(bs, s->l2_table_cache); 1276 qcow2_cache_destroy(bs, s->refcount_block_cache); 1277 1278 g_free(s->unknown_header_fields); 1279 cleanup_unknown_header_ext(bs); 1280 1281 g_free(s->cluster_cache); 1282 qemu_vfree(s->cluster_data); 1283 qcow2_refcount_close(bs); 1284 qcow2_free_snapshots(bs); 1285 } 1286 1287 static void qcow2_invalidate_cache(BlockDriverState *bs, Error **errp) 1288 { 1289 BDRVQcowState *s = bs->opaque; 1290 int flags = s->flags; 1291 AES_KEY aes_encrypt_key; 1292 AES_KEY aes_decrypt_key; 1293 uint32_t crypt_method = 0; 1294 QDict *options; 1295 Error *local_err = NULL; 1296 int ret; 1297 1298 /* 1299 * Backing files are read-only which makes all of their metadata immutable, 1300 * that means we don't have to worry about reopening them here. 1301 */ 1302 1303 if (s->crypt_method) { 1304 crypt_method = s->crypt_method; 1305 memcpy(&aes_encrypt_key, &s->aes_encrypt_key, sizeof(aes_encrypt_key)); 1306 memcpy(&aes_decrypt_key, &s->aes_decrypt_key, sizeof(aes_decrypt_key)); 1307 } 1308 1309 qcow2_close(bs); 1310 1311 bdrv_invalidate_cache(bs->file, &local_err); 1312 if (local_err) { 1313 error_propagate(errp, local_err); 1314 return; 1315 } 1316 1317 memset(s, 0, sizeof(BDRVQcowState)); 1318 options = qdict_clone_shallow(bs->options); 1319 1320 ret = qcow2_open(bs, options, flags, &local_err); 1321 QDECREF(options); 1322 if (local_err) { 1323 error_setg(errp, "Could not reopen qcow2 layer: %s", 1324 error_get_pretty(local_err)); 1325 error_free(local_err); 1326 return; 1327 } else if (ret < 0) { 1328 error_setg_errno(errp, -ret, "Could not reopen qcow2 layer"); 1329 return; 1330 } 1331 1332 if (crypt_method) { 1333 s->crypt_method = crypt_method; 1334 memcpy(&s->aes_encrypt_key, &aes_encrypt_key, sizeof(aes_encrypt_key)); 1335 memcpy(&s->aes_decrypt_key, &aes_decrypt_key, sizeof(aes_decrypt_key)); 1336 } 1337 } 1338 1339 static size_t header_ext_add(char *buf, uint32_t magic, const void *s, 1340 size_t len, size_t buflen) 1341 { 1342 QCowExtension *ext_backing_fmt = (QCowExtension*) buf; 1343 size_t ext_len = sizeof(QCowExtension) + ((len + 7) & ~7); 1344 1345 if (buflen < ext_len) { 1346 return -ENOSPC; 1347 } 1348 1349 *ext_backing_fmt = (QCowExtension) { 1350 .magic = cpu_to_be32(magic), 1351 .len = cpu_to_be32(len), 1352 }; 1353 memcpy(buf + sizeof(QCowExtension), s, len); 1354 1355 return ext_len; 1356 } 1357 1358 /* 1359 * Updates the qcow2 header, including the variable length parts of it, i.e. 1360 * the backing file name and all extensions. qcow2 was not designed to allow 1361 * such changes, so if we run out of space (we can only use the first cluster) 1362 * this function may fail. 1363 * 1364 * Returns 0 on success, -errno in error cases. 1365 */ 1366 int qcow2_update_header(BlockDriverState *bs) 1367 { 1368 BDRVQcowState *s = bs->opaque; 1369 QCowHeader *header; 1370 char *buf; 1371 size_t buflen = s->cluster_size; 1372 int ret; 1373 uint64_t total_size; 1374 uint32_t refcount_table_clusters; 1375 size_t header_length; 1376 Qcow2UnknownHeaderExtension *uext; 1377 1378 buf = qemu_blockalign(bs, buflen); 1379 1380 /* Header structure */ 1381 header = (QCowHeader*) buf; 1382 1383 if (buflen < sizeof(*header)) { 1384 ret = -ENOSPC; 1385 goto fail; 1386 } 1387 1388 header_length = sizeof(*header) + s->unknown_header_fields_size; 1389 total_size = bs->total_sectors * BDRV_SECTOR_SIZE; 1390 refcount_table_clusters = s->refcount_table_size >> (s->cluster_bits - 3); 1391 1392 *header = (QCowHeader) { 1393 /* Version 2 fields */ 1394 .magic = cpu_to_be32(QCOW_MAGIC), 1395 .version = cpu_to_be32(s->qcow_version), 1396 .backing_file_offset = 0, 1397 .backing_file_size = 0, 1398 .cluster_bits = cpu_to_be32(s->cluster_bits), 1399 .size = cpu_to_be64(total_size), 1400 .crypt_method = cpu_to_be32(s->crypt_method_header), 1401 .l1_size = cpu_to_be32(s->l1_size), 1402 .l1_table_offset = cpu_to_be64(s->l1_table_offset), 1403 .refcount_table_offset = cpu_to_be64(s->refcount_table_offset), 1404 .refcount_table_clusters = cpu_to_be32(refcount_table_clusters), 1405 .nb_snapshots = cpu_to_be32(s->nb_snapshots), 1406 .snapshots_offset = cpu_to_be64(s->snapshots_offset), 1407 1408 /* Version 3 fields */ 1409 .incompatible_features = cpu_to_be64(s->incompatible_features), 1410 .compatible_features = cpu_to_be64(s->compatible_features), 1411 .autoclear_features = cpu_to_be64(s->autoclear_features), 1412 .refcount_order = cpu_to_be32(s->refcount_order), 1413 .header_length = cpu_to_be32(header_length), 1414 }; 1415 1416 /* For older versions, write a shorter header */ 1417 switch (s->qcow_version) { 1418 case 2: 1419 ret = offsetof(QCowHeader, incompatible_features); 1420 break; 1421 case 3: 1422 ret = sizeof(*header); 1423 break; 1424 default: 1425 ret = -EINVAL; 1426 goto fail; 1427 } 1428 1429 buf += ret; 1430 buflen -= ret; 1431 memset(buf, 0, buflen); 1432 1433 /* Preserve any unknown field in the header */ 1434 if (s->unknown_header_fields_size) { 1435 if (buflen < s->unknown_header_fields_size) { 1436 ret = -ENOSPC; 1437 goto fail; 1438 } 1439 1440 memcpy(buf, s->unknown_header_fields, s->unknown_header_fields_size); 1441 buf += s->unknown_header_fields_size; 1442 buflen -= s->unknown_header_fields_size; 1443 } 1444 1445 /* Backing file format header extension */ 1446 if (*bs->backing_format) { 1447 ret = header_ext_add(buf, QCOW2_EXT_MAGIC_BACKING_FORMAT, 1448 bs->backing_format, strlen(bs->backing_format), 1449 buflen); 1450 if (ret < 0) { 1451 goto fail; 1452 } 1453 1454 buf += ret; 1455 buflen -= ret; 1456 } 1457 1458 /* Feature table */ 1459 Qcow2Feature features[] = { 1460 { 1461 .type = QCOW2_FEAT_TYPE_INCOMPATIBLE, 1462 .bit = QCOW2_INCOMPAT_DIRTY_BITNR, 1463 .name = "dirty bit", 1464 }, 1465 { 1466 .type = QCOW2_FEAT_TYPE_INCOMPATIBLE, 1467 .bit = QCOW2_INCOMPAT_CORRUPT_BITNR, 1468 .name = "corrupt bit", 1469 }, 1470 { 1471 .type = QCOW2_FEAT_TYPE_COMPATIBLE, 1472 .bit = QCOW2_COMPAT_LAZY_REFCOUNTS_BITNR, 1473 .name = "lazy refcounts", 1474 }, 1475 }; 1476 1477 ret = header_ext_add(buf, QCOW2_EXT_MAGIC_FEATURE_TABLE, 1478 features, sizeof(features), buflen); 1479 if (ret < 0) { 1480 goto fail; 1481 } 1482 buf += ret; 1483 buflen -= ret; 1484 1485 /* Keep unknown header extensions */ 1486 QLIST_FOREACH(uext, &s->unknown_header_ext, next) { 1487 ret = header_ext_add(buf, uext->magic, uext->data, uext->len, buflen); 1488 if (ret < 0) { 1489 goto fail; 1490 } 1491 1492 buf += ret; 1493 buflen -= ret; 1494 } 1495 1496 /* End of header extensions */ 1497 ret = header_ext_add(buf, QCOW2_EXT_MAGIC_END, NULL, 0, buflen); 1498 if (ret < 0) { 1499 goto fail; 1500 } 1501 1502 buf += ret; 1503 buflen -= ret; 1504 1505 /* Backing file name */ 1506 if (*bs->backing_file) { 1507 size_t backing_file_len = strlen(bs->backing_file); 1508 1509 if (buflen < backing_file_len) { 1510 ret = -ENOSPC; 1511 goto fail; 1512 } 1513 1514 /* Using strncpy is ok here, since buf is not NUL-terminated. */ 1515 strncpy(buf, bs->backing_file, buflen); 1516 1517 header->backing_file_offset = cpu_to_be64(buf - ((char*) header)); 1518 header->backing_file_size = cpu_to_be32(backing_file_len); 1519 } 1520 1521 /* Write the new header */ 1522 ret = bdrv_pwrite(bs->file, 0, header, s->cluster_size); 1523 if (ret < 0) { 1524 goto fail; 1525 } 1526 1527 ret = 0; 1528 fail: 1529 qemu_vfree(header); 1530 return ret; 1531 } 1532 1533 static int qcow2_change_backing_file(BlockDriverState *bs, 1534 const char *backing_file, const char *backing_fmt) 1535 { 1536 pstrcpy(bs->backing_file, sizeof(bs->backing_file), backing_file ?: ""); 1537 pstrcpy(bs->backing_format, sizeof(bs->backing_format), backing_fmt ?: ""); 1538 1539 return qcow2_update_header(bs); 1540 } 1541 1542 static int preallocate(BlockDriverState *bs) 1543 { 1544 uint64_t nb_sectors; 1545 uint64_t offset; 1546 uint64_t host_offset = 0; 1547 int num; 1548 int ret; 1549 QCowL2Meta *meta; 1550 1551 nb_sectors = bdrv_getlength(bs) >> BDRV_SECTOR_BITS; 1552 offset = 0; 1553 1554 while (nb_sectors) { 1555 num = MIN(nb_sectors, INT_MAX >> BDRV_SECTOR_BITS); 1556 ret = qcow2_alloc_cluster_offset(bs, offset, &num, 1557 &host_offset, &meta); 1558 if (ret < 0) { 1559 return ret; 1560 } 1561 1562 while (meta) { 1563 QCowL2Meta *next = meta->next; 1564 1565 ret = qcow2_alloc_cluster_link_l2(bs, meta); 1566 if (ret < 0) { 1567 qcow2_free_any_clusters(bs, meta->alloc_offset, 1568 meta->nb_clusters, QCOW2_DISCARD_NEVER); 1569 return ret; 1570 } 1571 1572 /* There are no dependent requests, but we need to remove our 1573 * request from the list of in-flight requests */ 1574 QLIST_REMOVE(meta, next_in_flight); 1575 1576 g_free(meta); 1577 meta = next; 1578 } 1579 1580 /* TODO Preallocate data if requested */ 1581 1582 nb_sectors -= num; 1583 offset += num << BDRV_SECTOR_BITS; 1584 } 1585 1586 /* 1587 * It is expected that the image file is large enough to actually contain 1588 * all of the allocated clusters (otherwise we get failing reads after 1589 * EOF). Extend the image to the last allocated sector. 1590 */ 1591 if (host_offset != 0) { 1592 uint8_t buf[BDRV_SECTOR_SIZE]; 1593 memset(buf, 0, BDRV_SECTOR_SIZE); 1594 ret = bdrv_write(bs->file, (host_offset >> BDRV_SECTOR_BITS) + num - 1, 1595 buf, 1); 1596 if (ret < 0) { 1597 return ret; 1598 } 1599 } 1600 1601 return 0; 1602 } 1603 1604 static int qcow2_create2(const char *filename, int64_t total_size, 1605 const char *backing_file, const char *backing_format, 1606 int flags, size_t cluster_size, int prealloc, 1607 QemuOpts *opts, int version, 1608 Error **errp) 1609 { 1610 /* Calculate cluster_bits */ 1611 int cluster_bits; 1612 cluster_bits = ffs(cluster_size) - 1; 1613 if (cluster_bits < MIN_CLUSTER_BITS || cluster_bits > MAX_CLUSTER_BITS || 1614 (1 << cluster_bits) != cluster_size) 1615 { 1616 error_setg(errp, "Cluster size must be a power of two between %d and " 1617 "%dk", 1 << MIN_CLUSTER_BITS, 1 << (MAX_CLUSTER_BITS - 10)); 1618 return -EINVAL; 1619 } 1620 1621 /* 1622 * Open the image file and write a minimal qcow2 header. 1623 * 1624 * We keep things simple and start with a zero-sized image. We also 1625 * do without refcount blocks or a L1 table for now. We'll fix the 1626 * inconsistency later. 1627 * 1628 * We do need a refcount table because growing the refcount table means 1629 * allocating two new refcount blocks - the seconds of which would be at 1630 * 2 GB for 64k clusters, and we don't want to have a 2 GB initial file 1631 * size for any qcow2 image. 1632 */ 1633 BlockDriverState* bs; 1634 QCowHeader *header; 1635 uint64_t* refcount_table; 1636 Error *local_err = NULL; 1637 int ret; 1638 1639 ret = bdrv_create_file(filename, opts, &local_err); 1640 if (ret < 0) { 1641 error_propagate(errp, local_err); 1642 return ret; 1643 } 1644 1645 bs = NULL; 1646 ret = bdrv_open(&bs, filename, NULL, NULL, BDRV_O_RDWR | BDRV_O_PROTOCOL, 1647 NULL, &local_err); 1648 if (ret < 0) { 1649 error_propagate(errp, local_err); 1650 return ret; 1651 } 1652 1653 /* Write the header */ 1654 QEMU_BUILD_BUG_ON((1 << MIN_CLUSTER_BITS) < sizeof(*header)); 1655 header = g_malloc0(cluster_size); 1656 *header = (QCowHeader) { 1657 .magic = cpu_to_be32(QCOW_MAGIC), 1658 .version = cpu_to_be32(version), 1659 .cluster_bits = cpu_to_be32(cluster_bits), 1660 .size = cpu_to_be64(0), 1661 .l1_table_offset = cpu_to_be64(0), 1662 .l1_size = cpu_to_be32(0), 1663 .refcount_table_offset = cpu_to_be64(cluster_size), 1664 .refcount_table_clusters = cpu_to_be32(1), 1665 .refcount_order = cpu_to_be32(3 + REFCOUNT_SHIFT), 1666 .header_length = cpu_to_be32(sizeof(*header)), 1667 }; 1668 1669 if (flags & BLOCK_FLAG_ENCRYPT) { 1670 header->crypt_method = cpu_to_be32(QCOW_CRYPT_AES); 1671 } else { 1672 header->crypt_method = cpu_to_be32(QCOW_CRYPT_NONE); 1673 } 1674 1675 if (flags & BLOCK_FLAG_LAZY_REFCOUNTS) { 1676 header->compatible_features |= 1677 cpu_to_be64(QCOW2_COMPAT_LAZY_REFCOUNTS); 1678 } 1679 1680 ret = bdrv_pwrite(bs, 0, header, cluster_size); 1681 g_free(header); 1682 if (ret < 0) { 1683 error_setg_errno(errp, -ret, "Could not write qcow2 header"); 1684 goto out; 1685 } 1686 1687 /* Write a refcount table with one refcount block */ 1688 refcount_table = g_malloc0(2 * cluster_size); 1689 refcount_table[0] = cpu_to_be64(2 * cluster_size); 1690 ret = bdrv_pwrite(bs, cluster_size, refcount_table, 2 * cluster_size); 1691 g_free(refcount_table); 1692 1693 if (ret < 0) { 1694 error_setg_errno(errp, -ret, "Could not write refcount table"); 1695 goto out; 1696 } 1697 1698 bdrv_unref(bs); 1699 bs = NULL; 1700 1701 /* 1702 * And now open the image and make it consistent first (i.e. increase the 1703 * refcount of the cluster that is occupied by the header and the refcount 1704 * table) 1705 */ 1706 BlockDriver* drv = bdrv_find_format("qcow2"); 1707 assert(drv != NULL); 1708 ret = bdrv_open(&bs, filename, NULL, NULL, 1709 BDRV_O_RDWR | BDRV_O_CACHE_WB | BDRV_O_NO_FLUSH, drv, &local_err); 1710 if (ret < 0) { 1711 error_propagate(errp, local_err); 1712 goto out; 1713 } 1714 1715 ret = qcow2_alloc_clusters(bs, 3 * cluster_size); 1716 if (ret < 0) { 1717 error_setg_errno(errp, -ret, "Could not allocate clusters for qcow2 " 1718 "header and refcount table"); 1719 goto out; 1720 1721 } else if (ret != 0) { 1722 error_report("Huh, first cluster in empty image is already in use?"); 1723 abort(); 1724 } 1725 1726 /* Okay, now that we have a valid image, let's give it the right size */ 1727 ret = bdrv_truncate(bs, total_size * BDRV_SECTOR_SIZE); 1728 if (ret < 0) { 1729 error_setg_errno(errp, -ret, "Could not resize image"); 1730 goto out; 1731 } 1732 1733 /* Want a backing file? There you go.*/ 1734 if (backing_file) { 1735 ret = bdrv_change_backing_file(bs, backing_file, backing_format); 1736 if (ret < 0) { 1737 error_setg_errno(errp, -ret, "Could not assign backing file '%s' " 1738 "with format '%s'", backing_file, backing_format); 1739 goto out; 1740 } 1741 } 1742 1743 /* And if we're supposed to preallocate metadata, do that now */ 1744 if (prealloc) { 1745 BDRVQcowState *s = bs->opaque; 1746 qemu_co_mutex_lock(&s->lock); 1747 ret = preallocate(bs); 1748 qemu_co_mutex_unlock(&s->lock); 1749 if (ret < 0) { 1750 error_setg_errno(errp, -ret, "Could not preallocate metadata"); 1751 goto out; 1752 } 1753 } 1754 1755 bdrv_unref(bs); 1756 bs = NULL; 1757 1758 /* Reopen the image without BDRV_O_NO_FLUSH to flush it before returning */ 1759 ret = bdrv_open(&bs, filename, NULL, NULL, 1760 BDRV_O_RDWR | BDRV_O_CACHE_WB | BDRV_O_NO_BACKING, 1761 drv, &local_err); 1762 if (local_err) { 1763 error_propagate(errp, local_err); 1764 goto out; 1765 } 1766 1767 ret = 0; 1768 out: 1769 if (bs) { 1770 bdrv_unref(bs); 1771 } 1772 return ret; 1773 } 1774 1775 static int qcow2_create(const char *filename, QemuOpts *opts, Error **errp) 1776 { 1777 char *backing_file = NULL; 1778 char *backing_fmt = NULL; 1779 char *buf = NULL; 1780 uint64_t sectors = 0; 1781 int flags = 0; 1782 size_t cluster_size = DEFAULT_CLUSTER_SIZE; 1783 int prealloc = 0; 1784 int version = 3; 1785 Error *local_err = NULL; 1786 int ret; 1787 1788 /* Read out options */ 1789 sectors = qemu_opt_get_size_del(opts, BLOCK_OPT_SIZE, 0) / 512; 1790 backing_file = qemu_opt_get_del(opts, BLOCK_OPT_BACKING_FILE); 1791 backing_fmt = qemu_opt_get_del(opts, BLOCK_OPT_BACKING_FMT); 1792 if (qemu_opt_get_bool_del(opts, BLOCK_OPT_ENCRYPT, false)) { 1793 flags |= BLOCK_FLAG_ENCRYPT; 1794 } 1795 cluster_size = qemu_opt_get_size_del(opts, BLOCK_OPT_CLUSTER_SIZE, 1796 DEFAULT_CLUSTER_SIZE); 1797 buf = qemu_opt_get_del(opts, BLOCK_OPT_PREALLOC); 1798 if (!buf || !strcmp(buf, "off")) { 1799 prealloc = 0; 1800 } else if (!strcmp(buf, "metadata")) { 1801 prealloc = 1; 1802 } else { 1803 error_setg(errp, "Invalid preallocation mode: '%s'", buf); 1804 ret = -EINVAL; 1805 goto finish; 1806 } 1807 g_free(buf); 1808 buf = qemu_opt_get_del(opts, BLOCK_OPT_COMPAT_LEVEL); 1809 if (!buf) { 1810 /* keep the default */ 1811 } else if (!strcmp(buf, "0.10")) { 1812 version = 2; 1813 } else if (!strcmp(buf, "1.1")) { 1814 version = 3; 1815 } else { 1816 error_setg(errp, "Invalid compatibility level: '%s'", buf); 1817 ret = -EINVAL; 1818 goto finish; 1819 } 1820 1821 if (qemu_opt_get_bool_del(opts, BLOCK_OPT_LAZY_REFCOUNTS, false)) { 1822 flags |= BLOCK_FLAG_LAZY_REFCOUNTS; 1823 } 1824 1825 if (backing_file && prealloc) { 1826 error_setg(errp, "Backing file and preallocation cannot be used at " 1827 "the same time"); 1828 ret = -EINVAL; 1829 goto finish; 1830 } 1831 1832 if (version < 3 && (flags & BLOCK_FLAG_LAZY_REFCOUNTS)) { 1833 error_setg(errp, "Lazy refcounts only supported with compatibility " 1834 "level 1.1 and above (use compat=1.1 or greater)"); 1835 ret = -EINVAL; 1836 goto finish; 1837 } 1838 1839 ret = qcow2_create2(filename, sectors, backing_file, backing_fmt, flags, 1840 cluster_size, prealloc, opts, version, &local_err); 1841 if (local_err) { 1842 error_propagate(errp, local_err); 1843 } 1844 1845 finish: 1846 g_free(backing_file); 1847 g_free(backing_fmt); 1848 g_free(buf); 1849 return ret; 1850 } 1851 1852 static coroutine_fn int qcow2_co_write_zeroes(BlockDriverState *bs, 1853 int64_t sector_num, int nb_sectors, BdrvRequestFlags flags) 1854 { 1855 int ret; 1856 BDRVQcowState *s = bs->opaque; 1857 1858 /* Emulate misaligned zero writes */ 1859 if (sector_num % s->cluster_sectors || nb_sectors % s->cluster_sectors) { 1860 return -ENOTSUP; 1861 } 1862 1863 /* Whatever is left can use real zero clusters */ 1864 qemu_co_mutex_lock(&s->lock); 1865 ret = qcow2_zero_clusters(bs, sector_num << BDRV_SECTOR_BITS, 1866 nb_sectors); 1867 qemu_co_mutex_unlock(&s->lock); 1868 1869 return ret; 1870 } 1871 1872 static coroutine_fn int qcow2_co_discard(BlockDriverState *bs, 1873 int64_t sector_num, int nb_sectors) 1874 { 1875 int ret; 1876 BDRVQcowState *s = bs->opaque; 1877 1878 qemu_co_mutex_lock(&s->lock); 1879 ret = qcow2_discard_clusters(bs, sector_num << BDRV_SECTOR_BITS, 1880 nb_sectors, QCOW2_DISCARD_REQUEST); 1881 qemu_co_mutex_unlock(&s->lock); 1882 return ret; 1883 } 1884 1885 static int qcow2_truncate(BlockDriverState *bs, int64_t offset) 1886 { 1887 BDRVQcowState *s = bs->opaque; 1888 int64_t new_l1_size; 1889 int ret; 1890 1891 if (offset & 511) { 1892 error_report("The new size must be a multiple of 512"); 1893 return -EINVAL; 1894 } 1895 1896 /* cannot proceed if image has snapshots */ 1897 if (s->nb_snapshots) { 1898 error_report("Can't resize an image which has snapshots"); 1899 return -ENOTSUP; 1900 } 1901 1902 /* shrinking is currently not supported */ 1903 if (offset < bs->total_sectors * 512) { 1904 error_report("qcow2 doesn't support shrinking images yet"); 1905 return -ENOTSUP; 1906 } 1907 1908 new_l1_size = size_to_l1(s, offset); 1909 ret = qcow2_grow_l1_table(bs, new_l1_size, true); 1910 if (ret < 0) { 1911 return ret; 1912 } 1913 1914 /* write updated header.size */ 1915 offset = cpu_to_be64(offset); 1916 ret = bdrv_pwrite_sync(bs->file, offsetof(QCowHeader, size), 1917 &offset, sizeof(uint64_t)); 1918 if (ret < 0) { 1919 return ret; 1920 } 1921 1922 s->l1_vm_state_index = new_l1_size; 1923 return 0; 1924 } 1925 1926 /* XXX: put compressed sectors first, then all the cluster aligned 1927 tables to avoid losing bytes in alignment */ 1928 static int qcow2_write_compressed(BlockDriverState *bs, int64_t sector_num, 1929 const uint8_t *buf, int nb_sectors) 1930 { 1931 BDRVQcowState *s = bs->opaque; 1932 z_stream strm; 1933 int ret, out_len; 1934 uint8_t *out_buf; 1935 uint64_t cluster_offset; 1936 1937 if (nb_sectors == 0) { 1938 /* align end of file to a sector boundary to ease reading with 1939 sector based I/Os */ 1940 cluster_offset = bdrv_getlength(bs->file); 1941 cluster_offset = (cluster_offset + 511) & ~511; 1942 bdrv_truncate(bs->file, cluster_offset); 1943 return 0; 1944 } 1945 1946 if (nb_sectors != s->cluster_sectors) { 1947 ret = -EINVAL; 1948 1949 /* Zero-pad last write if image size is not cluster aligned */ 1950 if (sector_num + nb_sectors == bs->total_sectors && 1951 nb_sectors < s->cluster_sectors) { 1952 uint8_t *pad_buf = qemu_blockalign(bs, s->cluster_size); 1953 memset(pad_buf, 0, s->cluster_size); 1954 memcpy(pad_buf, buf, nb_sectors * BDRV_SECTOR_SIZE); 1955 ret = qcow2_write_compressed(bs, sector_num, 1956 pad_buf, s->cluster_sectors); 1957 qemu_vfree(pad_buf); 1958 } 1959 return ret; 1960 } 1961 1962 out_buf = g_malloc(s->cluster_size + (s->cluster_size / 1000) + 128); 1963 1964 /* best compression, small window, no zlib header */ 1965 memset(&strm, 0, sizeof(strm)); 1966 ret = deflateInit2(&strm, Z_DEFAULT_COMPRESSION, 1967 Z_DEFLATED, -12, 1968 9, Z_DEFAULT_STRATEGY); 1969 if (ret != 0) { 1970 ret = -EINVAL; 1971 goto fail; 1972 } 1973 1974 strm.avail_in = s->cluster_size; 1975 strm.next_in = (uint8_t *)buf; 1976 strm.avail_out = s->cluster_size; 1977 strm.next_out = out_buf; 1978 1979 ret = deflate(&strm, Z_FINISH); 1980 if (ret != Z_STREAM_END && ret != Z_OK) { 1981 deflateEnd(&strm); 1982 ret = -EINVAL; 1983 goto fail; 1984 } 1985 out_len = strm.next_out - out_buf; 1986 1987 deflateEnd(&strm); 1988 1989 if (ret != Z_STREAM_END || out_len >= s->cluster_size) { 1990 /* could not compress: write normal cluster */ 1991 ret = bdrv_write(bs, sector_num, buf, s->cluster_sectors); 1992 if (ret < 0) { 1993 goto fail; 1994 } 1995 } else { 1996 cluster_offset = qcow2_alloc_compressed_cluster_offset(bs, 1997 sector_num << 9, out_len); 1998 if (!cluster_offset) { 1999 ret = -EIO; 2000 goto fail; 2001 } 2002 cluster_offset &= s->cluster_offset_mask; 2003 2004 ret = qcow2_pre_write_overlap_check(bs, 0, cluster_offset, out_len); 2005 if (ret < 0) { 2006 goto fail; 2007 } 2008 2009 BLKDBG_EVENT(bs->file, BLKDBG_WRITE_COMPRESSED); 2010 ret = bdrv_pwrite(bs->file, cluster_offset, out_buf, out_len); 2011 if (ret < 0) { 2012 goto fail; 2013 } 2014 } 2015 2016 ret = 0; 2017 fail: 2018 g_free(out_buf); 2019 return ret; 2020 } 2021 2022 static coroutine_fn int qcow2_co_flush_to_os(BlockDriverState *bs) 2023 { 2024 BDRVQcowState *s = bs->opaque; 2025 int ret; 2026 2027 qemu_co_mutex_lock(&s->lock); 2028 ret = qcow2_cache_flush(bs, s->l2_table_cache); 2029 if (ret < 0) { 2030 qemu_co_mutex_unlock(&s->lock); 2031 return ret; 2032 } 2033 2034 if (qcow2_need_accurate_refcounts(s)) { 2035 ret = qcow2_cache_flush(bs, s->refcount_block_cache); 2036 if (ret < 0) { 2037 qemu_co_mutex_unlock(&s->lock); 2038 return ret; 2039 } 2040 } 2041 qemu_co_mutex_unlock(&s->lock); 2042 2043 return 0; 2044 } 2045 2046 static int qcow2_get_info(BlockDriverState *bs, BlockDriverInfo *bdi) 2047 { 2048 BDRVQcowState *s = bs->opaque; 2049 bdi->unallocated_blocks_are_zero = true; 2050 bdi->can_write_zeroes_with_unmap = (s->qcow_version >= 3); 2051 bdi->cluster_size = s->cluster_size; 2052 bdi->vm_state_offset = qcow2_vm_state_offset(s); 2053 return 0; 2054 } 2055 2056 static ImageInfoSpecific *qcow2_get_specific_info(BlockDriverState *bs) 2057 { 2058 BDRVQcowState *s = bs->opaque; 2059 ImageInfoSpecific *spec_info = g_new(ImageInfoSpecific, 1); 2060 2061 *spec_info = (ImageInfoSpecific){ 2062 .kind = IMAGE_INFO_SPECIFIC_KIND_QCOW2, 2063 { 2064 .qcow2 = g_new(ImageInfoSpecificQCow2, 1), 2065 }, 2066 }; 2067 if (s->qcow_version == 2) { 2068 *spec_info->qcow2 = (ImageInfoSpecificQCow2){ 2069 .compat = g_strdup("0.10"), 2070 }; 2071 } else if (s->qcow_version == 3) { 2072 *spec_info->qcow2 = (ImageInfoSpecificQCow2){ 2073 .compat = g_strdup("1.1"), 2074 .lazy_refcounts = s->compatible_features & 2075 QCOW2_COMPAT_LAZY_REFCOUNTS, 2076 .has_lazy_refcounts = true, 2077 }; 2078 } 2079 2080 return spec_info; 2081 } 2082 2083 #if 0 2084 static void dump_refcounts(BlockDriverState *bs) 2085 { 2086 BDRVQcowState *s = bs->opaque; 2087 int64_t nb_clusters, k, k1, size; 2088 int refcount; 2089 2090 size = bdrv_getlength(bs->file); 2091 nb_clusters = size_to_clusters(s, size); 2092 for(k = 0; k < nb_clusters;) { 2093 k1 = k; 2094 refcount = get_refcount(bs, k); 2095 k++; 2096 while (k < nb_clusters && get_refcount(bs, k) == refcount) 2097 k++; 2098 printf("%" PRId64 ": refcount=%d nb=%" PRId64 "\n", k, refcount, 2099 k - k1); 2100 } 2101 } 2102 #endif 2103 2104 static int qcow2_save_vmstate(BlockDriverState *bs, QEMUIOVector *qiov, 2105 int64_t pos) 2106 { 2107 BDRVQcowState *s = bs->opaque; 2108 int64_t total_sectors = bs->total_sectors; 2109 int growable = bs->growable; 2110 bool zero_beyond_eof = bs->zero_beyond_eof; 2111 int ret; 2112 2113 BLKDBG_EVENT(bs->file, BLKDBG_VMSTATE_SAVE); 2114 bs->growable = 1; 2115 bs->zero_beyond_eof = false; 2116 ret = bdrv_pwritev(bs, qcow2_vm_state_offset(s) + pos, qiov); 2117 bs->growable = growable; 2118 bs->zero_beyond_eof = zero_beyond_eof; 2119 2120 /* bdrv_co_do_writev will have increased the total_sectors value to include 2121 * the VM state - the VM state is however not an actual part of the block 2122 * device, therefore, we need to restore the old value. */ 2123 bs->total_sectors = total_sectors; 2124 2125 return ret; 2126 } 2127 2128 static int qcow2_load_vmstate(BlockDriverState *bs, uint8_t *buf, 2129 int64_t pos, int size) 2130 { 2131 BDRVQcowState *s = bs->opaque; 2132 int growable = bs->growable; 2133 bool zero_beyond_eof = bs->zero_beyond_eof; 2134 int ret; 2135 2136 BLKDBG_EVENT(bs->file, BLKDBG_VMSTATE_LOAD); 2137 bs->growable = 1; 2138 bs->zero_beyond_eof = false; 2139 ret = bdrv_pread(bs, qcow2_vm_state_offset(s) + pos, buf, size); 2140 bs->growable = growable; 2141 bs->zero_beyond_eof = zero_beyond_eof; 2142 2143 return ret; 2144 } 2145 2146 /* 2147 * Downgrades an image's version. To achieve this, any incompatible features 2148 * have to be removed. 2149 */ 2150 static int qcow2_downgrade(BlockDriverState *bs, int target_version) 2151 { 2152 BDRVQcowState *s = bs->opaque; 2153 int current_version = s->qcow_version; 2154 int ret; 2155 2156 if (target_version == current_version) { 2157 return 0; 2158 } else if (target_version > current_version) { 2159 return -EINVAL; 2160 } else if (target_version != 2) { 2161 return -EINVAL; 2162 } 2163 2164 if (s->refcount_order != 4) { 2165 /* we would have to convert the image to a refcount_order == 4 image 2166 * here; however, since qemu (at the time of writing this) does not 2167 * support anything different than 4 anyway, there is no point in doing 2168 * so right now; however, we should error out (if qemu supports this in 2169 * the future and this code has not been adapted) */ 2170 error_report("qcow2_downgrade: Image refcount orders other than 4 are " 2171 "currently not supported."); 2172 return -ENOTSUP; 2173 } 2174 2175 /* clear incompatible features */ 2176 if (s->incompatible_features & QCOW2_INCOMPAT_DIRTY) { 2177 ret = qcow2_mark_clean(bs); 2178 if (ret < 0) { 2179 return ret; 2180 } 2181 } 2182 2183 /* with QCOW2_INCOMPAT_CORRUPT, it is pretty much impossible to get here in 2184 * the first place; if that happens nonetheless, returning -ENOTSUP is the 2185 * best thing to do anyway */ 2186 2187 if (s->incompatible_features) { 2188 return -ENOTSUP; 2189 } 2190 2191 /* since we can ignore compatible features, we can set them to 0 as well */ 2192 s->compatible_features = 0; 2193 /* if lazy refcounts have been used, they have already been fixed through 2194 * clearing the dirty flag */ 2195 2196 /* clearing autoclear features is trivial */ 2197 s->autoclear_features = 0; 2198 2199 ret = qcow2_expand_zero_clusters(bs); 2200 if (ret < 0) { 2201 return ret; 2202 } 2203 2204 s->qcow_version = target_version; 2205 ret = qcow2_update_header(bs); 2206 if (ret < 0) { 2207 s->qcow_version = current_version; 2208 return ret; 2209 } 2210 return 0; 2211 } 2212 2213 static int qcow2_amend_options(BlockDriverState *bs, QemuOpts *opts) 2214 { 2215 BDRVQcowState *s = bs->opaque; 2216 int old_version = s->qcow_version, new_version = old_version; 2217 uint64_t new_size = 0; 2218 const char *backing_file = NULL, *backing_format = NULL; 2219 bool lazy_refcounts = s->use_lazy_refcounts; 2220 const char *compat = NULL; 2221 uint64_t cluster_size = s->cluster_size; 2222 bool encrypt; 2223 int ret; 2224 QemuOptDesc *desc = opts->list->desc; 2225 2226 while (desc && desc->name) { 2227 if (!qemu_opt_find(opts, desc->name)) { 2228 /* only change explicitly defined options */ 2229 desc++; 2230 continue; 2231 } 2232 2233 if (!strcmp(desc->name, "compat")) { 2234 compat = qemu_opt_get(opts, "compat"); 2235 if (!compat) { 2236 /* preserve default */ 2237 } else if (!strcmp(compat, "0.10")) { 2238 new_version = 2; 2239 } else if (!strcmp(compat, "1.1")) { 2240 new_version = 3; 2241 } else { 2242 fprintf(stderr, "Unknown compatibility level %s.\n", compat); 2243 return -EINVAL; 2244 } 2245 } else if (!strcmp(desc->name, "preallocation")) { 2246 fprintf(stderr, "Cannot change preallocation mode.\n"); 2247 return -ENOTSUP; 2248 } else if (!strcmp(desc->name, "size")) { 2249 new_size = qemu_opt_get_size(opts, "size", 0); 2250 } else if (!strcmp(desc->name, "backing_file")) { 2251 backing_file = qemu_opt_get(opts, "backing_file"); 2252 } else if (!strcmp(desc->name, "backing_fmt")) { 2253 backing_format = qemu_opt_get(opts, "backing_fmt"); 2254 } else if (!strcmp(desc->name, "encryption")) { 2255 encrypt = qemu_opt_get_bool(opts, "encryption", s->crypt_method); 2256 if (encrypt != !!s->crypt_method) { 2257 fprintf(stderr, "Changing the encryption flag is not " 2258 "supported.\n"); 2259 return -ENOTSUP; 2260 } 2261 } else if (!strcmp(desc->name, "cluster_size")) { 2262 cluster_size = qemu_opt_get_size(opts, "cluster_size", 2263 cluster_size); 2264 if (cluster_size != s->cluster_size) { 2265 fprintf(stderr, "Changing the cluster size is not " 2266 "supported.\n"); 2267 return -ENOTSUP; 2268 } 2269 } else if (!strcmp(desc->name, "lazy_refcounts")) { 2270 lazy_refcounts = qemu_opt_get_bool(opts, "lazy_refcounts", 2271 lazy_refcounts); 2272 } else { 2273 /* if this assertion fails, this probably means a new option was 2274 * added without having it covered here */ 2275 assert(false); 2276 } 2277 2278 desc++; 2279 } 2280 2281 if (new_version != old_version) { 2282 if (new_version > old_version) { 2283 /* Upgrade */ 2284 s->qcow_version = new_version; 2285 ret = qcow2_update_header(bs); 2286 if (ret < 0) { 2287 s->qcow_version = old_version; 2288 return ret; 2289 } 2290 } else { 2291 ret = qcow2_downgrade(bs, new_version); 2292 if (ret < 0) { 2293 return ret; 2294 } 2295 } 2296 } 2297 2298 if (backing_file || backing_format) { 2299 ret = qcow2_change_backing_file(bs, backing_file ?: bs->backing_file, 2300 backing_format ?: bs->backing_format); 2301 if (ret < 0) { 2302 return ret; 2303 } 2304 } 2305 2306 if (s->use_lazy_refcounts != lazy_refcounts) { 2307 if (lazy_refcounts) { 2308 if (s->qcow_version < 3) { 2309 fprintf(stderr, "Lazy refcounts only supported with compatibility " 2310 "level 1.1 and above (use compat=1.1 or greater)\n"); 2311 return -EINVAL; 2312 } 2313 s->compatible_features |= QCOW2_COMPAT_LAZY_REFCOUNTS; 2314 ret = qcow2_update_header(bs); 2315 if (ret < 0) { 2316 s->compatible_features &= ~QCOW2_COMPAT_LAZY_REFCOUNTS; 2317 return ret; 2318 } 2319 s->use_lazy_refcounts = true; 2320 } else { 2321 /* make image clean first */ 2322 ret = qcow2_mark_clean(bs); 2323 if (ret < 0) { 2324 return ret; 2325 } 2326 /* now disallow lazy refcounts */ 2327 s->compatible_features &= ~QCOW2_COMPAT_LAZY_REFCOUNTS; 2328 ret = qcow2_update_header(bs); 2329 if (ret < 0) { 2330 s->compatible_features |= QCOW2_COMPAT_LAZY_REFCOUNTS; 2331 return ret; 2332 } 2333 s->use_lazy_refcounts = false; 2334 } 2335 } 2336 2337 if (new_size) { 2338 ret = bdrv_truncate(bs, new_size); 2339 if (ret < 0) { 2340 return ret; 2341 } 2342 } 2343 2344 return 0; 2345 } 2346 2347 static QemuOptsList qcow2_create_opts = { 2348 .name = "qcow2-create-opts", 2349 .head = QTAILQ_HEAD_INITIALIZER(qcow2_create_opts.head), 2350 .desc = { 2351 { 2352 .name = BLOCK_OPT_SIZE, 2353 .type = QEMU_OPT_SIZE, 2354 .help = "Virtual disk size" 2355 }, 2356 { 2357 .name = BLOCK_OPT_COMPAT_LEVEL, 2358 .type = QEMU_OPT_STRING, 2359 .help = "Compatibility level (0.10 or 1.1)" 2360 }, 2361 { 2362 .name = BLOCK_OPT_BACKING_FILE, 2363 .type = QEMU_OPT_STRING, 2364 .help = "File name of a base image" 2365 }, 2366 { 2367 .name = BLOCK_OPT_BACKING_FMT, 2368 .type = QEMU_OPT_STRING, 2369 .help = "Image format of the base image" 2370 }, 2371 { 2372 .name = BLOCK_OPT_ENCRYPT, 2373 .type = QEMU_OPT_BOOL, 2374 .help = "Encrypt the image", 2375 .def_value_str = "off" 2376 }, 2377 { 2378 .name = BLOCK_OPT_CLUSTER_SIZE, 2379 .type = QEMU_OPT_SIZE, 2380 .help = "qcow2 cluster size", 2381 .def_value_str = stringify(DEFAULT_CLUSTER_SIZE) 2382 }, 2383 { 2384 .name = BLOCK_OPT_PREALLOC, 2385 .type = QEMU_OPT_STRING, 2386 .help = "Preallocation mode (allowed values: off, metadata)" 2387 }, 2388 { 2389 .name = BLOCK_OPT_LAZY_REFCOUNTS, 2390 .type = QEMU_OPT_BOOL, 2391 .help = "Postpone refcount updates", 2392 .def_value_str = "off" 2393 }, 2394 { /* end of list */ } 2395 } 2396 }; 2397 2398 static BlockDriver bdrv_qcow2 = { 2399 .format_name = "qcow2", 2400 .instance_size = sizeof(BDRVQcowState), 2401 .bdrv_probe = qcow2_probe, 2402 .bdrv_open = qcow2_open, 2403 .bdrv_close = qcow2_close, 2404 .bdrv_reopen_prepare = qcow2_reopen_prepare, 2405 .bdrv_create = qcow2_create, 2406 .bdrv_has_zero_init = bdrv_has_zero_init_1, 2407 .bdrv_co_get_block_status = qcow2_co_get_block_status, 2408 .bdrv_set_key = qcow2_set_key, 2409 2410 .bdrv_co_readv = qcow2_co_readv, 2411 .bdrv_co_writev = qcow2_co_writev, 2412 .bdrv_co_flush_to_os = qcow2_co_flush_to_os, 2413 2414 .bdrv_co_write_zeroes = qcow2_co_write_zeroes, 2415 .bdrv_co_discard = qcow2_co_discard, 2416 .bdrv_truncate = qcow2_truncate, 2417 .bdrv_write_compressed = qcow2_write_compressed, 2418 2419 .bdrv_snapshot_create = qcow2_snapshot_create, 2420 .bdrv_snapshot_goto = qcow2_snapshot_goto, 2421 .bdrv_snapshot_delete = qcow2_snapshot_delete, 2422 .bdrv_snapshot_list = qcow2_snapshot_list, 2423 .bdrv_snapshot_load_tmp = qcow2_snapshot_load_tmp, 2424 .bdrv_get_info = qcow2_get_info, 2425 .bdrv_get_specific_info = qcow2_get_specific_info, 2426 2427 .bdrv_save_vmstate = qcow2_save_vmstate, 2428 .bdrv_load_vmstate = qcow2_load_vmstate, 2429 2430 .supports_backing = true, 2431 .bdrv_change_backing_file = qcow2_change_backing_file, 2432 2433 .bdrv_refresh_limits = qcow2_refresh_limits, 2434 .bdrv_invalidate_cache = qcow2_invalidate_cache, 2435 2436 .create_opts = &qcow2_create_opts, 2437 .bdrv_check = qcow2_check, 2438 .bdrv_amend_options = qcow2_amend_options, 2439 }; 2440 2441 static void bdrv_qcow2_init(void) 2442 { 2443 bdrv_register(&bdrv_qcow2); 2444 } 2445 2446 block_init(bdrv_qcow2_init); 2447