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_int.h" 26 #include "module.h" 27 #include <zlib.h> 28 #include "aes.h" 29 #include "block/qcow2.h" 30 #include "qemu-error.h" 31 #include "qerror.h" 32 #include "trace.h" 33 34 /* 35 Differences with QCOW: 36 37 - Support for multiple incremental snapshots. 38 - Memory management by reference counts. 39 - Clusters which have a reference count of one have the bit 40 QCOW_OFLAG_COPIED to optimize write performance. 41 - Size of compressed clusters is stored in sectors to reduce bit usage 42 in the cluster offsets. 43 - Support for storing additional data (such as the VM state) in the 44 snapshots. 45 - If a backing store is used, the cluster size is not constrained 46 (could be backported to QCOW). 47 - L2 tables have always a size of one cluster. 48 */ 49 50 51 typedef struct { 52 uint32_t magic; 53 uint32_t len; 54 } QCowExtension; 55 #define QCOW2_EXT_MAGIC_END 0 56 #define QCOW2_EXT_MAGIC_BACKING_FORMAT 0xE2792ACA 57 #define QCOW2_EXT_MAGIC_FEATURE_TABLE 0x6803f857 58 59 static int qcow2_probe(const uint8_t *buf, int buf_size, const char *filename) 60 { 61 const QCowHeader *cow_header = (const void *)buf; 62 63 if (buf_size >= sizeof(QCowHeader) && 64 be32_to_cpu(cow_header->magic) == QCOW_MAGIC && 65 be32_to_cpu(cow_header->version) >= 2) 66 return 100; 67 else 68 return 0; 69 } 70 71 72 /* 73 * read qcow2 extension and fill bs 74 * start reading from start_offset 75 * finish reading upon magic of value 0 or when end_offset reached 76 * unknown magic is skipped (future extension this version knows nothing about) 77 * return 0 upon success, non-0 otherwise 78 */ 79 static int qcow2_read_extensions(BlockDriverState *bs, uint64_t start_offset, 80 uint64_t end_offset, void **p_feature_table) 81 { 82 BDRVQcowState *s = bs->opaque; 83 QCowExtension ext; 84 uint64_t offset; 85 int ret; 86 87 #ifdef DEBUG_EXT 88 printf("qcow2_read_extensions: start=%ld end=%ld\n", start_offset, end_offset); 89 #endif 90 offset = start_offset; 91 while (offset < end_offset) { 92 93 #ifdef DEBUG_EXT 94 /* Sanity check */ 95 if (offset > s->cluster_size) 96 printf("qcow2_read_extension: suspicious offset %lu\n", offset); 97 98 printf("attempting to read extended header in offset %lu\n", offset); 99 #endif 100 101 if (bdrv_pread(bs->file, offset, &ext, sizeof(ext)) != sizeof(ext)) { 102 fprintf(stderr, "qcow2_read_extension: ERROR: " 103 "pread fail from offset %" PRIu64 "\n", 104 offset); 105 return 1; 106 } 107 be32_to_cpus(&ext.magic); 108 be32_to_cpus(&ext.len); 109 offset += sizeof(ext); 110 #ifdef DEBUG_EXT 111 printf("ext.magic = 0x%x\n", ext.magic); 112 #endif 113 if (ext.len > end_offset - offset) { 114 error_report("Header extension too large"); 115 return -EINVAL; 116 } 117 118 switch (ext.magic) { 119 case QCOW2_EXT_MAGIC_END: 120 return 0; 121 122 case QCOW2_EXT_MAGIC_BACKING_FORMAT: 123 if (ext.len >= sizeof(bs->backing_format)) { 124 fprintf(stderr, "ERROR: ext_backing_format: len=%u too large" 125 " (>=%zu)\n", 126 ext.len, sizeof(bs->backing_format)); 127 return 2; 128 } 129 if (bdrv_pread(bs->file, offset , bs->backing_format, 130 ext.len) != ext.len) 131 return 3; 132 bs->backing_format[ext.len] = '\0'; 133 #ifdef DEBUG_EXT 134 printf("Qcow2: Got format extension %s\n", bs->backing_format); 135 #endif 136 break; 137 138 case QCOW2_EXT_MAGIC_FEATURE_TABLE: 139 if (p_feature_table != NULL) { 140 void* feature_table = g_malloc0(ext.len + 2 * sizeof(Qcow2Feature)); 141 ret = bdrv_pread(bs->file, offset , feature_table, ext.len); 142 if (ret < 0) { 143 return ret; 144 } 145 146 *p_feature_table = feature_table; 147 } 148 break; 149 150 default: 151 /* unknown magic - save it in case we need to rewrite the header */ 152 { 153 Qcow2UnknownHeaderExtension *uext; 154 155 uext = g_malloc0(sizeof(*uext) + ext.len); 156 uext->magic = ext.magic; 157 uext->len = ext.len; 158 QLIST_INSERT_HEAD(&s->unknown_header_ext, uext, next); 159 160 ret = bdrv_pread(bs->file, offset , uext->data, uext->len); 161 if (ret < 0) { 162 return ret; 163 } 164 } 165 break; 166 } 167 168 offset += ((ext.len + 7) & ~7); 169 } 170 171 return 0; 172 } 173 174 static void cleanup_unknown_header_ext(BlockDriverState *bs) 175 { 176 BDRVQcowState *s = bs->opaque; 177 Qcow2UnknownHeaderExtension *uext, *next; 178 179 QLIST_FOREACH_SAFE(uext, &s->unknown_header_ext, next, next) { 180 QLIST_REMOVE(uext, next); 181 g_free(uext); 182 } 183 } 184 185 static void GCC_FMT_ATTR(2, 3) report_unsupported(BlockDriverState *bs, 186 const char *fmt, ...) 187 { 188 char msg[64]; 189 va_list ap; 190 191 va_start(ap, fmt); 192 vsnprintf(msg, sizeof(msg), fmt, ap); 193 va_end(ap); 194 195 qerror_report(QERR_UNKNOWN_BLOCK_FORMAT_FEATURE, 196 bs->device_name, "qcow2", msg); 197 } 198 199 static void report_unsupported_feature(BlockDriverState *bs, 200 Qcow2Feature *table, uint64_t mask) 201 { 202 while (table && table->name[0] != '\0') { 203 if (table->type == QCOW2_FEAT_TYPE_INCOMPATIBLE) { 204 if (mask & (1 << table->bit)) { 205 report_unsupported(bs, "%.46s",table->name); 206 mask &= ~(1 << table->bit); 207 } 208 } 209 table++; 210 } 211 212 if (mask) { 213 report_unsupported(bs, "Unknown incompatible feature: %" PRIx64, mask); 214 } 215 } 216 217 static int qcow2_open(BlockDriverState *bs, int flags) 218 { 219 BDRVQcowState *s = bs->opaque; 220 int len, i, ret = 0; 221 QCowHeader header; 222 uint64_t ext_end; 223 224 ret = bdrv_pread(bs->file, 0, &header, sizeof(header)); 225 if (ret < 0) { 226 goto fail; 227 } 228 be32_to_cpus(&header.magic); 229 be32_to_cpus(&header.version); 230 be64_to_cpus(&header.backing_file_offset); 231 be32_to_cpus(&header.backing_file_size); 232 be64_to_cpus(&header.size); 233 be32_to_cpus(&header.cluster_bits); 234 be32_to_cpus(&header.crypt_method); 235 be64_to_cpus(&header.l1_table_offset); 236 be32_to_cpus(&header.l1_size); 237 be64_to_cpus(&header.refcount_table_offset); 238 be32_to_cpus(&header.refcount_table_clusters); 239 be64_to_cpus(&header.snapshots_offset); 240 be32_to_cpus(&header.nb_snapshots); 241 242 if (header.magic != QCOW_MAGIC) { 243 ret = -EINVAL; 244 goto fail; 245 } 246 if (header.version < 2 || header.version > 3) { 247 report_unsupported(bs, "QCOW version %d", header.version); 248 ret = -ENOTSUP; 249 goto fail; 250 } 251 252 s->qcow_version = header.version; 253 254 /* Initialise version 3 header fields */ 255 if (header.version == 2) { 256 header.incompatible_features = 0; 257 header.compatible_features = 0; 258 header.autoclear_features = 0; 259 header.refcount_order = 4; 260 header.header_length = 72; 261 } else { 262 be64_to_cpus(&header.incompatible_features); 263 be64_to_cpus(&header.compatible_features); 264 be64_to_cpus(&header.autoclear_features); 265 be32_to_cpus(&header.refcount_order); 266 be32_to_cpus(&header.header_length); 267 } 268 269 if (header.header_length > sizeof(header)) { 270 s->unknown_header_fields_size = header.header_length - sizeof(header); 271 s->unknown_header_fields = g_malloc(s->unknown_header_fields_size); 272 ret = bdrv_pread(bs->file, sizeof(header), s->unknown_header_fields, 273 s->unknown_header_fields_size); 274 if (ret < 0) { 275 goto fail; 276 } 277 } 278 279 if (header.backing_file_offset) { 280 ext_end = header.backing_file_offset; 281 } else { 282 ext_end = 1 << header.cluster_bits; 283 } 284 285 /* Handle feature bits */ 286 s->incompatible_features = header.incompatible_features; 287 s->compatible_features = header.compatible_features; 288 s->autoclear_features = header.autoclear_features; 289 290 if (s->incompatible_features != 0) { 291 void *feature_table = NULL; 292 qcow2_read_extensions(bs, header.header_length, ext_end, 293 &feature_table); 294 report_unsupported_feature(bs, feature_table, 295 s->incompatible_features); 296 ret = -ENOTSUP; 297 goto fail; 298 } 299 300 /* Check support for various header values */ 301 if (header.refcount_order != 4) { 302 report_unsupported(bs, "%d bit reference counts", 303 1 << header.refcount_order); 304 ret = -ENOTSUP; 305 goto fail; 306 } 307 308 if (header.cluster_bits < MIN_CLUSTER_BITS || 309 header.cluster_bits > MAX_CLUSTER_BITS) { 310 ret = -EINVAL; 311 goto fail; 312 } 313 if (header.crypt_method > QCOW_CRYPT_AES) { 314 ret = -EINVAL; 315 goto fail; 316 } 317 s->crypt_method_header = header.crypt_method; 318 if (s->crypt_method_header) { 319 bs->encrypted = 1; 320 } 321 s->cluster_bits = header.cluster_bits; 322 s->cluster_size = 1 << s->cluster_bits; 323 s->cluster_sectors = 1 << (s->cluster_bits - 9); 324 s->l2_bits = s->cluster_bits - 3; /* L2 is always one cluster */ 325 s->l2_size = 1 << s->l2_bits; 326 bs->total_sectors = header.size / 512; 327 s->csize_shift = (62 - (s->cluster_bits - 8)); 328 s->csize_mask = (1 << (s->cluster_bits - 8)) - 1; 329 s->cluster_offset_mask = (1LL << s->csize_shift) - 1; 330 s->refcount_table_offset = header.refcount_table_offset; 331 s->refcount_table_size = 332 header.refcount_table_clusters << (s->cluster_bits - 3); 333 334 s->snapshots_offset = header.snapshots_offset; 335 s->nb_snapshots = header.nb_snapshots; 336 337 /* read the level 1 table */ 338 s->l1_size = header.l1_size; 339 s->l1_vm_state_index = size_to_l1(s, header.size); 340 /* the L1 table must contain at least enough entries to put 341 header.size bytes */ 342 if (s->l1_size < s->l1_vm_state_index) { 343 ret = -EINVAL; 344 goto fail; 345 } 346 s->l1_table_offset = header.l1_table_offset; 347 if (s->l1_size > 0) { 348 s->l1_table = g_malloc0( 349 align_offset(s->l1_size * sizeof(uint64_t), 512)); 350 ret = bdrv_pread(bs->file, s->l1_table_offset, s->l1_table, 351 s->l1_size * sizeof(uint64_t)); 352 if (ret < 0) { 353 goto fail; 354 } 355 for(i = 0;i < s->l1_size; i++) { 356 be64_to_cpus(&s->l1_table[i]); 357 } 358 } 359 360 /* alloc L2 table/refcount block cache */ 361 s->l2_table_cache = qcow2_cache_create(bs, L2_CACHE_SIZE); 362 s->refcount_block_cache = qcow2_cache_create(bs, REFCOUNT_CACHE_SIZE); 363 364 s->cluster_cache = g_malloc(s->cluster_size); 365 /* one more sector for decompressed data alignment */ 366 s->cluster_data = qemu_blockalign(bs, QCOW_MAX_CRYPT_CLUSTERS * s->cluster_size 367 + 512); 368 s->cluster_cache_offset = -1; 369 s->flags = flags; 370 371 ret = qcow2_refcount_init(bs); 372 if (ret != 0) { 373 goto fail; 374 } 375 376 QLIST_INIT(&s->cluster_allocs); 377 378 /* read qcow2 extensions */ 379 if (qcow2_read_extensions(bs, header.header_length, ext_end, NULL)) { 380 ret = -EINVAL; 381 goto fail; 382 } 383 384 /* read the backing file name */ 385 if (header.backing_file_offset != 0) { 386 len = header.backing_file_size; 387 if (len > 1023) { 388 len = 1023; 389 } 390 ret = bdrv_pread(bs->file, header.backing_file_offset, 391 bs->backing_file, len); 392 if (ret < 0) { 393 goto fail; 394 } 395 bs->backing_file[len] = '\0'; 396 } 397 398 ret = qcow2_read_snapshots(bs); 399 if (ret < 0) { 400 goto fail; 401 } 402 403 /* Clear unknown autoclear feature bits */ 404 if (!bs->read_only && s->autoclear_features != 0) { 405 s->autoclear_features = 0; 406 ret = qcow2_update_header(bs); 407 if (ret < 0) { 408 goto fail; 409 } 410 } 411 412 /* Initialise locks */ 413 qemu_co_mutex_init(&s->lock); 414 415 #ifdef DEBUG_ALLOC 416 { 417 BdrvCheckResult result = {0}; 418 qcow2_check_refcounts(bs, &result, 0); 419 } 420 #endif 421 return ret; 422 423 fail: 424 g_free(s->unknown_header_fields); 425 cleanup_unknown_header_ext(bs); 426 qcow2_free_snapshots(bs); 427 qcow2_refcount_close(bs); 428 g_free(s->l1_table); 429 if (s->l2_table_cache) { 430 qcow2_cache_destroy(bs, s->l2_table_cache); 431 } 432 g_free(s->cluster_cache); 433 qemu_vfree(s->cluster_data); 434 return ret; 435 } 436 437 static int qcow2_set_key(BlockDriverState *bs, const char *key) 438 { 439 BDRVQcowState *s = bs->opaque; 440 uint8_t keybuf[16]; 441 int len, i; 442 443 memset(keybuf, 0, 16); 444 len = strlen(key); 445 if (len > 16) 446 len = 16; 447 /* XXX: we could compress the chars to 7 bits to increase 448 entropy */ 449 for(i = 0;i < len;i++) { 450 keybuf[i] = key[i]; 451 } 452 s->crypt_method = s->crypt_method_header; 453 454 if (AES_set_encrypt_key(keybuf, 128, &s->aes_encrypt_key) != 0) 455 return -1; 456 if (AES_set_decrypt_key(keybuf, 128, &s->aes_decrypt_key) != 0) 457 return -1; 458 #if 0 459 /* test */ 460 { 461 uint8_t in[16]; 462 uint8_t out[16]; 463 uint8_t tmp[16]; 464 for(i=0;i<16;i++) 465 in[i] = i; 466 AES_encrypt(in, tmp, &s->aes_encrypt_key); 467 AES_decrypt(tmp, out, &s->aes_decrypt_key); 468 for(i = 0; i < 16; i++) 469 printf(" %02x", tmp[i]); 470 printf("\n"); 471 for(i = 0; i < 16; i++) 472 printf(" %02x", out[i]); 473 printf("\n"); 474 } 475 #endif 476 return 0; 477 } 478 479 static int coroutine_fn qcow2_co_is_allocated(BlockDriverState *bs, 480 int64_t sector_num, int nb_sectors, int *pnum) 481 { 482 BDRVQcowState *s = bs->opaque; 483 uint64_t cluster_offset; 484 int ret; 485 486 *pnum = nb_sectors; 487 /* FIXME We can get errors here, but the bdrv_co_is_allocated interface 488 * can't pass them on today */ 489 qemu_co_mutex_lock(&s->lock); 490 ret = qcow2_get_cluster_offset(bs, sector_num << 9, pnum, &cluster_offset); 491 qemu_co_mutex_unlock(&s->lock); 492 if (ret < 0) { 493 *pnum = 0; 494 } 495 496 return (cluster_offset != 0); 497 } 498 499 /* handle reading after the end of the backing file */ 500 int qcow2_backing_read1(BlockDriverState *bs, QEMUIOVector *qiov, 501 int64_t sector_num, int nb_sectors) 502 { 503 int n1; 504 if ((sector_num + nb_sectors) <= bs->total_sectors) 505 return nb_sectors; 506 if (sector_num >= bs->total_sectors) 507 n1 = 0; 508 else 509 n1 = bs->total_sectors - sector_num; 510 511 qemu_iovec_memset(qiov, 512 * n1, 0, 512 * (nb_sectors - n1)); 512 513 return n1; 514 } 515 516 static coroutine_fn int qcow2_co_readv(BlockDriverState *bs, int64_t sector_num, 517 int remaining_sectors, QEMUIOVector *qiov) 518 { 519 BDRVQcowState *s = bs->opaque; 520 int index_in_cluster, n1; 521 int ret; 522 int cur_nr_sectors; /* number of sectors in current iteration */ 523 uint64_t cluster_offset = 0; 524 uint64_t bytes_done = 0; 525 QEMUIOVector hd_qiov; 526 uint8_t *cluster_data = NULL; 527 528 qemu_iovec_init(&hd_qiov, qiov->niov); 529 530 qemu_co_mutex_lock(&s->lock); 531 532 while (remaining_sectors != 0) { 533 534 /* prepare next request */ 535 cur_nr_sectors = remaining_sectors; 536 if (s->crypt_method) { 537 cur_nr_sectors = MIN(cur_nr_sectors, 538 QCOW_MAX_CRYPT_CLUSTERS * s->cluster_sectors); 539 } 540 541 ret = qcow2_get_cluster_offset(bs, sector_num << 9, 542 &cur_nr_sectors, &cluster_offset); 543 if (ret < 0) { 544 goto fail; 545 } 546 547 index_in_cluster = sector_num & (s->cluster_sectors - 1); 548 549 qemu_iovec_reset(&hd_qiov); 550 qemu_iovec_concat(&hd_qiov, qiov, bytes_done, 551 cur_nr_sectors * 512); 552 553 switch (ret) { 554 case QCOW2_CLUSTER_UNALLOCATED: 555 556 if (bs->backing_hd) { 557 /* read from the base image */ 558 n1 = qcow2_backing_read1(bs->backing_hd, &hd_qiov, 559 sector_num, cur_nr_sectors); 560 if (n1 > 0) { 561 BLKDBG_EVENT(bs->file, BLKDBG_READ_BACKING_AIO); 562 qemu_co_mutex_unlock(&s->lock); 563 ret = bdrv_co_readv(bs->backing_hd, sector_num, 564 n1, &hd_qiov); 565 qemu_co_mutex_lock(&s->lock); 566 if (ret < 0) { 567 goto fail; 568 } 569 } 570 } else { 571 /* Note: in this case, no need to wait */ 572 qemu_iovec_memset(&hd_qiov, 0, 0, 512 * cur_nr_sectors); 573 } 574 break; 575 576 case QCOW2_CLUSTER_ZERO: 577 if (s->qcow_version < 3) { 578 ret = -EIO; 579 goto fail; 580 } 581 qemu_iovec_memset(&hd_qiov, 0, 0, 512 * cur_nr_sectors); 582 break; 583 584 case QCOW2_CLUSTER_COMPRESSED: 585 /* add AIO support for compressed blocks ? */ 586 ret = qcow2_decompress_cluster(bs, cluster_offset); 587 if (ret < 0) { 588 goto fail; 589 } 590 591 qemu_iovec_from_buf(&hd_qiov, 0, 592 s->cluster_cache + index_in_cluster * 512, 593 512 * cur_nr_sectors); 594 break; 595 596 case QCOW2_CLUSTER_NORMAL: 597 if ((cluster_offset & 511) != 0) { 598 ret = -EIO; 599 goto fail; 600 } 601 602 if (s->crypt_method) { 603 /* 604 * For encrypted images, read everything into a temporary 605 * contiguous buffer on which the AES functions can work. 606 */ 607 if (!cluster_data) { 608 cluster_data = 609 qemu_blockalign(bs, QCOW_MAX_CRYPT_CLUSTERS * s->cluster_size); 610 } 611 612 assert(cur_nr_sectors <= 613 QCOW_MAX_CRYPT_CLUSTERS * s->cluster_sectors); 614 qemu_iovec_reset(&hd_qiov); 615 qemu_iovec_add(&hd_qiov, cluster_data, 616 512 * cur_nr_sectors); 617 } 618 619 BLKDBG_EVENT(bs->file, BLKDBG_READ_AIO); 620 qemu_co_mutex_unlock(&s->lock); 621 ret = bdrv_co_readv(bs->file, 622 (cluster_offset >> 9) + index_in_cluster, 623 cur_nr_sectors, &hd_qiov); 624 qemu_co_mutex_lock(&s->lock); 625 if (ret < 0) { 626 goto fail; 627 } 628 if (s->crypt_method) { 629 qcow2_encrypt_sectors(s, sector_num, cluster_data, 630 cluster_data, cur_nr_sectors, 0, &s->aes_decrypt_key); 631 qemu_iovec_from_buf(qiov, bytes_done, 632 cluster_data, 512 * cur_nr_sectors); 633 } 634 break; 635 636 default: 637 g_assert_not_reached(); 638 ret = -EIO; 639 goto fail; 640 } 641 642 remaining_sectors -= cur_nr_sectors; 643 sector_num += cur_nr_sectors; 644 bytes_done += cur_nr_sectors * 512; 645 } 646 ret = 0; 647 648 fail: 649 qemu_co_mutex_unlock(&s->lock); 650 651 qemu_iovec_destroy(&hd_qiov); 652 qemu_vfree(cluster_data); 653 654 return ret; 655 } 656 657 static void run_dependent_requests(BDRVQcowState *s, QCowL2Meta *m) 658 { 659 /* Take the request off the list of running requests */ 660 if (m->nb_clusters != 0) { 661 QLIST_REMOVE(m, next_in_flight); 662 } 663 664 /* Restart all dependent requests */ 665 if (!qemu_co_queue_empty(&m->dependent_requests)) { 666 qemu_co_mutex_unlock(&s->lock); 667 qemu_co_queue_restart_all(&m->dependent_requests); 668 qemu_co_mutex_lock(&s->lock); 669 } 670 } 671 672 static coroutine_fn int qcow2_co_writev(BlockDriverState *bs, 673 int64_t sector_num, 674 int remaining_sectors, 675 QEMUIOVector *qiov) 676 { 677 BDRVQcowState *s = bs->opaque; 678 int index_in_cluster; 679 int n_end; 680 int ret; 681 int cur_nr_sectors; /* number of sectors in current iteration */ 682 uint64_t cluster_offset; 683 QEMUIOVector hd_qiov; 684 uint64_t bytes_done = 0; 685 uint8_t *cluster_data = NULL; 686 QCowL2Meta l2meta = { 687 .nb_clusters = 0, 688 }; 689 690 trace_qcow2_writev_start_req(qemu_coroutine_self(), sector_num, 691 remaining_sectors); 692 693 qemu_co_queue_init(&l2meta.dependent_requests); 694 695 qemu_iovec_init(&hd_qiov, qiov->niov); 696 697 s->cluster_cache_offset = -1; /* disable compressed cache */ 698 699 qemu_co_mutex_lock(&s->lock); 700 701 while (remaining_sectors != 0) { 702 703 trace_qcow2_writev_start_part(qemu_coroutine_self()); 704 index_in_cluster = sector_num & (s->cluster_sectors - 1); 705 n_end = index_in_cluster + remaining_sectors; 706 if (s->crypt_method && 707 n_end > QCOW_MAX_CRYPT_CLUSTERS * s->cluster_sectors) { 708 n_end = QCOW_MAX_CRYPT_CLUSTERS * s->cluster_sectors; 709 } 710 711 ret = qcow2_alloc_cluster_offset(bs, sector_num << 9, 712 index_in_cluster, n_end, &cur_nr_sectors, &l2meta); 713 if (ret < 0) { 714 goto fail; 715 } 716 717 cluster_offset = l2meta.cluster_offset; 718 assert((cluster_offset & 511) == 0); 719 720 qemu_iovec_reset(&hd_qiov); 721 qemu_iovec_concat(&hd_qiov, qiov, bytes_done, 722 cur_nr_sectors * 512); 723 724 if (s->crypt_method) { 725 if (!cluster_data) { 726 cluster_data = qemu_blockalign(bs, QCOW_MAX_CRYPT_CLUSTERS * 727 s->cluster_size); 728 } 729 730 assert(hd_qiov.size <= 731 QCOW_MAX_CRYPT_CLUSTERS * s->cluster_size); 732 qemu_iovec_to_buf(&hd_qiov, 0, cluster_data, hd_qiov.size); 733 734 qcow2_encrypt_sectors(s, sector_num, cluster_data, 735 cluster_data, cur_nr_sectors, 1, &s->aes_encrypt_key); 736 737 qemu_iovec_reset(&hd_qiov); 738 qemu_iovec_add(&hd_qiov, cluster_data, 739 cur_nr_sectors * 512); 740 } 741 742 BLKDBG_EVENT(bs->file, BLKDBG_WRITE_AIO); 743 qemu_co_mutex_unlock(&s->lock); 744 trace_qcow2_writev_data(qemu_coroutine_self(), 745 (cluster_offset >> 9) + index_in_cluster); 746 ret = bdrv_co_writev(bs->file, 747 (cluster_offset >> 9) + index_in_cluster, 748 cur_nr_sectors, &hd_qiov); 749 qemu_co_mutex_lock(&s->lock); 750 if (ret < 0) { 751 goto fail; 752 } 753 754 ret = qcow2_alloc_cluster_link_l2(bs, &l2meta); 755 if (ret < 0) { 756 goto fail; 757 } 758 759 run_dependent_requests(s, &l2meta); 760 761 remaining_sectors -= cur_nr_sectors; 762 sector_num += cur_nr_sectors; 763 bytes_done += cur_nr_sectors * 512; 764 trace_qcow2_writev_done_part(qemu_coroutine_self(), cur_nr_sectors); 765 } 766 ret = 0; 767 768 fail: 769 run_dependent_requests(s, &l2meta); 770 771 qemu_co_mutex_unlock(&s->lock); 772 773 qemu_iovec_destroy(&hd_qiov); 774 qemu_vfree(cluster_data); 775 trace_qcow2_writev_done_req(qemu_coroutine_self(), ret); 776 777 return ret; 778 } 779 780 static void qcow2_close(BlockDriverState *bs) 781 { 782 BDRVQcowState *s = bs->opaque; 783 g_free(s->l1_table); 784 785 qcow2_cache_flush(bs, s->l2_table_cache); 786 qcow2_cache_flush(bs, s->refcount_block_cache); 787 788 qcow2_cache_destroy(bs, s->l2_table_cache); 789 qcow2_cache_destroy(bs, s->refcount_block_cache); 790 791 g_free(s->unknown_header_fields); 792 cleanup_unknown_header_ext(bs); 793 794 g_free(s->cluster_cache); 795 qemu_vfree(s->cluster_data); 796 qcow2_refcount_close(bs); 797 qcow2_free_snapshots(bs); 798 } 799 800 static void qcow2_invalidate_cache(BlockDriverState *bs) 801 { 802 BDRVQcowState *s = bs->opaque; 803 int flags = s->flags; 804 AES_KEY aes_encrypt_key; 805 AES_KEY aes_decrypt_key; 806 uint32_t crypt_method = 0; 807 808 /* 809 * Backing files are read-only which makes all of their metadata immutable, 810 * that means we don't have to worry about reopening them here. 811 */ 812 813 if (s->crypt_method) { 814 crypt_method = s->crypt_method; 815 memcpy(&aes_encrypt_key, &s->aes_encrypt_key, sizeof(aes_encrypt_key)); 816 memcpy(&aes_decrypt_key, &s->aes_decrypt_key, sizeof(aes_decrypt_key)); 817 } 818 819 qcow2_close(bs); 820 821 memset(s, 0, sizeof(BDRVQcowState)); 822 qcow2_open(bs, flags); 823 824 if (crypt_method) { 825 s->crypt_method = crypt_method; 826 memcpy(&s->aes_encrypt_key, &aes_encrypt_key, sizeof(aes_encrypt_key)); 827 memcpy(&s->aes_decrypt_key, &aes_decrypt_key, sizeof(aes_decrypt_key)); 828 } 829 } 830 831 static size_t header_ext_add(char *buf, uint32_t magic, const void *s, 832 size_t len, size_t buflen) 833 { 834 QCowExtension *ext_backing_fmt = (QCowExtension*) buf; 835 size_t ext_len = sizeof(QCowExtension) + ((len + 7) & ~7); 836 837 if (buflen < ext_len) { 838 return -ENOSPC; 839 } 840 841 *ext_backing_fmt = (QCowExtension) { 842 .magic = cpu_to_be32(magic), 843 .len = cpu_to_be32(len), 844 }; 845 memcpy(buf + sizeof(QCowExtension), s, len); 846 847 return ext_len; 848 } 849 850 /* 851 * Updates the qcow2 header, including the variable length parts of it, i.e. 852 * the backing file name and all extensions. qcow2 was not designed to allow 853 * such changes, so if we run out of space (we can only use the first cluster) 854 * this function may fail. 855 * 856 * Returns 0 on success, -errno in error cases. 857 */ 858 int qcow2_update_header(BlockDriverState *bs) 859 { 860 BDRVQcowState *s = bs->opaque; 861 QCowHeader *header; 862 char *buf; 863 size_t buflen = s->cluster_size; 864 int ret; 865 uint64_t total_size; 866 uint32_t refcount_table_clusters; 867 size_t header_length; 868 Qcow2UnknownHeaderExtension *uext; 869 870 buf = qemu_blockalign(bs, buflen); 871 872 /* Header structure */ 873 header = (QCowHeader*) buf; 874 875 if (buflen < sizeof(*header)) { 876 ret = -ENOSPC; 877 goto fail; 878 } 879 880 header_length = sizeof(*header) + s->unknown_header_fields_size; 881 total_size = bs->total_sectors * BDRV_SECTOR_SIZE; 882 refcount_table_clusters = s->refcount_table_size >> (s->cluster_bits - 3); 883 884 *header = (QCowHeader) { 885 /* Version 2 fields */ 886 .magic = cpu_to_be32(QCOW_MAGIC), 887 .version = cpu_to_be32(s->qcow_version), 888 .backing_file_offset = 0, 889 .backing_file_size = 0, 890 .cluster_bits = cpu_to_be32(s->cluster_bits), 891 .size = cpu_to_be64(total_size), 892 .crypt_method = cpu_to_be32(s->crypt_method_header), 893 .l1_size = cpu_to_be32(s->l1_size), 894 .l1_table_offset = cpu_to_be64(s->l1_table_offset), 895 .refcount_table_offset = cpu_to_be64(s->refcount_table_offset), 896 .refcount_table_clusters = cpu_to_be32(refcount_table_clusters), 897 .nb_snapshots = cpu_to_be32(s->nb_snapshots), 898 .snapshots_offset = cpu_to_be64(s->snapshots_offset), 899 900 /* Version 3 fields */ 901 .incompatible_features = cpu_to_be64(s->incompatible_features), 902 .compatible_features = cpu_to_be64(s->compatible_features), 903 .autoclear_features = cpu_to_be64(s->autoclear_features), 904 .refcount_order = cpu_to_be32(3 + REFCOUNT_SHIFT), 905 .header_length = cpu_to_be32(header_length), 906 }; 907 908 /* For older versions, write a shorter header */ 909 switch (s->qcow_version) { 910 case 2: 911 ret = offsetof(QCowHeader, incompatible_features); 912 break; 913 case 3: 914 ret = sizeof(*header); 915 break; 916 default: 917 ret = -EINVAL; 918 goto fail; 919 } 920 921 buf += ret; 922 buflen -= ret; 923 memset(buf, 0, buflen); 924 925 /* Preserve any unknown field in the header */ 926 if (s->unknown_header_fields_size) { 927 if (buflen < s->unknown_header_fields_size) { 928 ret = -ENOSPC; 929 goto fail; 930 } 931 932 memcpy(buf, s->unknown_header_fields, s->unknown_header_fields_size); 933 buf += s->unknown_header_fields_size; 934 buflen -= s->unknown_header_fields_size; 935 } 936 937 /* Backing file format header extension */ 938 if (*bs->backing_format) { 939 ret = header_ext_add(buf, QCOW2_EXT_MAGIC_BACKING_FORMAT, 940 bs->backing_format, strlen(bs->backing_format), 941 buflen); 942 if (ret < 0) { 943 goto fail; 944 } 945 946 buf += ret; 947 buflen -= ret; 948 } 949 950 /* Feature table */ 951 Qcow2Feature features[] = { 952 /* no feature defined yet */ 953 }; 954 955 ret = header_ext_add(buf, QCOW2_EXT_MAGIC_FEATURE_TABLE, 956 features, sizeof(features), buflen); 957 if (ret < 0) { 958 goto fail; 959 } 960 buf += ret; 961 buflen -= ret; 962 963 /* Keep unknown header extensions */ 964 QLIST_FOREACH(uext, &s->unknown_header_ext, next) { 965 ret = header_ext_add(buf, uext->magic, uext->data, uext->len, buflen); 966 if (ret < 0) { 967 goto fail; 968 } 969 970 buf += ret; 971 buflen -= ret; 972 } 973 974 /* End of header extensions */ 975 ret = header_ext_add(buf, QCOW2_EXT_MAGIC_END, NULL, 0, buflen); 976 if (ret < 0) { 977 goto fail; 978 } 979 980 buf += ret; 981 buflen -= ret; 982 983 /* Backing file name */ 984 if (*bs->backing_file) { 985 size_t backing_file_len = strlen(bs->backing_file); 986 987 if (buflen < backing_file_len) { 988 ret = -ENOSPC; 989 goto fail; 990 } 991 992 strncpy(buf, bs->backing_file, buflen); 993 994 header->backing_file_offset = cpu_to_be64(buf - ((char*) header)); 995 header->backing_file_size = cpu_to_be32(backing_file_len); 996 } 997 998 /* Write the new header */ 999 ret = bdrv_pwrite(bs->file, 0, header, s->cluster_size); 1000 if (ret < 0) { 1001 goto fail; 1002 } 1003 1004 ret = 0; 1005 fail: 1006 qemu_vfree(header); 1007 return ret; 1008 } 1009 1010 static int qcow2_change_backing_file(BlockDriverState *bs, 1011 const char *backing_file, const char *backing_fmt) 1012 { 1013 pstrcpy(bs->backing_file, sizeof(bs->backing_file), backing_file ?: ""); 1014 pstrcpy(bs->backing_format, sizeof(bs->backing_format), backing_fmt ?: ""); 1015 1016 return qcow2_update_header(bs); 1017 } 1018 1019 static int preallocate(BlockDriverState *bs) 1020 { 1021 uint64_t nb_sectors; 1022 uint64_t offset; 1023 int num; 1024 int ret; 1025 QCowL2Meta meta; 1026 1027 nb_sectors = bdrv_getlength(bs) >> 9; 1028 offset = 0; 1029 qemu_co_queue_init(&meta.dependent_requests); 1030 meta.cluster_offset = 0; 1031 1032 while (nb_sectors) { 1033 num = MIN(nb_sectors, INT_MAX >> 9); 1034 ret = qcow2_alloc_cluster_offset(bs, offset, 0, num, &num, &meta); 1035 if (ret < 0) { 1036 return ret; 1037 } 1038 1039 ret = qcow2_alloc_cluster_link_l2(bs, &meta); 1040 if (ret < 0) { 1041 qcow2_free_any_clusters(bs, meta.cluster_offset, meta.nb_clusters); 1042 return ret; 1043 } 1044 1045 /* There are no dependent requests, but we need to remove our request 1046 * from the list of in-flight requests */ 1047 run_dependent_requests(bs->opaque, &meta); 1048 1049 /* TODO Preallocate data if requested */ 1050 1051 nb_sectors -= num; 1052 offset += num << 9; 1053 } 1054 1055 /* 1056 * It is expected that the image file is large enough to actually contain 1057 * all of the allocated clusters (otherwise we get failing reads after 1058 * EOF). Extend the image to the last allocated sector. 1059 */ 1060 if (meta.cluster_offset != 0) { 1061 uint8_t buf[512]; 1062 memset(buf, 0, 512); 1063 ret = bdrv_write(bs->file, (meta.cluster_offset >> 9) + num - 1, buf, 1); 1064 if (ret < 0) { 1065 return ret; 1066 } 1067 } 1068 1069 return 0; 1070 } 1071 1072 static int qcow2_create2(const char *filename, int64_t total_size, 1073 const char *backing_file, const char *backing_format, 1074 int flags, size_t cluster_size, int prealloc, 1075 QEMUOptionParameter *options, int version) 1076 { 1077 /* Calculate cluster_bits */ 1078 int cluster_bits; 1079 cluster_bits = ffs(cluster_size) - 1; 1080 if (cluster_bits < MIN_CLUSTER_BITS || cluster_bits > MAX_CLUSTER_BITS || 1081 (1 << cluster_bits) != cluster_size) 1082 { 1083 error_report( 1084 "Cluster size must be a power of two between %d and %dk", 1085 1 << MIN_CLUSTER_BITS, 1 << (MAX_CLUSTER_BITS - 10)); 1086 return -EINVAL; 1087 } 1088 1089 /* 1090 * Open the image file and write a minimal qcow2 header. 1091 * 1092 * We keep things simple and start with a zero-sized image. We also 1093 * do without refcount blocks or a L1 table for now. We'll fix the 1094 * inconsistency later. 1095 * 1096 * We do need a refcount table because growing the refcount table means 1097 * allocating two new refcount blocks - the seconds of which would be at 1098 * 2 GB for 64k clusters, and we don't want to have a 2 GB initial file 1099 * size for any qcow2 image. 1100 */ 1101 BlockDriverState* bs; 1102 QCowHeader header; 1103 uint8_t* refcount_table; 1104 int ret; 1105 1106 ret = bdrv_create_file(filename, options); 1107 if (ret < 0) { 1108 return ret; 1109 } 1110 1111 ret = bdrv_file_open(&bs, filename, BDRV_O_RDWR); 1112 if (ret < 0) { 1113 return ret; 1114 } 1115 1116 /* Write the header */ 1117 memset(&header, 0, sizeof(header)); 1118 header.magic = cpu_to_be32(QCOW_MAGIC); 1119 header.version = cpu_to_be32(version); 1120 header.cluster_bits = cpu_to_be32(cluster_bits); 1121 header.size = cpu_to_be64(0); 1122 header.l1_table_offset = cpu_to_be64(0); 1123 header.l1_size = cpu_to_be32(0); 1124 header.refcount_table_offset = cpu_to_be64(cluster_size); 1125 header.refcount_table_clusters = cpu_to_be32(1); 1126 header.refcount_order = cpu_to_be32(3 + REFCOUNT_SHIFT); 1127 header.header_length = cpu_to_be32(sizeof(header)); 1128 1129 if (flags & BLOCK_FLAG_ENCRYPT) { 1130 header.crypt_method = cpu_to_be32(QCOW_CRYPT_AES); 1131 } else { 1132 header.crypt_method = cpu_to_be32(QCOW_CRYPT_NONE); 1133 } 1134 1135 ret = bdrv_pwrite(bs, 0, &header, sizeof(header)); 1136 if (ret < 0) { 1137 goto out; 1138 } 1139 1140 /* Write an empty refcount table */ 1141 refcount_table = g_malloc0(cluster_size); 1142 ret = bdrv_pwrite(bs, cluster_size, refcount_table, cluster_size); 1143 g_free(refcount_table); 1144 1145 if (ret < 0) { 1146 goto out; 1147 } 1148 1149 bdrv_close(bs); 1150 1151 /* 1152 * And now open the image and make it consistent first (i.e. increase the 1153 * refcount of the cluster that is occupied by the header and the refcount 1154 * table) 1155 */ 1156 BlockDriver* drv = bdrv_find_format("qcow2"); 1157 assert(drv != NULL); 1158 ret = bdrv_open(bs, filename, 1159 BDRV_O_RDWR | BDRV_O_CACHE_WB | BDRV_O_NO_FLUSH, drv); 1160 if (ret < 0) { 1161 goto out; 1162 } 1163 1164 ret = qcow2_alloc_clusters(bs, 2 * cluster_size); 1165 if (ret < 0) { 1166 goto out; 1167 1168 } else if (ret != 0) { 1169 error_report("Huh, first cluster in empty image is already in use?"); 1170 abort(); 1171 } 1172 1173 /* Okay, now that we have a valid image, let's give it the right size */ 1174 ret = bdrv_truncate(bs, total_size * BDRV_SECTOR_SIZE); 1175 if (ret < 0) { 1176 goto out; 1177 } 1178 1179 /* Want a backing file? There you go.*/ 1180 if (backing_file) { 1181 ret = bdrv_change_backing_file(bs, backing_file, backing_format); 1182 if (ret < 0) { 1183 goto out; 1184 } 1185 } 1186 1187 /* And if we're supposed to preallocate metadata, do that now */ 1188 if (prealloc) { 1189 BDRVQcowState *s = bs->opaque; 1190 qemu_co_mutex_lock(&s->lock); 1191 ret = preallocate(bs); 1192 qemu_co_mutex_unlock(&s->lock); 1193 if (ret < 0) { 1194 goto out; 1195 } 1196 } 1197 1198 ret = 0; 1199 out: 1200 bdrv_delete(bs); 1201 return ret; 1202 } 1203 1204 static int qcow2_create(const char *filename, QEMUOptionParameter *options) 1205 { 1206 const char *backing_file = NULL; 1207 const char *backing_fmt = NULL; 1208 uint64_t sectors = 0; 1209 int flags = 0; 1210 size_t cluster_size = DEFAULT_CLUSTER_SIZE; 1211 int prealloc = 0; 1212 int version = 2; 1213 1214 /* Read out options */ 1215 while (options && options->name) { 1216 if (!strcmp(options->name, BLOCK_OPT_SIZE)) { 1217 sectors = options->value.n / 512; 1218 } else if (!strcmp(options->name, BLOCK_OPT_BACKING_FILE)) { 1219 backing_file = options->value.s; 1220 } else if (!strcmp(options->name, BLOCK_OPT_BACKING_FMT)) { 1221 backing_fmt = options->value.s; 1222 } else if (!strcmp(options->name, BLOCK_OPT_ENCRYPT)) { 1223 flags |= options->value.n ? BLOCK_FLAG_ENCRYPT : 0; 1224 } else if (!strcmp(options->name, BLOCK_OPT_CLUSTER_SIZE)) { 1225 if (options->value.n) { 1226 cluster_size = options->value.n; 1227 } 1228 } else if (!strcmp(options->name, BLOCK_OPT_PREALLOC)) { 1229 if (!options->value.s || !strcmp(options->value.s, "off")) { 1230 prealloc = 0; 1231 } else if (!strcmp(options->value.s, "metadata")) { 1232 prealloc = 1; 1233 } else { 1234 fprintf(stderr, "Invalid preallocation mode: '%s'\n", 1235 options->value.s); 1236 return -EINVAL; 1237 } 1238 } else if (!strcmp(options->name, BLOCK_OPT_COMPAT_LEVEL)) { 1239 if (!options->value.s || !strcmp(options->value.s, "0.10")) { 1240 version = 2; 1241 } else if (!strcmp(options->value.s, "1.1")) { 1242 version = 3; 1243 } else { 1244 fprintf(stderr, "Invalid compatibility level: '%s'\n", 1245 options->value.s); 1246 return -EINVAL; 1247 } 1248 } 1249 options++; 1250 } 1251 1252 if (backing_file && prealloc) { 1253 fprintf(stderr, "Backing file and preallocation cannot be used at " 1254 "the same time\n"); 1255 return -EINVAL; 1256 } 1257 1258 return qcow2_create2(filename, sectors, backing_file, backing_fmt, flags, 1259 cluster_size, prealloc, options, version); 1260 } 1261 1262 static int qcow2_make_empty(BlockDriverState *bs) 1263 { 1264 #if 0 1265 /* XXX: not correct */ 1266 BDRVQcowState *s = bs->opaque; 1267 uint32_t l1_length = s->l1_size * sizeof(uint64_t); 1268 int ret; 1269 1270 memset(s->l1_table, 0, l1_length); 1271 if (bdrv_pwrite(bs->file, s->l1_table_offset, s->l1_table, l1_length) < 0) 1272 return -1; 1273 ret = bdrv_truncate(bs->file, s->l1_table_offset + l1_length); 1274 if (ret < 0) 1275 return ret; 1276 1277 l2_cache_reset(bs); 1278 #endif 1279 return 0; 1280 } 1281 1282 static coroutine_fn int qcow2_co_write_zeroes(BlockDriverState *bs, 1283 int64_t sector_num, int nb_sectors) 1284 { 1285 int ret; 1286 BDRVQcowState *s = bs->opaque; 1287 1288 /* Emulate misaligned zero writes */ 1289 if (sector_num % s->cluster_sectors || nb_sectors % s->cluster_sectors) { 1290 return -ENOTSUP; 1291 } 1292 1293 /* Whatever is left can use real zero clusters */ 1294 qemu_co_mutex_lock(&s->lock); 1295 ret = qcow2_zero_clusters(bs, sector_num << BDRV_SECTOR_BITS, 1296 nb_sectors); 1297 qemu_co_mutex_unlock(&s->lock); 1298 1299 return ret; 1300 } 1301 1302 static coroutine_fn int qcow2_co_discard(BlockDriverState *bs, 1303 int64_t sector_num, int nb_sectors) 1304 { 1305 int ret; 1306 BDRVQcowState *s = bs->opaque; 1307 1308 qemu_co_mutex_lock(&s->lock); 1309 ret = qcow2_discard_clusters(bs, sector_num << BDRV_SECTOR_BITS, 1310 nb_sectors); 1311 qemu_co_mutex_unlock(&s->lock); 1312 return ret; 1313 } 1314 1315 static int qcow2_truncate(BlockDriverState *bs, int64_t offset) 1316 { 1317 BDRVQcowState *s = bs->opaque; 1318 int ret, new_l1_size; 1319 1320 if (offset & 511) { 1321 error_report("The new size must be a multiple of 512"); 1322 return -EINVAL; 1323 } 1324 1325 /* cannot proceed if image has snapshots */ 1326 if (s->nb_snapshots) { 1327 error_report("Can't resize an image which has snapshots"); 1328 return -ENOTSUP; 1329 } 1330 1331 /* shrinking is currently not supported */ 1332 if (offset < bs->total_sectors * 512) { 1333 error_report("qcow2 doesn't support shrinking images yet"); 1334 return -ENOTSUP; 1335 } 1336 1337 new_l1_size = size_to_l1(s, offset); 1338 ret = qcow2_grow_l1_table(bs, new_l1_size, true); 1339 if (ret < 0) { 1340 return ret; 1341 } 1342 1343 /* write updated header.size */ 1344 offset = cpu_to_be64(offset); 1345 ret = bdrv_pwrite_sync(bs->file, offsetof(QCowHeader, size), 1346 &offset, sizeof(uint64_t)); 1347 if (ret < 0) { 1348 return ret; 1349 } 1350 1351 s->l1_vm_state_index = new_l1_size; 1352 return 0; 1353 } 1354 1355 /* XXX: put compressed sectors first, then all the cluster aligned 1356 tables to avoid losing bytes in alignment */ 1357 static int qcow2_write_compressed(BlockDriverState *bs, int64_t sector_num, 1358 const uint8_t *buf, int nb_sectors) 1359 { 1360 BDRVQcowState *s = bs->opaque; 1361 z_stream strm; 1362 int ret, out_len; 1363 uint8_t *out_buf; 1364 uint64_t cluster_offset; 1365 1366 if (nb_sectors == 0) { 1367 /* align end of file to a sector boundary to ease reading with 1368 sector based I/Os */ 1369 cluster_offset = bdrv_getlength(bs->file); 1370 cluster_offset = (cluster_offset + 511) & ~511; 1371 bdrv_truncate(bs->file, cluster_offset); 1372 return 0; 1373 } 1374 1375 if (nb_sectors != s->cluster_sectors) 1376 return -EINVAL; 1377 1378 out_buf = g_malloc(s->cluster_size + (s->cluster_size / 1000) + 128); 1379 1380 /* best compression, small window, no zlib header */ 1381 memset(&strm, 0, sizeof(strm)); 1382 ret = deflateInit2(&strm, Z_DEFAULT_COMPRESSION, 1383 Z_DEFLATED, -12, 1384 9, Z_DEFAULT_STRATEGY); 1385 if (ret != 0) { 1386 ret = -EINVAL; 1387 goto fail; 1388 } 1389 1390 strm.avail_in = s->cluster_size; 1391 strm.next_in = (uint8_t *)buf; 1392 strm.avail_out = s->cluster_size; 1393 strm.next_out = out_buf; 1394 1395 ret = deflate(&strm, Z_FINISH); 1396 if (ret != Z_STREAM_END && ret != Z_OK) { 1397 deflateEnd(&strm); 1398 ret = -EINVAL; 1399 goto fail; 1400 } 1401 out_len = strm.next_out - out_buf; 1402 1403 deflateEnd(&strm); 1404 1405 if (ret != Z_STREAM_END || out_len >= s->cluster_size) { 1406 /* could not compress: write normal cluster */ 1407 ret = bdrv_write(bs, sector_num, buf, s->cluster_sectors); 1408 if (ret < 0) { 1409 goto fail; 1410 } 1411 } else { 1412 cluster_offset = qcow2_alloc_compressed_cluster_offset(bs, 1413 sector_num << 9, out_len); 1414 if (!cluster_offset) { 1415 ret = -EIO; 1416 goto fail; 1417 } 1418 cluster_offset &= s->cluster_offset_mask; 1419 BLKDBG_EVENT(bs->file, BLKDBG_WRITE_COMPRESSED); 1420 ret = bdrv_pwrite(bs->file, cluster_offset, out_buf, out_len); 1421 if (ret < 0) { 1422 goto fail; 1423 } 1424 } 1425 1426 ret = 0; 1427 fail: 1428 g_free(out_buf); 1429 return ret; 1430 } 1431 1432 static coroutine_fn int qcow2_co_flush_to_os(BlockDriverState *bs) 1433 { 1434 BDRVQcowState *s = bs->opaque; 1435 int ret; 1436 1437 qemu_co_mutex_lock(&s->lock); 1438 ret = qcow2_cache_flush(bs, s->l2_table_cache); 1439 if (ret < 0) { 1440 qemu_co_mutex_unlock(&s->lock); 1441 return ret; 1442 } 1443 1444 ret = qcow2_cache_flush(bs, s->refcount_block_cache); 1445 if (ret < 0) { 1446 qemu_co_mutex_unlock(&s->lock); 1447 return ret; 1448 } 1449 qemu_co_mutex_unlock(&s->lock); 1450 1451 return 0; 1452 } 1453 1454 static int64_t qcow2_vm_state_offset(BDRVQcowState *s) 1455 { 1456 return (int64_t)s->l1_vm_state_index << (s->cluster_bits + s->l2_bits); 1457 } 1458 1459 static int qcow2_get_info(BlockDriverState *bs, BlockDriverInfo *bdi) 1460 { 1461 BDRVQcowState *s = bs->opaque; 1462 bdi->cluster_size = s->cluster_size; 1463 bdi->vm_state_offset = qcow2_vm_state_offset(s); 1464 return 0; 1465 } 1466 1467 1468 static int qcow2_check(BlockDriverState *bs, BdrvCheckResult *result, 1469 BdrvCheckMode fix) 1470 { 1471 return qcow2_check_refcounts(bs, result, fix); 1472 } 1473 1474 #if 0 1475 static void dump_refcounts(BlockDriverState *bs) 1476 { 1477 BDRVQcowState *s = bs->opaque; 1478 int64_t nb_clusters, k, k1, size; 1479 int refcount; 1480 1481 size = bdrv_getlength(bs->file); 1482 nb_clusters = size_to_clusters(s, size); 1483 for(k = 0; k < nb_clusters;) { 1484 k1 = k; 1485 refcount = get_refcount(bs, k); 1486 k++; 1487 while (k < nb_clusters && get_refcount(bs, k) == refcount) 1488 k++; 1489 printf("%" PRId64 ": refcount=%d nb=%" PRId64 "\n", k, refcount, 1490 k - k1); 1491 } 1492 } 1493 #endif 1494 1495 static int qcow2_save_vmstate(BlockDriverState *bs, const uint8_t *buf, 1496 int64_t pos, int size) 1497 { 1498 BDRVQcowState *s = bs->opaque; 1499 int growable = bs->growable; 1500 int ret; 1501 1502 BLKDBG_EVENT(bs->file, BLKDBG_VMSTATE_SAVE); 1503 bs->growable = 1; 1504 ret = bdrv_pwrite(bs, qcow2_vm_state_offset(s) + pos, buf, size); 1505 bs->growable = growable; 1506 1507 return ret; 1508 } 1509 1510 static int qcow2_load_vmstate(BlockDriverState *bs, uint8_t *buf, 1511 int64_t pos, int size) 1512 { 1513 BDRVQcowState *s = bs->opaque; 1514 int growable = bs->growable; 1515 int ret; 1516 1517 BLKDBG_EVENT(bs->file, BLKDBG_VMSTATE_LOAD); 1518 bs->growable = 1; 1519 ret = bdrv_pread(bs, qcow2_vm_state_offset(s) + pos, buf, size); 1520 bs->growable = growable; 1521 1522 return ret; 1523 } 1524 1525 static QEMUOptionParameter qcow2_create_options[] = { 1526 { 1527 .name = BLOCK_OPT_SIZE, 1528 .type = OPT_SIZE, 1529 .help = "Virtual disk size" 1530 }, 1531 { 1532 .name = BLOCK_OPT_COMPAT_LEVEL, 1533 .type = OPT_STRING, 1534 .help = "Compatibility level (0.10 or 1.1)" 1535 }, 1536 { 1537 .name = BLOCK_OPT_BACKING_FILE, 1538 .type = OPT_STRING, 1539 .help = "File name of a base image" 1540 }, 1541 { 1542 .name = BLOCK_OPT_BACKING_FMT, 1543 .type = OPT_STRING, 1544 .help = "Image format of the base image" 1545 }, 1546 { 1547 .name = BLOCK_OPT_ENCRYPT, 1548 .type = OPT_FLAG, 1549 .help = "Encrypt the image" 1550 }, 1551 { 1552 .name = BLOCK_OPT_CLUSTER_SIZE, 1553 .type = OPT_SIZE, 1554 .help = "qcow2 cluster size", 1555 .value = { .n = DEFAULT_CLUSTER_SIZE }, 1556 }, 1557 { 1558 .name = BLOCK_OPT_PREALLOC, 1559 .type = OPT_STRING, 1560 .help = "Preallocation mode (allowed values: off, metadata)" 1561 }, 1562 { NULL } 1563 }; 1564 1565 static BlockDriver bdrv_qcow2 = { 1566 .format_name = "qcow2", 1567 .instance_size = sizeof(BDRVQcowState), 1568 .bdrv_probe = qcow2_probe, 1569 .bdrv_open = qcow2_open, 1570 .bdrv_close = qcow2_close, 1571 .bdrv_create = qcow2_create, 1572 .bdrv_co_is_allocated = qcow2_co_is_allocated, 1573 .bdrv_set_key = qcow2_set_key, 1574 .bdrv_make_empty = qcow2_make_empty, 1575 1576 .bdrv_co_readv = qcow2_co_readv, 1577 .bdrv_co_writev = qcow2_co_writev, 1578 .bdrv_co_flush_to_os = qcow2_co_flush_to_os, 1579 1580 .bdrv_co_write_zeroes = qcow2_co_write_zeroes, 1581 .bdrv_co_discard = qcow2_co_discard, 1582 .bdrv_truncate = qcow2_truncate, 1583 .bdrv_write_compressed = qcow2_write_compressed, 1584 1585 .bdrv_snapshot_create = qcow2_snapshot_create, 1586 .bdrv_snapshot_goto = qcow2_snapshot_goto, 1587 .bdrv_snapshot_delete = qcow2_snapshot_delete, 1588 .bdrv_snapshot_list = qcow2_snapshot_list, 1589 .bdrv_snapshot_load_tmp = qcow2_snapshot_load_tmp, 1590 .bdrv_get_info = qcow2_get_info, 1591 1592 .bdrv_save_vmstate = qcow2_save_vmstate, 1593 .bdrv_load_vmstate = qcow2_load_vmstate, 1594 1595 .bdrv_change_backing_file = qcow2_change_backing_file, 1596 1597 .bdrv_invalidate_cache = qcow2_invalidate_cache, 1598 1599 .create_options = qcow2_create_options, 1600 .bdrv_check = qcow2_check, 1601 }; 1602 1603 static void bdrv_qcow2_init(void) 1604 { 1605 bdrv_register(&bdrv_qcow2); 1606 } 1607 1608 block_init(bdrv_qcow2_init); 1609