1 /* 2 * Block driver for the QCOW 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 25 #include "qemu/osdep.h" 26 #include "qapi/error.h" 27 #include "qemu/error-report.h" 28 #include "block/block_int.h" 29 #include "sysemu/block-backend.h" 30 #include "qemu/module.h" 31 #include "qemu/option.h" 32 #include "qemu/bswap.h" 33 #include <zlib.h> 34 #include "qapi/qmp/qdict.h" 35 #include "qapi/qmp/qstring.h" 36 #include "crypto/block.h" 37 #include "migration/blocker.h" 38 #include "block/crypto.h" 39 40 /**************************************************************/ 41 /* QEMU COW block driver with compression and encryption support */ 42 43 #define QCOW_MAGIC (('Q' << 24) | ('F' << 16) | ('I' << 8) | 0xfb) 44 #define QCOW_VERSION 1 45 46 #define QCOW_CRYPT_NONE 0 47 #define QCOW_CRYPT_AES 1 48 49 #define QCOW_OFLAG_COMPRESSED (1LL << 63) 50 51 typedef struct QCowHeader { 52 uint32_t magic; 53 uint32_t version; 54 uint64_t backing_file_offset; 55 uint32_t backing_file_size; 56 uint32_t mtime; 57 uint64_t size; /* in bytes */ 58 uint8_t cluster_bits; 59 uint8_t l2_bits; 60 uint16_t padding; 61 uint32_t crypt_method; 62 uint64_t l1_table_offset; 63 } QEMU_PACKED QCowHeader; 64 65 #define L2_CACHE_SIZE 16 66 67 typedef struct BDRVQcowState { 68 int cluster_bits; 69 int cluster_size; 70 int cluster_sectors; 71 int l2_bits; 72 int l2_size; 73 unsigned int l1_size; 74 uint64_t cluster_offset_mask; 75 uint64_t l1_table_offset; 76 uint64_t *l1_table; 77 uint64_t *l2_cache; 78 uint64_t l2_cache_offsets[L2_CACHE_SIZE]; 79 uint32_t l2_cache_counts[L2_CACHE_SIZE]; 80 uint8_t *cluster_cache; 81 uint8_t *cluster_data; 82 uint64_t cluster_cache_offset; 83 QCryptoBlock *crypto; /* Disk encryption format driver */ 84 uint32_t crypt_method_header; 85 CoMutex lock; 86 Error *migration_blocker; 87 } BDRVQcowState; 88 89 static int decompress_cluster(BlockDriverState *bs, uint64_t cluster_offset); 90 91 static int qcow_probe(const uint8_t *buf, int buf_size, const char *filename) 92 { 93 const QCowHeader *cow_header = (const void *)buf; 94 95 if (buf_size >= sizeof(QCowHeader) && 96 be32_to_cpu(cow_header->magic) == QCOW_MAGIC && 97 be32_to_cpu(cow_header->version) == QCOW_VERSION) 98 return 100; 99 else 100 return 0; 101 } 102 103 static QemuOptsList qcow_runtime_opts = { 104 .name = "qcow", 105 .head = QTAILQ_HEAD_INITIALIZER(qcow_runtime_opts.head), 106 .desc = { 107 BLOCK_CRYPTO_OPT_DEF_QCOW_KEY_SECRET("encrypt."), 108 { /* end of list */ } 109 }, 110 }; 111 112 static int qcow_open(BlockDriverState *bs, QDict *options, int flags, 113 Error **errp) 114 { 115 BDRVQcowState *s = bs->opaque; 116 unsigned int len, i, shift; 117 int ret; 118 QCowHeader header; 119 Error *local_err = NULL; 120 QCryptoBlockOpenOptions *crypto_opts = NULL; 121 unsigned int cflags = 0; 122 QDict *encryptopts = NULL; 123 const char *encryptfmt; 124 125 qdict_extract_subqdict(options, &encryptopts, "encrypt."); 126 encryptfmt = qdict_get_try_str(encryptopts, "format"); 127 128 bs->file = bdrv_open_child(NULL, options, "file", bs, &child_file, 129 false, errp); 130 if (!bs->file) { 131 ret = -EINVAL; 132 goto fail; 133 } 134 135 ret = bdrv_pread(bs->file, 0, &header, sizeof(header)); 136 if (ret < 0) { 137 goto fail; 138 } 139 be32_to_cpus(&header.magic); 140 be32_to_cpus(&header.version); 141 be64_to_cpus(&header.backing_file_offset); 142 be32_to_cpus(&header.backing_file_size); 143 be32_to_cpus(&header.mtime); 144 be64_to_cpus(&header.size); 145 be32_to_cpus(&header.crypt_method); 146 be64_to_cpus(&header.l1_table_offset); 147 148 if (header.magic != QCOW_MAGIC) { 149 error_setg(errp, "Image not in qcow format"); 150 ret = -EINVAL; 151 goto fail; 152 } 153 if (header.version != QCOW_VERSION) { 154 error_setg(errp, "Unsupported qcow version %" PRIu32, header.version); 155 ret = -ENOTSUP; 156 goto fail; 157 } 158 159 if (header.size <= 1) { 160 error_setg(errp, "Image size is too small (must be at least 2 bytes)"); 161 ret = -EINVAL; 162 goto fail; 163 } 164 if (header.cluster_bits < 9 || header.cluster_bits > 16) { 165 error_setg(errp, "Cluster size must be between 512 and 64k"); 166 ret = -EINVAL; 167 goto fail; 168 } 169 170 /* l2_bits specifies number of entries; storing a uint64_t in each entry, 171 * so bytes = num_entries << 3. */ 172 if (header.l2_bits < 9 - 3 || header.l2_bits > 16 - 3) { 173 error_setg(errp, "L2 table size must be between 512 and 64k"); 174 ret = -EINVAL; 175 goto fail; 176 } 177 178 s->crypt_method_header = header.crypt_method; 179 if (s->crypt_method_header) { 180 if (bdrv_uses_whitelist() && 181 s->crypt_method_header == QCOW_CRYPT_AES) { 182 error_setg(errp, 183 "Use of AES-CBC encrypted qcow images is no longer " 184 "supported in system emulators"); 185 error_append_hint(errp, 186 "You can use 'qemu-img convert' to convert your " 187 "image to an alternative supported format, such " 188 "as unencrypted qcow, or raw with the LUKS " 189 "format instead.\n"); 190 ret = -ENOSYS; 191 goto fail; 192 } 193 if (s->crypt_method_header == QCOW_CRYPT_AES) { 194 if (encryptfmt && !g_str_equal(encryptfmt, "aes")) { 195 error_setg(errp, 196 "Header reported 'aes' encryption format but " 197 "options specify '%s'", encryptfmt); 198 ret = -EINVAL; 199 goto fail; 200 } 201 qdict_del(encryptopts, "format"); 202 crypto_opts = block_crypto_open_opts_init( 203 Q_CRYPTO_BLOCK_FORMAT_QCOW, encryptopts, errp); 204 if (!crypto_opts) { 205 ret = -EINVAL; 206 goto fail; 207 } 208 209 if (flags & BDRV_O_NO_IO) { 210 cflags |= QCRYPTO_BLOCK_OPEN_NO_IO; 211 } 212 s->crypto = qcrypto_block_open(crypto_opts, "encrypt.", 213 NULL, NULL, cflags, errp); 214 if (!s->crypto) { 215 ret = -EINVAL; 216 goto fail; 217 } 218 } else { 219 error_setg(errp, "invalid encryption method in qcow header"); 220 ret = -EINVAL; 221 goto fail; 222 } 223 bs->encrypted = true; 224 } else { 225 if (encryptfmt) { 226 error_setg(errp, "No encryption in image header, but options " 227 "specified format '%s'", encryptfmt); 228 ret = -EINVAL; 229 goto fail; 230 } 231 } 232 s->cluster_bits = header.cluster_bits; 233 s->cluster_size = 1 << s->cluster_bits; 234 s->cluster_sectors = 1 << (s->cluster_bits - 9); 235 s->l2_bits = header.l2_bits; 236 s->l2_size = 1 << s->l2_bits; 237 bs->total_sectors = header.size / 512; 238 s->cluster_offset_mask = (1LL << (63 - s->cluster_bits)) - 1; 239 240 /* read the level 1 table */ 241 shift = s->cluster_bits + s->l2_bits; 242 if (header.size > UINT64_MAX - (1LL << shift)) { 243 error_setg(errp, "Image too large"); 244 ret = -EINVAL; 245 goto fail; 246 } else { 247 uint64_t l1_size = (header.size + (1LL << shift) - 1) >> shift; 248 if (l1_size > INT_MAX / sizeof(uint64_t)) { 249 error_setg(errp, "Image too large"); 250 ret = -EINVAL; 251 goto fail; 252 } 253 s->l1_size = l1_size; 254 } 255 256 s->l1_table_offset = header.l1_table_offset; 257 s->l1_table = g_try_new(uint64_t, s->l1_size); 258 if (s->l1_table == NULL) { 259 error_setg(errp, "Could not allocate memory for L1 table"); 260 ret = -ENOMEM; 261 goto fail; 262 } 263 264 ret = bdrv_pread(bs->file, s->l1_table_offset, s->l1_table, 265 s->l1_size * sizeof(uint64_t)); 266 if (ret < 0) { 267 goto fail; 268 } 269 270 for(i = 0;i < s->l1_size; i++) { 271 be64_to_cpus(&s->l1_table[i]); 272 } 273 274 /* alloc L2 cache (max. 64k * 16 * 8 = 8 MB) */ 275 s->l2_cache = 276 qemu_try_blockalign(bs->file->bs, 277 s->l2_size * L2_CACHE_SIZE * sizeof(uint64_t)); 278 if (s->l2_cache == NULL) { 279 error_setg(errp, "Could not allocate L2 table cache"); 280 ret = -ENOMEM; 281 goto fail; 282 } 283 s->cluster_cache = g_malloc(s->cluster_size); 284 s->cluster_data = g_malloc(s->cluster_size); 285 s->cluster_cache_offset = -1; 286 287 /* read the backing file name */ 288 if (header.backing_file_offset != 0) { 289 len = header.backing_file_size; 290 if (len > 1023 || len >= sizeof(bs->backing_file)) { 291 error_setg(errp, "Backing file name too long"); 292 ret = -EINVAL; 293 goto fail; 294 } 295 ret = bdrv_pread(bs->file, header.backing_file_offset, 296 bs->backing_file, len); 297 if (ret < 0) { 298 goto fail; 299 } 300 bs->backing_file[len] = '\0'; 301 } 302 303 /* Disable migration when qcow images are used */ 304 error_setg(&s->migration_blocker, "The qcow format used by node '%s' " 305 "does not support live migration", 306 bdrv_get_device_or_node_name(bs)); 307 ret = migrate_add_blocker(s->migration_blocker, &local_err); 308 if (local_err) { 309 error_propagate(errp, local_err); 310 error_free(s->migration_blocker); 311 goto fail; 312 } 313 314 QDECREF(encryptopts); 315 qapi_free_QCryptoBlockOpenOptions(crypto_opts); 316 qemu_co_mutex_init(&s->lock); 317 return 0; 318 319 fail: 320 g_free(s->l1_table); 321 qemu_vfree(s->l2_cache); 322 g_free(s->cluster_cache); 323 g_free(s->cluster_data); 324 qcrypto_block_free(s->crypto); 325 QDECREF(encryptopts); 326 qapi_free_QCryptoBlockOpenOptions(crypto_opts); 327 return ret; 328 } 329 330 331 /* We have nothing to do for QCOW reopen, stubs just return 332 * success */ 333 static int qcow_reopen_prepare(BDRVReopenState *state, 334 BlockReopenQueue *queue, Error **errp) 335 { 336 return 0; 337 } 338 339 340 /* 'allocate' is: 341 * 342 * 0 to not allocate. 343 * 344 * 1 to allocate a normal cluster (for sector indexes 'n_start' to 345 * 'n_end') 346 * 347 * 2 to allocate a compressed cluster of size 348 * 'compressed_size'. 'compressed_size' must be > 0 and < 349 * cluster_size 350 * 351 * return 0 if not allocated, 1 if *result is assigned, and negative 352 * errno on failure. 353 */ 354 static int get_cluster_offset(BlockDriverState *bs, 355 uint64_t offset, int allocate, 356 int compressed_size, 357 int n_start, int n_end, uint64_t *result) 358 { 359 BDRVQcowState *s = bs->opaque; 360 int min_index, i, j, l1_index, l2_index, ret; 361 int64_t l2_offset; 362 uint64_t *l2_table, cluster_offset, tmp; 363 uint32_t min_count; 364 int new_l2_table; 365 366 *result = 0; 367 l1_index = offset >> (s->l2_bits + s->cluster_bits); 368 l2_offset = s->l1_table[l1_index]; 369 new_l2_table = 0; 370 if (!l2_offset) { 371 if (!allocate) 372 return 0; 373 /* allocate a new l2 entry */ 374 l2_offset = bdrv_getlength(bs->file->bs); 375 if (l2_offset < 0) { 376 return l2_offset; 377 } 378 /* round to cluster size */ 379 l2_offset = QEMU_ALIGN_UP(l2_offset, s->cluster_size); 380 /* update the L1 entry */ 381 s->l1_table[l1_index] = l2_offset; 382 tmp = cpu_to_be64(l2_offset); 383 BLKDBG_EVENT(bs->file, BLKDBG_L1_UPDATE); 384 ret = bdrv_pwrite_sync(bs->file, 385 s->l1_table_offset + l1_index * sizeof(tmp), 386 &tmp, sizeof(tmp)); 387 if (ret < 0) { 388 return ret; 389 } 390 new_l2_table = 1; 391 } 392 for(i = 0; i < L2_CACHE_SIZE; i++) { 393 if (l2_offset == s->l2_cache_offsets[i]) { 394 /* increment the hit count */ 395 if (++s->l2_cache_counts[i] == 0xffffffff) { 396 for(j = 0; j < L2_CACHE_SIZE; j++) { 397 s->l2_cache_counts[j] >>= 1; 398 } 399 } 400 l2_table = s->l2_cache + (i << s->l2_bits); 401 goto found; 402 } 403 } 404 /* not found: load a new entry in the least used one */ 405 min_index = 0; 406 min_count = 0xffffffff; 407 for(i = 0; i < L2_CACHE_SIZE; i++) { 408 if (s->l2_cache_counts[i] < min_count) { 409 min_count = s->l2_cache_counts[i]; 410 min_index = i; 411 } 412 } 413 l2_table = s->l2_cache + (min_index << s->l2_bits); 414 BLKDBG_EVENT(bs->file, BLKDBG_L2_LOAD); 415 if (new_l2_table) { 416 memset(l2_table, 0, s->l2_size * sizeof(uint64_t)); 417 ret = bdrv_pwrite_sync(bs->file, l2_offset, l2_table, 418 s->l2_size * sizeof(uint64_t)); 419 if (ret < 0) { 420 return ret; 421 } 422 } else { 423 ret = bdrv_pread(bs->file, l2_offset, l2_table, 424 s->l2_size * sizeof(uint64_t)); 425 if (ret < 0) { 426 return ret; 427 } 428 } 429 s->l2_cache_offsets[min_index] = l2_offset; 430 s->l2_cache_counts[min_index] = 1; 431 found: 432 l2_index = (offset >> s->cluster_bits) & (s->l2_size - 1); 433 cluster_offset = be64_to_cpu(l2_table[l2_index]); 434 if (!cluster_offset || 435 ((cluster_offset & QCOW_OFLAG_COMPRESSED) && allocate == 1)) { 436 if (!allocate) 437 return 0; 438 BLKDBG_EVENT(bs->file, BLKDBG_CLUSTER_ALLOC); 439 /* allocate a new cluster */ 440 if ((cluster_offset & QCOW_OFLAG_COMPRESSED) && 441 (n_end - n_start) < s->cluster_sectors) { 442 /* if the cluster is already compressed, we must 443 decompress it in the case it is not completely 444 overwritten */ 445 if (decompress_cluster(bs, cluster_offset) < 0) { 446 return -EIO; 447 } 448 cluster_offset = bdrv_getlength(bs->file->bs); 449 if ((int64_t) cluster_offset < 0) { 450 return cluster_offset; 451 } 452 cluster_offset = QEMU_ALIGN_UP(cluster_offset, s->cluster_size); 453 /* write the cluster content */ 454 BLKDBG_EVENT(bs->file, BLKDBG_WRITE_AIO); 455 ret = bdrv_pwrite(bs->file, cluster_offset, s->cluster_cache, 456 s->cluster_size); 457 if (ret < 0) { 458 return ret; 459 } 460 } else { 461 cluster_offset = bdrv_getlength(bs->file->bs); 462 if ((int64_t) cluster_offset < 0) { 463 return cluster_offset; 464 } 465 if (allocate == 1) { 466 /* round to cluster size */ 467 cluster_offset = QEMU_ALIGN_UP(cluster_offset, s->cluster_size); 468 if (cluster_offset + s->cluster_size > INT64_MAX) { 469 return -E2BIG; 470 } 471 ret = bdrv_truncate(bs->file, cluster_offset + s->cluster_size, 472 PREALLOC_MODE_OFF, NULL); 473 if (ret < 0) { 474 return ret; 475 } 476 /* if encrypted, we must initialize the cluster 477 content which won't be written */ 478 if (bs->encrypted && 479 (n_end - n_start) < s->cluster_sectors) { 480 uint64_t start_sect; 481 assert(s->crypto); 482 start_sect = (offset & ~(s->cluster_size - 1)) >> 9; 483 for(i = 0; i < s->cluster_sectors; i++) { 484 if (i < n_start || i >= n_end) { 485 memset(s->cluster_data, 0x00, 512); 486 if (qcrypto_block_encrypt(s->crypto, 487 (start_sect + i) * 488 BDRV_SECTOR_SIZE, 489 s->cluster_data, 490 BDRV_SECTOR_SIZE, 491 NULL) < 0) { 492 return -EIO; 493 } 494 BLKDBG_EVENT(bs->file, BLKDBG_WRITE_AIO); 495 ret = bdrv_pwrite(bs->file, 496 cluster_offset + i * 512, 497 s->cluster_data, 512); 498 if (ret < 0) { 499 return ret; 500 } 501 } 502 } 503 } 504 } else if (allocate == 2) { 505 cluster_offset |= QCOW_OFLAG_COMPRESSED | 506 (uint64_t)compressed_size << (63 - s->cluster_bits); 507 } 508 } 509 /* update L2 table */ 510 tmp = cpu_to_be64(cluster_offset); 511 l2_table[l2_index] = tmp; 512 if (allocate == 2) { 513 BLKDBG_EVENT(bs->file, BLKDBG_L2_UPDATE_COMPRESSED); 514 } else { 515 BLKDBG_EVENT(bs->file, BLKDBG_L2_UPDATE); 516 } 517 ret = bdrv_pwrite_sync(bs->file, l2_offset + l2_index * sizeof(tmp), 518 &tmp, sizeof(tmp)); 519 if (ret < 0) { 520 return ret; 521 } 522 } 523 *result = cluster_offset; 524 return 1; 525 } 526 527 static int coroutine_fn qcow_co_block_status(BlockDriverState *bs, 528 bool want_zero, 529 int64_t offset, int64_t bytes, 530 int64_t *pnum, int64_t *map, 531 BlockDriverState **file) 532 { 533 BDRVQcowState *s = bs->opaque; 534 int index_in_cluster, ret; 535 int64_t n; 536 uint64_t cluster_offset; 537 538 qemu_co_mutex_lock(&s->lock); 539 ret = get_cluster_offset(bs, offset, 0, 0, 0, 0, &cluster_offset); 540 qemu_co_mutex_unlock(&s->lock); 541 if (ret < 0) { 542 return ret; 543 } 544 index_in_cluster = offset & (s->cluster_size - 1); 545 n = s->cluster_size - index_in_cluster; 546 if (n > bytes) { 547 n = bytes; 548 } 549 *pnum = n; 550 if (!cluster_offset) { 551 return 0; 552 } 553 if ((cluster_offset & QCOW_OFLAG_COMPRESSED) || s->crypto) { 554 return BDRV_BLOCK_DATA; 555 } 556 *map = cluster_offset | index_in_cluster; 557 *file = bs->file->bs; 558 return BDRV_BLOCK_DATA | BDRV_BLOCK_OFFSET_VALID; 559 } 560 561 static int decompress_buffer(uint8_t *out_buf, int out_buf_size, 562 const uint8_t *buf, int buf_size) 563 { 564 z_stream strm1, *strm = &strm1; 565 int ret, out_len; 566 567 memset(strm, 0, sizeof(*strm)); 568 569 strm->next_in = (uint8_t *)buf; 570 strm->avail_in = buf_size; 571 strm->next_out = out_buf; 572 strm->avail_out = out_buf_size; 573 574 ret = inflateInit2(strm, -12); 575 if (ret != Z_OK) 576 return -1; 577 ret = inflate(strm, Z_FINISH); 578 out_len = strm->next_out - out_buf; 579 if ((ret != Z_STREAM_END && ret != Z_BUF_ERROR) || 580 out_len != out_buf_size) { 581 inflateEnd(strm); 582 return -1; 583 } 584 inflateEnd(strm); 585 return 0; 586 } 587 588 static int decompress_cluster(BlockDriverState *bs, uint64_t cluster_offset) 589 { 590 BDRVQcowState *s = bs->opaque; 591 int ret, csize; 592 uint64_t coffset; 593 594 coffset = cluster_offset & s->cluster_offset_mask; 595 if (s->cluster_cache_offset != coffset) { 596 csize = cluster_offset >> (63 - s->cluster_bits); 597 csize &= (s->cluster_size - 1); 598 BLKDBG_EVENT(bs->file, BLKDBG_READ_COMPRESSED); 599 ret = bdrv_pread(bs->file, coffset, s->cluster_data, csize); 600 if (ret != csize) 601 return -1; 602 if (decompress_buffer(s->cluster_cache, s->cluster_size, 603 s->cluster_data, csize) < 0) { 604 return -1; 605 } 606 s->cluster_cache_offset = coffset; 607 } 608 return 0; 609 } 610 611 static coroutine_fn int qcow_co_readv(BlockDriverState *bs, int64_t sector_num, 612 int nb_sectors, QEMUIOVector *qiov) 613 { 614 BDRVQcowState *s = bs->opaque; 615 int index_in_cluster; 616 int ret = 0, n; 617 uint64_t cluster_offset; 618 struct iovec hd_iov; 619 QEMUIOVector hd_qiov; 620 uint8_t *buf; 621 void *orig_buf; 622 623 if (qiov->niov > 1) { 624 buf = orig_buf = qemu_try_blockalign(bs, qiov->size); 625 if (buf == NULL) { 626 return -ENOMEM; 627 } 628 } else { 629 orig_buf = NULL; 630 buf = (uint8_t *)qiov->iov->iov_base; 631 } 632 633 qemu_co_mutex_lock(&s->lock); 634 635 while (nb_sectors != 0) { 636 /* prepare next request */ 637 ret = get_cluster_offset(bs, sector_num << 9, 638 0, 0, 0, 0, &cluster_offset); 639 if (ret < 0) { 640 break; 641 } 642 index_in_cluster = sector_num & (s->cluster_sectors - 1); 643 n = s->cluster_sectors - index_in_cluster; 644 if (n > nb_sectors) { 645 n = nb_sectors; 646 } 647 648 if (!cluster_offset) { 649 if (bs->backing) { 650 /* read from the base image */ 651 hd_iov.iov_base = (void *)buf; 652 hd_iov.iov_len = n * 512; 653 qemu_iovec_init_external(&hd_qiov, &hd_iov, 1); 654 qemu_co_mutex_unlock(&s->lock); 655 /* qcow2 emits this on bs->file instead of bs->backing */ 656 BLKDBG_EVENT(bs->file, BLKDBG_READ_BACKING_AIO); 657 ret = bdrv_co_readv(bs->backing, sector_num, n, &hd_qiov); 658 qemu_co_mutex_lock(&s->lock); 659 if (ret < 0) { 660 break; 661 } 662 } else { 663 /* Note: in this case, no need to wait */ 664 memset(buf, 0, 512 * n); 665 } 666 } else if (cluster_offset & QCOW_OFLAG_COMPRESSED) { 667 /* add AIO support for compressed blocks ? */ 668 if (decompress_cluster(bs, cluster_offset) < 0) { 669 ret = -EIO; 670 break; 671 } 672 memcpy(buf, 673 s->cluster_cache + index_in_cluster * 512, 512 * n); 674 } else { 675 if ((cluster_offset & 511) != 0) { 676 ret = -EIO; 677 break; 678 } 679 hd_iov.iov_base = (void *)buf; 680 hd_iov.iov_len = n * 512; 681 qemu_iovec_init_external(&hd_qiov, &hd_iov, 1); 682 qemu_co_mutex_unlock(&s->lock); 683 BLKDBG_EVENT(bs->file, BLKDBG_READ_AIO); 684 ret = bdrv_co_readv(bs->file, 685 (cluster_offset >> 9) + index_in_cluster, 686 n, &hd_qiov); 687 qemu_co_mutex_lock(&s->lock); 688 if (ret < 0) { 689 break; 690 } 691 if (bs->encrypted) { 692 assert(s->crypto); 693 if (qcrypto_block_decrypt(s->crypto, 694 sector_num * BDRV_SECTOR_SIZE, buf, 695 n * BDRV_SECTOR_SIZE, NULL) < 0) { 696 ret = -EIO; 697 break; 698 } 699 } 700 } 701 ret = 0; 702 703 nb_sectors -= n; 704 sector_num += n; 705 buf += n * 512; 706 } 707 708 qemu_co_mutex_unlock(&s->lock); 709 710 if (qiov->niov > 1) { 711 qemu_iovec_from_buf(qiov, 0, orig_buf, qiov->size); 712 qemu_vfree(orig_buf); 713 } 714 715 return ret; 716 } 717 718 static coroutine_fn int qcow_co_writev(BlockDriverState *bs, int64_t sector_num, 719 int nb_sectors, QEMUIOVector *qiov) 720 { 721 BDRVQcowState *s = bs->opaque; 722 int index_in_cluster; 723 uint64_t cluster_offset; 724 int ret = 0, n; 725 struct iovec hd_iov; 726 QEMUIOVector hd_qiov; 727 uint8_t *buf; 728 void *orig_buf; 729 730 s->cluster_cache_offset = -1; /* disable compressed cache */ 731 732 /* We must always copy the iov when encrypting, so we 733 * don't modify the original data buffer during encryption */ 734 if (bs->encrypted || qiov->niov > 1) { 735 buf = orig_buf = qemu_try_blockalign(bs, qiov->size); 736 if (buf == NULL) { 737 return -ENOMEM; 738 } 739 qemu_iovec_to_buf(qiov, 0, buf, qiov->size); 740 } else { 741 orig_buf = NULL; 742 buf = (uint8_t *)qiov->iov->iov_base; 743 } 744 745 qemu_co_mutex_lock(&s->lock); 746 747 while (nb_sectors != 0) { 748 749 index_in_cluster = sector_num & (s->cluster_sectors - 1); 750 n = s->cluster_sectors - index_in_cluster; 751 if (n > nb_sectors) { 752 n = nb_sectors; 753 } 754 ret = get_cluster_offset(bs, sector_num << 9, 1, 0, 755 index_in_cluster, 756 index_in_cluster + n, &cluster_offset); 757 if (ret < 0) { 758 break; 759 } 760 if (!cluster_offset || (cluster_offset & 511) != 0) { 761 ret = -EIO; 762 break; 763 } 764 if (bs->encrypted) { 765 assert(s->crypto); 766 if (qcrypto_block_encrypt(s->crypto, sector_num * BDRV_SECTOR_SIZE, 767 buf, n * BDRV_SECTOR_SIZE, NULL) < 0) { 768 ret = -EIO; 769 break; 770 } 771 } 772 773 hd_iov.iov_base = (void *)buf; 774 hd_iov.iov_len = n * 512; 775 qemu_iovec_init_external(&hd_qiov, &hd_iov, 1); 776 qemu_co_mutex_unlock(&s->lock); 777 BLKDBG_EVENT(bs->file, BLKDBG_WRITE_AIO); 778 ret = bdrv_co_writev(bs->file, 779 (cluster_offset >> 9) + index_in_cluster, 780 n, &hd_qiov); 781 qemu_co_mutex_lock(&s->lock); 782 if (ret < 0) { 783 break; 784 } 785 ret = 0; 786 787 nb_sectors -= n; 788 sector_num += n; 789 buf += n * 512; 790 } 791 qemu_co_mutex_unlock(&s->lock); 792 793 qemu_vfree(orig_buf); 794 795 return ret; 796 } 797 798 static void qcow_close(BlockDriverState *bs) 799 { 800 BDRVQcowState *s = bs->opaque; 801 802 qcrypto_block_free(s->crypto); 803 s->crypto = NULL; 804 g_free(s->l1_table); 805 qemu_vfree(s->l2_cache); 806 g_free(s->cluster_cache); 807 g_free(s->cluster_data); 808 809 migrate_del_blocker(s->migration_blocker); 810 error_free(s->migration_blocker); 811 } 812 813 static int coroutine_fn qcow_co_create_opts(const char *filename, QemuOpts *opts, 814 Error **errp) 815 { 816 int header_size, backing_filename_len, l1_size, shift, i; 817 QCowHeader header; 818 uint8_t *tmp; 819 int64_t total_size = 0; 820 char *backing_file = NULL; 821 Error *local_err = NULL; 822 int ret; 823 BlockBackend *qcow_blk; 824 char *encryptfmt = NULL; 825 QDict *options; 826 QDict *encryptopts = NULL; 827 QCryptoBlockCreateOptions *crypto_opts = NULL; 828 QCryptoBlock *crypto = NULL; 829 830 /* Read out options */ 831 total_size = ROUND_UP(qemu_opt_get_size_del(opts, BLOCK_OPT_SIZE, 0), 832 BDRV_SECTOR_SIZE); 833 if (total_size == 0) { 834 error_setg(errp, "Image size is too small, cannot be zero length"); 835 ret = -EINVAL; 836 goto cleanup; 837 } 838 839 backing_file = qemu_opt_get_del(opts, BLOCK_OPT_BACKING_FILE); 840 encryptfmt = qemu_opt_get_del(opts, BLOCK_OPT_ENCRYPT_FORMAT); 841 if (encryptfmt) { 842 if (qemu_opt_get(opts, BLOCK_OPT_ENCRYPT)) { 843 error_setg(errp, "Options " BLOCK_OPT_ENCRYPT " and " 844 BLOCK_OPT_ENCRYPT_FORMAT " are mutually exclusive"); 845 ret = -EINVAL; 846 goto cleanup; 847 } 848 } else if (qemu_opt_get_bool_del(opts, BLOCK_OPT_ENCRYPT, false)) { 849 encryptfmt = g_strdup("aes"); 850 } 851 852 ret = bdrv_create_file(filename, opts, &local_err); 853 if (ret < 0) { 854 error_propagate(errp, local_err); 855 goto cleanup; 856 } 857 858 qcow_blk = blk_new_open(filename, NULL, NULL, 859 BDRV_O_RDWR | BDRV_O_RESIZE | BDRV_O_PROTOCOL, 860 &local_err); 861 if (qcow_blk == NULL) { 862 error_propagate(errp, local_err); 863 ret = -EIO; 864 goto cleanup; 865 } 866 867 blk_set_allow_write_beyond_eof(qcow_blk, true); 868 869 ret = blk_truncate(qcow_blk, 0, PREALLOC_MODE_OFF, errp); 870 if (ret < 0) { 871 goto exit; 872 } 873 874 memset(&header, 0, sizeof(header)); 875 header.magic = cpu_to_be32(QCOW_MAGIC); 876 header.version = cpu_to_be32(QCOW_VERSION); 877 header.size = cpu_to_be64(total_size); 878 header_size = sizeof(header); 879 backing_filename_len = 0; 880 if (backing_file) { 881 if (strcmp(backing_file, "fat:")) { 882 header.backing_file_offset = cpu_to_be64(header_size); 883 backing_filename_len = strlen(backing_file); 884 header.backing_file_size = cpu_to_be32(backing_filename_len); 885 header_size += backing_filename_len; 886 } else { 887 /* special backing file for vvfat */ 888 g_free(backing_file); 889 backing_file = NULL; 890 } 891 header.cluster_bits = 9; /* 512 byte cluster to avoid copying 892 unmodified sectors */ 893 header.l2_bits = 12; /* 32 KB L2 tables */ 894 } else { 895 header.cluster_bits = 12; /* 4 KB clusters */ 896 header.l2_bits = 9; /* 4 KB L2 tables */ 897 } 898 header_size = (header_size + 7) & ~7; 899 shift = header.cluster_bits + header.l2_bits; 900 l1_size = (total_size + (1LL << shift) - 1) >> shift; 901 902 header.l1_table_offset = cpu_to_be64(header_size); 903 904 options = qemu_opts_to_qdict(opts, NULL); 905 qdict_extract_subqdict(options, &encryptopts, "encrypt."); 906 QDECREF(options); 907 if (encryptfmt) { 908 if (!g_str_equal(encryptfmt, "aes")) { 909 error_setg(errp, "Unknown encryption format '%s', expected 'aes'", 910 encryptfmt); 911 ret = -EINVAL; 912 goto exit; 913 } 914 header.crypt_method = cpu_to_be32(QCOW_CRYPT_AES); 915 916 crypto_opts = block_crypto_create_opts_init( 917 Q_CRYPTO_BLOCK_FORMAT_QCOW, encryptopts, errp); 918 if (!crypto_opts) { 919 ret = -EINVAL; 920 goto exit; 921 } 922 923 crypto = qcrypto_block_create(crypto_opts, "encrypt.", 924 NULL, NULL, NULL, errp); 925 if (!crypto) { 926 ret = -EINVAL; 927 goto exit; 928 } 929 } else { 930 header.crypt_method = cpu_to_be32(QCOW_CRYPT_NONE); 931 } 932 933 /* write all the data */ 934 ret = blk_pwrite(qcow_blk, 0, &header, sizeof(header), 0); 935 if (ret != sizeof(header)) { 936 goto exit; 937 } 938 939 if (backing_file) { 940 ret = blk_pwrite(qcow_blk, sizeof(header), 941 backing_file, backing_filename_len, 0); 942 if (ret != backing_filename_len) { 943 goto exit; 944 } 945 } 946 947 tmp = g_malloc0(BDRV_SECTOR_SIZE); 948 for (i = 0; i < DIV_ROUND_UP(sizeof(uint64_t) * l1_size, BDRV_SECTOR_SIZE); 949 i++) { 950 ret = blk_pwrite(qcow_blk, header_size + BDRV_SECTOR_SIZE * i, 951 tmp, BDRV_SECTOR_SIZE, 0); 952 if (ret != BDRV_SECTOR_SIZE) { 953 g_free(tmp); 954 goto exit; 955 } 956 } 957 958 g_free(tmp); 959 ret = 0; 960 exit: 961 blk_unref(qcow_blk); 962 cleanup: 963 QDECREF(encryptopts); 964 g_free(encryptfmt); 965 qcrypto_block_free(crypto); 966 qapi_free_QCryptoBlockCreateOptions(crypto_opts); 967 g_free(backing_file); 968 return ret; 969 } 970 971 static int qcow_make_empty(BlockDriverState *bs) 972 { 973 BDRVQcowState *s = bs->opaque; 974 uint32_t l1_length = s->l1_size * sizeof(uint64_t); 975 int ret; 976 977 memset(s->l1_table, 0, l1_length); 978 if (bdrv_pwrite_sync(bs->file, s->l1_table_offset, s->l1_table, 979 l1_length) < 0) 980 return -1; 981 ret = bdrv_truncate(bs->file, s->l1_table_offset + l1_length, 982 PREALLOC_MODE_OFF, NULL); 983 if (ret < 0) 984 return ret; 985 986 memset(s->l2_cache, 0, s->l2_size * L2_CACHE_SIZE * sizeof(uint64_t)); 987 memset(s->l2_cache_offsets, 0, L2_CACHE_SIZE * sizeof(uint64_t)); 988 memset(s->l2_cache_counts, 0, L2_CACHE_SIZE * sizeof(uint32_t)); 989 990 return 0; 991 } 992 993 /* XXX: put compressed sectors first, then all the cluster aligned 994 tables to avoid losing bytes in alignment */ 995 static coroutine_fn int 996 qcow_co_pwritev_compressed(BlockDriverState *bs, uint64_t offset, 997 uint64_t bytes, QEMUIOVector *qiov) 998 { 999 BDRVQcowState *s = bs->opaque; 1000 QEMUIOVector hd_qiov; 1001 struct iovec iov; 1002 z_stream strm; 1003 int ret, out_len; 1004 uint8_t *buf, *out_buf; 1005 uint64_t cluster_offset; 1006 1007 buf = qemu_blockalign(bs, s->cluster_size); 1008 if (bytes != s->cluster_size) { 1009 if (bytes > s->cluster_size || 1010 offset + bytes != bs->total_sectors << BDRV_SECTOR_BITS) 1011 { 1012 qemu_vfree(buf); 1013 return -EINVAL; 1014 } 1015 /* Zero-pad last write if image size is not cluster aligned */ 1016 memset(buf + bytes, 0, s->cluster_size - bytes); 1017 } 1018 qemu_iovec_to_buf(qiov, 0, buf, qiov->size); 1019 1020 out_buf = g_malloc(s->cluster_size); 1021 1022 /* best compression, small window, no zlib header */ 1023 memset(&strm, 0, sizeof(strm)); 1024 ret = deflateInit2(&strm, Z_DEFAULT_COMPRESSION, 1025 Z_DEFLATED, -12, 1026 9, Z_DEFAULT_STRATEGY); 1027 if (ret != 0) { 1028 ret = -EINVAL; 1029 goto fail; 1030 } 1031 1032 strm.avail_in = s->cluster_size; 1033 strm.next_in = (uint8_t *)buf; 1034 strm.avail_out = s->cluster_size; 1035 strm.next_out = out_buf; 1036 1037 ret = deflate(&strm, Z_FINISH); 1038 if (ret != Z_STREAM_END && ret != Z_OK) { 1039 deflateEnd(&strm); 1040 ret = -EINVAL; 1041 goto fail; 1042 } 1043 out_len = strm.next_out - out_buf; 1044 1045 deflateEnd(&strm); 1046 1047 if (ret != Z_STREAM_END || out_len >= s->cluster_size) { 1048 /* could not compress: write normal cluster */ 1049 ret = qcow_co_writev(bs, offset >> BDRV_SECTOR_BITS, 1050 bytes >> BDRV_SECTOR_BITS, qiov); 1051 if (ret < 0) { 1052 goto fail; 1053 } 1054 goto success; 1055 } 1056 qemu_co_mutex_lock(&s->lock); 1057 ret = get_cluster_offset(bs, offset, 2, out_len, 0, 0, &cluster_offset); 1058 qemu_co_mutex_unlock(&s->lock); 1059 if (ret < 0) { 1060 goto fail; 1061 } 1062 if (cluster_offset == 0) { 1063 ret = -EIO; 1064 goto fail; 1065 } 1066 cluster_offset &= s->cluster_offset_mask; 1067 1068 iov = (struct iovec) { 1069 .iov_base = out_buf, 1070 .iov_len = out_len, 1071 }; 1072 qemu_iovec_init_external(&hd_qiov, &iov, 1); 1073 BLKDBG_EVENT(bs->file, BLKDBG_WRITE_COMPRESSED); 1074 ret = bdrv_co_pwritev(bs->file, cluster_offset, out_len, &hd_qiov, 0); 1075 if (ret < 0) { 1076 goto fail; 1077 } 1078 success: 1079 ret = 0; 1080 fail: 1081 qemu_vfree(buf); 1082 g_free(out_buf); 1083 return ret; 1084 } 1085 1086 static int qcow_get_info(BlockDriverState *bs, BlockDriverInfo *bdi) 1087 { 1088 BDRVQcowState *s = bs->opaque; 1089 bdi->cluster_size = s->cluster_size; 1090 return 0; 1091 } 1092 1093 static QemuOptsList qcow_create_opts = { 1094 .name = "qcow-create-opts", 1095 .head = QTAILQ_HEAD_INITIALIZER(qcow_create_opts.head), 1096 .desc = { 1097 { 1098 .name = BLOCK_OPT_SIZE, 1099 .type = QEMU_OPT_SIZE, 1100 .help = "Virtual disk size" 1101 }, 1102 { 1103 .name = BLOCK_OPT_BACKING_FILE, 1104 .type = QEMU_OPT_STRING, 1105 .help = "File name of a base image" 1106 }, 1107 { 1108 .name = BLOCK_OPT_ENCRYPT, 1109 .type = QEMU_OPT_BOOL, 1110 .help = "Encrypt the image with format 'aes'. (Deprecated " 1111 "in favor of " BLOCK_OPT_ENCRYPT_FORMAT "=aes)", 1112 }, 1113 { 1114 .name = BLOCK_OPT_ENCRYPT_FORMAT, 1115 .type = QEMU_OPT_STRING, 1116 .help = "Encrypt the image, format choices: 'aes'", 1117 }, 1118 BLOCK_CRYPTO_OPT_DEF_QCOW_KEY_SECRET("encrypt."), 1119 { /* end of list */ } 1120 } 1121 }; 1122 1123 static BlockDriver bdrv_qcow = { 1124 .format_name = "qcow", 1125 .instance_size = sizeof(BDRVQcowState), 1126 .bdrv_probe = qcow_probe, 1127 .bdrv_open = qcow_open, 1128 .bdrv_close = qcow_close, 1129 .bdrv_child_perm = bdrv_format_default_perms, 1130 .bdrv_reopen_prepare = qcow_reopen_prepare, 1131 .bdrv_co_create_opts = qcow_co_create_opts, 1132 .bdrv_has_zero_init = bdrv_has_zero_init_1, 1133 .supports_backing = true, 1134 1135 .bdrv_co_readv = qcow_co_readv, 1136 .bdrv_co_writev = qcow_co_writev, 1137 .bdrv_co_block_status = qcow_co_block_status, 1138 1139 .bdrv_make_empty = qcow_make_empty, 1140 .bdrv_co_pwritev_compressed = qcow_co_pwritev_compressed, 1141 .bdrv_get_info = qcow_get_info, 1142 1143 .create_opts = &qcow_create_opts, 1144 }; 1145 1146 static void bdrv_qcow_init(void) 1147 { 1148 bdrv_register(&bdrv_qcow); 1149 } 1150 1151 block_init(bdrv_qcow_init); 1152