qcow2: Add qcow2_get_subcluster_range_type()
[qemu/ar7.git] / block / qcow2-cluster.c
blob2fe7a0f79c458c542817046dc7b90ac6e4d5d8c7
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 "qcow2.h"
30 #include "qemu/bswap.h"
31 #include "trace.h"
33 int qcow2_shrink_l1_table(BlockDriverState *bs, uint64_t exact_size)
35 BDRVQcow2State *s = bs->opaque;
36 int new_l1_size, i, ret;
38 if (exact_size >= s->l1_size) {
39 return 0;
42 new_l1_size = exact_size;
44 #ifdef DEBUG_ALLOC2
45 fprintf(stderr, "shrink l1_table from %d to %d\n", s->l1_size, new_l1_size);
46 #endif
48 BLKDBG_EVENT(bs->file, BLKDBG_L1_SHRINK_WRITE_TABLE);
49 ret = bdrv_pwrite_zeroes(bs->file, s->l1_table_offset +
50 new_l1_size * sizeof(uint64_t),
51 (s->l1_size - new_l1_size) * sizeof(uint64_t), 0);
52 if (ret < 0) {
53 goto fail;
56 ret = bdrv_flush(bs->file->bs);
57 if (ret < 0) {
58 goto fail;
61 BLKDBG_EVENT(bs->file, BLKDBG_L1_SHRINK_FREE_L2_CLUSTERS);
62 for (i = s->l1_size - 1; i > new_l1_size - 1; i--) {
63 if ((s->l1_table[i] & L1E_OFFSET_MASK) == 0) {
64 continue;
66 qcow2_free_clusters(bs, s->l1_table[i] & L1E_OFFSET_MASK,
67 s->cluster_size, QCOW2_DISCARD_ALWAYS);
68 s->l1_table[i] = 0;
70 return 0;
72 fail:
74 * If the write in the l1_table failed the image may contain a partially
75 * overwritten l1_table. In this case it would be better to clear the
76 * l1_table in memory to avoid possible image corruption.
78 memset(s->l1_table + new_l1_size, 0,
79 (s->l1_size - new_l1_size) * sizeof(uint64_t));
80 return ret;
83 int qcow2_grow_l1_table(BlockDriverState *bs, uint64_t min_size,
84 bool exact_size)
86 BDRVQcow2State *s = bs->opaque;
87 int new_l1_size2, ret, i;
88 uint64_t *new_l1_table;
89 int64_t old_l1_table_offset, old_l1_size;
90 int64_t new_l1_table_offset, new_l1_size;
91 uint8_t data[12];
93 if (min_size <= s->l1_size)
94 return 0;
96 /* Do a sanity check on min_size before trying to calculate new_l1_size
97 * (this prevents overflows during the while loop for the calculation of
98 * new_l1_size) */
99 if (min_size > INT_MAX / sizeof(uint64_t)) {
100 return -EFBIG;
103 if (exact_size) {
104 new_l1_size = min_size;
105 } else {
106 /* Bump size up to reduce the number of times we have to grow */
107 new_l1_size = s->l1_size;
108 if (new_l1_size == 0) {
109 new_l1_size = 1;
111 while (min_size > new_l1_size) {
112 new_l1_size = DIV_ROUND_UP(new_l1_size * 3, 2);
116 QEMU_BUILD_BUG_ON(QCOW_MAX_L1_SIZE > INT_MAX);
117 if (new_l1_size > QCOW_MAX_L1_SIZE / sizeof(uint64_t)) {
118 return -EFBIG;
121 #ifdef DEBUG_ALLOC2
122 fprintf(stderr, "grow l1_table from %d to %" PRId64 "\n",
123 s->l1_size, new_l1_size);
124 #endif
126 new_l1_size2 = sizeof(uint64_t) * new_l1_size;
127 new_l1_table = qemu_try_blockalign(bs->file->bs, new_l1_size2);
128 if (new_l1_table == NULL) {
129 return -ENOMEM;
131 memset(new_l1_table, 0, new_l1_size2);
133 if (s->l1_size) {
134 memcpy(new_l1_table, s->l1_table, s->l1_size * sizeof(uint64_t));
137 /* write new table (align to cluster) */
138 BLKDBG_EVENT(bs->file, BLKDBG_L1_GROW_ALLOC_TABLE);
139 new_l1_table_offset = qcow2_alloc_clusters(bs, new_l1_size2);
140 if (new_l1_table_offset < 0) {
141 qemu_vfree(new_l1_table);
142 return new_l1_table_offset;
145 ret = qcow2_cache_flush(bs, s->refcount_block_cache);
146 if (ret < 0) {
147 goto fail;
150 /* the L1 position has not yet been updated, so these clusters must
151 * indeed be completely free */
152 ret = qcow2_pre_write_overlap_check(bs, 0, new_l1_table_offset,
153 new_l1_size2, false);
154 if (ret < 0) {
155 goto fail;
158 BLKDBG_EVENT(bs->file, BLKDBG_L1_GROW_WRITE_TABLE);
159 for(i = 0; i < s->l1_size; i++)
160 new_l1_table[i] = cpu_to_be64(new_l1_table[i]);
161 ret = bdrv_pwrite_sync(bs->file, new_l1_table_offset,
162 new_l1_table, new_l1_size2);
163 if (ret < 0)
164 goto fail;
165 for(i = 0; i < s->l1_size; i++)
166 new_l1_table[i] = be64_to_cpu(new_l1_table[i]);
168 /* set new table */
169 BLKDBG_EVENT(bs->file, BLKDBG_L1_GROW_ACTIVATE_TABLE);
170 stl_be_p(data, new_l1_size);
171 stq_be_p(data + 4, new_l1_table_offset);
172 ret = bdrv_pwrite_sync(bs->file, offsetof(QCowHeader, l1_size),
173 data, sizeof(data));
174 if (ret < 0) {
175 goto fail;
177 qemu_vfree(s->l1_table);
178 old_l1_table_offset = s->l1_table_offset;
179 s->l1_table_offset = new_l1_table_offset;
180 s->l1_table = new_l1_table;
181 old_l1_size = s->l1_size;
182 s->l1_size = new_l1_size;
183 qcow2_free_clusters(bs, old_l1_table_offset, old_l1_size * sizeof(uint64_t),
184 QCOW2_DISCARD_OTHER);
185 return 0;
186 fail:
187 qemu_vfree(new_l1_table);
188 qcow2_free_clusters(bs, new_l1_table_offset, new_l1_size2,
189 QCOW2_DISCARD_OTHER);
190 return ret;
194 * l2_load
196 * @bs: The BlockDriverState
197 * @offset: A guest offset, used to calculate what slice of the L2
198 * table to load.
199 * @l2_offset: Offset to the L2 table in the image file.
200 * @l2_slice: Location to store the pointer to the L2 slice.
202 * Loads a L2 slice into memory (L2 slices are the parts of L2 tables
203 * that are loaded by the qcow2 cache). If the slice is in the cache,
204 * the cache is used; otherwise the L2 slice is loaded from the image
205 * file.
207 static int l2_load(BlockDriverState *bs, uint64_t offset,
208 uint64_t l2_offset, uint64_t **l2_slice)
210 BDRVQcow2State *s = bs->opaque;
211 int start_of_slice = l2_entry_size(s) *
212 (offset_to_l2_index(s, offset) - offset_to_l2_slice_index(s, offset));
214 return qcow2_cache_get(bs, s->l2_table_cache, l2_offset + start_of_slice,
215 (void **)l2_slice);
219 * Writes an L1 entry to disk (note that depending on the alignment
220 * requirements this function may write more that just one entry in
221 * order to prevent bdrv_pwrite from performing a read-modify-write)
223 int qcow2_write_l1_entry(BlockDriverState *bs, int l1_index)
225 BDRVQcow2State *s = bs->opaque;
226 int l1_start_index;
227 int i, ret;
228 int bufsize = MAX(sizeof(uint64_t),
229 MIN(bs->file->bs->bl.request_alignment, s->cluster_size));
230 int nentries = bufsize / sizeof(uint64_t);
231 g_autofree uint64_t *buf = g_try_new0(uint64_t, nentries);
233 if (buf == NULL) {
234 return -ENOMEM;
237 l1_start_index = QEMU_ALIGN_DOWN(l1_index, nentries);
238 for (i = 0; i < MIN(nentries, s->l1_size - l1_start_index); i++) {
239 buf[i] = cpu_to_be64(s->l1_table[l1_start_index + i]);
242 ret = qcow2_pre_write_overlap_check(bs, QCOW2_OL_ACTIVE_L1,
243 s->l1_table_offset + 8 * l1_start_index, bufsize, false);
244 if (ret < 0) {
245 return ret;
248 BLKDBG_EVENT(bs->file, BLKDBG_L1_UPDATE);
249 ret = bdrv_pwrite_sync(bs->file,
250 s->l1_table_offset + 8 * l1_start_index,
251 buf, bufsize);
252 if (ret < 0) {
253 return ret;
256 return 0;
260 * l2_allocate
262 * Allocate a new l2 entry in the file. If l1_index points to an already
263 * used entry in the L2 table (i.e. we are doing a copy on write for the L2
264 * table) copy the contents of the old L2 table into the newly allocated one.
265 * Otherwise the new table is initialized with zeros.
269 static int l2_allocate(BlockDriverState *bs, int l1_index)
271 BDRVQcow2State *s = bs->opaque;
272 uint64_t old_l2_offset;
273 uint64_t *l2_slice = NULL;
274 unsigned slice, slice_size2, n_slices;
275 int64_t l2_offset;
276 int ret;
278 old_l2_offset = s->l1_table[l1_index];
280 trace_qcow2_l2_allocate(bs, l1_index);
282 /* allocate a new l2 entry */
284 l2_offset = qcow2_alloc_clusters(bs, s->l2_size * l2_entry_size(s));
285 if (l2_offset < 0) {
286 ret = l2_offset;
287 goto fail;
290 /* The offset must fit in the offset field of the L1 table entry */
291 assert((l2_offset & L1E_OFFSET_MASK) == l2_offset);
293 /* If we're allocating the table at offset 0 then something is wrong */
294 if (l2_offset == 0) {
295 qcow2_signal_corruption(bs, true, -1, -1, "Preventing invalid "
296 "allocation of L2 table at offset 0");
297 ret = -EIO;
298 goto fail;
301 ret = qcow2_cache_flush(bs, s->refcount_block_cache);
302 if (ret < 0) {
303 goto fail;
306 /* allocate a new entry in the l2 cache */
308 slice_size2 = s->l2_slice_size * l2_entry_size(s);
309 n_slices = s->cluster_size / slice_size2;
311 trace_qcow2_l2_allocate_get_empty(bs, l1_index);
312 for (slice = 0; slice < n_slices; slice++) {
313 ret = qcow2_cache_get_empty(bs, s->l2_table_cache,
314 l2_offset + slice * slice_size2,
315 (void **) &l2_slice);
316 if (ret < 0) {
317 goto fail;
320 if ((old_l2_offset & L1E_OFFSET_MASK) == 0) {
321 /* if there was no old l2 table, clear the new slice */
322 memset(l2_slice, 0, slice_size2);
323 } else {
324 uint64_t *old_slice;
325 uint64_t old_l2_slice_offset =
326 (old_l2_offset & L1E_OFFSET_MASK) + slice * slice_size2;
328 /* if there was an old l2 table, read a slice from the disk */
329 BLKDBG_EVENT(bs->file, BLKDBG_L2_ALLOC_COW_READ);
330 ret = qcow2_cache_get(bs, s->l2_table_cache, old_l2_slice_offset,
331 (void **) &old_slice);
332 if (ret < 0) {
333 goto fail;
336 memcpy(l2_slice, old_slice, slice_size2);
338 qcow2_cache_put(s->l2_table_cache, (void **) &old_slice);
341 /* write the l2 slice to the file */
342 BLKDBG_EVENT(bs->file, BLKDBG_L2_ALLOC_WRITE);
344 trace_qcow2_l2_allocate_write_l2(bs, l1_index);
345 qcow2_cache_entry_mark_dirty(s->l2_table_cache, l2_slice);
346 qcow2_cache_put(s->l2_table_cache, (void **) &l2_slice);
349 ret = qcow2_cache_flush(bs, s->l2_table_cache);
350 if (ret < 0) {
351 goto fail;
354 /* update the L1 entry */
355 trace_qcow2_l2_allocate_write_l1(bs, l1_index);
356 s->l1_table[l1_index] = l2_offset | QCOW_OFLAG_COPIED;
357 ret = qcow2_write_l1_entry(bs, l1_index);
358 if (ret < 0) {
359 goto fail;
362 trace_qcow2_l2_allocate_done(bs, l1_index, 0);
363 return 0;
365 fail:
366 trace_qcow2_l2_allocate_done(bs, l1_index, ret);
367 if (l2_slice != NULL) {
368 qcow2_cache_put(s->l2_table_cache, (void **) &l2_slice);
370 s->l1_table[l1_index] = old_l2_offset;
371 if (l2_offset > 0) {
372 qcow2_free_clusters(bs, l2_offset, s->l2_size * l2_entry_size(s),
373 QCOW2_DISCARD_ALWAYS);
375 return ret;
379 * For a given L2 entry, count the number of contiguous subclusters of
380 * the same type starting from @sc_from. Compressed clusters are
381 * treated as if they were divided into subclusters of size
382 * s->subcluster_size.
384 * Return the number of contiguous subclusters and set @type to the
385 * subcluster type.
387 * If the L2 entry is invalid return -errno and set @type to
388 * QCOW2_SUBCLUSTER_INVALID.
390 G_GNUC_UNUSED
391 static int qcow2_get_subcluster_range_type(BlockDriverState *bs,
392 uint64_t l2_entry,
393 uint64_t l2_bitmap,
394 unsigned sc_from,
395 QCow2SubclusterType *type)
397 BDRVQcow2State *s = bs->opaque;
398 uint32_t val;
400 *type = qcow2_get_subcluster_type(bs, l2_entry, l2_bitmap, sc_from);
402 if (*type == QCOW2_SUBCLUSTER_INVALID) {
403 return -EINVAL;
404 } else if (!has_subclusters(s) || *type == QCOW2_SUBCLUSTER_COMPRESSED) {
405 return s->subclusters_per_cluster - sc_from;
408 switch (*type) {
409 case QCOW2_SUBCLUSTER_NORMAL:
410 val = l2_bitmap | QCOW_OFLAG_SUB_ALLOC_RANGE(0, sc_from);
411 return cto32(val) - sc_from;
413 case QCOW2_SUBCLUSTER_ZERO_PLAIN:
414 case QCOW2_SUBCLUSTER_ZERO_ALLOC:
415 val = (l2_bitmap | QCOW_OFLAG_SUB_ZERO_RANGE(0, sc_from)) >> 32;
416 return cto32(val) - sc_from;
418 case QCOW2_SUBCLUSTER_UNALLOCATED_PLAIN:
419 case QCOW2_SUBCLUSTER_UNALLOCATED_ALLOC:
420 val = ((l2_bitmap >> 32) | l2_bitmap)
421 & ~QCOW_OFLAG_SUB_ALLOC_RANGE(0, sc_from);
422 return ctz32(val) - sc_from;
424 default:
425 g_assert_not_reached();
430 * Checks how many clusters in a given L2 slice are contiguous in the image
431 * file. As soon as one of the flags in the bitmask stop_flags changes compared
432 * to the first cluster, the search is stopped and the cluster is not counted
433 * as contiguous. (This allows it, for example, to stop at the first compressed
434 * cluster which may require a different handling)
436 static int count_contiguous_clusters(BlockDriverState *bs, int nb_clusters,
437 int cluster_size, uint64_t *l2_slice, int l2_index, uint64_t stop_flags)
439 BDRVQcow2State *s = bs->opaque;
440 int i;
441 QCow2ClusterType first_cluster_type;
442 uint64_t mask = stop_flags | L2E_OFFSET_MASK | QCOW_OFLAG_COMPRESSED;
443 uint64_t first_entry = get_l2_entry(s, l2_slice, l2_index);
444 uint64_t offset = first_entry & mask;
446 first_cluster_type = qcow2_get_cluster_type(bs, first_entry);
447 if (first_cluster_type == QCOW2_CLUSTER_UNALLOCATED) {
448 return 0;
451 /* must be allocated */
452 assert(first_cluster_type == QCOW2_CLUSTER_NORMAL ||
453 first_cluster_type == QCOW2_CLUSTER_ZERO_ALLOC);
455 for (i = 0; i < nb_clusters; i++) {
456 uint64_t l2_entry = get_l2_entry(s, l2_slice, l2_index + i) & mask;
457 if (offset + (uint64_t) i * cluster_size != l2_entry) {
458 break;
462 return i;
466 * Checks how many consecutive unallocated clusters in a given L2
467 * slice have the same cluster type.
469 static int count_contiguous_clusters_unallocated(BlockDriverState *bs,
470 int nb_clusters,
471 uint64_t *l2_slice,
472 int l2_index,
473 QCow2ClusterType wanted_type)
475 BDRVQcow2State *s = bs->opaque;
476 int i;
478 assert(wanted_type == QCOW2_CLUSTER_ZERO_PLAIN ||
479 wanted_type == QCOW2_CLUSTER_UNALLOCATED);
480 for (i = 0; i < nb_clusters; i++) {
481 uint64_t entry = get_l2_entry(s, l2_slice, l2_index + i);
482 QCow2ClusterType type = qcow2_get_cluster_type(bs, entry);
484 if (type != wanted_type) {
485 break;
489 return i;
492 static int coroutine_fn do_perform_cow_read(BlockDriverState *bs,
493 uint64_t src_cluster_offset,
494 unsigned offset_in_cluster,
495 QEMUIOVector *qiov)
497 int ret;
499 if (qiov->size == 0) {
500 return 0;
503 BLKDBG_EVENT(bs->file, BLKDBG_COW_READ);
505 if (!bs->drv) {
506 return -ENOMEDIUM;
509 /* Call .bdrv_co_readv() directly instead of using the public block-layer
510 * interface. This avoids double I/O throttling and request tracking,
511 * which can lead to deadlock when block layer copy-on-read is enabled.
513 ret = bs->drv->bdrv_co_preadv_part(bs,
514 src_cluster_offset + offset_in_cluster,
515 qiov->size, qiov, 0, 0);
516 if (ret < 0) {
517 return ret;
520 return 0;
523 static int coroutine_fn do_perform_cow_write(BlockDriverState *bs,
524 uint64_t cluster_offset,
525 unsigned offset_in_cluster,
526 QEMUIOVector *qiov)
528 BDRVQcow2State *s = bs->opaque;
529 int ret;
531 if (qiov->size == 0) {
532 return 0;
535 ret = qcow2_pre_write_overlap_check(bs, 0,
536 cluster_offset + offset_in_cluster, qiov->size, true);
537 if (ret < 0) {
538 return ret;
541 BLKDBG_EVENT(bs->file, BLKDBG_COW_WRITE);
542 ret = bdrv_co_pwritev(s->data_file, cluster_offset + offset_in_cluster,
543 qiov->size, qiov, 0);
544 if (ret < 0) {
545 return ret;
548 return 0;
553 * get_host_offset
555 * For a given offset of the virtual disk find the equivalent host
556 * offset in the qcow2 file and store it in *host_offset. Neither
557 * offset needs to be aligned to a cluster boundary.
559 * If the cluster is unallocated then *host_offset will be 0.
560 * If the cluster is compressed then *host_offset will contain the
561 * complete compressed cluster descriptor.
563 * On entry, *bytes is the maximum number of contiguous bytes starting at
564 * offset that we are interested in.
566 * On exit, *bytes is the number of bytes starting at offset that have the same
567 * cluster type and (if applicable) are stored contiguously in the image file.
568 * Compressed clusters are always returned one by one.
570 * Returns the cluster type (QCOW2_CLUSTER_*) on success, -errno in error
571 * cases.
573 int qcow2_get_host_offset(BlockDriverState *bs, uint64_t offset,
574 unsigned int *bytes, uint64_t *host_offset)
576 BDRVQcow2State *s = bs->opaque;
577 unsigned int l2_index;
578 uint64_t l1_index, l2_offset, *l2_slice, l2_entry;
579 int c;
580 unsigned int offset_in_cluster;
581 uint64_t bytes_available, bytes_needed, nb_clusters;
582 QCow2ClusterType type;
583 int ret;
585 offset_in_cluster = offset_into_cluster(s, offset);
586 bytes_needed = (uint64_t) *bytes + offset_in_cluster;
588 /* compute how many bytes there are between the start of the cluster
589 * containing offset and the end of the l2 slice that contains
590 * the entry pointing to it */
591 bytes_available =
592 ((uint64_t) (s->l2_slice_size - offset_to_l2_slice_index(s, offset)))
593 << s->cluster_bits;
595 if (bytes_needed > bytes_available) {
596 bytes_needed = bytes_available;
599 *host_offset = 0;
601 /* seek to the l2 offset in the l1 table */
603 l1_index = offset_to_l1_index(s, offset);
604 if (l1_index >= s->l1_size) {
605 type = QCOW2_CLUSTER_UNALLOCATED;
606 goto out;
609 l2_offset = s->l1_table[l1_index] & L1E_OFFSET_MASK;
610 if (!l2_offset) {
611 type = QCOW2_CLUSTER_UNALLOCATED;
612 goto out;
615 if (offset_into_cluster(s, l2_offset)) {
616 qcow2_signal_corruption(bs, true, -1, -1, "L2 table offset %#" PRIx64
617 " unaligned (L1 index: %#" PRIx64 ")",
618 l2_offset, l1_index);
619 return -EIO;
622 /* load the l2 slice in memory */
624 ret = l2_load(bs, offset, l2_offset, &l2_slice);
625 if (ret < 0) {
626 return ret;
629 /* find the cluster offset for the given disk offset */
631 l2_index = offset_to_l2_slice_index(s, offset);
632 l2_entry = get_l2_entry(s, l2_slice, l2_index);
634 nb_clusters = size_to_clusters(s, bytes_needed);
635 /* bytes_needed <= *bytes + offset_in_cluster, both of which are unsigned
636 * integers; the minimum cluster size is 512, so this assertion is always
637 * true */
638 assert(nb_clusters <= INT_MAX);
640 type = qcow2_get_cluster_type(bs, l2_entry);
641 if (s->qcow_version < 3 && (type == QCOW2_CLUSTER_ZERO_PLAIN ||
642 type == QCOW2_CLUSTER_ZERO_ALLOC)) {
643 qcow2_signal_corruption(bs, true, -1, -1, "Zero cluster entry found"
644 " in pre-v3 image (L2 offset: %#" PRIx64
645 ", L2 index: %#x)", l2_offset, l2_index);
646 ret = -EIO;
647 goto fail;
649 switch (type) {
650 case QCOW2_CLUSTER_COMPRESSED:
651 if (has_data_file(bs)) {
652 qcow2_signal_corruption(bs, true, -1, -1, "Compressed cluster "
653 "entry found in image with external data "
654 "file (L2 offset: %#" PRIx64 ", L2 index: "
655 "%#x)", l2_offset, l2_index);
656 ret = -EIO;
657 goto fail;
659 /* Compressed clusters can only be processed one by one */
660 c = 1;
661 *host_offset = l2_entry & L2E_COMPRESSED_OFFSET_SIZE_MASK;
662 break;
663 case QCOW2_CLUSTER_ZERO_PLAIN:
664 case QCOW2_CLUSTER_UNALLOCATED:
665 /* how many empty clusters ? */
666 c = count_contiguous_clusters_unallocated(bs, nb_clusters,
667 l2_slice, l2_index, type);
668 break;
669 case QCOW2_CLUSTER_ZERO_ALLOC:
670 case QCOW2_CLUSTER_NORMAL: {
671 uint64_t host_cluster_offset = l2_entry & L2E_OFFSET_MASK;
672 *host_offset = host_cluster_offset + offset_in_cluster;
673 /* how many allocated clusters ? */
674 c = count_contiguous_clusters(bs, nb_clusters, s->cluster_size,
675 l2_slice, l2_index, QCOW_OFLAG_ZERO);
676 if (offset_into_cluster(s, host_cluster_offset)) {
677 qcow2_signal_corruption(bs, true, -1, -1,
678 "Cluster allocation offset %#"
679 PRIx64 " unaligned (L2 offset: %#" PRIx64
680 ", L2 index: %#x)", host_cluster_offset,
681 l2_offset, l2_index);
682 ret = -EIO;
683 goto fail;
685 if (has_data_file(bs) && *host_offset != offset) {
686 qcow2_signal_corruption(bs, true, -1, -1,
687 "External data file host cluster offset %#"
688 PRIx64 " does not match guest cluster "
689 "offset: %#" PRIx64
690 ", L2 index: %#x)", host_cluster_offset,
691 offset - offset_in_cluster, l2_index);
692 ret = -EIO;
693 goto fail;
695 break;
697 default:
698 abort();
701 qcow2_cache_put(s->l2_table_cache, (void **) &l2_slice);
703 bytes_available = (int64_t)c * s->cluster_size;
705 out:
706 if (bytes_available > bytes_needed) {
707 bytes_available = bytes_needed;
710 /* bytes_available <= bytes_needed <= *bytes + offset_in_cluster;
711 * subtracting offset_in_cluster will therefore definitely yield something
712 * not exceeding UINT_MAX */
713 assert(bytes_available - offset_in_cluster <= UINT_MAX);
714 *bytes = bytes_available - offset_in_cluster;
716 return type;
718 fail:
719 qcow2_cache_put(s->l2_table_cache, (void **)&l2_slice);
720 return ret;
724 * get_cluster_table
726 * for a given disk offset, load (and allocate if needed)
727 * the appropriate slice of its l2 table.
729 * the cluster index in the l2 slice is given to the caller.
731 * Returns 0 on success, -errno in failure case
733 static int get_cluster_table(BlockDriverState *bs, uint64_t offset,
734 uint64_t **new_l2_slice,
735 int *new_l2_index)
737 BDRVQcow2State *s = bs->opaque;
738 unsigned int l2_index;
739 uint64_t l1_index, l2_offset;
740 uint64_t *l2_slice = NULL;
741 int ret;
743 /* seek to the l2 offset in the l1 table */
745 l1_index = offset_to_l1_index(s, offset);
746 if (l1_index >= s->l1_size) {
747 ret = qcow2_grow_l1_table(bs, l1_index + 1, false);
748 if (ret < 0) {
749 return ret;
753 assert(l1_index < s->l1_size);
754 l2_offset = s->l1_table[l1_index] & L1E_OFFSET_MASK;
755 if (offset_into_cluster(s, l2_offset)) {
756 qcow2_signal_corruption(bs, true, -1, -1, "L2 table offset %#" PRIx64
757 " unaligned (L1 index: %#" PRIx64 ")",
758 l2_offset, l1_index);
759 return -EIO;
762 if (!(s->l1_table[l1_index] & QCOW_OFLAG_COPIED)) {
763 /* First allocate a new L2 table (and do COW if needed) */
764 ret = l2_allocate(bs, l1_index);
765 if (ret < 0) {
766 return ret;
769 /* Then decrease the refcount of the old table */
770 if (l2_offset) {
771 qcow2_free_clusters(bs, l2_offset, s->l2_size * l2_entry_size(s),
772 QCOW2_DISCARD_OTHER);
775 /* Get the offset of the newly-allocated l2 table */
776 l2_offset = s->l1_table[l1_index] & L1E_OFFSET_MASK;
777 assert(offset_into_cluster(s, l2_offset) == 0);
780 /* load the l2 slice in memory */
781 ret = l2_load(bs, offset, l2_offset, &l2_slice);
782 if (ret < 0) {
783 return ret;
786 /* find the cluster offset for the given disk offset */
788 l2_index = offset_to_l2_slice_index(s, offset);
790 *new_l2_slice = l2_slice;
791 *new_l2_index = l2_index;
793 return 0;
797 * alloc_compressed_cluster_offset
799 * For a given offset on the virtual disk, allocate a new compressed cluster
800 * and put the host offset of the cluster into *host_offset. If a cluster is
801 * already allocated at the offset, return an error.
803 * Return 0 on success and -errno in error cases
805 int qcow2_alloc_compressed_cluster_offset(BlockDriverState *bs,
806 uint64_t offset,
807 int compressed_size,
808 uint64_t *host_offset)
810 BDRVQcow2State *s = bs->opaque;
811 int l2_index, ret;
812 uint64_t *l2_slice;
813 int64_t cluster_offset;
814 int nb_csectors;
816 if (has_data_file(bs)) {
817 return 0;
820 ret = get_cluster_table(bs, offset, &l2_slice, &l2_index);
821 if (ret < 0) {
822 return ret;
825 /* Compression can't overwrite anything. Fail if the cluster was already
826 * allocated. */
827 cluster_offset = get_l2_entry(s, l2_slice, l2_index);
828 if (cluster_offset & L2E_OFFSET_MASK) {
829 qcow2_cache_put(s->l2_table_cache, (void **) &l2_slice);
830 return -EIO;
833 cluster_offset = qcow2_alloc_bytes(bs, compressed_size);
834 if (cluster_offset < 0) {
835 qcow2_cache_put(s->l2_table_cache, (void **) &l2_slice);
836 return cluster_offset;
839 nb_csectors =
840 (cluster_offset + compressed_size - 1) / QCOW2_COMPRESSED_SECTOR_SIZE -
841 (cluster_offset / QCOW2_COMPRESSED_SECTOR_SIZE);
843 /* The offset and size must fit in their fields of the L2 table entry */
844 assert((cluster_offset & s->cluster_offset_mask) == cluster_offset);
845 assert((nb_csectors & s->csize_mask) == nb_csectors);
847 cluster_offset |= QCOW_OFLAG_COMPRESSED |
848 ((uint64_t)nb_csectors << s->csize_shift);
850 /* update L2 table */
852 /* compressed clusters never have the copied flag */
854 BLKDBG_EVENT(bs->file, BLKDBG_L2_UPDATE_COMPRESSED);
855 qcow2_cache_entry_mark_dirty(s->l2_table_cache, l2_slice);
856 set_l2_entry(s, l2_slice, l2_index, cluster_offset);
857 qcow2_cache_put(s->l2_table_cache, (void **) &l2_slice);
859 *host_offset = cluster_offset & s->cluster_offset_mask;
860 return 0;
863 static int perform_cow(BlockDriverState *bs, QCowL2Meta *m)
865 BDRVQcow2State *s = bs->opaque;
866 Qcow2COWRegion *start = &m->cow_start;
867 Qcow2COWRegion *end = &m->cow_end;
868 unsigned buffer_size;
869 unsigned data_bytes = end->offset - (start->offset + start->nb_bytes);
870 bool merge_reads;
871 uint8_t *start_buffer, *end_buffer;
872 QEMUIOVector qiov;
873 int ret;
875 assert(start->nb_bytes <= UINT_MAX - end->nb_bytes);
876 assert(start->nb_bytes + end->nb_bytes <= UINT_MAX - data_bytes);
877 assert(start->offset + start->nb_bytes <= end->offset);
879 if ((start->nb_bytes == 0 && end->nb_bytes == 0) || m->skip_cow) {
880 return 0;
883 /* If we have to read both the start and end COW regions and the
884 * middle region is not too large then perform just one read
885 * operation */
886 merge_reads = start->nb_bytes && end->nb_bytes && data_bytes <= 16384;
887 if (merge_reads) {
888 buffer_size = start->nb_bytes + data_bytes + end->nb_bytes;
889 } else {
890 /* If we have to do two reads, add some padding in the middle
891 * if necessary to make sure that the end region is optimally
892 * aligned. */
893 size_t align = bdrv_opt_mem_align(bs);
894 assert(align > 0 && align <= UINT_MAX);
895 assert(QEMU_ALIGN_UP(start->nb_bytes, align) <=
896 UINT_MAX - end->nb_bytes);
897 buffer_size = QEMU_ALIGN_UP(start->nb_bytes, align) + end->nb_bytes;
900 /* Reserve a buffer large enough to store all the data that we're
901 * going to read */
902 start_buffer = qemu_try_blockalign(bs, buffer_size);
903 if (start_buffer == NULL) {
904 return -ENOMEM;
906 /* The part of the buffer where the end region is located */
907 end_buffer = start_buffer + buffer_size - end->nb_bytes;
909 qemu_iovec_init(&qiov, 2 + (m->data_qiov ?
910 qemu_iovec_subvec_niov(m->data_qiov,
911 m->data_qiov_offset,
912 data_bytes)
913 : 0));
915 qemu_co_mutex_unlock(&s->lock);
916 /* First we read the existing data from both COW regions. We
917 * either read the whole region in one go, or the start and end
918 * regions separately. */
919 if (merge_reads) {
920 qemu_iovec_add(&qiov, start_buffer, buffer_size);
921 ret = do_perform_cow_read(bs, m->offset, start->offset, &qiov);
922 } else {
923 qemu_iovec_add(&qiov, start_buffer, start->nb_bytes);
924 ret = do_perform_cow_read(bs, m->offset, start->offset, &qiov);
925 if (ret < 0) {
926 goto fail;
929 qemu_iovec_reset(&qiov);
930 qemu_iovec_add(&qiov, end_buffer, end->nb_bytes);
931 ret = do_perform_cow_read(bs, m->offset, end->offset, &qiov);
933 if (ret < 0) {
934 goto fail;
937 /* Encrypt the data if necessary before writing it */
938 if (bs->encrypted) {
939 ret = qcow2_co_encrypt(bs,
940 m->alloc_offset + start->offset,
941 m->offset + start->offset,
942 start_buffer, start->nb_bytes);
943 if (ret < 0) {
944 goto fail;
947 ret = qcow2_co_encrypt(bs,
948 m->alloc_offset + end->offset,
949 m->offset + end->offset,
950 end_buffer, end->nb_bytes);
951 if (ret < 0) {
952 goto fail;
956 /* And now we can write everything. If we have the guest data we
957 * can write everything in one single operation */
958 if (m->data_qiov) {
959 qemu_iovec_reset(&qiov);
960 if (start->nb_bytes) {
961 qemu_iovec_add(&qiov, start_buffer, start->nb_bytes);
963 qemu_iovec_concat(&qiov, m->data_qiov, m->data_qiov_offset, data_bytes);
964 if (end->nb_bytes) {
965 qemu_iovec_add(&qiov, end_buffer, end->nb_bytes);
967 /* NOTE: we have a write_aio blkdebug event here followed by
968 * a cow_write one in do_perform_cow_write(), but there's only
969 * one single I/O operation */
970 BLKDBG_EVENT(bs->file, BLKDBG_WRITE_AIO);
971 ret = do_perform_cow_write(bs, m->alloc_offset, start->offset, &qiov);
972 } else {
973 /* If there's no guest data then write both COW regions separately */
974 qemu_iovec_reset(&qiov);
975 qemu_iovec_add(&qiov, start_buffer, start->nb_bytes);
976 ret = do_perform_cow_write(bs, m->alloc_offset, start->offset, &qiov);
977 if (ret < 0) {
978 goto fail;
981 qemu_iovec_reset(&qiov);
982 qemu_iovec_add(&qiov, end_buffer, end->nb_bytes);
983 ret = do_perform_cow_write(bs, m->alloc_offset, end->offset, &qiov);
986 fail:
987 qemu_co_mutex_lock(&s->lock);
990 * Before we update the L2 table to actually point to the new cluster, we
991 * need to be sure that the refcounts have been increased and COW was
992 * handled.
994 if (ret == 0) {
995 qcow2_cache_depends_on_flush(s->l2_table_cache);
998 qemu_vfree(start_buffer);
999 qemu_iovec_destroy(&qiov);
1000 return ret;
1003 int qcow2_alloc_cluster_link_l2(BlockDriverState *bs, QCowL2Meta *m)
1005 BDRVQcow2State *s = bs->opaque;
1006 int i, j = 0, l2_index, ret;
1007 uint64_t *old_cluster, *l2_slice;
1008 uint64_t cluster_offset = m->alloc_offset;
1010 trace_qcow2_cluster_link_l2(qemu_coroutine_self(), m->nb_clusters);
1011 assert(m->nb_clusters > 0);
1013 old_cluster = g_try_new(uint64_t, m->nb_clusters);
1014 if (old_cluster == NULL) {
1015 ret = -ENOMEM;
1016 goto err;
1019 /* copy content of unmodified sectors */
1020 ret = perform_cow(bs, m);
1021 if (ret < 0) {
1022 goto err;
1025 /* Update L2 table. */
1026 if (s->use_lazy_refcounts) {
1027 qcow2_mark_dirty(bs);
1029 if (qcow2_need_accurate_refcounts(s)) {
1030 qcow2_cache_set_dependency(bs, s->l2_table_cache,
1031 s->refcount_block_cache);
1034 ret = get_cluster_table(bs, m->offset, &l2_slice, &l2_index);
1035 if (ret < 0) {
1036 goto err;
1038 qcow2_cache_entry_mark_dirty(s->l2_table_cache, l2_slice);
1040 assert(l2_index + m->nb_clusters <= s->l2_slice_size);
1041 for (i = 0; i < m->nb_clusters; i++) {
1042 uint64_t offset = cluster_offset + ((uint64_t)i << s->cluster_bits);
1043 /* if two concurrent writes happen to the same unallocated cluster
1044 * each write allocates separate cluster and writes data concurrently.
1045 * The first one to complete updates l2 table with pointer to its
1046 * cluster the second one has to do RMW (which is done above by
1047 * perform_cow()), update l2 table with its cluster pointer and free
1048 * old cluster. This is what this loop does */
1049 if (get_l2_entry(s, l2_slice, l2_index + i) != 0) {
1050 old_cluster[j++] = get_l2_entry(s, l2_slice, l2_index + i);
1053 /* The offset must fit in the offset field of the L2 table entry */
1054 assert((offset & L2E_OFFSET_MASK) == offset);
1056 set_l2_entry(s, l2_slice, l2_index + i, offset | QCOW_OFLAG_COPIED);
1060 qcow2_cache_put(s->l2_table_cache, (void **) &l2_slice);
1063 * If this was a COW, we need to decrease the refcount of the old cluster.
1065 * Don't discard clusters that reach a refcount of 0 (e.g. compressed
1066 * clusters), the next write will reuse them anyway.
1068 if (!m->keep_old_clusters && j != 0) {
1069 for (i = 0; i < j; i++) {
1070 qcow2_free_any_clusters(bs, old_cluster[i], 1, QCOW2_DISCARD_NEVER);
1074 ret = 0;
1075 err:
1076 g_free(old_cluster);
1077 return ret;
1081 * Frees the allocated clusters because the request failed and they won't
1082 * actually be linked.
1084 void qcow2_alloc_cluster_abort(BlockDriverState *bs, QCowL2Meta *m)
1086 BDRVQcow2State *s = bs->opaque;
1087 if (!has_data_file(bs) && !m->keep_old_clusters) {
1088 qcow2_free_clusters(bs, m->alloc_offset,
1089 m->nb_clusters << s->cluster_bits,
1090 QCOW2_DISCARD_NEVER);
1095 * For a given write request, create a new QCowL2Meta structure, add
1096 * it to @m and the BDRVQcow2State.cluster_allocs list. If the write
1097 * request does not need copy-on-write or changes to the L2 metadata
1098 * then this function does nothing.
1100 * @host_cluster_offset points to the beginning of the first cluster.
1102 * @guest_offset and @bytes indicate the offset and length of the
1103 * request.
1105 * @l2_slice contains the L2 entries of all clusters involved in this
1106 * write request.
1108 * If @keep_old is true it means that the clusters were already
1109 * allocated and will be overwritten. If false then the clusters are
1110 * new and we have to decrease the reference count of the old ones.
1112 static void calculate_l2_meta(BlockDriverState *bs,
1113 uint64_t host_cluster_offset,
1114 uint64_t guest_offset, unsigned bytes,
1115 uint64_t *l2_slice, QCowL2Meta **m, bool keep_old)
1117 BDRVQcow2State *s = bs->opaque;
1118 int l2_index = offset_to_l2_slice_index(s, guest_offset);
1119 uint64_t l2_entry;
1120 unsigned cow_start_from, cow_end_to;
1121 unsigned cow_start_to = offset_into_cluster(s, guest_offset);
1122 unsigned cow_end_from = cow_start_to + bytes;
1123 unsigned nb_clusters = size_to_clusters(s, cow_end_from);
1124 QCowL2Meta *old_m = *m;
1125 QCow2ClusterType type;
1127 assert(nb_clusters <= s->l2_slice_size - l2_index);
1129 /* Return if there's no COW (all clusters are normal and we keep them) */
1130 if (keep_old) {
1131 int i;
1132 for (i = 0; i < nb_clusters; i++) {
1133 l2_entry = get_l2_entry(s, l2_slice, l2_index + i);
1134 if (qcow2_get_cluster_type(bs, l2_entry) != QCOW2_CLUSTER_NORMAL) {
1135 break;
1138 if (i == nb_clusters) {
1139 return;
1143 /* Get the L2 entry of the first cluster */
1144 l2_entry = get_l2_entry(s, l2_slice, l2_index);
1145 type = qcow2_get_cluster_type(bs, l2_entry);
1147 if (type == QCOW2_CLUSTER_NORMAL && keep_old) {
1148 cow_start_from = cow_start_to;
1149 } else {
1150 cow_start_from = 0;
1153 /* Get the L2 entry of the last cluster */
1154 l2_entry = get_l2_entry(s, l2_slice, l2_index + nb_clusters - 1);
1155 type = qcow2_get_cluster_type(bs, l2_entry);
1157 if (type == QCOW2_CLUSTER_NORMAL && keep_old) {
1158 cow_end_to = cow_end_from;
1159 } else {
1160 cow_end_to = ROUND_UP(cow_end_from, s->cluster_size);
1163 *m = g_malloc0(sizeof(**m));
1164 **m = (QCowL2Meta) {
1165 .next = old_m,
1167 .alloc_offset = host_cluster_offset,
1168 .offset = start_of_cluster(s, guest_offset),
1169 .nb_clusters = nb_clusters,
1171 .keep_old_clusters = keep_old,
1173 .cow_start = {
1174 .offset = cow_start_from,
1175 .nb_bytes = cow_start_to - cow_start_from,
1177 .cow_end = {
1178 .offset = cow_end_from,
1179 .nb_bytes = cow_end_to - cow_end_from,
1183 qemu_co_queue_init(&(*m)->dependent_requests);
1184 QLIST_INSERT_HEAD(&s->cluster_allocs, *m, next_in_flight);
1188 * Returns true if writing to the cluster pointed to by @l2_entry
1189 * requires a new allocation (that is, if the cluster is unallocated
1190 * or has refcount > 1 and therefore cannot be written in-place).
1192 static bool cluster_needs_new_alloc(BlockDriverState *bs, uint64_t l2_entry)
1194 switch (qcow2_get_cluster_type(bs, l2_entry)) {
1195 case QCOW2_CLUSTER_NORMAL:
1196 case QCOW2_CLUSTER_ZERO_ALLOC:
1197 if (l2_entry & QCOW_OFLAG_COPIED) {
1198 return false;
1200 case QCOW2_CLUSTER_UNALLOCATED:
1201 case QCOW2_CLUSTER_COMPRESSED:
1202 case QCOW2_CLUSTER_ZERO_PLAIN:
1203 return true;
1204 default:
1205 abort();
1210 * Returns the number of contiguous clusters that can be written to
1211 * using one single write request, starting from @l2_index.
1212 * At most @nb_clusters are checked.
1214 * If @new_alloc is true this counts clusters that are either
1215 * unallocated, or allocated but with refcount > 1 (so they need to be
1216 * newly allocated and COWed).
1218 * If @new_alloc is false this counts clusters that are already
1219 * allocated and can be overwritten in-place (this includes clusters
1220 * of type QCOW2_CLUSTER_ZERO_ALLOC).
1222 static int count_single_write_clusters(BlockDriverState *bs, int nb_clusters,
1223 uint64_t *l2_slice, int l2_index,
1224 bool new_alloc)
1226 BDRVQcow2State *s = bs->opaque;
1227 uint64_t l2_entry = get_l2_entry(s, l2_slice, l2_index);
1228 uint64_t expected_offset = l2_entry & L2E_OFFSET_MASK;
1229 int i;
1231 for (i = 0; i < nb_clusters; i++) {
1232 l2_entry = get_l2_entry(s, l2_slice, l2_index + i);
1233 if (cluster_needs_new_alloc(bs, l2_entry) != new_alloc) {
1234 break;
1236 if (!new_alloc) {
1237 if (expected_offset != (l2_entry & L2E_OFFSET_MASK)) {
1238 break;
1240 expected_offset += s->cluster_size;
1244 assert(i <= nb_clusters);
1245 return i;
1249 * Check if there already is an AIO write request in flight which allocates
1250 * the same cluster. In this case we need to wait until the previous
1251 * request has completed and updated the L2 table accordingly.
1253 * Returns:
1254 * 0 if there was no dependency. *cur_bytes indicates the number of
1255 * bytes from guest_offset that can be read before the next
1256 * dependency must be processed (or the request is complete)
1258 * -EAGAIN if we had to wait for another request, previously gathered
1259 * information on cluster allocation may be invalid now. The caller
1260 * must start over anyway, so consider *cur_bytes undefined.
1262 static int handle_dependencies(BlockDriverState *bs, uint64_t guest_offset,
1263 uint64_t *cur_bytes, QCowL2Meta **m)
1265 BDRVQcow2State *s = bs->opaque;
1266 QCowL2Meta *old_alloc;
1267 uint64_t bytes = *cur_bytes;
1269 QLIST_FOREACH(old_alloc, &s->cluster_allocs, next_in_flight) {
1271 uint64_t start = guest_offset;
1272 uint64_t end = start + bytes;
1273 uint64_t old_start = l2meta_cow_start(old_alloc);
1274 uint64_t old_end = l2meta_cow_end(old_alloc);
1276 if (end <= old_start || start >= old_end) {
1277 /* No intersection */
1278 } else {
1279 if (start < old_start) {
1280 /* Stop at the start of a running allocation */
1281 bytes = old_start - start;
1282 } else {
1283 bytes = 0;
1286 /* Stop if already an l2meta exists. After yielding, it wouldn't
1287 * be valid any more, so we'd have to clean up the old L2Metas
1288 * and deal with requests depending on them before starting to
1289 * gather new ones. Not worth the trouble. */
1290 if (bytes == 0 && *m) {
1291 *cur_bytes = 0;
1292 return 0;
1295 if (bytes == 0) {
1296 /* Wait for the dependency to complete. We need to recheck
1297 * the free/allocated clusters when we continue. */
1298 qemu_co_queue_wait(&old_alloc->dependent_requests, &s->lock);
1299 return -EAGAIN;
1304 /* Make sure that existing clusters and new allocations are only used up to
1305 * the next dependency if we shortened the request above */
1306 *cur_bytes = bytes;
1308 return 0;
1312 * Checks how many already allocated clusters that don't require a new
1313 * allocation there are at the given guest_offset (up to *bytes).
1314 * If *host_offset is not INV_OFFSET, only physically contiguous clusters
1315 * beginning at this host offset are counted.
1317 * Note that guest_offset may not be cluster aligned. In this case, the
1318 * returned *host_offset points to exact byte referenced by guest_offset and
1319 * therefore isn't cluster aligned as well.
1321 * Returns:
1322 * 0: if no allocated clusters are available at the given offset.
1323 * *bytes is normally unchanged. It is set to 0 if the cluster
1324 * is allocated and can be overwritten in-place but doesn't have
1325 * the right physical offset.
1327 * 1: if allocated clusters that can be overwritten in place are
1328 * available at the requested offset. *bytes may have decreased
1329 * and describes the length of the area that can be written to.
1331 * -errno: in error cases
1333 static int handle_copied(BlockDriverState *bs, uint64_t guest_offset,
1334 uint64_t *host_offset, uint64_t *bytes, QCowL2Meta **m)
1336 BDRVQcow2State *s = bs->opaque;
1337 int l2_index;
1338 uint64_t l2_entry, cluster_offset;
1339 uint64_t *l2_slice;
1340 uint64_t nb_clusters;
1341 unsigned int keep_clusters;
1342 int ret;
1344 trace_qcow2_handle_copied(qemu_coroutine_self(), guest_offset, *host_offset,
1345 *bytes);
1347 assert(*host_offset == INV_OFFSET || offset_into_cluster(s, guest_offset)
1348 == offset_into_cluster(s, *host_offset));
1351 * Calculate the number of clusters to look for. We stop at L2 slice
1352 * boundaries to keep things simple.
1354 nb_clusters =
1355 size_to_clusters(s, offset_into_cluster(s, guest_offset) + *bytes);
1357 l2_index = offset_to_l2_slice_index(s, guest_offset);
1358 nb_clusters = MIN(nb_clusters, s->l2_slice_size - l2_index);
1359 /* Limit total byte count to BDRV_REQUEST_MAX_BYTES */
1360 nb_clusters = MIN(nb_clusters, BDRV_REQUEST_MAX_BYTES >> s->cluster_bits);
1362 /* Find L2 entry for the first involved cluster */
1363 ret = get_cluster_table(bs, guest_offset, &l2_slice, &l2_index);
1364 if (ret < 0) {
1365 return ret;
1368 l2_entry = get_l2_entry(s, l2_slice, l2_index);
1369 cluster_offset = l2_entry & L2E_OFFSET_MASK;
1371 if (!cluster_needs_new_alloc(bs, l2_entry)) {
1372 if (offset_into_cluster(s, cluster_offset)) {
1373 qcow2_signal_corruption(bs, true, -1, -1, "%s cluster offset "
1374 "%#" PRIx64 " unaligned (guest offset: %#"
1375 PRIx64 ")", l2_entry & QCOW_OFLAG_ZERO ?
1376 "Preallocated zero" : "Data",
1377 cluster_offset, guest_offset);
1378 ret = -EIO;
1379 goto out;
1382 /* If a specific host_offset is required, check it */
1383 if (*host_offset != INV_OFFSET && cluster_offset != *host_offset) {
1384 *bytes = 0;
1385 ret = 0;
1386 goto out;
1389 /* We keep all QCOW_OFLAG_COPIED clusters */
1390 keep_clusters = count_single_write_clusters(bs, nb_clusters, l2_slice,
1391 l2_index, false);
1392 assert(keep_clusters <= nb_clusters);
1394 *bytes = MIN(*bytes,
1395 keep_clusters * s->cluster_size
1396 - offset_into_cluster(s, guest_offset));
1397 assert(*bytes != 0);
1399 calculate_l2_meta(bs, cluster_offset, guest_offset,
1400 *bytes, l2_slice, m, true);
1402 ret = 1;
1403 } else {
1404 ret = 0;
1407 /* Cleanup */
1408 out:
1409 qcow2_cache_put(s->l2_table_cache, (void **) &l2_slice);
1411 /* Only return a host offset if we actually made progress. Otherwise we
1412 * would make requirements for handle_alloc() that it can't fulfill */
1413 if (ret > 0) {
1414 *host_offset = cluster_offset + offset_into_cluster(s, guest_offset);
1417 return ret;
1421 * Allocates new clusters for the given guest_offset.
1423 * At most *nb_clusters are allocated, and on return *nb_clusters is updated to
1424 * contain the number of clusters that have been allocated and are contiguous
1425 * in the image file.
1427 * If *host_offset is not INV_OFFSET, it specifies the offset in the image file
1428 * at which the new clusters must start. *nb_clusters can be 0 on return in
1429 * this case if the cluster at host_offset is already in use. If *host_offset
1430 * is INV_OFFSET, the clusters can be allocated anywhere in the image file.
1432 * *host_offset is updated to contain the offset into the image file at which
1433 * the first allocated cluster starts.
1435 * Return 0 on success and -errno in error cases. -EAGAIN means that the
1436 * function has been waiting for another request and the allocation must be
1437 * restarted, but the whole request should not be failed.
1439 static int do_alloc_cluster_offset(BlockDriverState *bs, uint64_t guest_offset,
1440 uint64_t *host_offset, uint64_t *nb_clusters)
1442 BDRVQcow2State *s = bs->opaque;
1444 trace_qcow2_do_alloc_clusters_offset(qemu_coroutine_self(), guest_offset,
1445 *host_offset, *nb_clusters);
1447 if (has_data_file(bs)) {
1448 assert(*host_offset == INV_OFFSET ||
1449 *host_offset == start_of_cluster(s, guest_offset));
1450 *host_offset = start_of_cluster(s, guest_offset);
1451 return 0;
1454 /* Allocate new clusters */
1455 trace_qcow2_cluster_alloc_phys(qemu_coroutine_self());
1456 if (*host_offset == INV_OFFSET) {
1457 int64_t cluster_offset =
1458 qcow2_alloc_clusters(bs, *nb_clusters * s->cluster_size);
1459 if (cluster_offset < 0) {
1460 return cluster_offset;
1462 *host_offset = cluster_offset;
1463 return 0;
1464 } else {
1465 int64_t ret = qcow2_alloc_clusters_at(bs, *host_offset, *nb_clusters);
1466 if (ret < 0) {
1467 return ret;
1469 *nb_clusters = ret;
1470 return 0;
1475 * Allocates new clusters for an area that is either still unallocated or
1476 * cannot be overwritten in-place. If *host_offset is not INV_OFFSET,
1477 * clusters are only allocated if the new allocation can match the specified
1478 * host offset.
1480 * Note that guest_offset may not be cluster aligned. In this case, the
1481 * returned *host_offset points to exact byte referenced by guest_offset and
1482 * therefore isn't cluster aligned as well.
1484 * Returns:
1485 * 0: if no clusters could be allocated. *bytes is set to 0,
1486 * *host_offset is left unchanged.
1488 * 1: if new clusters were allocated. *bytes may be decreased if the
1489 * new allocation doesn't cover all of the requested area.
1490 * *host_offset is updated to contain the host offset of the first
1491 * newly allocated cluster.
1493 * -errno: in error cases
1495 static int handle_alloc(BlockDriverState *bs, uint64_t guest_offset,
1496 uint64_t *host_offset, uint64_t *bytes, QCowL2Meta **m)
1498 BDRVQcow2State *s = bs->opaque;
1499 int l2_index;
1500 uint64_t *l2_slice;
1501 uint64_t nb_clusters;
1502 int ret;
1504 uint64_t alloc_cluster_offset;
1506 trace_qcow2_handle_alloc(qemu_coroutine_self(), guest_offset, *host_offset,
1507 *bytes);
1508 assert(*bytes > 0);
1511 * Calculate the number of clusters to look for. We stop at L2 slice
1512 * boundaries to keep things simple.
1514 nb_clusters =
1515 size_to_clusters(s, offset_into_cluster(s, guest_offset) + *bytes);
1517 l2_index = offset_to_l2_slice_index(s, guest_offset);
1518 nb_clusters = MIN(nb_clusters, s->l2_slice_size - l2_index);
1519 /* Limit total allocation byte count to BDRV_REQUEST_MAX_BYTES */
1520 nb_clusters = MIN(nb_clusters, BDRV_REQUEST_MAX_BYTES >> s->cluster_bits);
1522 /* Find L2 entry for the first involved cluster */
1523 ret = get_cluster_table(bs, guest_offset, &l2_slice, &l2_index);
1524 if (ret < 0) {
1525 return ret;
1528 nb_clusters = count_single_write_clusters(bs, nb_clusters,
1529 l2_slice, l2_index, true);
1531 /* This function is only called when there were no non-COW clusters, so if
1532 * we can't find any unallocated or COW clusters either, something is
1533 * wrong with our code. */
1534 assert(nb_clusters > 0);
1536 /* Allocate at a given offset in the image file */
1537 alloc_cluster_offset = *host_offset == INV_OFFSET ? INV_OFFSET :
1538 start_of_cluster(s, *host_offset);
1539 ret = do_alloc_cluster_offset(bs, guest_offset, &alloc_cluster_offset,
1540 &nb_clusters);
1541 if (ret < 0) {
1542 goto out;
1545 /* Can't extend contiguous allocation */
1546 if (nb_clusters == 0) {
1547 *bytes = 0;
1548 ret = 0;
1549 goto out;
1552 assert(alloc_cluster_offset != INV_OFFSET);
1555 * Save info needed for meta data update.
1557 * requested_bytes: Number of bytes from the start of the first
1558 * newly allocated cluster to the end of the (possibly shortened
1559 * before) write request.
1561 * avail_bytes: Number of bytes from the start of the first
1562 * newly allocated to the end of the last newly allocated cluster.
1564 * nb_bytes: The number of bytes from the start of the first
1565 * newly allocated cluster to the end of the area that the write
1566 * request actually writes to (excluding COW at the end)
1568 uint64_t requested_bytes = *bytes + offset_into_cluster(s, guest_offset);
1569 int avail_bytes = nb_clusters << s->cluster_bits;
1570 int nb_bytes = MIN(requested_bytes, avail_bytes);
1572 *host_offset = alloc_cluster_offset + offset_into_cluster(s, guest_offset);
1573 *bytes = MIN(*bytes, nb_bytes - offset_into_cluster(s, guest_offset));
1574 assert(*bytes != 0);
1576 calculate_l2_meta(bs, alloc_cluster_offset, guest_offset, *bytes, l2_slice,
1577 m, false);
1579 ret = 1;
1581 out:
1582 qcow2_cache_put(s->l2_table_cache, (void **) &l2_slice);
1583 if (ret < 0 && *m && (*m)->nb_clusters > 0) {
1584 QLIST_REMOVE(*m, next_in_flight);
1586 return ret;
1590 * alloc_cluster_offset
1592 * For a given offset on the virtual disk, find the cluster offset in qcow2
1593 * file. If the offset is not found, allocate a new cluster.
1595 * If the cluster was already allocated, m->nb_clusters is set to 0 and
1596 * other fields in m are meaningless.
1598 * If the cluster is newly allocated, m->nb_clusters is set to the number of
1599 * contiguous clusters that have been allocated. In this case, the other
1600 * fields of m are valid and contain information about the first allocated
1601 * cluster.
1603 * If the request conflicts with another write request in flight, the coroutine
1604 * is queued and will be reentered when the dependency has completed.
1606 * Return 0 on success and -errno in error cases
1608 int qcow2_alloc_cluster_offset(BlockDriverState *bs, uint64_t offset,
1609 unsigned int *bytes, uint64_t *host_offset,
1610 QCowL2Meta **m)
1612 BDRVQcow2State *s = bs->opaque;
1613 uint64_t start, remaining;
1614 uint64_t cluster_offset;
1615 uint64_t cur_bytes;
1616 int ret;
1618 trace_qcow2_alloc_clusters_offset(qemu_coroutine_self(), offset, *bytes);
1620 again:
1621 start = offset;
1622 remaining = *bytes;
1623 cluster_offset = INV_OFFSET;
1624 *host_offset = INV_OFFSET;
1625 cur_bytes = 0;
1626 *m = NULL;
1628 while (true) {
1630 if (*host_offset == INV_OFFSET && cluster_offset != INV_OFFSET) {
1631 *host_offset = start_of_cluster(s, cluster_offset);
1634 assert(remaining >= cur_bytes);
1636 start += cur_bytes;
1637 remaining -= cur_bytes;
1639 if (cluster_offset != INV_OFFSET) {
1640 cluster_offset += cur_bytes;
1643 if (remaining == 0) {
1644 break;
1647 cur_bytes = remaining;
1650 * Now start gathering as many contiguous clusters as possible:
1652 * 1. Check for overlaps with in-flight allocations
1654 * a) Overlap not in the first cluster -> shorten this request and
1655 * let the caller handle the rest in its next loop iteration.
1657 * b) Real overlaps of two requests. Yield and restart the search
1658 * for contiguous clusters (the situation could have changed
1659 * while we were sleeping)
1661 * c) TODO: Request starts in the same cluster as the in-flight
1662 * allocation ends. Shorten the COW of the in-fight allocation,
1663 * set cluster_offset to write to the same cluster and set up
1664 * the right synchronisation between the in-flight request and
1665 * the new one.
1667 ret = handle_dependencies(bs, start, &cur_bytes, m);
1668 if (ret == -EAGAIN) {
1669 /* Currently handle_dependencies() doesn't yield if we already had
1670 * an allocation. If it did, we would have to clean up the L2Meta
1671 * structs before starting over. */
1672 assert(*m == NULL);
1673 goto again;
1674 } else if (ret < 0) {
1675 return ret;
1676 } else if (cur_bytes == 0) {
1677 break;
1678 } else {
1679 /* handle_dependencies() may have decreased cur_bytes (shortened
1680 * the allocations below) so that the next dependency is processed
1681 * correctly during the next loop iteration. */
1685 * 2. Count contiguous COPIED clusters.
1687 ret = handle_copied(bs, start, &cluster_offset, &cur_bytes, m);
1688 if (ret < 0) {
1689 return ret;
1690 } else if (ret) {
1691 continue;
1692 } else if (cur_bytes == 0) {
1693 break;
1697 * 3. If the request still hasn't completed, allocate new clusters,
1698 * considering any cluster_offset of steps 1c or 2.
1700 ret = handle_alloc(bs, start, &cluster_offset, &cur_bytes, m);
1701 if (ret < 0) {
1702 return ret;
1703 } else if (ret) {
1704 continue;
1705 } else {
1706 assert(cur_bytes == 0);
1707 break;
1711 *bytes -= remaining;
1712 assert(*bytes > 0);
1713 assert(*host_offset != INV_OFFSET);
1715 return 0;
1719 * This discards as many clusters of nb_clusters as possible at once (i.e.
1720 * all clusters in the same L2 slice) and returns the number of discarded
1721 * clusters.
1723 static int discard_in_l2_slice(BlockDriverState *bs, uint64_t offset,
1724 uint64_t nb_clusters,
1725 enum qcow2_discard_type type, bool full_discard)
1727 BDRVQcow2State *s = bs->opaque;
1728 uint64_t *l2_slice;
1729 int l2_index;
1730 int ret;
1731 int i;
1733 ret = get_cluster_table(bs, offset, &l2_slice, &l2_index);
1734 if (ret < 0) {
1735 return ret;
1738 /* Limit nb_clusters to one L2 slice */
1739 nb_clusters = MIN(nb_clusters, s->l2_slice_size - l2_index);
1740 assert(nb_clusters <= INT_MAX);
1742 for (i = 0; i < nb_clusters; i++) {
1743 uint64_t old_l2_entry;
1745 old_l2_entry = get_l2_entry(s, l2_slice, l2_index + i);
1748 * If full_discard is false, make sure that a discarded area reads back
1749 * as zeroes for v3 images (we cannot do it for v2 without actually
1750 * writing a zero-filled buffer). We can skip the operation if the
1751 * cluster is already marked as zero, or if it's unallocated and we
1752 * don't have a backing file.
1754 * TODO We might want to use bdrv_block_status(bs) here, but we're
1755 * holding s->lock, so that doesn't work today.
1757 * If full_discard is true, the sector should not read back as zeroes,
1758 * but rather fall through to the backing file.
1760 switch (qcow2_get_cluster_type(bs, old_l2_entry)) {
1761 case QCOW2_CLUSTER_UNALLOCATED:
1762 if (full_discard || !bs->backing) {
1763 continue;
1765 break;
1767 case QCOW2_CLUSTER_ZERO_PLAIN:
1768 if (!full_discard) {
1769 continue;
1771 break;
1773 case QCOW2_CLUSTER_ZERO_ALLOC:
1774 case QCOW2_CLUSTER_NORMAL:
1775 case QCOW2_CLUSTER_COMPRESSED:
1776 break;
1778 default:
1779 abort();
1782 /* First remove L2 entries */
1783 qcow2_cache_entry_mark_dirty(s->l2_table_cache, l2_slice);
1784 if (!full_discard && s->qcow_version >= 3) {
1785 set_l2_entry(s, l2_slice, l2_index + i, QCOW_OFLAG_ZERO);
1786 } else {
1787 set_l2_entry(s, l2_slice, l2_index + i, 0);
1790 /* Then decrease the refcount */
1791 qcow2_free_any_clusters(bs, old_l2_entry, 1, type);
1794 qcow2_cache_put(s->l2_table_cache, (void **) &l2_slice);
1796 return nb_clusters;
1799 int qcow2_cluster_discard(BlockDriverState *bs, uint64_t offset,
1800 uint64_t bytes, enum qcow2_discard_type type,
1801 bool full_discard)
1803 BDRVQcow2State *s = bs->opaque;
1804 uint64_t end_offset = offset + bytes;
1805 uint64_t nb_clusters;
1806 int64_t cleared;
1807 int ret;
1809 /* Caller must pass aligned values, except at image end */
1810 assert(QEMU_IS_ALIGNED(offset, s->cluster_size));
1811 assert(QEMU_IS_ALIGNED(end_offset, s->cluster_size) ||
1812 end_offset == bs->total_sectors << BDRV_SECTOR_BITS);
1814 nb_clusters = size_to_clusters(s, bytes);
1816 s->cache_discards = true;
1818 /* Each L2 slice is handled by its own loop iteration */
1819 while (nb_clusters > 0) {
1820 cleared = discard_in_l2_slice(bs, offset, nb_clusters, type,
1821 full_discard);
1822 if (cleared < 0) {
1823 ret = cleared;
1824 goto fail;
1827 nb_clusters -= cleared;
1828 offset += (cleared * s->cluster_size);
1831 ret = 0;
1832 fail:
1833 s->cache_discards = false;
1834 qcow2_process_discards(bs, ret);
1836 return ret;
1840 * This zeroes as many clusters of nb_clusters as possible at once (i.e.
1841 * all clusters in the same L2 slice) and returns the number of zeroed
1842 * clusters.
1844 static int zero_in_l2_slice(BlockDriverState *bs, uint64_t offset,
1845 uint64_t nb_clusters, int flags)
1847 BDRVQcow2State *s = bs->opaque;
1848 uint64_t *l2_slice;
1849 int l2_index;
1850 int ret;
1851 int i;
1852 bool unmap = !!(flags & BDRV_REQ_MAY_UNMAP);
1854 ret = get_cluster_table(bs, offset, &l2_slice, &l2_index);
1855 if (ret < 0) {
1856 return ret;
1859 /* Limit nb_clusters to one L2 slice */
1860 nb_clusters = MIN(nb_clusters, s->l2_slice_size - l2_index);
1861 assert(nb_clusters <= INT_MAX);
1863 for (i = 0; i < nb_clusters; i++) {
1864 uint64_t old_offset;
1865 QCow2ClusterType cluster_type;
1867 old_offset = get_l2_entry(s, l2_slice, l2_index + i);
1870 * Minimize L2 changes if the cluster already reads back as
1871 * zeroes with correct allocation.
1873 cluster_type = qcow2_get_cluster_type(bs, old_offset);
1874 if (cluster_type == QCOW2_CLUSTER_ZERO_PLAIN ||
1875 (cluster_type == QCOW2_CLUSTER_ZERO_ALLOC && !unmap)) {
1876 continue;
1879 qcow2_cache_entry_mark_dirty(s->l2_table_cache, l2_slice);
1880 if (cluster_type == QCOW2_CLUSTER_COMPRESSED || unmap) {
1881 set_l2_entry(s, l2_slice, l2_index + i, QCOW_OFLAG_ZERO);
1882 qcow2_free_any_clusters(bs, old_offset, 1, QCOW2_DISCARD_REQUEST);
1883 } else {
1884 uint64_t entry = get_l2_entry(s, l2_slice, l2_index + i);
1885 set_l2_entry(s, l2_slice, l2_index + i, entry | QCOW_OFLAG_ZERO);
1889 qcow2_cache_put(s->l2_table_cache, (void **) &l2_slice);
1891 return nb_clusters;
1894 int qcow2_cluster_zeroize(BlockDriverState *bs, uint64_t offset,
1895 uint64_t bytes, int flags)
1897 BDRVQcow2State *s = bs->opaque;
1898 uint64_t end_offset = offset + bytes;
1899 uint64_t nb_clusters;
1900 int64_t cleared;
1901 int ret;
1903 /* If we have to stay in sync with an external data file, zero out
1904 * s->data_file first. */
1905 if (data_file_is_raw(bs)) {
1906 assert(has_data_file(bs));
1907 ret = bdrv_co_pwrite_zeroes(s->data_file, offset, bytes, flags);
1908 if (ret < 0) {
1909 return ret;
1913 /* Caller must pass aligned values, except at image end */
1914 assert(QEMU_IS_ALIGNED(offset, s->cluster_size));
1915 assert(QEMU_IS_ALIGNED(end_offset, s->cluster_size) ||
1916 end_offset >= bs->total_sectors << BDRV_SECTOR_BITS);
1919 * The zero flag is only supported by version 3 and newer. However, if we
1920 * have no backing file, we can resort to discard in version 2.
1922 if (s->qcow_version < 3) {
1923 if (!bs->backing) {
1924 return qcow2_cluster_discard(bs, offset, bytes,
1925 QCOW2_DISCARD_REQUEST, false);
1927 return -ENOTSUP;
1930 /* Each L2 slice is handled by its own loop iteration */
1931 nb_clusters = size_to_clusters(s, bytes);
1933 s->cache_discards = true;
1935 while (nb_clusters > 0) {
1936 cleared = zero_in_l2_slice(bs, offset, nb_clusters, flags);
1937 if (cleared < 0) {
1938 ret = cleared;
1939 goto fail;
1942 nb_clusters -= cleared;
1943 offset += (cleared * s->cluster_size);
1946 ret = 0;
1947 fail:
1948 s->cache_discards = false;
1949 qcow2_process_discards(bs, ret);
1951 return ret;
1955 * Expands all zero clusters in a specific L1 table (or deallocates them, for
1956 * non-backed non-pre-allocated zero clusters).
1958 * l1_entries and *visited_l1_entries are used to keep track of progress for
1959 * status_cb(). l1_entries contains the total number of L1 entries and
1960 * *visited_l1_entries counts all visited L1 entries.
1962 static int expand_zero_clusters_in_l1(BlockDriverState *bs, uint64_t *l1_table,
1963 int l1_size, int64_t *visited_l1_entries,
1964 int64_t l1_entries,
1965 BlockDriverAmendStatusCB *status_cb,
1966 void *cb_opaque)
1968 BDRVQcow2State *s = bs->opaque;
1969 bool is_active_l1 = (l1_table == s->l1_table);
1970 uint64_t *l2_slice = NULL;
1971 unsigned slice, slice_size2, n_slices;
1972 int ret;
1973 int i, j;
1975 slice_size2 = s->l2_slice_size * l2_entry_size(s);
1976 n_slices = s->cluster_size / slice_size2;
1978 if (!is_active_l1) {
1979 /* inactive L2 tables require a buffer to be stored in when loading
1980 * them from disk */
1981 l2_slice = qemu_try_blockalign(bs->file->bs, slice_size2);
1982 if (l2_slice == NULL) {
1983 return -ENOMEM;
1987 for (i = 0; i < l1_size; i++) {
1988 uint64_t l2_offset = l1_table[i] & L1E_OFFSET_MASK;
1989 uint64_t l2_refcount;
1991 if (!l2_offset) {
1992 /* unallocated */
1993 (*visited_l1_entries)++;
1994 if (status_cb) {
1995 status_cb(bs, *visited_l1_entries, l1_entries, cb_opaque);
1997 continue;
2000 if (offset_into_cluster(s, l2_offset)) {
2001 qcow2_signal_corruption(bs, true, -1, -1, "L2 table offset %#"
2002 PRIx64 " unaligned (L1 index: %#x)",
2003 l2_offset, i);
2004 ret = -EIO;
2005 goto fail;
2008 ret = qcow2_get_refcount(bs, l2_offset >> s->cluster_bits,
2009 &l2_refcount);
2010 if (ret < 0) {
2011 goto fail;
2014 for (slice = 0; slice < n_slices; slice++) {
2015 uint64_t slice_offset = l2_offset + slice * slice_size2;
2016 bool l2_dirty = false;
2017 if (is_active_l1) {
2018 /* get active L2 tables from cache */
2019 ret = qcow2_cache_get(bs, s->l2_table_cache, slice_offset,
2020 (void **)&l2_slice);
2021 } else {
2022 /* load inactive L2 tables from disk */
2023 ret = bdrv_pread(bs->file, slice_offset, l2_slice, slice_size2);
2025 if (ret < 0) {
2026 goto fail;
2029 for (j = 0; j < s->l2_slice_size; j++) {
2030 uint64_t l2_entry = get_l2_entry(s, l2_slice, j);
2031 int64_t offset = l2_entry & L2E_OFFSET_MASK;
2032 QCow2ClusterType cluster_type =
2033 qcow2_get_cluster_type(bs, l2_entry);
2035 if (cluster_type != QCOW2_CLUSTER_ZERO_PLAIN &&
2036 cluster_type != QCOW2_CLUSTER_ZERO_ALLOC) {
2037 continue;
2040 if (cluster_type == QCOW2_CLUSTER_ZERO_PLAIN) {
2041 if (!bs->backing) {
2042 /* not backed; therefore we can simply deallocate the
2043 * cluster */
2044 set_l2_entry(s, l2_slice, j, 0);
2045 l2_dirty = true;
2046 continue;
2049 offset = qcow2_alloc_clusters(bs, s->cluster_size);
2050 if (offset < 0) {
2051 ret = offset;
2052 goto fail;
2055 /* The offset must fit in the offset field */
2056 assert((offset & L2E_OFFSET_MASK) == offset);
2058 if (l2_refcount > 1) {
2059 /* For shared L2 tables, set the refcount accordingly
2060 * (it is already 1 and needs to be l2_refcount) */
2061 ret = qcow2_update_cluster_refcount(
2062 bs, offset >> s->cluster_bits,
2063 refcount_diff(1, l2_refcount), false,
2064 QCOW2_DISCARD_OTHER);
2065 if (ret < 0) {
2066 qcow2_free_clusters(bs, offset, s->cluster_size,
2067 QCOW2_DISCARD_OTHER);
2068 goto fail;
2073 if (offset_into_cluster(s, offset)) {
2074 int l2_index = slice * s->l2_slice_size + j;
2075 qcow2_signal_corruption(
2076 bs, true, -1, -1,
2077 "Cluster allocation offset "
2078 "%#" PRIx64 " unaligned (L2 offset: %#"
2079 PRIx64 ", L2 index: %#x)", offset,
2080 l2_offset, l2_index);
2081 if (cluster_type == QCOW2_CLUSTER_ZERO_PLAIN) {
2082 qcow2_free_clusters(bs, offset, s->cluster_size,
2083 QCOW2_DISCARD_ALWAYS);
2085 ret = -EIO;
2086 goto fail;
2089 ret = qcow2_pre_write_overlap_check(bs, 0, offset,
2090 s->cluster_size, true);
2091 if (ret < 0) {
2092 if (cluster_type == QCOW2_CLUSTER_ZERO_PLAIN) {
2093 qcow2_free_clusters(bs, offset, s->cluster_size,
2094 QCOW2_DISCARD_ALWAYS);
2096 goto fail;
2099 ret = bdrv_pwrite_zeroes(s->data_file, offset,
2100 s->cluster_size, 0);
2101 if (ret < 0) {
2102 if (cluster_type == QCOW2_CLUSTER_ZERO_PLAIN) {
2103 qcow2_free_clusters(bs, offset, s->cluster_size,
2104 QCOW2_DISCARD_ALWAYS);
2106 goto fail;
2109 if (l2_refcount == 1) {
2110 set_l2_entry(s, l2_slice, j, offset | QCOW_OFLAG_COPIED);
2111 } else {
2112 set_l2_entry(s, l2_slice, j, offset);
2114 l2_dirty = true;
2117 if (is_active_l1) {
2118 if (l2_dirty) {
2119 qcow2_cache_entry_mark_dirty(s->l2_table_cache, l2_slice);
2120 qcow2_cache_depends_on_flush(s->l2_table_cache);
2122 qcow2_cache_put(s->l2_table_cache, (void **) &l2_slice);
2123 } else {
2124 if (l2_dirty) {
2125 ret = qcow2_pre_write_overlap_check(
2126 bs, QCOW2_OL_INACTIVE_L2 | QCOW2_OL_ACTIVE_L2,
2127 slice_offset, slice_size2, false);
2128 if (ret < 0) {
2129 goto fail;
2132 ret = bdrv_pwrite(bs->file, slice_offset,
2133 l2_slice, slice_size2);
2134 if (ret < 0) {
2135 goto fail;
2141 (*visited_l1_entries)++;
2142 if (status_cb) {
2143 status_cb(bs, *visited_l1_entries, l1_entries, cb_opaque);
2147 ret = 0;
2149 fail:
2150 if (l2_slice) {
2151 if (!is_active_l1) {
2152 qemu_vfree(l2_slice);
2153 } else {
2154 qcow2_cache_put(s->l2_table_cache, (void **) &l2_slice);
2157 return ret;
2161 * For backed images, expands all zero clusters on the image. For non-backed
2162 * images, deallocates all non-pre-allocated zero clusters (and claims the
2163 * allocation for pre-allocated ones). This is important for downgrading to a
2164 * qcow2 version which doesn't yet support metadata zero clusters.
2166 int qcow2_expand_zero_clusters(BlockDriverState *bs,
2167 BlockDriverAmendStatusCB *status_cb,
2168 void *cb_opaque)
2170 BDRVQcow2State *s = bs->opaque;
2171 uint64_t *l1_table = NULL;
2172 int64_t l1_entries = 0, visited_l1_entries = 0;
2173 int ret;
2174 int i, j;
2176 if (status_cb) {
2177 l1_entries = s->l1_size;
2178 for (i = 0; i < s->nb_snapshots; i++) {
2179 l1_entries += s->snapshots[i].l1_size;
2183 ret = expand_zero_clusters_in_l1(bs, s->l1_table, s->l1_size,
2184 &visited_l1_entries, l1_entries,
2185 status_cb, cb_opaque);
2186 if (ret < 0) {
2187 goto fail;
2190 /* Inactive L1 tables may point to active L2 tables - therefore it is
2191 * necessary to flush the L2 table cache before trying to access the L2
2192 * tables pointed to by inactive L1 entries (else we might try to expand
2193 * zero clusters that have already been expanded); furthermore, it is also
2194 * necessary to empty the L2 table cache, since it may contain tables which
2195 * are now going to be modified directly on disk, bypassing the cache.
2196 * qcow2_cache_empty() does both for us. */
2197 ret = qcow2_cache_empty(bs, s->l2_table_cache);
2198 if (ret < 0) {
2199 goto fail;
2202 for (i = 0; i < s->nb_snapshots; i++) {
2203 int l1_size2;
2204 uint64_t *new_l1_table;
2205 Error *local_err = NULL;
2207 ret = qcow2_validate_table(bs, s->snapshots[i].l1_table_offset,
2208 s->snapshots[i].l1_size, sizeof(uint64_t),
2209 QCOW_MAX_L1_SIZE, "Snapshot L1 table",
2210 &local_err);
2211 if (ret < 0) {
2212 error_report_err(local_err);
2213 goto fail;
2216 l1_size2 = s->snapshots[i].l1_size * sizeof(uint64_t);
2217 new_l1_table = g_try_realloc(l1_table, l1_size2);
2219 if (!new_l1_table) {
2220 ret = -ENOMEM;
2221 goto fail;
2224 l1_table = new_l1_table;
2226 ret = bdrv_pread(bs->file, s->snapshots[i].l1_table_offset,
2227 l1_table, l1_size2);
2228 if (ret < 0) {
2229 goto fail;
2232 for (j = 0; j < s->snapshots[i].l1_size; j++) {
2233 be64_to_cpus(&l1_table[j]);
2236 ret = expand_zero_clusters_in_l1(bs, l1_table, s->snapshots[i].l1_size,
2237 &visited_l1_entries, l1_entries,
2238 status_cb, cb_opaque);
2239 if (ret < 0) {
2240 goto fail;
2244 ret = 0;
2246 fail:
2247 g_free(l1_table);
2248 return ret;