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