docker: add --include-files argument to 'build' command
[qemu/kevin.git] / block / qcow2-cluster.c
blobd779ea19cf4019c8d97be012efed6e1c95571458
1 /*
2 * Block driver for the QCOW version 2 format
4 * Copyright (c) 2004-2006 Fabrice Bellard
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:
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
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.
25 #include "qemu/osdep.h"
26 #include <zlib.h>
28 #include "qapi/error.h"
29 #include "qemu-common.h"
30 #include "block/block_int.h"
31 #include "block/qcow2.h"
32 #include "qemu/bswap.h"
33 #include "trace.h"
35 int qcow2_grow_l1_table(BlockDriverState *bs, uint64_t min_size,
36 bool exact_size)
38 BDRVQcow2State *s = bs->opaque;
39 int new_l1_size2, ret, i;
40 uint64_t *new_l1_table;
41 int64_t old_l1_table_offset, old_l1_size;
42 int64_t new_l1_table_offset, new_l1_size;
43 uint8_t data[12];
45 if (min_size <= s->l1_size)
46 return 0;
48 /* Do a sanity check on min_size before trying to calculate new_l1_size
49 * (this prevents overflows during the while loop for the calculation of
50 * new_l1_size) */
51 if (min_size > INT_MAX / sizeof(uint64_t)) {
52 return -EFBIG;
55 if (exact_size) {
56 new_l1_size = min_size;
57 } else {
58 /* Bump size up to reduce the number of times we have to grow */
59 new_l1_size = s->l1_size;
60 if (new_l1_size == 0) {
61 new_l1_size = 1;
63 while (min_size > new_l1_size) {
64 new_l1_size = (new_l1_size * 3 + 1) / 2;
68 QEMU_BUILD_BUG_ON(QCOW_MAX_L1_SIZE > INT_MAX);
69 if (new_l1_size > QCOW_MAX_L1_SIZE / sizeof(uint64_t)) {
70 return -EFBIG;
73 #ifdef DEBUG_ALLOC2
74 fprintf(stderr, "grow l1_table from %d to %" PRId64 "\n",
75 s->l1_size, new_l1_size);
76 #endif
78 new_l1_size2 = sizeof(uint64_t) * new_l1_size;
79 new_l1_table = qemu_try_blockalign(bs->file->bs,
80 align_offset(new_l1_size2, 512));
81 if (new_l1_table == NULL) {
82 return -ENOMEM;
84 memset(new_l1_table, 0, align_offset(new_l1_size2, 512));
86 if (s->l1_size) {
87 memcpy(new_l1_table, s->l1_table, s->l1_size * sizeof(uint64_t));
90 /* write new table (align to cluster) */
91 BLKDBG_EVENT(bs->file, BLKDBG_L1_GROW_ALLOC_TABLE);
92 new_l1_table_offset = qcow2_alloc_clusters(bs, new_l1_size2);
93 if (new_l1_table_offset < 0) {
94 qemu_vfree(new_l1_table);
95 return new_l1_table_offset;
98 ret = qcow2_cache_flush(bs, s->refcount_block_cache);
99 if (ret < 0) {
100 goto fail;
103 /* the L1 position has not yet been updated, so these clusters must
104 * indeed be completely free */
105 ret = qcow2_pre_write_overlap_check(bs, 0, new_l1_table_offset,
106 new_l1_size2);
107 if (ret < 0) {
108 goto fail;
111 BLKDBG_EVENT(bs->file, BLKDBG_L1_GROW_WRITE_TABLE);
112 for(i = 0; i < s->l1_size; i++)
113 new_l1_table[i] = cpu_to_be64(new_l1_table[i]);
114 ret = bdrv_pwrite_sync(bs->file, new_l1_table_offset,
115 new_l1_table, new_l1_size2);
116 if (ret < 0)
117 goto fail;
118 for(i = 0; i < s->l1_size; i++)
119 new_l1_table[i] = be64_to_cpu(new_l1_table[i]);
121 /* set new table */
122 BLKDBG_EVENT(bs->file, BLKDBG_L1_GROW_ACTIVATE_TABLE);
123 stl_be_p(data, new_l1_size);
124 stq_be_p(data + 4, new_l1_table_offset);
125 ret = bdrv_pwrite_sync(bs->file, offsetof(QCowHeader, l1_size),
126 data, sizeof(data));
127 if (ret < 0) {
128 goto fail;
130 qemu_vfree(s->l1_table);
131 old_l1_table_offset = s->l1_table_offset;
132 s->l1_table_offset = new_l1_table_offset;
133 s->l1_table = new_l1_table;
134 old_l1_size = s->l1_size;
135 s->l1_size = new_l1_size;
136 qcow2_free_clusters(bs, old_l1_table_offset, old_l1_size * sizeof(uint64_t),
137 QCOW2_DISCARD_OTHER);
138 return 0;
139 fail:
140 qemu_vfree(new_l1_table);
141 qcow2_free_clusters(bs, new_l1_table_offset, new_l1_size2,
142 QCOW2_DISCARD_OTHER);
143 return ret;
147 * l2_load
149 * Loads a L2 table into memory. If the table is in the cache, the cache
150 * is used; otherwise the L2 table is loaded from the image file.
152 * Returns a pointer to the L2 table on success, or NULL if the read from
153 * the image file failed.
156 static int l2_load(BlockDriverState *bs, uint64_t l2_offset,
157 uint64_t **l2_table)
159 BDRVQcow2State *s = bs->opaque;
161 return qcow2_cache_get(bs, s->l2_table_cache, l2_offset,
162 (void **)l2_table);
166 * Writes one sector of the L1 table to the disk (can't update single entries
167 * and we really don't want bdrv_pread to perform a read-modify-write)
169 #define L1_ENTRIES_PER_SECTOR (512 / 8)
170 int qcow2_write_l1_entry(BlockDriverState *bs, int l1_index)
172 BDRVQcow2State *s = bs->opaque;
173 uint64_t buf[L1_ENTRIES_PER_SECTOR] = { 0 };
174 int l1_start_index;
175 int i, ret;
177 l1_start_index = l1_index & ~(L1_ENTRIES_PER_SECTOR - 1);
178 for (i = 0; i < L1_ENTRIES_PER_SECTOR && l1_start_index + i < s->l1_size;
179 i++)
181 buf[i] = cpu_to_be64(s->l1_table[l1_start_index + i]);
184 ret = qcow2_pre_write_overlap_check(bs, QCOW2_OL_ACTIVE_L1,
185 s->l1_table_offset + 8 * l1_start_index, sizeof(buf));
186 if (ret < 0) {
187 return ret;
190 BLKDBG_EVENT(bs->file, BLKDBG_L1_UPDATE);
191 ret = bdrv_pwrite_sync(bs->file,
192 s->l1_table_offset + 8 * l1_start_index,
193 buf, sizeof(buf));
194 if (ret < 0) {
195 return ret;
198 return 0;
202 * l2_allocate
204 * Allocate a new l2 entry in the file. If l1_index points to an already
205 * used entry in the L2 table (i.e. we are doing a copy on write for the L2
206 * table) copy the contents of the old L2 table into the newly allocated one.
207 * Otherwise the new table is initialized with zeros.
211 static int l2_allocate(BlockDriverState *bs, int l1_index, uint64_t **table)
213 BDRVQcow2State *s = bs->opaque;
214 uint64_t old_l2_offset;
215 uint64_t *l2_table = NULL;
216 int64_t l2_offset;
217 int ret;
219 old_l2_offset = s->l1_table[l1_index];
221 trace_qcow2_l2_allocate(bs, l1_index);
223 /* allocate a new l2 entry */
225 l2_offset = qcow2_alloc_clusters(bs, s->l2_size * sizeof(uint64_t));
226 if (l2_offset < 0) {
227 ret = l2_offset;
228 goto fail;
231 ret = qcow2_cache_flush(bs, s->refcount_block_cache);
232 if (ret < 0) {
233 goto fail;
236 /* allocate a new entry in the l2 cache */
238 trace_qcow2_l2_allocate_get_empty(bs, l1_index);
239 ret = qcow2_cache_get_empty(bs, s->l2_table_cache, l2_offset, (void**) table);
240 if (ret < 0) {
241 goto fail;
244 l2_table = *table;
246 if ((old_l2_offset & L1E_OFFSET_MASK) == 0) {
247 /* if there was no old l2 table, clear the new table */
248 memset(l2_table, 0, s->l2_size * sizeof(uint64_t));
249 } else {
250 uint64_t* old_table;
252 /* if there was an old l2 table, read it from the disk */
253 BLKDBG_EVENT(bs->file, BLKDBG_L2_ALLOC_COW_READ);
254 ret = qcow2_cache_get(bs, s->l2_table_cache,
255 old_l2_offset & L1E_OFFSET_MASK,
256 (void**) &old_table);
257 if (ret < 0) {
258 goto fail;
261 memcpy(l2_table, old_table, s->cluster_size);
263 qcow2_cache_put(bs, s->l2_table_cache, (void **) &old_table);
266 /* write the l2 table to the file */
267 BLKDBG_EVENT(bs->file, BLKDBG_L2_ALLOC_WRITE);
269 trace_qcow2_l2_allocate_write_l2(bs, l1_index);
270 qcow2_cache_entry_mark_dirty(bs, s->l2_table_cache, l2_table);
271 ret = qcow2_cache_flush(bs, s->l2_table_cache);
272 if (ret < 0) {
273 goto fail;
276 /* update the L1 entry */
277 trace_qcow2_l2_allocate_write_l1(bs, l1_index);
278 s->l1_table[l1_index] = l2_offset | QCOW_OFLAG_COPIED;
279 ret = qcow2_write_l1_entry(bs, l1_index);
280 if (ret < 0) {
281 goto fail;
284 *table = l2_table;
285 trace_qcow2_l2_allocate_done(bs, l1_index, 0);
286 return 0;
288 fail:
289 trace_qcow2_l2_allocate_done(bs, l1_index, ret);
290 if (l2_table != NULL) {
291 qcow2_cache_put(bs, s->l2_table_cache, (void**) table);
293 s->l1_table[l1_index] = old_l2_offset;
294 if (l2_offset > 0) {
295 qcow2_free_clusters(bs, l2_offset, s->l2_size * sizeof(uint64_t),
296 QCOW2_DISCARD_ALWAYS);
298 return ret;
302 * Checks how many clusters in a given L2 table are contiguous in the image
303 * file. As soon as one of the flags in the bitmask stop_flags changes compared
304 * to the first cluster, the search is stopped and the cluster is not counted
305 * as contiguous. (This allows it, for example, to stop at the first compressed
306 * cluster which may require a different handling)
308 static int count_contiguous_clusters(int nb_clusters, int cluster_size,
309 uint64_t *l2_table, uint64_t stop_flags)
311 int i;
312 QCow2ClusterType first_cluster_type;
313 uint64_t mask = stop_flags | L2E_OFFSET_MASK | QCOW_OFLAG_COMPRESSED;
314 uint64_t first_entry = be64_to_cpu(l2_table[0]);
315 uint64_t offset = first_entry & mask;
317 if (!offset) {
318 return 0;
321 /* must be allocated */
322 first_cluster_type = qcow2_get_cluster_type(first_entry);
323 assert(first_cluster_type == QCOW2_CLUSTER_NORMAL ||
324 first_cluster_type == QCOW2_CLUSTER_ZERO_ALLOC);
326 for (i = 0; i < nb_clusters; i++) {
327 uint64_t l2_entry = be64_to_cpu(l2_table[i]) & mask;
328 if (offset + (uint64_t) i * cluster_size != l2_entry) {
329 break;
333 return i;
337 * Checks how many consecutive unallocated clusters in a given L2
338 * table have the same cluster type.
340 static int count_contiguous_clusters_unallocated(int nb_clusters,
341 uint64_t *l2_table,
342 QCow2ClusterType wanted_type)
344 int i;
346 assert(wanted_type == QCOW2_CLUSTER_ZERO_PLAIN ||
347 wanted_type == QCOW2_CLUSTER_UNALLOCATED);
348 for (i = 0; i < nb_clusters; i++) {
349 uint64_t entry = be64_to_cpu(l2_table[i]);
350 QCow2ClusterType type = qcow2_get_cluster_type(entry);
352 if (type != wanted_type) {
353 break;
357 return i;
360 /* The crypt function is compatible with the linux cryptoloop
361 algorithm for < 4 GB images. NOTE: out_buf == in_buf is
362 supported */
363 int qcow2_encrypt_sectors(BDRVQcow2State *s, int64_t sector_num,
364 uint8_t *out_buf, const uint8_t *in_buf,
365 int nb_sectors, bool enc,
366 Error **errp)
368 union {
369 uint64_t ll[2];
370 uint8_t b[16];
371 } ivec;
372 int i;
373 int ret;
375 for(i = 0; i < nb_sectors; i++) {
376 ivec.ll[0] = cpu_to_le64(sector_num);
377 ivec.ll[1] = 0;
378 if (qcrypto_cipher_setiv(s->cipher,
379 ivec.b, G_N_ELEMENTS(ivec.b),
380 errp) < 0) {
381 return -1;
383 if (enc) {
384 ret = qcrypto_cipher_encrypt(s->cipher,
385 in_buf,
386 out_buf,
387 512,
388 errp);
389 } else {
390 ret = qcrypto_cipher_decrypt(s->cipher,
391 in_buf,
392 out_buf,
393 512,
394 errp);
396 if (ret < 0) {
397 return -1;
399 sector_num++;
400 in_buf += 512;
401 out_buf += 512;
403 return 0;
406 static int coroutine_fn do_perform_cow(BlockDriverState *bs,
407 uint64_t src_cluster_offset,
408 uint64_t cluster_offset,
409 int offset_in_cluster,
410 int bytes)
412 BDRVQcow2State *s = bs->opaque;
413 QEMUIOVector qiov;
414 struct iovec iov;
415 int ret;
417 iov.iov_len = bytes;
418 iov.iov_base = qemu_try_blockalign(bs, iov.iov_len);
419 if (iov.iov_base == NULL) {
420 return -ENOMEM;
423 qemu_iovec_init_external(&qiov, &iov, 1);
425 BLKDBG_EVENT(bs->file, BLKDBG_COW_READ);
427 if (!bs->drv) {
428 ret = -ENOMEDIUM;
429 goto out;
432 /* Call .bdrv_co_readv() directly instead of using the public block-layer
433 * interface. This avoids double I/O throttling and request tracking,
434 * which can lead to deadlock when block layer copy-on-read is enabled.
436 ret = bs->drv->bdrv_co_preadv(bs, src_cluster_offset + offset_in_cluster,
437 bytes, &qiov, 0);
438 if (ret < 0) {
439 goto out;
442 if (bs->encrypted) {
443 Error *err = NULL;
444 int64_t sector = (src_cluster_offset + offset_in_cluster)
445 >> BDRV_SECTOR_BITS;
446 assert(s->cipher);
447 assert((offset_in_cluster & ~BDRV_SECTOR_MASK) == 0);
448 assert((bytes & ~BDRV_SECTOR_MASK) == 0);
449 if (qcow2_encrypt_sectors(s, sector, iov.iov_base, iov.iov_base,
450 bytes >> BDRV_SECTOR_BITS, true, &err) < 0) {
451 ret = -EIO;
452 error_free(err);
453 goto out;
457 ret = qcow2_pre_write_overlap_check(bs, 0,
458 cluster_offset + offset_in_cluster, bytes);
459 if (ret < 0) {
460 goto out;
463 BLKDBG_EVENT(bs->file, BLKDBG_COW_WRITE);
464 ret = bdrv_co_pwritev(bs->file, cluster_offset + offset_in_cluster,
465 bytes, &qiov, 0);
466 if (ret < 0) {
467 goto out;
470 ret = 0;
471 out:
472 qemu_vfree(iov.iov_base);
473 return ret;
478 * get_cluster_offset
480 * For a given offset of the virtual disk, find the cluster type and offset in
481 * the qcow2 file. The offset is stored in *cluster_offset.
483 * On entry, *bytes is the maximum number of contiguous bytes starting at
484 * offset that we are interested in.
486 * On exit, *bytes is the number of bytes starting at offset that have the same
487 * cluster type and (if applicable) are stored contiguously in the image file.
488 * Compressed clusters are always returned one by one.
490 * Returns the cluster type (QCOW2_CLUSTER_*) on success, -errno in error
491 * cases.
493 int qcow2_get_cluster_offset(BlockDriverState *bs, uint64_t offset,
494 unsigned int *bytes, uint64_t *cluster_offset)
496 BDRVQcow2State *s = bs->opaque;
497 unsigned int l2_index;
498 uint64_t l1_index, l2_offset, *l2_table;
499 int l1_bits, c;
500 unsigned int offset_in_cluster;
501 uint64_t bytes_available, bytes_needed, nb_clusters;
502 QCow2ClusterType type;
503 int ret;
505 offset_in_cluster = offset_into_cluster(s, offset);
506 bytes_needed = (uint64_t) *bytes + offset_in_cluster;
508 l1_bits = s->l2_bits + s->cluster_bits;
510 /* compute how many bytes there are between the start of the cluster
511 * containing offset and the end of the l1 entry */
512 bytes_available = (1ULL << l1_bits) - (offset & ((1ULL << l1_bits) - 1))
513 + offset_in_cluster;
515 if (bytes_needed > bytes_available) {
516 bytes_needed = bytes_available;
519 *cluster_offset = 0;
521 /* seek to the l2 offset in the l1 table */
523 l1_index = offset >> l1_bits;
524 if (l1_index >= s->l1_size) {
525 type = QCOW2_CLUSTER_UNALLOCATED;
526 goto out;
529 l2_offset = s->l1_table[l1_index] & L1E_OFFSET_MASK;
530 if (!l2_offset) {
531 type = QCOW2_CLUSTER_UNALLOCATED;
532 goto out;
535 if (offset_into_cluster(s, l2_offset)) {
536 qcow2_signal_corruption(bs, true, -1, -1, "L2 table offset %#" PRIx64
537 " unaligned (L1 index: %#" PRIx64 ")",
538 l2_offset, l1_index);
539 return -EIO;
542 /* load the l2 table in memory */
544 ret = l2_load(bs, l2_offset, &l2_table);
545 if (ret < 0) {
546 return ret;
549 /* find the cluster offset for the given disk offset */
551 l2_index = (offset >> s->cluster_bits) & (s->l2_size - 1);
552 *cluster_offset = be64_to_cpu(l2_table[l2_index]);
554 nb_clusters = size_to_clusters(s, bytes_needed);
555 /* bytes_needed <= *bytes + offset_in_cluster, both of which are unsigned
556 * integers; the minimum cluster size is 512, so this assertion is always
557 * true */
558 assert(nb_clusters <= INT_MAX);
560 type = qcow2_get_cluster_type(*cluster_offset);
561 if (s->qcow_version < 3 && (type == QCOW2_CLUSTER_ZERO_PLAIN ||
562 type == QCOW2_CLUSTER_ZERO_ALLOC)) {
563 qcow2_signal_corruption(bs, true, -1, -1, "Zero cluster entry found"
564 " in pre-v3 image (L2 offset: %#" PRIx64
565 ", L2 index: %#x)", l2_offset, l2_index);
566 ret = -EIO;
567 goto fail;
569 switch (type) {
570 case QCOW2_CLUSTER_COMPRESSED:
571 /* Compressed clusters can only be processed one by one */
572 c = 1;
573 *cluster_offset &= L2E_COMPRESSED_OFFSET_SIZE_MASK;
574 break;
575 case QCOW2_CLUSTER_ZERO_PLAIN:
576 case QCOW2_CLUSTER_UNALLOCATED:
577 /* how many empty clusters ? */
578 c = count_contiguous_clusters_unallocated(nb_clusters,
579 &l2_table[l2_index], type);
580 *cluster_offset = 0;
581 break;
582 case QCOW2_CLUSTER_ZERO_ALLOC:
583 case QCOW2_CLUSTER_NORMAL:
584 /* how many allocated clusters ? */
585 c = count_contiguous_clusters(nb_clusters, s->cluster_size,
586 &l2_table[l2_index], QCOW_OFLAG_ZERO);
587 *cluster_offset &= L2E_OFFSET_MASK;
588 if (offset_into_cluster(s, *cluster_offset)) {
589 qcow2_signal_corruption(bs, true, -1, -1,
590 "Cluster allocation offset %#"
591 PRIx64 " unaligned (L2 offset: %#" PRIx64
592 ", L2 index: %#x)", *cluster_offset,
593 l2_offset, l2_index);
594 ret = -EIO;
595 goto fail;
597 break;
598 default:
599 abort();
602 qcow2_cache_put(bs, s->l2_table_cache, (void**) &l2_table);
604 bytes_available = (int64_t)c * s->cluster_size;
606 out:
607 if (bytes_available > bytes_needed) {
608 bytes_available = bytes_needed;
611 /* bytes_available <= bytes_needed <= *bytes + offset_in_cluster;
612 * subtracting offset_in_cluster will therefore definitely yield something
613 * not exceeding UINT_MAX */
614 assert(bytes_available - offset_in_cluster <= UINT_MAX);
615 *bytes = bytes_available - offset_in_cluster;
617 return type;
619 fail:
620 qcow2_cache_put(bs, s->l2_table_cache, (void **)&l2_table);
621 return ret;
625 * get_cluster_table
627 * for a given disk offset, load (and allocate if needed)
628 * the l2 table.
630 * the l2 table offset in the qcow2 file and the cluster index
631 * in the l2 table are given to the caller.
633 * Returns 0 on success, -errno in failure case
635 static int get_cluster_table(BlockDriverState *bs, uint64_t offset,
636 uint64_t **new_l2_table,
637 int *new_l2_index)
639 BDRVQcow2State *s = bs->opaque;
640 unsigned int l2_index;
641 uint64_t l1_index, l2_offset;
642 uint64_t *l2_table = NULL;
643 int ret;
645 /* seek to the l2 offset in the l1 table */
647 l1_index = offset >> (s->l2_bits + s->cluster_bits);
648 if (l1_index >= s->l1_size) {
649 ret = qcow2_grow_l1_table(bs, l1_index + 1, false);
650 if (ret < 0) {
651 return ret;
655 assert(l1_index < s->l1_size);
656 l2_offset = s->l1_table[l1_index] & L1E_OFFSET_MASK;
657 if (offset_into_cluster(s, l2_offset)) {
658 qcow2_signal_corruption(bs, true, -1, -1, "L2 table offset %#" PRIx64
659 " unaligned (L1 index: %#" PRIx64 ")",
660 l2_offset, l1_index);
661 return -EIO;
664 /* seek the l2 table of the given l2 offset */
666 if (s->l1_table[l1_index] & QCOW_OFLAG_COPIED) {
667 /* load the l2 table in memory */
668 ret = l2_load(bs, l2_offset, &l2_table);
669 if (ret < 0) {
670 return ret;
672 } else {
673 /* First allocate a new L2 table (and do COW if needed) */
674 ret = l2_allocate(bs, l1_index, &l2_table);
675 if (ret < 0) {
676 return ret;
679 /* Then decrease the refcount of the old table */
680 if (l2_offset) {
681 qcow2_free_clusters(bs, l2_offset, s->l2_size * sizeof(uint64_t),
682 QCOW2_DISCARD_OTHER);
686 /* find the cluster offset for the given disk offset */
688 l2_index = (offset >> s->cluster_bits) & (s->l2_size - 1);
690 *new_l2_table = l2_table;
691 *new_l2_index = l2_index;
693 return 0;
697 * alloc_compressed_cluster_offset
699 * For a given offset of the disk image, return cluster offset in
700 * qcow2 file.
702 * If the offset is not found, allocate a new compressed cluster.
704 * Return the cluster offset if successful,
705 * Return 0, otherwise.
709 uint64_t qcow2_alloc_compressed_cluster_offset(BlockDriverState *bs,
710 uint64_t offset,
711 int compressed_size)
713 BDRVQcow2State *s = bs->opaque;
714 int l2_index, ret;
715 uint64_t *l2_table;
716 int64_t cluster_offset;
717 int nb_csectors;
719 ret = get_cluster_table(bs, offset, &l2_table, &l2_index);
720 if (ret < 0) {
721 return 0;
724 /* Compression can't overwrite anything. Fail if the cluster was already
725 * allocated. */
726 cluster_offset = be64_to_cpu(l2_table[l2_index]);
727 if (cluster_offset & L2E_OFFSET_MASK) {
728 qcow2_cache_put(bs, s->l2_table_cache, (void**) &l2_table);
729 return 0;
732 cluster_offset = qcow2_alloc_bytes(bs, compressed_size);
733 if (cluster_offset < 0) {
734 qcow2_cache_put(bs, s->l2_table_cache, (void**) &l2_table);
735 return 0;
738 nb_csectors = ((cluster_offset + compressed_size - 1) >> 9) -
739 (cluster_offset >> 9);
741 cluster_offset |= QCOW_OFLAG_COMPRESSED |
742 ((uint64_t)nb_csectors << s->csize_shift);
744 /* update L2 table */
746 /* compressed clusters never have the copied flag */
748 BLKDBG_EVENT(bs->file, BLKDBG_L2_UPDATE_COMPRESSED);
749 qcow2_cache_entry_mark_dirty(bs, s->l2_table_cache, l2_table);
750 l2_table[l2_index] = cpu_to_be64(cluster_offset);
751 qcow2_cache_put(bs, s->l2_table_cache, (void **) &l2_table);
753 return cluster_offset;
756 static int perform_cow(BlockDriverState *bs, QCowL2Meta *m, Qcow2COWRegion *r)
758 BDRVQcow2State *s = bs->opaque;
759 int ret;
761 if (r->nb_bytes == 0) {
762 return 0;
765 qemu_co_mutex_unlock(&s->lock);
766 ret = do_perform_cow(bs, m->offset, m->alloc_offset, r->offset, r->nb_bytes);
767 qemu_co_mutex_lock(&s->lock);
769 if (ret < 0) {
770 return ret;
774 * Before we update the L2 table to actually point to the new cluster, we
775 * need to be sure that the refcounts have been increased and COW was
776 * handled.
778 qcow2_cache_depends_on_flush(s->l2_table_cache);
780 return 0;
783 int qcow2_alloc_cluster_link_l2(BlockDriverState *bs, QCowL2Meta *m)
785 BDRVQcow2State *s = bs->opaque;
786 int i, j = 0, l2_index, ret;
787 uint64_t *old_cluster, *l2_table;
788 uint64_t cluster_offset = m->alloc_offset;
790 trace_qcow2_cluster_link_l2(qemu_coroutine_self(), m->nb_clusters);
791 assert(m->nb_clusters > 0);
793 old_cluster = g_try_new(uint64_t, m->nb_clusters);
794 if (old_cluster == NULL) {
795 ret = -ENOMEM;
796 goto err;
799 /* copy content of unmodified sectors */
800 ret = perform_cow(bs, m, &m->cow_start);
801 if (ret < 0) {
802 goto err;
805 ret = perform_cow(bs, m, &m->cow_end);
806 if (ret < 0) {
807 goto err;
810 /* Update L2 table. */
811 if (s->use_lazy_refcounts) {
812 qcow2_mark_dirty(bs);
814 if (qcow2_need_accurate_refcounts(s)) {
815 qcow2_cache_set_dependency(bs, s->l2_table_cache,
816 s->refcount_block_cache);
819 ret = get_cluster_table(bs, m->offset, &l2_table, &l2_index);
820 if (ret < 0) {
821 goto err;
823 qcow2_cache_entry_mark_dirty(bs, s->l2_table_cache, l2_table);
825 assert(l2_index + m->nb_clusters <= s->l2_size);
826 for (i = 0; i < m->nb_clusters; i++) {
827 /* if two concurrent writes happen to the same unallocated cluster
828 * each write allocates separate cluster and writes data concurrently.
829 * The first one to complete updates l2 table with pointer to its
830 * cluster the second one has to do RMW (which is done above by
831 * perform_cow()), update l2 table with its cluster pointer and free
832 * old cluster. This is what this loop does */
833 if (l2_table[l2_index + i] != 0) {
834 old_cluster[j++] = l2_table[l2_index + i];
837 l2_table[l2_index + i] = cpu_to_be64((cluster_offset +
838 (i << s->cluster_bits)) | QCOW_OFLAG_COPIED);
842 qcow2_cache_put(bs, s->l2_table_cache, (void **) &l2_table);
845 * If this was a COW, we need to decrease the refcount of the old cluster.
847 * Don't discard clusters that reach a refcount of 0 (e.g. compressed
848 * clusters), the next write will reuse them anyway.
850 if (!m->keep_old_clusters && j != 0) {
851 for (i = 0; i < j; i++) {
852 qcow2_free_any_clusters(bs, be64_to_cpu(old_cluster[i]), 1,
853 QCOW2_DISCARD_NEVER);
857 ret = 0;
858 err:
859 g_free(old_cluster);
860 return ret;
864 * Returns the number of contiguous clusters that can be used for an allocating
865 * write, but require COW to be performed (this includes yet unallocated space,
866 * which must copy from the backing file)
868 static int count_cow_clusters(BDRVQcow2State *s, int nb_clusters,
869 uint64_t *l2_table, int l2_index)
871 int i;
873 for (i = 0; i < nb_clusters; i++) {
874 uint64_t l2_entry = be64_to_cpu(l2_table[l2_index + i]);
875 QCow2ClusterType cluster_type = qcow2_get_cluster_type(l2_entry);
877 switch(cluster_type) {
878 case QCOW2_CLUSTER_NORMAL:
879 if (l2_entry & QCOW_OFLAG_COPIED) {
880 goto out;
882 break;
883 case QCOW2_CLUSTER_UNALLOCATED:
884 case QCOW2_CLUSTER_COMPRESSED:
885 case QCOW2_CLUSTER_ZERO_PLAIN:
886 case QCOW2_CLUSTER_ZERO_ALLOC:
887 break;
888 default:
889 abort();
893 out:
894 assert(i <= nb_clusters);
895 return i;
899 * Check if there already is an AIO write request in flight which allocates
900 * the same cluster. In this case we need to wait until the previous
901 * request has completed and updated the L2 table accordingly.
903 * Returns:
904 * 0 if there was no dependency. *cur_bytes indicates the number of
905 * bytes from guest_offset that can be read before the next
906 * dependency must be processed (or the request is complete)
908 * -EAGAIN if we had to wait for another request, previously gathered
909 * information on cluster allocation may be invalid now. The caller
910 * must start over anyway, so consider *cur_bytes undefined.
912 static int handle_dependencies(BlockDriverState *bs, uint64_t guest_offset,
913 uint64_t *cur_bytes, QCowL2Meta **m)
915 BDRVQcow2State *s = bs->opaque;
916 QCowL2Meta *old_alloc;
917 uint64_t bytes = *cur_bytes;
919 QLIST_FOREACH(old_alloc, &s->cluster_allocs, next_in_flight) {
921 uint64_t start = guest_offset;
922 uint64_t end = start + bytes;
923 uint64_t old_start = l2meta_cow_start(old_alloc);
924 uint64_t old_end = l2meta_cow_end(old_alloc);
926 if (end <= old_start || start >= old_end) {
927 /* No intersection */
928 } else {
929 if (start < old_start) {
930 /* Stop at the start of a running allocation */
931 bytes = old_start - start;
932 } else {
933 bytes = 0;
936 /* Stop if already an l2meta exists. After yielding, it wouldn't
937 * be valid any more, so we'd have to clean up the old L2Metas
938 * and deal with requests depending on them before starting to
939 * gather new ones. Not worth the trouble. */
940 if (bytes == 0 && *m) {
941 *cur_bytes = 0;
942 return 0;
945 if (bytes == 0) {
946 /* Wait for the dependency to complete. We need to recheck
947 * the free/allocated clusters when we continue. */
948 qemu_co_queue_wait(&old_alloc->dependent_requests, &s->lock);
949 return -EAGAIN;
954 /* Make sure that existing clusters and new allocations are only used up to
955 * the next dependency if we shortened the request above */
956 *cur_bytes = bytes;
958 return 0;
962 * Checks how many already allocated clusters that don't require a copy on
963 * write there are at the given guest_offset (up to *bytes). If
964 * *host_offset is not zero, only physically contiguous clusters beginning at
965 * this host offset are counted.
967 * Note that guest_offset may not be cluster aligned. In this case, the
968 * returned *host_offset points to exact byte referenced by guest_offset and
969 * therefore isn't cluster aligned as well.
971 * Returns:
972 * 0: if no allocated clusters are available at the given offset.
973 * *bytes is normally unchanged. It is set to 0 if the cluster
974 * is allocated and doesn't need COW, but doesn't have the right
975 * physical offset.
977 * 1: if allocated clusters that don't require a COW are available at
978 * the requested offset. *bytes may have decreased and describes
979 * the length of the area that can be written to.
981 * -errno: in error cases
983 static int handle_copied(BlockDriverState *bs, uint64_t guest_offset,
984 uint64_t *host_offset, uint64_t *bytes, QCowL2Meta **m)
986 BDRVQcow2State *s = bs->opaque;
987 int l2_index;
988 uint64_t cluster_offset;
989 uint64_t *l2_table;
990 uint64_t nb_clusters;
991 unsigned int keep_clusters;
992 int ret;
994 trace_qcow2_handle_copied(qemu_coroutine_self(), guest_offset, *host_offset,
995 *bytes);
997 assert(*host_offset == 0 || offset_into_cluster(s, guest_offset)
998 == offset_into_cluster(s, *host_offset));
1001 * Calculate the number of clusters to look for. We stop at L2 table
1002 * boundaries to keep things simple.
1004 nb_clusters =
1005 size_to_clusters(s, offset_into_cluster(s, guest_offset) + *bytes);
1007 l2_index = offset_to_l2_index(s, guest_offset);
1008 nb_clusters = MIN(nb_clusters, s->l2_size - l2_index);
1009 assert(nb_clusters <= INT_MAX);
1011 /* Find L2 entry for the first involved cluster */
1012 ret = get_cluster_table(bs, guest_offset, &l2_table, &l2_index);
1013 if (ret < 0) {
1014 return ret;
1017 cluster_offset = be64_to_cpu(l2_table[l2_index]);
1019 /* Check how many clusters are already allocated and don't need COW */
1020 if (qcow2_get_cluster_type(cluster_offset) == QCOW2_CLUSTER_NORMAL
1021 && (cluster_offset & QCOW_OFLAG_COPIED))
1023 /* If a specific host_offset is required, check it */
1024 bool offset_matches =
1025 (cluster_offset & L2E_OFFSET_MASK) == *host_offset;
1027 if (offset_into_cluster(s, cluster_offset & L2E_OFFSET_MASK)) {
1028 qcow2_signal_corruption(bs, true, -1, -1, "Data cluster offset "
1029 "%#llx unaligned (guest offset: %#" PRIx64
1030 ")", cluster_offset & L2E_OFFSET_MASK,
1031 guest_offset);
1032 ret = -EIO;
1033 goto out;
1036 if (*host_offset != 0 && !offset_matches) {
1037 *bytes = 0;
1038 ret = 0;
1039 goto out;
1042 /* We keep all QCOW_OFLAG_COPIED clusters */
1043 keep_clusters =
1044 count_contiguous_clusters(nb_clusters, s->cluster_size,
1045 &l2_table[l2_index],
1046 QCOW_OFLAG_COPIED | QCOW_OFLAG_ZERO);
1047 assert(keep_clusters <= nb_clusters);
1049 *bytes = MIN(*bytes,
1050 keep_clusters * s->cluster_size
1051 - offset_into_cluster(s, guest_offset));
1053 ret = 1;
1054 } else {
1055 ret = 0;
1058 /* Cleanup */
1059 out:
1060 qcow2_cache_put(bs, s->l2_table_cache, (void **) &l2_table);
1062 /* Only return a host offset if we actually made progress. Otherwise we
1063 * would make requirements for handle_alloc() that it can't fulfill */
1064 if (ret > 0) {
1065 *host_offset = (cluster_offset & L2E_OFFSET_MASK)
1066 + offset_into_cluster(s, guest_offset);
1069 return ret;
1073 * Allocates new clusters for the given guest_offset.
1075 * At most *nb_clusters are allocated, and on return *nb_clusters is updated to
1076 * contain the number of clusters that have been allocated and are contiguous
1077 * in the image file.
1079 * If *host_offset is non-zero, it specifies the offset in the image file at
1080 * which the new clusters must start. *nb_clusters can be 0 on return in this
1081 * case if the cluster at host_offset is already in use. If *host_offset is
1082 * zero, the clusters can be allocated anywhere in the image file.
1084 * *host_offset is updated to contain the offset into the image file at which
1085 * the first allocated cluster starts.
1087 * Return 0 on success and -errno in error cases. -EAGAIN means that the
1088 * function has been waiting for another request and the allocation must be
1089 * restarted, but the whole request should not be failed.
1091 static int do_alloc_cluster_offset(BlockDriverState *bs, uint64_t guest_offset,
1092 uint64_t *host_offset, uint64_t *nb_clusters)
1094 BDRVQcow2State *s = bs->opaque;
1096 trace_qcow2_do_alloc_clusters_offset(qemu_coroutine_self(), guest_offset,
1097 *host_offset, *nb_clusters);
1099 /* Allocate new clusters */
1100 trace_qcow2_cluster_alloc_phys(qemu_coroutine_self());
1101 if (*host_offset == 0) {
1102 int64_t cluster_offset =
1103 qcow2_alloc_clusters(bs, *nb_clusters * s->cluster_size);
1104 if (cluster_offset < 0) {
1105 return cluster_offset;
1107 *host_offset = cluster_offset;
1108 return 0;
1109 } else {
1110 int64_t ret = qcow2_alloc_clusters_at(bs, *host_offset, *nb_clusters);
1111 if (ret < 0) {
1112 return ret;
1114 *nb_clusters = ret;
1115 return 0;
1120 * Allocates new clusters for an area that either is yet unallocated or needs a
1121 * copy on write. If *host_offset is non-zero, clusters are only allocated if
1122 * the new allocation can match the specified host offset.
1124 * Note that guest_offset may not be cluster aligned. In this case, the
1125 * returned *host_offset points to exact byte referenced by guest_offset and
1126 * therefore isn't cluster aligned as well.
1128 * Returns:
1129 * 0: if no clusters could be allocated. *bytes is set to 0,
1130 * *host_offset is left unchanged.
1132 * 1: if new clusters were allocated. *bytes may be decreased if the
1133 * new allocation doesn't cover all of the requested area.
1134 * *host_offset is updated to contain the host offset of the first
1135 * newly allocated cluster.
1137 * -errno: in error cases
1139 static int handle_alloc(BlockDriverState *bs, uint64_t guest_offset,
1140 uint64_t *host_offset, uint64_t *bytes, QCowL2Meta **m)
1142 BDRVQcow2State *s = bs->opaque;
1143 int l2_index;
1144 uint64_t *l2_table;
1145 uint64_t entry;
1146 uint64_t nb_clusters;
1147 int ret;
1148 bool keep_old_clusters = false;
1150 uint64_t alloc_cluster_offset = 0;
1152 trace_qcow2_handle_alloc(qemu_coroutine_self(), guest_offset, *host_offset,
1153 *bytes);
1154 assert(*bytes > 0);
1157 * Calculate the number of clusters to look for. We stop at L2 table
1158 * boundaries to keep things simple.
1160 nb_clusters =
1161 size_to_clusters(s, offset_into_cluster(s, guest_offset) + *bytes);
1163 l2_index = offset_to_l2_index(s, guest_offset);
1164 nb_clusters = MIN(nb_clusters, s->l2_size - l2_index);
1165 assert(nb_clusters <= INT_MAX);
1167 /* Find L2 entry for the first involved cluster */
1168 ret = get_cluster_table(bs, guest_offset, &l2_table, &l2_index);
1169 if (ret < 0) {
1170 return ret;
1173 entry = be64_to_cpu(l2_table[l2_index]);
1175 /* For the moment, overwrite compressed clusters one by one */
1176 if (entry & QCOW_OFLAG_COMPRESSED) {
1177 nb_clusters = 1;
1178 } else {
1179 nb_clusters = count_cow_clusters(s, nb_clusters, l2_table, l2_index);
1182 /* This function is only called when there were no non-COW clusters, so if
1183 * we can't find any unallocated or COW clusters either, something is
1184 * wrong with our code. */
1185 assert(nb_clusters > 0);
1187 if (qcow2_get_cluster_type(entry) == QCOW2_CLUSTER_ZERO_ALLOC &&
1188 (entry & QCOW_OFLAG_COPIED) &&
1189 (!*host_offset ||
1190 start_of_cluster(s, *host_offset) == (entry & L2E_OFFSET_MASK)))
1192 /* Try to reuse preallocated zero clusters; contiguous normal clusters
1193 * would be fine, too, but count_cow_clusters() above has limited
1194 * nb_clusters already to a range of COW clusters */
1195 int preallocated_nb_clusters =
1196 count_contiguous_clusters(nb_clusters, s->cluster_size,
1197 &l2_table[l2_index], QCOW_OFLAG_COPIED);
1198 assert(preallocated_nb_clusters > 0);
1200 nb_clusters = preallocated_nb_clusters;
1201 alloc_cluster_offset = entry & L2E_OFFSET_MASK;
1203 /* We want to reuse these clusters, so qcow2_alloc_cluster_link_l2()
1204 * should not free them. */
1205 keep_old_clusters = true;
1208 qcow2_cache_put(bs, s->l2_table_cache, (void **) &l2_table);
1210 if (!alloc_cluster_offset) {
1211 /* Allocate, if necessary at a given offset in the image file */
1212 alloc_cluster_offset = start_of_cluster(s, *host_offset);
1213 ret = do_alloc_cluster_offset(bs, guest_offset, &alloc_cluster_offset,
1214 &nb_clusters);
1215 if (ret < 0) {
1216 goto fail;
1219 /* Can't extend contiguous allocation */
1220 if (nb_clusters == 0) {
1221 *bytes = 0;
1222 return 0;
1225 /* !*host_offset would overwrite the image header and is reserved for
1226 * "no host offset preferred". If 0 was a valid host offset, it'd
1227 * trigger the following overlap check; do that now to avoid having an
1228 * invalid value in *host_offset. */
1229 if (!alloc_cluster_offset) {
1230 ret = qcow2_pre_write_overlap_check(bs, 0, alloc_cluster_offset,
1231 nb_clusters * s->cluster_size);
1232 assert(ret < 0);
1233 goto fail;
1238 * Save info needed for meta data update.
1240 * requested_bytes: Number of bytes from the start of the first
1241 * newly allocated cluster to the end of the (possibly shortened
1242 * before) write request.
1244 * avail_bytes: Number of bytes from the start of the first
1245 * newly allocated to the end of the last newly allocated cluster.
1247 * nb_bytes: The number of bytes from the start of the first
1248 * newly allocated cluster to the end of the area that the write
1249 * request actually writes to (excluding COW at the end)
1251 uint64_t requested_bytes = *bytes + offset_into_cluster(s, guest_offset);
1252 int avail_bytes = MIN(INT_MAX, nb_clusters << s->cluster_bits);
1253 int nb_bytes = MIN(requested_bytes, avail_bytes);
1254 QCowL2Meta *old_m = *m;
1256 *m = g_malloc0(sizeof(**m));
1258 **m = (QCowL2Meta) {
1259 .next = old_m,
1261 .alloc_offset = alloc_cluster_offset,
1262 .offset = start_of_cluster(s, guest_offset),
1263 .nb_clusters = nb_clusters,
1265 .keep_old_clusters = keep_old_clusters,
1267 .cow_start = {
1268 .offset = 0,
1269 .nb_bytes = offset_into_cluster(s, guest_offset),
1271 .cow_end = {
1272 .offset = nb_bytes,
1273 .nb_bytes = avail_bytes - nb_bytes,
1276 qemu_co_queue_init(&(*m)->dependent_requests);
1277 QLIST_INSERT_HEAD(&s->cluster_allocs, *m, next_in_flight);
1279 *host_offset = alloc_cluster_offset + offset_into_cluster(s, guest_offset);
1280 *bytes = MIN(*bytes, nb_bytes - offset_into_cluster(s, guest_offset));
1281 assert(*bytes != 0);
1283 return 1;
1285 fail:
1286 if (*m && (*m)->nb_clusters > 0) {
1287 QLIST_REMOVE(*m, next_in_flight);
1289 return ret;
1293 * alloc_cluster_offset
1295 * For a given offset on the virtual disk, find the cluster offset in qcow2
1296 * file. If the offset is not found, allocate a new cluster.
1298 * If the cluster was already allocated, m->nb_clusters is set to 0 and
1299 * other fields in m are meaningless.
1301 * If the cluster is newly allocated, m->nb_clusters is set to the number of
1302 * contiguous clusters that have been allocated. In this case, the other
1303 * fields of m are valid and contain information about the first allocated
1304 * cluster.
1306 * If the request conflicts with another write request in flight, the coroutine
1307 * is queued and will be reentered when the dependency has completed.
1309 * Return 0 on success and -errno in error cases
1311 int qcow2_alloc_cluster_offset(BlockDriverState *bs, uint64_t offset,
1312 unsigned int *bytes, uint64_t *host_offset,
1313 QCowL2Meta **m)
1315 BDRVQcow2State *s = bs->opaque;
1316 uint64_t start, remaining;
1317 uint64_t cluster_offset;
1318 uint64_t cur_bytes;
1319 int ret;
1321 trace_qcow2_alloc_clusters_offset(qemu_coroutine_self(), offset, *bytes);
1323 again:
1324 start = offset;
1325 remaining = *bytes;
1326 cluster_offset = 0;
1327 *host_offset = 0;
1328 cur_bytes = 0;
1329 *m = NULL;
1331 while (true) {
1333 if (!*host_offset) {
1334 *host_offset = start_of_cluster(s, cluster_offset);
1337 assert(remaining >= cur_bytes);
1339 start += cur_bytes;
1340 remaining -= cur_bytes;
1341 cluster_offset += cur_bytes;
1343 if (remaining == 0) {
1344 break;
1347 cur_bytes = remaining;
1350 * Now start gathering as many contiguous clusters as possible:
1352 * 1. Check for overlaps with in-flight allocations
1354 * a) Overlap not in the first cluster -> shorten this request and
1355 * let the caller handle the rest in its next loop iteration.
1357 * b) Real overlaps of two requests. Yield and restart the search
1358 * for contiguous clusters (the situation could have changed
1359 * while we were sleeping)
1361 * c) TODO: Request starts in the same cluster as the in-flight
1362 * allocation ends. Shorten the COW of the in-fight allocation,
1363 * set cluster_offset to write to the same cluster and set up
1364 * the right synchronisation between the in-flight request and
1365 * the new one.
1367 ret = handle_dependencies(bs, start, &cur_bytes, m);
1368 if (ret == -EAGAIN) {
1369 /* Currently handle_dependencies() doesn't yield if we already had
1370 * an allocation. If it did, we would have to clean up the L2Meta
1371 * structs before starting over. */
1372 assert(*m == NULL);
1373 goto again;
1374 } else if (ret < 0) {
1375 return ret;
1376 } else if (cur_bytes == 0) {
1377 break;
1378 } else {
1379 /* handle_dependencies() may have decreased cur_bytes (shortened
1380 * the allocations below) so that the next dependency is processed
1381 * correctly during the next loop iteration. */
1385 * 2. Count contiguous COPIED clusters.
1387 ret = handle_copied(bs, start, &cluster_offset, &cur_bytes, m);
1388 if (ret < 0) {
1389 return ret;
1390 } else if (ret) {
1391 continue;
1392 } else if (cur_bytes == 0) {
1393 break;
1397 * 3. If the request still hasn't completed, allocate new clusters,
1398 * considering any cluster_offset of steps 1c or 2.
1400 ret = handle_alloc(bs, start, &cluster_offset, &cur_bytes, m);
1401 if (ret < 0) {
1402 return ret;
1403 } else if (ret) {
1404 continue;
1405 } else {
1406 assert(cur_bytes == 0);
1407 break;
1411 *bytes -= remaining;
1412 assert(*bytes > 0);
1413 assert(*host_offset != 0);
1415 return 0;
1418 static int decompress_buffer(uint8_t *out_buf, int out_buf_size,
1419 const uint8_t *buf, int buf_size)
1421 z_stream strm1, *strm = &strm1;
1422 int ret, out_len;
1424 memset(strm, 0, sizeof(*strm));
1426 strm->next_in = (uint8_t *)buf;
1427 strm->avail_in = buf_size;
1428 strm->next_out = out_buf;
1429 strm->avail_out = out_buf_size;
1431 ret = inflateInit2(strm, -12);
1432 if (ret != Z_OK)
1433 return -1;
1434 ret = inflate(strm, Z_FINISH);
1435 out_len = strm->next_out - out_buf;
1436 if ((ret != Z_STREAM_END && ret != Z_BUF_ERROR) ||
1437 out_len != out_buf_size) {
1438 inflateEnd(strm);
1439 return -1;
1441 inflateEnd(strm);
1442 return 0;
1445 int qcow2_decompress_cluster(BlockDriverState *bs, uint64_t cluster_offset)
1447 BDRVQcow2State *s = bs->opaque;
1448 int ret, csize, nb_csectors, sector_offset;
1449 uint64_t coffset;
1451 coffset = cluster_offset & s->cluster_offset_mask;
1452 if (s->cluster_cache_offset != coffset) {
1453 nb_csectors = ((cluster_offset >> s->csize_shift) & s->csize_mask) + 1;
1454 sector_offset = coffset & 511;
1455 csize = nb_csectors * 512 - sector_offset;
1456 BLKDBG_EVENT(bs->file, BLKDBG_READ_COMPRESSED);
1457 ret = bdrv_read(bs->file, coffset >> 9, s->cluster_data,
1458 nb_csectors);
1459 if (ret < 0) {
1460 return ret;
1462 if (decompress_buffer(s->cluster_cache, s->cluster_size,
1463 s->cluster_data + sector_offset, csize) < 0) {
1464 return -EIO;
1466 s->cluster_cache_offset = coffset;
1468 return 0;
1472 * This discards as many clusters of nb_clusters as possible at once (i.e.
1473 * all clusters in the same L2 table) and returns the number of discarded
1474 * clusters.
1476 static int discard_single_l2(BlockDriverState *bs, uint64_t offset,
1477 uint64_t nb_clusters, enum qcow2_discard_type type,
1478 bool full_discard)
1480 BDRVQcow2State *s = bs->opaque;
1481 uint64_t *l2_table;
1482 int l2_index;
1483 int ret;
1484 int i;
1486 ret = get_cluster_table(bs, offset, &l2_table, &l2_index);
1487 if (ret < 0) {
1488 return ret;
1491 /* Limit nb_clusters to one L2 table */
1492 nb_clusters = MIN(nb_clusters, s->l2_size - l2_index);
1493 assert(nb_clusters <= INT_MAX);
1495 for (i = 0; i < nb_clusters; i++) {
1496 uint64_t old_l2_entry;
1498 old_l2_entry = be64_to_cpu(l2_table[l2_index + i]);
1501 * If full_discard is false, make sure that a discarded area reads back
1502 * as zeroes for v3 images (we cannot do it for v2 without actually
1503 * writing a zero-filled buffer). We can skip the operation if the
1504 * cluster is already marked as zero, or if it's unallocated and we
1505 * don't have a backing file.
1507 * TODO We might want to use bdrv_get_block_status(bs) here, but we're
1508 * holding s->lock, so that doesn't work today.
1510 * If full_discard is true, the sector should not read back as zeroes,
1511 * but rather fall through to the backing file.
1513 switch (qcow2_get_cluster_type(old_l2_entry)) {
1514 case QCOW2_CLUSTER_UNALLOCATED:
1515 if (full_discard || !bs->backing) {
1516 continue;
1518 break;
1520 case QCOW2_CLUSTER_ZERO_PLAIN:
1521 if (!full_discard) {
1522 continue;
1524 break;
1526 case QCOW2_CLUSTER_ZERO_ALLOC:
1527 case QCOW2_CLUSTER_NORMAL:
1528 case QCOW2_CLUSTER_COMPRESSED:
1529 break;
1531 default:
1532 abort();
1535 /* First remove L2 entries */
1536 qcow2_cache_entry_mark_dirty(bs, s->l2_table_cache, l2_table);
1537 if (!full_discard && s->qcow_version >= 3) {
1538 l2_table[l2_index + i] = cpu_to_be64(QCOW_OFLAG_ZERO);
1539 } else {
1540 l2_table[l2_index + i] = cpu_to_be64(0);
1543 /* Then decrease the refcount */
1544 qcow2_free_any_clusters(bs, old_l2_entry, 1, type);
1547 qcow2_cache_put(bs, s->l2_table_cache, (void **) &l2_table);
1549 return nb_clusters;
1552 int qcow2_cluster_discard(BlockDriverState *bs, uint64_t offset,
1553 uint64_t bytes, enum qcow2_discard_type type,
1554 bool full_discard)
1556 BDRVQcow2State *s = bs->opaque;
1557 uint64_t end_offset = offset + bytes;
1558 uint64_t nb_clusters;
1559 int64_t cleared;
1560 int ret;
1562 /* Caller must pass aligned values, except at image end */
1563 assert(QEMU_IS_ALIGNED(offset, s->cluster_size));
1564 assert(QEMU_IS_ALIGNED(end_offset, s->cluster_size) ||
1565 end_offset == bs->total_sectors << BDRV_SECTOR_BITS);
1567 nb_clusters = size_to_clusters(s, bytes);
1569 s->cache_discards = true;
1571 /* Each L2 table is handled by its own loop iteration */
1572 while (nb_clusters > 0) {
1573 cleared = discard_single_l2(bs, offset, nb_clusters, type,
1574 full_discard);
1575 if (cleared < 0) {
1576 ret = cleared;
1577 goto fail;
1580 nb_clusters -= cleared;
1581 offset += (cleared * s->cluster_size);
1584 ret = 0;
1585 fail:
1586 s->cache_discards = false;
1587 qcow2_process_discards(bs, ret);
1589 return ret;
1593 * This zeroes as many clusters of nb_clusters as possible at once (i.e.
1594 * all clusters in the same L2 table) and returns the number of zeroed
1595 * clusters.
1597 static int zero_single_l2(BlockDriverState *bs, uint64_t offset,
1598 uint64_t nb_clusters, int flags)
1600 BDRVQcow2State *s = bs->opaque;
1601 uint64_t *l2_table;
1602 int l2_index;
1603 int ret;
1604 int i;
1605 bool unmap = !!(flags & BDRV_REQ_MAY_UNMAP);
1607 ret = get_cluster_table(bs, offset, &l2_table, &l2_index);
1608 if (ret < 0) {
1609 return ret;
1612 /* Limit nb_clusters to one L2 table */
1613 nb_clusters = MIN(nb_clusters, s->l2_size - l2_index);
1614 assert(nb_clusters <= INT_MAX);
1616 for (i = 0; i < nb_clusters; i++) {
1617 uint64_t old_offset;
1618 QCow2ClusterType cluster_type;
1620 old_offset = be64_to_cpu(l2_table[l2_index + i]);
1623 * Minimize L2 changes if the cluster already reads back as
1624 * zeroes with correct allocation.
1626 cluster_type = qcow2_get_cluster_type(old_offset);
1627 if (cluster_type == QCOW2_CLUSTER_ZERO_PLAIN ||
1628 (cluster_type == QCOW2_CLUSTER_ZERO_ALLOC && !unmap)) {
1629 continue;
1632 qcow2_cache_entry_mark_dirty(bs, s->l2_table_cache, l2_table);
1633 if (cluster_type == QCOW2_CLUSTER_COMPRESSED || unmap) {
1634 l2_table[l2_index + i] = cpu_to_be64(QCOW_OFLAG_ZERO);
1635 qcow2_free_any_clusters(bs, old_offset, 1, QCOW2_DISCARD_REQUEST);
1636 } else {
1637 l2_table[l2_index + i] |= cpu_to_be64(QCOW_OFLAG_ZERO);
1641 qcow2_cache_put(bs, s->l2_table_cache, (void **) &l2_table);
1643 return nb_clusters;
1646 int qcow2_cluster_zeroize(BlockDriverState *bs, uint64_t offset,
1647 uint64_t bytes, int flags)
1649 BDRVQcow2State *s = bs->opaque;
1650 uint64_t end_offset = offset + bytes;
1651 uint64_t nb_clusters;
1652 int64_t cleared;
1653 int ret;
1655 /* Caller must pass aligned values, except at image end */
1656 assert(QEMU_IS_ALIGNED(offset, s->cluster_size));
1657 assert(QEMU_IS_ALIGNED(end_offset, s->cluster_size) ||
1658 end_offset == bs->total_sectors << BDRV_SECTOR_BITS);
1660 /* The zero flag is only supported by version 3 and newer */
1661 if (s->qcow_version < 3) {
1662 return -ENOTSUP;
1665 /* Each L2 table is handled by its own loop iteration */
1666 nb_clusters = size_to_clusters(s, bytes);
1668 s->cache_discards = true;
1670 while (nb_clusters > 0) {
1671 cleared = zero_single_l2(bs, offset, nb_clusters, flags);
1672 if (cleared < 0) {
1673 ret = cleared;
1674 goto fail;
1677 nb_clusters -= cleared;
1678 offset += (cleared * s->cluster_size);
1681 ret = 0;
1682 fail:
1683 s->cache_discards = false;
1684 qcow2_process_discards(bs, ret);
1686 return ret;
1690 * Expands all zero clusters in a specific L1 table (or deallocates them, for
1691 * non-backed non-pre-allocated zero clusters).
1693 * l1_entries and *visited_l1_entries are used to keep track of progress for
1694 * status_cb(). l1_entries contains the total number of L1 entries and
1695 * *visited_l1_entries counts all visited L1 entries.
1697 static int expand_zero_clusters_in_l1(BlockDriverState *bs, uint64_t *l1_table,
1698 int l1_size, int64_t *visited_l1_entries,
1699 int64_t l1_entries,
1700 BlockDriverAmendStatusCB *status_cb,
1701 void *cb_opaque)
1703 BDRVQcow2State *s = bs->opaque;
1704 bool is_active_l1 = (l1_table == s->l1_table);
1705 uint64_t *l2_table = NULL;
1706 int ret;
1707 int i, j;
1709 if (!is_active_l1) {
1710 /* inactive L2 tables require a buffer to be stored in when loading
1711 * them from disk */
1712 l2_table = qemu_try_blockalign(bs->file->bs, s->cluster_size);
1713 if (l2_table == NULL) {
1714 return -ENOMEM;
1718 for (i = 0; i < l1_size; i++) {
1719 uint64_t l2_offset = l1_table[i] & L1E_OFFSET_MASK;
1720 bool l2_dirty = false;
1721 uint64_t l2_refcount;
1723 if (!l2_offset) {
1724 /* unallocated */
1725 (*visited_l1_entries)++;
1726 if (status_cb) {
1727 status_cb(bs, *visited_l1_entries, l1_entries, cb_opaque);
1729 continue;
1732 if (offset_into_cluster(s, l2_offset)) {
1733 qcow2_signal_corruption(bs, true, -1, -1, "L2 table offset %#"
1734 PRIx64 " unaligned (L1 index: %#x)",
1735 l2_offset, i);
1736 ret = -EIO;
1737 goto fail;
1740 if (is_active_l1) {
1741 /* get active L2 tables from cache */
1742 ret = qcow2_cache_get(bs, s->l2_table_cache, l2_offset,
1743 (void **)&l2_table);
1744 } else {
1745 /* load inactive L2 tables from disk */
1746 ret = bdrv_read(bs->file, l2_offset / BDRV_SECTOR_SIZE,
1747 (void *)l2_table, s->cluster_sectors);
1749 if (ret < 0) {
1750 goto fail;
1753 ret = qcow2_get_refcount(bs, l2_offset >> s->cluster_bits,
1754 &l2_refcount);
1755 if (ret < 0) {
1756 goto fail;
1759 for (j = 0; j < s->l2_size; j++) {
1760 uint64_t l2_entry = be64_to_cpu(l2_table[j]);
1761 int64_t offset = l2_entry & L2E_OFFSET_MASK;
1762 QCow2ClusterType cluster_type = qcow2_get_cluster_type(l2_entry);
1764 if (cluster_type != QCOW2_CLUSTER_ZERO_PLAIN &&
1765 cluster_type != QCOW2_CLUSTER_ZERO_ALLOC) {
1766 continue;
1769 if (cluster_type == QCOW2_CLUSTER_ZERO_PLAIN) {
1770 if (!bs->backing) {
1771 /* not backed; therefore we can simply deallocate the
1772 * cluster */
1773 l2_table[j] = 0;
1774 l2_dirty = true;
1775 continue;
1778 offset = qcow2_alloc_clusters(bs, s->cluster_size);
1779 if (offset < 0) {
1780 ret = offset;
1781 goto fail;
1784 if (l2_refcount > 1) {
1785 /* For shared L2 tables, set the refcount accordingly (it is
1786 * already 1 and needs to be l2_refcount) */
1787 ret = qcow2_update_cluster_refcount(bs,
1788 offset >> s->cluster_bits,
1789 refcount_diff(1, l2_refcount), false,
1790 QCOW2_DISCARD_OTHER);
1791 if (ret < 0) {
1792 qcow2_free_clusters(bs, offset, s->cluster_size,
1793 QCOW2_DISCARD_OTHER);
1794 goto fail;
1799 if (offset_into_cluster(s, offset)) {
1800 qcow2_signal_corruption(bs, true, -1, -1,
1801 "Cluster allocation offset "
1802 "%#" PRIx64 " unaligned (L2 offset: %#"
1803 PRIx64 ", L2 index: %#x)", offset,
1804 l2_offset, j);
1805 if (cluster_type == QCOW2_CLUSTER_ZERO_PLAIN) {
1806 qcow2_free_clusters(bs, offset, s->cluster_size,
1807 QCOW2_DISCARD_ALWAYS);
1809 ret = -EIO;
1810 goto fail;
1813 ret = qcow2_pre_write_overlap_check(bs, 0, offset, s->cluster_size);
1814 if (ret < 0) {
1815 if (cluster_type == QCOW2_CLUSTER_ZERO_PLAIN) {
1816 qcow2_free_clusters(bs, offset, s->cluster_size,
1817 QCOW2_DISCARD_ALWAYS);
1819 goto fail;
1822 ret = bdrv_pwrite_zeroes(bs->file, offset, s->cluster_size, 0);
1823 if (ret < 0) {
1824 if (cluster_type == QCOW2_CLUSTER_ZERO_PLAIN) {
1825 qcow2_free_clusters(bs, offset, s->cluster_size,
1826 QCOW2_DISCARD_ALWAYS);
1828 goto fail;
1831 if (l2_refcount == 1) {
1832 l2_table[j] = cpu_to_be64(offset | QCOW_OFLAG_COPIED);
1833 } else {
1834 l2_table[j] = cpu_to_be64(offset);
1836 l2_dirty = true;
1839 if (is_active_l1) {
1840 if (l2_dirty) {
1841 qcow2_cache_entry_mark_dirty(bs, s->l2_table_cache, l2_table);
1842 qcow2_cache_depends_on_flush(s->l2_table_cache);
1844 qcow2_cache_put(bs, s->l2_table_cache, (void **) &l2_table);
1845 } else {
1846 if (l2_dirty) {
1847 ret = qcow2_pre_write_overlap_check(bs,
1848 QCOW2_OL_INACTIVE_L2 | QCOW2_OL_ACTIVE_L2, l2_offset,
1849 s->cluster_size);
1850 if (ret < 0) {
1851 goto fail;
1854 ret = bdrv_write(bs->file, l2_offset / BDRV_SECTOR_SIZE,
1855 (void *)l2_table, s->cluster_sectors);
1856 if (ret < 0) {
1857 goto fail;
1862 (*visited_l1_entries)++;
1863 if (status_cb) {
1864 status_cb(bs, *visited_l1_entries, l1_entries, cb_opaque);
1868 ret = 0;
1870 fail:
1871 if (l2_table) {
1872 if (!is_active_l1) {
1873 qemu_vfree(l2_table);
1874 } else {
1875 qcow2_cache_put(bs, s->l2_table_cache, (void **) &l2_table);
1878 return ret;
1882 * For backed images, expands all zero clusters on the image. For non-backed
1883 * images, deallocates all non-pre-allocated zero clusters (and claims the
1884 * allocation for pre-allocated ones). This is important for downgrading to a
1885 * qcow2 version which doesn't yet support metadata zero clusters.
1887 int qcow2_expand_zero_clusters(BlockDriverState *bs,
1888 BlockDriverAmendStatusCB *status_cb,
1889 void *cb_opaque)
1891 BDRVQcow2State *s = bs->opaque;
1892 uint64_t *l1_table = NULL;
1893 int64_t l1_entries = 0, visited_l1_entries = 0;
1894 int ret;
1895 int i, j;
1897 if (status_cb) {
1898 l1_entries = s->l1_size;
1899 for (i = 0; i < s->nb_snapshots; i++) {
1900 l1_entries += s->snapshots[i].l1_size;
1904 ret = expand_zero_clusters_in_l1(bs, s->l1_table, s->l1_size,
1905 &visited_l1_entries, l1_entries,
1906 status_cb, cb_opaque);
1907 if (ret < 0) {
1908 goto fail;
1911 /* Inactive L1 tables may point to active L2 tables - therefore it is
1912 * necessary to flush the L2 table cache before trying to access the L2
1913 * tables pointed to by inactive L1 entries (else we might try to expand
1914 * zero clusters that have already been expanded); furthermore, it is also
1915 * necessary to empty the L2 table cache, since it may contain tables which
1916 * are now going to be modified directly on disk, bypassing the cache.
1917 * qcow2_cache_empty() does both for us. */
1918 ret = qcow2_cache_empty(bs, s->l2_table_cache);
1919 if (ret < 0) {
1920 goto fail;
1923 for (i = 0; i < s->nb_snapshots; i++) {
1924 int l1_sectors = DIV_ROUND_UP(s->snapshots[i].l1_size *
1925 sizeof(uint64_t), BDRV_SECTOR_SIZE);
1927 l1_table = g_realloc(l1_table, l1_sectors * BDRV_SECTOR_SIZE);
1929 ret = bdrv_read(bs->file,
1930 s->snapshots[i].l1_table_offset / BDRV_SECTOR_SIZE,
1931 (void *)l1_table, l1_sectors);
1932 if (ret < 0) {
1933 goto fail;
1936 for (j = 0; j < s->snapshots[i].l1_size; j++) {
1937 be64_to_cpus(&l1_table[j]);
1940 ret = expand_zero_clusters_in_l1(bs, l1_table, s->snapshots[i].l1_size,
1941 &visited_l1_entries, l1_entries,
1942 status_cb, cb_opaque);
1943 if (ret < 0) {
1944 goto fail;
1948 ret = 0;
1950 fail:
1951 g_free(l1_table);
1952 return ret;