hostmem: Add hostmem-epc as a backend for SGX EPC
[qemu/kevin.git] / block / qcow2-cluster.c
blob4ebb49a087df2b5cedd97d4bfe2ced8077fc23cb
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 * L1E_SIZE,
51 (s->l1_size - new_l1_size) * L1E_SIZE, 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) * L1E_SIZE);
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 / L1E_SIZE) {
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 / L1E_SIZE) {
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 = L1E_SIZE * 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 * L1E_SIZE);
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 * L1E_SIZE,
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(L1E_SIZE,
229 MIN(bs->file->bs->bl.request_alignment, s->cluster_size));
230 int nentries = bufsize / L1E_SIZE;
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 + L1E_SIZE * 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 + L1E_SIZE * 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 static int qcow2_get_subcluster_range_type(BlockDriverState *bs,
391 uint64_t l2_entry,
392 uint64_t l2_bitmap,
393 unsigned sc_from,
394 QCow2SubclusterType *type)
396 BDRVQcow2State *s = bs->opaque;
397 uint32_t val;
399 *type = qcow2_get_subcluster_type(bs, l2_entry, l2_bitmap, sc_from);
401 if (*type == QCOW2_SUBCLUSTER_INVALID) {
402 return -EINVAL;
403 } else if (!has_subclusters(s) || *type == QCOW2_SUBCLUSTER_COMPRESSED) {
404 return s->subclusters_per_cluster - sc_from;
407 switch (*type) {
408 case QCOW2_SUBCLUSTER_NORMAL:
409 val = l2_bitmap | QCOW_OFLAG_SUB_ALLOC_RANGE(0, sc_from);
410 return cto32(val) - sc_from;
412 case QCOW2_SUBCLUSTER_ZERO_PLAIN:
413 case QCOW2_SUBCLUSTER_ZERO_ALLOC:
414 val = (l2_bitmap | QCOW_OFLAG_SUB_ZERO_RANGE(0, sc_from)) >> 32;
415 return cto32(val) - sc_from;
417 case QCOW2_SUBCLUSTER_UNALLOCATED_PLAIN:
418 case QCOW2_SUBCLUSTER_UNALLOCATED_ALLOC:
419 val = ((l2_bitmap >> 32) | l2_bitmap)
420 & ~QCOW_OFLAG_SUB_ALLOC_RANGE(0, sc_from);
421 return ctz32(val) - sc_from;
423 default:
424 g_assert_not_reached();
429 * Return the number of contiguous subclusters of the exact same type
430 * in a given L2 slice, starting from cluster @l2_index, subcluster
431 * @sc_index. Allocated subclusters are required to be contiguous in
432 * the image file.
433 * At most @nb_clusters are checked (note that this means clusters,
434 * not subclusters).
435 * Compressed clusters are always processed one by one but for the
436 * purpose of this count they are treated as if they were divided into
437 * subclusters of size s->subcluster_size.
438 * On failure return -errno and update @l2_index to point to the
439 * invalid entry.
441 static int count_contiguous_subclusters(BlockDriverState *bs, int nb_clusters,
442 unsigned sc_index, uint64_t *l2_slice,
443 unsigned *l2_index)
445 BDRVQcow2State *s = bs->opaque;
446 int i, count = 0;
447 bool check_offset = false;
448 uint64_t expected_offset = 0;
449 QCow2SubclusterType expected_type = QCOW2_SUBCLUSTER_NORMAL, type;
451 assert(*l2_index + nb_clusters <= s->l2_slice_size);
453 for (i = 0; i < nb_clusters; i++) {
454 unsigned first_sc = (i == 0) ? sc_index : 0;
455 uint64_t l2_entry = get_l2_entry(s, l2_slice, *l2_index + i);
456 uint64_t l2_bitmap = get_l2_bitmap(s, l2_slice, *l2_index + i);
457 int ret = qcow2_get_subcluster_range_type(bs, l2_entry, l2_bitmap,
458 first_sc, &type);
459 if (ret < 0) {
460 *l2_index += i; /* Point to the invalid entry */
461 return -EIO;
463 if (i == 0) {
464 if (type == QCOW2_SUBCLUSTER_COMPRESSED) {
465 /* Compressed clusters are always processed one by one */
466 return ret;
468 expected_type = type;
469 expected_offset = l2_entry & L2E_OFFSET_MASK;
470 check_offset = (type == QCOW2_SUBCLUSTER_NORMAL ||
471 type == QCOW2_SUBCLUSTER_ZERO_ALLOC ||
472 type == QCOW2_SUBCLUSTER_UNALLOCATED_ALLOC);
473 } else if (type != expected_type) {
474 break;
475 } else if (check_offset) {
476 expected_offset += s->cluster_size;
477 if (expected_offset != (l2_entry & L2E_OFFSET_MASK)) {
478 break;
481 count += ret;
482 /* Stop if there are type changes before the end of the cluster */
483 if (first_sc + ret < s->subclusters_per_cluster) {
484 break;
488 return count;
491 static int coroutine_fn do_perform_cow_read(BlockDriverState *bs,
492 uint64_t src_cluster_offset,
493 unsigned offset_in_cluster,
494 QEMUIOVector *qiov)
496 int ret;
498 if (qiov->size == 0) {
499 return 0;
502 BLKDBG_EVENT(bs->file, BLKDBG_COW_READ);
504 if (!bs->drv) {
505 return -ENOMEDIUM;
508 /* Call .bdrv_co_readv() directly instead of using the public block-layer
509 * interface. This avoids double I/O throttling and request tracking,
510 * which can lead to deadlock when block layer copy-on-read is enabled.
512 ret = bs->drv->bdrv_co_preadv_part(bs,
513 src_cluster_offset + offset_in_cluster,
514 qiov->size, qiov, 0, 0);
515 if (ret < 0) {
516 return ret;
519 return 0;
522 static int coroutine_fn do_perform_cow_write(BlockDriverState *bs,
523 uint64_t cluster_offset,
524 unsigned offset_in_cluster,
525 QEMUIOVector *qiov)
527 BDRVQcow2State *s = bs->opaque;
528 int ret;
530 if (qiov->size == 0) {
531 return 0;
534 ret = qcow2_pre_write_overlap_check(bs, 0,
535 cluster_offset + offset_in_cluster, qiov->size, true);
536 if (ret < 0) {
537 return ret;
540 BLKDBG_EVENT(bs->file, BLKDBG_COW_WRITE);
541 ret = bdrv_co_pwritev(s->data_file, cluster_offset + offset_in_cluster,
542 qiov->size, qiov, 0);
543 if (ret < 0) {
544 return ret;
547 return 0;
552 * get_host_offset
554 * For a given offset of the virtual disk find the equivalent host
555 * offset in the qcow2 file and store it in *host_offset. Neither
556 * offset needs to be aligned to a cluster boundary.
558 * If the cluster is unallocated then *host_offset will be 0.
559 * If the cluster is compressed then *host_offset will contain the l2 entry.
561 * On entry, *bytes is the maximum number of contiguous bytes starting at
562 * offset that we are interested in.
564 * On exit, *bytes is the number of bytes starting at offset that have the same
565 * subcluster type and (if applicable) are stored contiguously in the image
566 * file. The subcluster type is stored in *subcluster_type.
567 * Compressed clusters are always processed one by one.
569 * Returns 0 on success, -errno in error cases.
571 int qcow2_get_host_offset(BlockDriverState *bs, uint64_t offset,
572 unsigned int *bytes, uint64_t *host_offset,
573 QCow2SubclusterType *subcluster_type)
575 BDRVQcow2State *s = bs->opaque;
576 unsigned int l2_index, sc_index;
577 uint64_t l1_index, l2_offset, *l2_slice, l2_entry, l2_bitmap;
578 int sc;
579 unsigned int offset_in_cluster;
580 uint64_t bytes_available, bytes_needed, nb_clusters;
581 QCow2SubclusterType type;
582 int ret;
584 offset_in_cluster = offset_into_cluster(s, offset);
585 bytes_needed = (uint64_t) *bytes + offset_in_cluster;
587 /* compute how many bytes there are between the start of the cluster
588 * containing offset and the end of the l2 slice that contains
589 * the entry pointing to it */
590 bytes_available =
591 ((uint64_t) (s->l2_slice_size - offset_to_l2_slice_index(s, offset)))
592 << s->cluster_bits;
594 if (bytes_needed > bytes_available) {
595 bytes_needed = bytes_available;
598 *host_offset = 0;
600 /* seek to the l2 offset in the l1 table */
602 l1_index = offset_to_l1_index(s, offset);
603 if (l1_index >= s->l1_size) {
604 type = QCOW2_SUBCLUSTER_UNALLOCATED_PLAIN;
605 goto out;
608 l2_offset = s->l1_table[l1_index] & L1E_OFFSET_MASK;
609 if (!l2_offset) {
610 type = QCOW2_SUBCLUSTER_UNALLOCATED_PLAIN;
611 goto out;
614 if (offset_into_cluster(s, l2_offset)) {
615 qcow2_signal_corruption(bs, true, -1, -1, "L2 table offset %#" PRIx64
616 " unaligned (L1 index: %#" PRIx64 ")",
617 l2_offset, l1_index);
618 return -EIO;
621 /* load the l2 slice in memory */
623 ret = l2_load(bs, offset, l2_offset, &l2_slice);
624 if (ret < 0) {
625 return ret;
628 /* find the cluster offset for the given disk offset */
630 l2_index = offset_to_l2_slice_index(s, offset);
631 sc_index = offset_to_sc_index(s, offset);
632 l2_entry = get_l2_entry(s, l2_slice, l2_index);
633 l2_bitmap = get_l2_bitmap(s, l2_slice, l2_index);
635 nb_clusters = size_to_clusters(s, bytes_needed);
636 /* bytes_needed <= *bytes + offset_in_cluster, both of which are unsigned
637 * integers; the minimum cluster size is 512, so this assertion is always
638 * true */
639 assert(nb_clusters <= INT_MAX);
641 type = qcow2_get_subcluster_type(bs, l2_entry, l2_bitmap, sc_index);
642 if (s->qcow_version < 3 && (type == QCOW2_SUBCLUSTER_ZERO_PLAIN ||
643 type == QCOW2_SUBCLUSTER_ZERO_ALLOC)) {
644 qcow2_signal_corruption(bs, true, -1, -1, "Zero cluster entry found"
645 " in pre-v3 image (L2 offset: %#" PRIx64
646 ", L2 index: %#x)", l2_offset, l2_index);
647 ret = -EIO;
648 goto fail;
650 switch (type) {
651 case QCOW2_SUBCLUSTER_INVALID:
652 break; /* This is handled by count_contiguous_subclusters() below */
653 case QCOW2_SUBCLUSTER_COMPRESSED:
654 if (has_data_file(bs)) {
655 qcow2_signal_corruption(bs, true, -1, -1, "Compressed cluster "
656 "entry found in image with external data "
657 "file (L2 offset: %#" PRIx64 ", L2 index: "
658 "%#x)", l2_offset, l2_index);
659 ret = -EIO;
660 goto fail;
662 *host_offset = l2_entry;
663 break;
664 case QCOW2_SUBCLUSTER_ZERO_PLAIN:
665 case QCOW2_SUBCLUSTER_UNALLOCATED_PLAIN:
666 break;
667 case QCOW2_SUBCLUSTER_ZERO_ALLOC:
668 case QCOW2_SUBCLUSTER_NORMAL:
669 case QCOW2_SUBCLUSTER_UNALLOCATED_ALLOC: {
670 uint64_t host_cluster_offset = l2_entry & L2E_OFFSET_MASK;
671 *host_offset = host_cluster_offset + offset_in_cluster;
672 if (offset_into_cluster(s, host_cluster_offset)) {
673 qcow2_signal_corruption(bs, true, -1, -1,
674 "Cluster allocation offset %#"
675 PRIx64 " unaligned (L2 offset: %#" PRIx64
676 ", L2 index: %#x)", host_cluster_offset,
677 l2_offset, l2_index);
678 ret = -EIO;
679 goto fail;
681 if (has_data_file(bs) && *host_offset != offset) {
682 qcow2_signal_corruption(bs, true, -1, -1,
683 "External data file host cluster offset %#"
684 PRIx64 " does not match guest cluster "
685 "offset: %#" PRIx64
686 ", L2 index: %#x)", host_cluster_offset,
687 offset - offset_in_cluster, l2_index);
688 ret = -EIO;
689 goto fail;
691 break;
693 default:
694 abort();
697 sc = count_contiguous_subclusters(bs, nb_clusters, sc_index,
698 l2_slice, &l2_index);
699 if (sc < 0) {
700 qcow2_signal_corruption(bs, true, -1, -1, "Invalid cluster entry found "
701 " (L2 offset: %#" PRIx64 ", L2 index: %#x)",
702 l2_offset, l2_index);
703 ret = -EIO;
704 goto fail;
706 qcow2_cache_put(s->l2_table_cache, (void **) &l2_slice);
708 bytes_available = ((int64_t)sc + sc_index) << s->subcluster_bits;
710 out:
711 if (bytes_available > bytes_needed) {
712 bytes_available = bytes_needed;
715 /* bytes_available <= bytes_needed <= *bytes + offset_in_cluster;
716 * subtracting offset_in_cluster will therefore definitely yield something
717 * not exceeding UINT_MAX */
718 assert(bytes_available - offset_in_cluster <= UINT_MAX);
719 *bytes = bytes_available - offset_in_cluster;
721 *subcluster_type = type;
723 return 0;
725 fail:
726 qcow2_cache_put(s->l2_table_cache, (void **)&l2_slice);
727 return ret;
731 * get_cluster_table
733 * for a given disk offset, load (and allocate if needed)
734 * the appropriate slice of its l2 table.
736 * the cluster index in the l2 slice is given to the caller.
738 * Returns 0 on success, -errno in failure case
740 static int get_cluster_table(BlockDriverState *bs, uint64_t offset,
741 uint64_t **new_l2_slice,
742 int *new_l2_index)
744 BDRVQcow2State *s = bs->opaque;
745 unsigned int l2_index;
746 uint64_t l1_index, l2_offset;
747 uint64_t *l2_slice = NULL;
748 int ret;
750 /* seek to the l2 offset in the l1 table */
752 l1_index = offset_to_l1_index(s, offset);
753 if (l1_index >= s->l1_size) {
754 ret = qcow2_grow_l1_table(bs, l1_index + 1, false);
755 if (ret < 0) {
756 return ret;
760 assert(l1_index < s->l1_size);
761 l2_offset = s->l1_table[l1_index] & L1E_OFFSET_MASK;
762 if (offset_into_cluster(s, l2_offset)) {
763 qcow2_signal_corruption(bs, true, -1, -1, "L2 table offset %#" PRIx64
764 " unaligned (L1 index: %#" PRIx64 ")",
765 l2_offset, l1_index);
766 return -EIO;
769 if (!(s->l1_table[l1_index] & QCOW_OFLAG_COPIED)) {
770 /* First allocate a new L2 table (and do COW if needed) */
771 ret = l2_allocate(bs, l1_index);
772 if (ret < 0) {
773 return ret;
776 /* Then decrease the refcount of the old table */
777 if (l2_offset) {
778 qcow2_free_clusters(bs, l2_offset, s->l2_size * l2_entry_size(s),
779 QCOW2_DISCARD_OTHER);
782 /* Get the offset of the newly-allocated l2 table */
783 l2_offset = s->l1_table[l1_index] & L1E_OFFSET_MASK;
784 assert(offset_into_cluster(s, l2_offset) == 0);
787 /* load the l2 slice in memory */
788 ret = l2_load(bs, offset, l2_offset, &l2_slice);
789 if (ret < 0) {
790 return ret;
793 /* find the cluster offset for the given disk offset */
795 l2_index = offset_to_l2_slice_index(s, offset);
797 *new_l2_slice = l2_slice;
798 *new_l2_index = l2_index;
800 return 0;
804 * alloc_compressed_cluster_offset
806 * For a given offset on the virtual disk, allocate a new compressed cluster
807 * and put the host offset of the cluster into *host_offset. If a cluster is
808 * already allocated at the offset, return an error.
810 * Return 0 on success and -errno in error cases
812 int qcow2_alloc_compressed_cluster_offset(BlockDriverState *bs,
813 uint64_t offset,
814 int compressed_size,
815 uint64_t *host_offset)
817 BDRVQcow2State *s = bs->opaque;
818 int l2_index, ret;
819 uint64_t *l2_slice;
820 int64_t cluster_offset;
821 int nb_csectors;
823 if (has_data_file(bs)) {
824 return 0;
827 ret = get_cluster_table(bs, offset, &l2_slice, &l2_index);
828 if (ret < 0) {
829 return ret;
832 /* Compression can't overwrite anything. Fail if the cluster was already
833 * allocated. */
834 cluster_offset = get_l2_entry(s, l2_slice, l2_index);
835 if (cluster_offset & L2E_OFFSET_MASK) {
836 qcow2_cache_put(s->l2_table_cache, (void **) &l2_slice);
837 return -EIO;
840 cluster_offset = qcow2_alloc_bytes(bs, compressed_size);
841 if (cluster_offset < 0) {
842 qcow2_cache_put(s->l2_table_cache, (void **) &l2_slice);
843 return cluster_offset;
846 nb_csectors =
847 (cluster_offset + compressed_size - 1) / QCOW2_COMPRESSED_SECTOR_SIZE -
848 (cluster_offset / QCOW2_COMPRESSED_SECTOR_SIZE);
850 /* The offset and size must fit in their fields of the L2 table entry */
851 assert((cluster_offset & s->cluster_offset_mask) == cluster_offset);
852 assert((nb_csectors & s->csize_mask) == nb_csectors);
854 cluster_offset |= QCOW_OFLAG_COMPRESSED |
855 ((uint64_t)nb_csectors << s->csize_shift);
857 /* update L2 table */
859 /* compressed clusters never have the copied flag */
861 BLKDBG_EVENT(bs->file, BLKDBG_L2_UPDATE_COMPRESSED);
862 qcow2_cache_entry_mark_dirty(s->l2_table_cache, l2_slice);
863 set_l2_entry(s, l2_slice, l2_index, cluster_offset);
864 if (has_subclusters(s)) {
865 set_l2_bitmap(s, l2_slice, l2_index, 0);
867 qcow2_cache_put(s->l2_table_cache, (void **) &l2_slice);
869 *host_offset = cluster_offset & s->cluster_offset_mask;
870 return 0;
873 static int perform_cow(BlockDriverState *bs, QCowL2Meta *m)
875 BDRVQcow2State *s = bs->opaque;
876 Qcow2COWRegion *start = &m->cow_start;
877 Qcow2COWRegion *end = &m->cow_end;
878 unsigned buffer_size;
879 unsigned data_bytes = end->offset - (start->offset + start->nb_bytes);
880 bool merge_reads;
881 uint8_t *start_buffer, *end_buffer;
882 QEMUIOVector qiov;
883 int ret;
885 assert(start->nb_bytes <= UINT_MAX - end->nb_bytes);
886 assert(start->nb_bytes + end->nb_bytes <= UINT_MAX - data_bytes);
887 assert(start->offset + start->nb_bytes <= end->offset);
889 if ((start->nb_bytes == 0 && end->nb_bytes == 0) || m->skip_cow) {
890 return 0;
893 /* If we have to read both the start and end COW regions and the
894 * middle region is not too large then perform just one read
895 * operation */
896 merge_reads = start->nb_bytes && end->nb_bytes && data_bytes <= 16384;
897 if (merge_reads) {
898 buffer_size = start->nb_bytes + data_bytes + end->nb_bytes;
899 } else {
900 /* If we have to do two reads, add some padding in the middle
901 * if necessary to make sure that the end region is optimally
902 * aligned. */
903 size_t align = bdrv_opt_mem_align(bs);
904 assert(align > 0 && align <= UINT_MAX);
905 assert(QEMU_ALIGN_UP(start->nb_bytes, align) <=
906 UINT_MAX - end->nb_bytes);
907 buffer_size = QEMU_ALIGN_UP(start->nb_bytes, align) + end->nb_bytes;
910 /* Reserve a buffer large enough to store all the data that we're
911 * going to read */
912 start_buffer = qemu_try_blockalign(bs, buffer_size);
913 if (start_buffer == NULL) {
914 return -ENOMEM;
916 /* The part of the buffer where the end region is located */
917 end_buffer = start_buffer + buffer_size - end->nb_bytes;
919 qemu_iovec_init(&qiov, 2 + (m->data_qiov ?
920 qemu_iovec_subvec_niov(m->data_qiov,
921 m->data_qiov_offset,
922 data_bytes)
923 : 0));
925 qemu_co_mutex_unlock(&s->lock);
926 /* First we read the existing data from both COW regions. We
927 * either read the whole region in one go, or the start and end
928 * regions separately. */
929 if (merge_reads) {
930 qemu_iovec_add(&qiov, start_buffer, buffer_size);
931 ret = do_perform_cow_read(bs, m->offset, start->offset, &qiov);
932 } else {
933 qemu_iovec_add(&qiov, start_buffer, start->nb_bytes);
934 ret = do_perform_cow_read(bs, m->offset, start->offset, &qiov);
935 if (ret < 0) {
936 goto fail;
939 qemu_iovec_reset(&qiov);
940 qemu_iovec_add(&qiov, end_buffer, end->nb_bytes);
941 ret = do_perform_cow_read(bs, m->offset, end->offset, &qiov);
943 if (ret < 0) {
944 goto fail;
947 /* Encrypt the data if necessary before writing it */
948 if (bs->encrypted) {
949 ret = qcow2_co_encrypt(bs,
950 m->alloc_offset + start->offset,
951 m->offset + start->offset,
952 start_buffer, start->nb_bytes);
953 if (ret < 0) {
954 goto fail;
957 ret = qcow2_co_encrypt(bs,
958 m->alloc_offset + end->offset,
959 m->offset + end->offset,
960 end_buffer, end->nb_bytes);
961 if (ret < 0) {
962 goto fail;
966 /* And now we can write everything. If we have the guest data we
967 * can write everything in one single operation */
968 if (m->data_qiov) {
969 qemu_iovec_reset(&qiov);
970 if (start->nb_bytes) {
971 qemu_iovec_add(&qiov, start_buffer, start->nb_bytes);
973 qemu_iovec_concat(&qiov, m->data_qiov, m->data_qiov_offset, data_bytes);
974 if (end->nb_bytes) {
975 qemu_iovec_add(&qiov, end_buffer, end->nb_bytes);
977 /* NOTE: we have a write_aio blkdebug event here followed by
978 * a cow_write one in do_perform_cow_write(), but there's only
979 * one single I/O operation */
980 BLKDBG_EVENT(bs->file, BLKDBG_WRITE_AIO);
981 ret = do_perform_cow_write(bs, m->alloc_offset, start->offset, &qiov);
982 } else {
983 /* If there's no guest data then write both COW regions separately */
984 qemu_iovec_reset(&qiov);
985 qemu_iovec_add(&qiov, start_buffer, start->nb_bytes);
986 ret = do_perform_cow_write(bs, m->alloc_offset, start->offset, &qiov);
987 if (ret < 0) {
988 goto fail;
991 qemu_iovec_reset(&qiov);
992 qemu_iovec_add(&qiov, end_buffer, end->nb_bytes);
993 ret = do_perform_cow_write(bs, m->alloc_offset, end->offset, &qiov);
996 fail:
997 qemu_co_mutex_lock(&s->lock);
1000 * Before we update the L2 table to actually point to the new cluster, we
1001 * need to be sure that the refcounts have been increased and COW was
1002 * handled.
1004 if (ret == 0) {
1005 qcow2_cache_depends_on_flush(s->l2_table_cache);
1008 qemu_vfree(start_buffer);
1009 qemu_iovec_destroy(&qiov);
1010 return ret;
1013 int qcow2_alloc_cluster_link_l2(BlockDriverState *bs, QCowL2Meta *m)
1015 BDRVQcow2State *s = bs->opaque;
1016 int i, j = 0, l2_index, ret;
1017 uint64_t *old_cluster, *l2_slice;
1018 uint64_t cluster_offset = m->alloc_offset;
1020 trace_qcow2_cluster_link_l2(qemu_coroutine_self(), m->nb_clusters);
1021 assert(m->nb_clusters > 0);
1023 old_cluster = g_try_new(uint64_t, m->nb_clusters);
1024 if (old_cluster == NULL) {
1025 ret = -ENOMEM;
1026 goto err;
1029 /* copy content of unmodified sectors */
1030 ret = perform_cow(bs, m);
1031 if (ret < 0) {
1032 goto err;
1035 /* Update L2 table. */
1036 if (s->use_lazy_refcounts) {
1037 qcow2_mark_dirty(bs);
1039 if (qcow2_need_accurate_refcounts(s)) {
1040 qcow2_cache_set_dependency(bs, s->l2_table_cache,
1041 s->refcount_block_cache);
1044 ret = get_cluster_table(bs, m->offset, &l2_slice, &l2_index);
1045 if (ret < 0) {
1046 goto err;
1048 qcow2_cache_entry_mark_dirty(s->l2_table_cache, l2_slice);
1050 assert(l2_index + m->nb_clusters <= s->l2_slice_size);
1051 assert(m->cow_end.offset + m->cow_end.nb_bytes <=
1052 m->nb_clusters << s->cluster_bits);
1053 for (i = 0; i < m->nb_clusters; i++) {
1054 uint64_t offset = cluster_offset + ((uint64_t)i << s->cluster_bits);
1055 /* if two concurrent writes happen to the same unallocated cluster
1056 * each write allocates separate cluster and writes data concurrently.
1057 * The first one to complete updates l2 table with pointer to its
1058 * cluster the second one has to do RMW (which is done above by
1059 * perform_cow()), update l2 table with its cluster pointer and free
1060 * old cluster. This is what this loop does */
1061 if (get_l2_entry(s, l2_slice, l2_index + i) != 0) {
1062 old_cluster[j++] = get_l2_entry(s, l2_slice, l2_index + i);
1065 /* The offset must fit in the offset field of the L2 table entry */
1066 assert((offset & L2E_OFFSET_MASK) == offset);
1068 set_l2_entry(s, l2_slice, l2_index + i, offset | QCOW_OFLAG_COPIED);
1070 /* Update bitmap with the subclusters that were just written */
1071 if (has_subclusters(s) && !m->prealloc) {
1072 uint64_t l2_bitmap = get_l2_bitmap(s, l2_slice, l2_index + i);
1073 unsigned written_from = m->cow_start.offset;
1074 unsigned written_to = m->cow_end.offset + m->cow_end.nb_bytes;
1075 int first_sc, last_sc;
1076 /* Narrow written_from and written_to down to the current cluster */
1077 written_from = MAX(written_from, i << s->cluster_bits);
1078 written_to = MIN(written_to, (i + 1) << s->cluster_bits);
1079 assert(written_from < written_to);
1080 first_sc = offset_to_sc_index(s, written_from);
1081 last_sc = offset_to_sc_index(s, written_to - 1);
1082 l2_bitmap |= QCOW_OFLAG_SUB_ALLOC_RANGE(first_sc, last_sc + 1);
1083 l2_bitmap &= ~QCOW_OFLAG_SUB_ZERO_RANGE(first_sc, last_sc + 1);
1084 set_l2_bitmap(s, l2_slice, l2_index + i, l2_bitmap);
1089 qcow2_cache_put(s->l2_table_cache, (void **) &l2_slice);
1092 * If this was a COW, we need to decrease the refcount of the old cluster.
1094 * Don't discard clusters that reach a refcount of 0 (e.g. compressed
1095 * clusters), the next write will reuse them anyway.
1097 if (!m->keep_old_clusters && j != 0) {
1098 for (i = 0; i < j; i++) {
1099 qcow2_free_any_cluster(bs, old_cluster[i], QCOW2_DISCARD_NEVER);
1103 ret = 0;
1104 err:
1105 g_free(old_cluster);
1106 return ret;
1110 * Frees the allocated clusters because the request failed and they won't
1111 * actually be linked.
1113 void qcow2_alloc_cluster_abort(BlockDriverState *bs, QCowL2Meta *m)
1115 BDRVQcow2State *s = bs->opaque;
1116 if (!has_data_file(bs) && !m->keep_old_clusters) {
1117 qcow2_free_clusters(bs, m->alloc_offset,
1118 m->nb_clusters << s->cluster_bits,
1119 QCOW2_DISCARD_NEVER);
1124 * For a given write request, create a new QCowL2Meta structure, add
1125 * it to @m and the BDRVQcow2State.cluster_allocs list. If the write
1126 * request does not need copy-on-write or changes to the L2 metadata
1127 * then this function does nothing.
1129 * @host_cluster_offset points to the beginning of the first cluster.
1131 * @guest_offset and @bytes indicate the offset and length of the
1132 * request.
1134 * @l2_slice contains the L2 entries of all clusters involved in this
1135 * write request.
1137 * If @keep_old is true it means that the clusters were already
1138 * allocated and will be overwritten. If false then the clusters are
1139 * new and we have to decrease the reference count of the old ones.
1141 * Returns 0 on success, -errno on failure.
1143 static int calculate_l2_meta(BlockDriverState *bs, uint64_t host_cluster_offset,
1144 uint64_t guest_offset, unsigned bytes,
1145 uint64_t *l2_slice, QCowL2Meta **m, bool keep_old)
1147 BDRVQcow2State *s = bs->opaque;
1148 int sc_index, l2_index = offset_to_l2_slice_index(s, guest_offset);
1149 uint64_t l2_entry, l2_bitmap;
1150 unsigned cow_start_from, cow_end_to;
1151 unsigned cow_start_to = offset_into_cluster(s, guest_offset);
1152 unsigned cow_end_from = cow_start_to + bytes;
1153 unsigned nb_clusters = size_to_clusters(s, cow_end_from);
1154 QCowL2Meta *old_m = *m;
1155 QCow2SubclusterType type;
1156 int i;
1157 bool skip_cow = keep_old;
1159 assert(nb_clusters <= s->l2_slice_size - l2_index);
1161 /* Check the type of all affected subclusters */
1162 for (i = 0; i < nb_clusters; i++) {
1163 l2_entry = get_l2_entry(s, l2_slice, l2_index + i);
1164 l2_bitmap = get_l2_bitmap(s, l2_slice, l2_index + i);
1165 if (skip_cow) {
1166 unsigned write_from = MAX(cow_start_to, i << s->cluster_bits);
1167 unsigned write_to = MIN(cow_end_from, (i + 1) << s->cluster_bits);
1168 int first_sc = offset_to_sc_index(s, write_from);
1169 int last_sc = offset_to_sc_index(s, write_to - 1);
1170 int cnt = qcow2_get_subcluster_range_type(bs, l2_entry, l2_bitmap,
1171 first_sc, &type);
1172 /* Is any of the subclusters of type != QCOW2_SUBCLUSTER_NORMAL ? */
1173 if (type != QCOW2_SUBCLUSTER_NORMAL || first_sc + cnt <= last_sc) {
1174 skip_cow = false;
1176 } else {
1177 /* If we can't skip the cow we can still look for invalid entries */
1178 type = qcow2_get_subcluster_type(bs, l2_entry, l2_bitmap, 0);
1180 if (type == QCOW2_SUBCLUSTER_INVALID) {
1181 int l1_index = offset_to_l1_index(s, guest_offset);
1182 uint64_t l2_offset = s->l1_table[l1_index] & L1E_OFFSET_MASK;
1183 qcow2_signal_corruption(bs, true, -1, -1, "Invalid cluster "
1184 "entry found (L2 offset: %#" PRIx64
1185 ", L2 index: %#x)",
1186 l2_offset, l2_index + i);
1187 return -EIO;
1191 if (skip_cow) {
1192 return 0;
1195 /* Get the L2 entry of the first cluster */
1196 l2_entry = get_l2_entry(s, l2_slice, l2_index);
1197 l2_bitmap = get_l2_bitmap(s, l2_slice, l2_index);
1198 sc_index = offset_to_sc_index(s, guest_offset);
1199 type = qcow2_get_subcluster_type(bs, l2_entry, l2_bitmap, sc_index);
1201 if (!keep_old) {
1202 switch (type) {
1203 case QCOW2_SUBCLUSTER_COMPRESSED:
1204 cow_start_from = 0;
1205 break;
1206 case QCOW2_SUBCLUSTER_NORMAL:
1207 case QCOW2_SUBCLUSTER_ZERO_ALLOC:
1208 case QCOW2_SUBCLUSTER_UNALLOCATED_ALLOC:
1209 if (has_subclusters(s)) {
1210 /* Skip all leading zero and unallocated subclusters */
1211 uint32_t alloc_bitmap = l2_bitmap & QCOW_L2_BITMAP_ALL_ALLOC;
1212 cow_start_from =
1213 MIN(sc_index, ctz32(alloc_bitmap)) << s->subcluster_bits;
1214 } else {
1215 cow_start_from = 0;
1217 break;
1218 case QCOW2_SUBCLUSTER_ZERO_PLAIN:
1219 case QCOW2_SUBCLUSTER_UNALLOCATED_PLAIN:
1220 cow_start_from = sc_index << s->subcluster_bits;
1221 break;
1222 default:
1223 g_assert_not_reached();
1225 } else {
1226 switch (type) {
1227 case QCOW2_SUBCLUSTER_NORMAL:
1228 cow_start_from = cow_start_to;
1229 break;
1230 case QCOW2_SUBCLUSTER_ZERO_ALLOC:
1231 case QCOW2_SUBCLUSTER_UNALLOCATED_ALLOC:
1232 cow_start_from = sc_index << s->subcluster_bits;
1233 break;
1234 default:
1235 g_assert_not_reached();
1239 /* Get the L2 entry of the last cluster */
1240 l2_index += nb_clusters - 1;
1241 l2_entry = get_l2_entry(s, l2_slice, l2_index);
1242 l2_bitmap = get_l2_bitmap(s, l2_slice, l2_index);
1243 sc_index = offset_to_sc_index(s, guest_offset + bytes - 1);
1244 type = qcow2_get_subcluster_type(bs, l2_entry, l2_bitmap, sc_index);
1246 if (!keep_old) {
1247 switch (type) {
1248 case QCOW2_SUBCLUSTER_COMPRESSED:
1249 cow_end_to = ROUND_UP(cow_end_from, s->cluster_size);
1250 break;
1251 case QCOW2_SUBCLUSTER_NORMAL:
1252 case QCOW2_SUBCLUSTER_ZERO_ALLOC:
1253 case QCOW2_SUBCLUSTER_UNALLOCATED_ALLOC:
1254 cow_end_to = ROUND_UP(cow_end_from, s->cluster_size);
1255 if (has_subclusters(s)) {
1256 /* Skip all trailing zero and unallocated subclusters */
1257 uint32_t alloc_bitmap = l2_bitmap & QCOW_L2_BITMAP_ALL_ALLOC;
1258 cow_end_to -=
1259 MIN(s->subclusters_per_cluster - sc_index - 1,
1260 clz32(alloc_bitmap)) << s->subcluster_bits;
1262 break;
1263 case QCOW2_SUBCLUSTER_ZERO_PLAIN:
1264 case QCOW2_SUBCLUSTER_UNALLOCATED_PLAIN:
1265 cow_end_to = ROUND_UP(cow_end_from, s->subcluster_size);
1266 break;
1267 default:
1268 g_assert_not_reached();
1270 } else {
1271 switch (type) {
1272 case QCOW2_SUBCLUSTER_NORMAL:
1273 cow_end_to = cow_end_from;
1274 break;
1275 case QCOW2_SUBCLUSTER_ZERO_ALLOC:
1276 case QCOW2_SUBCLUSTER_UNALLOCATED_ALLOC:
1277 cow_end_to = ROUND_UP(cow_end_from, s->subcluster_size);
1278 break;
1279 default:
1280 g_assert_not_reached();
1284 *m = g_malloc0(sizeof(**m));
1285 **m = (QCowL2Meta) {
1286 .next = old_m,
1288 .alloc_offset = host_cluster_offset,
1289 .offset = start_of_cluster(s, guest_offset),
1290 .nb_clusters = nb_clusters,
1292 .keep_old_clusters = keep_old,
1294 .cow_start = {
1295 .offset = cow_start_from,
1296 .nb_bytes = cow_start_to - cow_start_from,
1298 .cow_end = {
1299 .offset = cow_end_from,
1300 .nb_bytes = cow_end_to - cow_end_from,
1304 qemu_co_queue_init(&(*m)->dependent_requests);
1305 QLIST_INSERT_HEAD(&s->cluster_allocs, *m, next_in_flight);
1307 return 0;
1311 * Returns true if writing to the cluster pointed to by @l2_entry
1312 * requires a new allocation (that is, if the cluster is unallocated
1313 * or has refcount > 1 and therefore cannot be written in-place).
1315 static bool cluster_needs_new_alloc(BlockDriverState *bs, uint64_t l2_entry)
1317 switch (qcow2_get_cluster_type(bs, l2_entry)) {
1318 case QCOW2_CLUSTER_NORMAL:
1319 case QCOW2_CLUSTER_ZERO_ALLOC:
1320 if (l2_entry & QCOW_OFLAG_COPIED) {
1321 return false;
1323 /* fallthrough */
1324 case QCOW2_CLUSTER_UNALLOCATED:
1325 case QCOW2_CLUSTER_COMPRESSED:
1326 case QCOW2_CLUSTER_ZERO_PLAIN:
1327 return true;
1328 default:
1329 abort();
1334 * Returns the number of contiguous clusters that can be written to
1335 * using one single write request, starting from @l2_index.
1336 * At most @nb_clusters are checked.
1338 * If @new_alloc is true this counts clusters that are either
1339 * unallocated, or allocated but with refcount > 1 (so they need to be
1340 * newly allocated and COWed).
1342 * If @new_alloc is false this counts clusters that are already
1343 * allocated and can be overwritten in-place (this includes clusters
1344 * of type QCOW2_CLUSTER_ZERO_ALLOC).
1346 static int count_single_write_clusters(BlockDriverState *bs, int nb_clusters,
1347 uint64_t *l2_slice, int l2_index,
1348 bool new_alloc)
1350 BDRVQcow2State *s = bs->opaque;
1351 uint64_t l2_entry = get_l2_entry(s, l2_slice, l2_index);
1352 uint64_t expected_offset = l2_entry & L2E_OFFSET_MASK;
1353 int i;
1355 for (i = 0; i < nb_clusters; i++) {
1356 l2_entry = get_l2_entry(s, l2_slice, l2_index + i);
1357 if (cluster_needs_new_alloc(bs, l2_entry) != new_alloc) {
1358 break;
1360 if (!new_alloc) {
1361 if (expected_offset != (l2_entry & L2E_OFFSET_MASK)) {
1362 break;
1364 expected_offset += s->cluster_size;
1368 assert(i <= nb_clusters);
1369 return i;
1373 * Check if there already is an AIO write request in flight which allocates
1374 * the same cluster. In this case we need to wait until the previous
1375 * request has completed and updated the L2 table accordingly.
1377 * Returns:
1378 * 0 if there was no dependency. *cur_bytes indicates the number of
1379 * bytes from guest_offset that can be read before the next
1380 * dependency must be processed (or the request is complete)
1382 * -EAGAIN if we had to wait for another request, previously gathered
1383 * information on cluster allocation may be invalid now. The caller
1384 * must start over anyway, so consider *cur_bytes undefined.
1386 static int handle_dependencies(BlockDriverState *bs, uint64_t guest_offset,
1387 uint64_t *cur_bytes, QCowL2Meta **m)
1389 BDRVQcow2State *s = bs->opaque;
1390 QCowL2Meta *old_alloc;
1391 uint64_t bytes = *cur_bytes;
1393 QLIST_FOREACH(old_alloc, &s->cluster_allocs, next_in_flight) {
1395 uint64_t start = guest_offset;
1396 uint64_t end = start + bytes;
1397 uint64_t old_start = start_of_cluster(s, l2meta_cow_start(old_alloc));
1398 uint64_t old_end = ROUND_UP(l2meta_cow_end(old_alloc), s->cluster_size);
1400 if (end <= old_start || start >= old_end) {
1401 /* No intersection */
1402 continue;
1405 if (old_alloc->keep_old_clusters &&
1406 (end <= l2meta_cow_start(old_alloc) ||
1407 start >= l2meta_cow_end(old_alloc)))
1410 * Clusters intersect but COW areas don't. And cluster itself is
1411 * already allocated. So, there is no actual conflict.
1413 continue;
1416 /* Conflict */
1418 if (start < old_start) {
1419 /* Stop at the start of a running allocation */
1420 bytes = old_start - start;
1421 } else {
1422 bytes = 0;
1426 * Stop if an l2meta already exists. After yielding, it wouldn't
1427 * be valid any more, so we'd have to clean up the old L2Metas
1428 * and deal with requests depending on them before starting to
1429 * gather new ones. Not worth the trouble.
1431 if (bytes == 0 && *m) {
1432 *cur_bytes = 0;
1433 return 0;
1436 if (bytes == 0) {
1438 * Wait for the dependency to complete. We need to recheck
1439 * the free/allocated clusters when we continue.
1441 qemu_co_queue_wait(&old_alloc->dependent_requests, &s->lock);
1442 return -EAGAIN;
1446 /* Make sure that existing clusters and new allocations are only used up to
1447 * the next dependency if we shortened the request above */
1448 *cur_bytes = bytes;
1450 return 0;
1454 * Checks how many already allocated clusters that don't require a new
1455 * allocation there are at the given guest_offset (up to *bytes).
1456 * If *host_offset is not INV_OFFSET, only physically contiguous clusters
1457 * beginning at this host offset are counted.
1459 * Note that guest_offset may not be cluster aligned. In this case, the
1460 * returned *host_offset points to exact byte referenced by guest_offset and
1461 * therefore isn't cluster aligned as well.
1463 * Returns:
1464 * 0: if no allocated clusters are available at the given offset.
1465 * *bytes is normally unchanged. It is set to 0 if the cluster
1466 * is allocated and can be overwritten in-place but doesn't have
1467 * the right physical offset.
1469 * 1: if allocated clusters that can be overwritten in place are
1470 * available at the requested offset. *bytes may have decreased
1471 * and describes the length of the area that can be written to.
1473 * -errno: in error cases
1475 static int handle_copied(BlockDriverState *bs, uint64_t guest_offset,
1476 uint64_t *host_offset, uint64_t *bytes, QCowL2Meta **m)
1478 BDRVQcow2State *s = bs->opaque;
1479 int l2_index;
1480 uint64_t l2_entry, cluster_offset;
1481 uint64_t *l2_slice;
1482 uint64_t nb_clusters;
1483 unsigned int keep_clusters;
1484 int ret;
1486 trace_qcow2_handle_copied(qemu_coroutine_self(), guest_offset, *host_offset,
1487 *bytes);
1489 assert(*host_offset == INV_OFFSET || offset_into_cluster(s, guest_offset)
1490 == offset_into_cluster(s, *host_offset));
1493 * Calculate the number of clusters to look for. We stop at L2 slice
1494 * boundaries to keep things simple.
1496 nb_clusters =
1497 size_to_clusters(s, offset_into_cluster(s, guest_offset) + *bytes);
1499 l2_index = offset_to_l2_slice_index(s, guest_offset);
1500 nb_clusters = MIN(nb_clusters, s->l2_slice_size - l2_index);
1501 /* Limit total byte count to BDRV_REQUEST_MAX_BYTES */
1502 nb_clusters = MIN(nb_clusters, BDRV_REQUEST_MAX_BYTES >> s->cluster_bits);
1504 /* Find L2 entry for the first involved cluster */
1505 ret = get_cluster_table(bs, guest_offset, &l2_slice, &l2_index);
1506 if (ret < 0) {
1507 return ret;
1510 l2_entry = get_l2_entry(s, l2_slice, l2_index);
1511 cluster_offset = l2_entry & L2E_OFFSET_MASK;
1513 if (!cluster_needs_new_alloc(bs, l2_entry)) {
1514 if (offset_into_cluster(s, cluster_offset)) {
1515 qcow2_signal_corruption(bs, true, -1, -1, "%s cluster offset "
1516 "%#" PRIx64 " unaligned (guest offset: %#"
1517 PRIx64 ")", l2_entry & QCOW_OFLAG_ZERO ?
1518 "Preallocated zero" : "Data",
1519 cluster_offset, guest_offset);
1520 ret = -EIO;
1521 goto out;
1524 /* If a specific host_offset is required, check it */
1525 if (*host_offset != INV_OFFSET && cluster_offset != *host_offset) {
1526 *bytes = 0;
1527 ret = 0;
1528 goto out;
1531 /* We keep all QCOW_OFLAG_COPIED clusters */
1532 keep_clusters = count_single_write_clusters(bs, nb_clusters, l2_slice,
1533 l2_index, false);
1534 assert(keep_clusters <= nb_clusters);
1536 *bytes = MIN(*bytes,
1537 keep_clusters * s->cluster_size
1538 - offset_into_cluster(s, guest_offset));
1539 assert(*bytes != 0);
1541 ret = calculate_l2_meta(bs, cluster_offset, guest_offset,
1542 *bytes, l2_slice, m, true);
1543 if (ret < 0) {
1544 goto out;
1547 ret = 1;
1548 } else {
1549 ret = 0;
1552 /* Cleanup */
1553 out:
1554 qcow2_cache_put(s->l2_table_cache, (void **) &l2_slice);
1556 /* Only return a host offset if we actually made progress. Otherwise we
1557 * would make requirements for handle_alloc() that it can't fulfill */
1558 if (ret > 0) {
1559 *host_offset = cluster_offset + offset_into_cluster(s, guest_offset);
1562 return ret;
1566 * Allocates new clusters for the given guest_offset.
1568 * At most *nb_clusters are allocated, and on return *nb_clusters is updated to
1569 * contain the number of clusters that have been allocated and are contiguous
1570 * in the image file.
1572 * If *host_offset is not INV_OFFSET, it specifies the offset in the image file
1573 * at which the new clusters must start. *nb_clusters can be 0 on return in
1574 * this case if the cluster at host_offset is already in use. If *host_offset
1575 * is INV_OFFSET, the clusters can be allocated anywhere in the image file.
1577 * *host_offset is updated to contain the offset into the image file at which
1578 * the first allocated cluster starts.
1580 * Return 0 on success and -errno in error cases. -EAGAIN means that the
1581 * function has been waiting for another request and the allocation must be
1582 * restarted, but the whole request should not be failed.
1584 static int do_alloc_cluster_offset(BlockDriverState *bs, uint64_t guest_offset,
1585 uint64_t *host_offset, uint64_t *nb_clusters)
1587 BDRVQcow2State *s = bs->opaque;
1589 trace_qcow2_do_alloc_clusters_offset(qemu_coroutine_self(), guest_offset,
1590 *host_offset, *nb_clusters);
1592 if (has_data_file(bs)) {
1593 assert(*host_offset == INV_OFFSET ||
1594 *host_offset == start_of_cluster(s, guest_offset));
1595 *host_offset = start_of_cluster(s, guest_offset);
1596 return 0;
1599 /* Allocate new clusters */
1600 trace_qcow2_cluster_alloc_phys(qemu_coroutine_self());
1601 if (*host_offset == INV_OFFSET) {
1602 int64_t cluster_offset =
1603 qcow2_alloc_clusters(bs, *nb_clusters * s->cluster_size);
1604 if (cluster_offset < 0) {
1605 return cluster_offset;
1607 *host_offset = cluster_offset;
1608 return 0;
1609 } else {
1610 int64_t ret = qcow2_alloc_clusters_at(bs, *host_offset, *nb_clusters);
1611 if (ret < 0) {
1612 return ret;
1614 *nb_clusters = ret;
1615 return 0;
1620 * Allocates new clusters for an area that is either still unallocated or
1621 * cannot be overwritten in-place. If *host_offset is not INV_OFFSET,
1622 * clusters are only allocated if the new allocation can match the specified
1623 * host offset.
1625 * Note that guest_offset may not be cluster aligned. In this case, the
1626 * returned *host_offset points to exact byte referenced by guest_offset and
1627 * therefore isn't cluster aligned as well.
1629 * Returns:
1630 * 0: if no clusters could be allocated. *bytes is set to 0,
1631 * *host_offset is left unchanged.
1633 * 1: if new clusters were allocated. *bytes may be decreased if the
1634 * new allocation doesn't cover all of the requested area.
1635 * *host_offset is updated to contain the host offset of the first
1636 * newly allocated cluster.
1638 * -errno: in error cases
1640 static int handle_alloc(BlockDriverState *bs, uint64_t guest_offset,
1641 uint64_t *host_offset, uint64_t *bytes, QCowL2Meta **m)
1643 BDRVQcow2State *s = bs->opaque;
1644 int l2_index;
1645 uint64_t *l2_slice;
1646 uint64_t nb_clusters;
1647 int ret;
1649 uint64_t alloc_cluster_offset;
1651 trace_qcow2_handle_alloc(qemu_coroutine_self(), guest_offset, *host_offset,
1652 *bytes);
1653 assert(*bytes > 0);
1656 * Calculate the number of clusters to look for. We stop at L2 slice
1657 * boundaries to keep things simple.
1659 nb_clusters =
1660 size_to_clusters(s, offset_into_cluster(s, guest_offset) + *bytes);
1662 l2_index = offset_to_l2_slice_index(s, guest_offset);
1663 nb_clusters = MIN(nb_clusters, s->l2_slice_size - l2_index);
1664 /* Limit total allocation byte count to BDRV_REQUEST_MAX_BYTES */
1665 nb_clusters = MIN(nb_clusters, BDRV_REQUEST_MAX_BYTES >> s->cluster_bits);
1667 /* Find L2 entry for the first involved cluster */
1668 ret = get_cluster_table(bs, guest_offset, &l2_slice, &l2_index);
1669 if (ret < 0) {
1670 return ret;
1673 nb_clusters = count_single_write_clusters(bs, nb_clusters,
1674 l2_slice, l2_index, true);
1676 /* This function is only called when there were no non-COW clusters, so if
1677 * we can't find any unallocated or COW clusters either, something is
1678 * wrong with our code. */
1679 assert(nb_clusters > 0);
1681 /* Allocate at a given offset in the image file */
1682 alloc_cluster_offset = *host_offset == INV_OFFSET ? INV_OFFSET :
1683 start_of_cluster(s, *host_offset);
1684 ret = do_alloc_cluster_offset(bs, guest_offset, &alloc_cluster_offset,
1685 &nb_clusters);
1686 if (ret < 0) {
1687 goto out;
1690 /* Can't extend contiguous allocation */
1691 if (nb_clusters == 0) {
1692 *bytes = 0;
1693 ret = 0;
1694 goto out;
1697 assert(alloc_cluster_offset != INV_OFFSET);
1700 * Save info needed for meta data update.
1702 * requested_bytes: Number of bytes from the start of the first
1703 * newly allocated cluster to the end of the (possibly shortened
1704 * before) write request.
1706 * avail_bytes: Number of bytes from the start of the first
1707 * newly allocated to the end of the last newly allocated cluster.
1709 * nb_bytes: The number of bytes from the start of the first
1710 * newly allocated cluster to the end of the area that the write
1711 * request actually writes to (excluding COW at the end)
1713 uint64_t requested_bytes = *bytes + offset_into_cluster(s, guest_offset);
1714 int avail_bytes = nb_clusters << s->cluster_bits;
1715 int nb_bytes = MIN(requested_bytes, avail_bytes);
1717 *host_offset = alloc_cluster_offset + offset_into_cluster(s, guest_offset);
1718 *bytes = MIN(*bytes, nb_bytes - offset_into_cluster(s, guest_offset));
1719 assert(*bytes != 0);
1721 ret = calculate_l2_meta(bs, alloc_cluster_offset, guest_offset, *bytes,
1722 l2_slice, m, false);
1723 if (ret < 0) {
1724 goto out;
1727 ret = 1;
1729 out:
1730 qcow2_cache_put(s->l2_table_cache, (void **) &l2_slice);
1731 return ret;
1735 * For a given area on the virtual disk defined by @offset and @bytes,
1736 * find the corresponding area on the qcow2 image, allocating new
1737 * clusters (or subclusters) if necessary. The result can span a
1738 * combination of allocated and previously unallocated clusters.
1740 * Note that offset may not be cluster aligned. In this case, the returned
1741 * *host_offset points to exact byte referenced by offset and therefore
1742 * isn't cluster aligned as well.
1744 * On return, @host_offset is set to the beginning of the requested
1745 * area. This area is guaranteed to be contiguous on the qcow2 file
1746 * but it can be smaller than initially requested. In this case @bytes
1747 * is updated with the actual size.
1749 * If any clusters or subclusters were allocated then @m contains a
1750 * list with the information of all the affected regions. Note that
1751 * this can happen regardless of whether this function succeeds or
1752 * not. The caller is responsible for updating the L2 metadata of the
1753 * allocated clusters (on success) or freeing them (on failure), and
1754 * for clearing the contents of @m afterwards in both cases.
1756 * If the request conflicts with another write request in flight, the coroutine
1757 * is queued and will be reentered when the dependency has completed.
1759 * Return 0 on success and -errno in error cases
1761 int qcow2_alloc_host_offset(BlockDriverState *bs, uint64_t offset,
1762 unsigned int *bytes, uint64_t *host_offset,
1763 QCowL2Meta **m)
1765 BDRVQcow2State *s = bs->opaque;
1766 uint64_t start, remaining;
1767 uint64_t cluster_offset;
1768 uint64_t cur_bytes;
1769 int ret;
1771 trace_qcow2_alloc_clusters_offset(qemu_coroutine_self(), offset, *bytes);
1773 again:
1774 start = offset;
1775 remaining = *bytes;
1776 cluster_offset = INV_OFFSET;
1777 *host_offset = INV_OFFSET;
1778 cur_bytes = 0;
1779 *m = NULL;
1781 while (true) {
1783 if (*host_offset == INV_OFFSET && cluster_offset != INV_OFFSET) {
1784 *host_offset = cluster_offset;
1787 assert(remaining >= cur_bytes);
1789 start += cur_bytes;
1790 remaining -= cur_bytes;
1792 if (cluster_offset != INV_OFFSET) {
1793 cluster_offset += cur_bytes;
1796 if (remaining == 0) {
1797 break;
1800 cur_bytes = remaining;
1803 * Now start gathering as many contiguous clusters as possible:
1805 * 1. Check for overlaps with in-flight allocations
1807 * a) Overlap not in the first cluster -> shorten this request and
1808 * let the caller handle the rest in its next loop iteration.
1810 * b) Real overlaps of two requests. Yield and restart the search
1811 * for contiguous clusters (the situation could have changed
1812 * while we were sleeping)
1814 * c) TODO: Request starts in the same cluster as the in-flight
1815 * allocation ends. Shorten the COW of the in-fight allocation,
1816 * set cluster_offset to write to the same cluster and set up
1817 * the right synchronisation between the in-flight request and
1818 * the new one.
1820 ret = handle_dependencies(bs, start, &cur_bytes, m);
1821 if (ret == -EAGAIN) {
1822 /* Currently handle_dependencies() doesn't yield if we already had
1823 * an allocation. If it did, we would have to clean up the L2Meta
1824 * structs before starting over. */
1825 assert(*m == NULL);
1826 goto again;
1827 } else if (ret < 0) {
1828 return ret;
1829 } else if (cur_bytes == 0) {
1830 break;
1831 } else {
1832 /* handle_dependencies() may have decreased cur_bytes (shortened
1833 * the allocations below) so that the next dependency is processed
1834 * correctly during the next loop iteration. */
1838 * 2. Count contiguous COPIED clusters.
1840 ret = handle_copied(bs, start, &cluster_offset, &cur_bytes, m);
1841 if (ret < 0) {
1842 return ret;
1843 } else if (ret) {
1844 continue;
1845 } else if (cur_bytes == 0) {
1846 break;
1850 * 3. If the request still hasn't completed, allocate new clusters,
1851 * considering any cluster_offset of steps 1c or 2.
1853 ret = handle_alloc(bs, start, &cluster_offset, &cur_bytes, m);
1854 if (ret < 0) {
1855 return ret;
1856 } else if (ret) {
1857 continue;
1858 } else {
1859 assert(cur_bytes == 0);
1860 break;
1864 *bytes -= remaining;
1865 assert(*bytes > 0);
1866 assert(*host_offset != INV_OFFSET);
1867 assert(offset_into_cluster(s, *host_offset) ==
1868 offset_into_cluster(s, offset));
1870 return 0;
1874 * This discards as many clusters of nb_clusters as possible at once (i.e.
1875 * all clusters in the same L2 slice) and returns the number of discarded
1876 * clusters.
1878 static int discard_in_l2_slice(BlockDriverState *bs, uint64_t offset,
1879 uint64_t nb_clusters,
1880 enum qcow2_discard_type type, bool full_discard)
1882 BDRVQcow2State *s = bs->opaque;
1883 uint64_t *l2_slice;
1884 int l2_index;
1885 int ret;
1886 int i;
1888 ret = get_cluster_table(bs, offset, &l2_slice, &l2_index);
1889 if (ret < 0) {
1890 return ret;
1893 /* Limit nb_clusters to one L2 slice */
1894 nb_clusters = MIN(nb_clusters, s->l2_slice_size - l2_index);
1895 assert(nb_clusters <= INT_MAX);
1897 for (i = 0; i < nb_clusters; i++) {
1898 uint64_t old_l2_entry = get_l2_entry(s, l2_slice, l2_index + i);
1899 uint64_t old_l2_bitmap = get_l2_bitmap(s, l2_slice, l2_index + i);
1900 uint64_t new_l2_entry = old_l2_entry;
1901 uint64_t new_l2_bitmap = old_l2_bitmap;
1902 QCow2ClusterType cluster_type =
1903 qcow2_get_cluster_type(bs, old_l2_entry);
1906 * If full_discard is true, the cluster should not read back as zeroes,
1907 * but rather fall through to the backing file.
1909 * If full_discard is false, make sure that a discarded area reads back
1910 * as zeroes for v3 images (we cannot do it for v2 without actually
1911 * writing a zero-filled buffer). We can skip the operation if the
1912 * cluster is already marked as zero, or if it's unallocated and we
1913 * don't have a backing file.
1915 * TODO We might want to use bdrv_block_status(bs) here, but we're
1916 * holding s->lock, so that doesn't work today.
1918 if (full_discard) {
1919 new_l2_entry = new_l2_bitmap = 0;
1920 } else if (bs->backing || qcow2_cluster_is_allocated(cluster_type)) {
1921 if (has_subclusters(s)) {
1922 new_l2_entry = 0;
1923 new_l2_bitmap = QCOW_L2_BITMAP_ALL_ZEROES;
1924 } else {
1925 new_l2_entry = s->qcow_version >= 3 ? QCOW_OFLAG_ZERO : 0;
1929 if (old_l2_entry == new_l2_entry && old_l2_bitmap == new_l2_bitmap) {
1930 continue;
1933 /* First remove L2 entries */
1934 qcow2_cache_entry_mark_dirty(s->l2_table_cache, l2_slice);
1935 set_l2_entry(s, l2_slice, l2_index + i, new_l2_entry);
1936 if (has_subclusters(s)) {
1937 set_l2_bitmap(s, l2_slice, l2_index + i, new_l2_bitmap);
1939 /* Then decrease the refcount */
1940 qcow2_free_any_cluster(bs, old_l2_entry, type);
1943 qcow2_cache_put(s->l2_table_cache, (void **) &l2_slice);
1945 return nb_clusters;
1948 int qcow2_cluster_discard(BlockDriverState *bs, uint64_t offset,
1949 uint64_t bytes, enum qcow2_discard_type type,
1950 bool full_discard)
1952 BDRVQcow2State *s = bs->opaque;
1953 uint64_t end_offset = offset + bytes;
1954 uint64_t nb_clusters;
1955 int64_t cleared;
1956 int ret;
1958 /* Caller must pass aligned values, except at image end */
1959 assert(QEMU_IS_ALIGNED(offset, s->cluster_size));
1960 assert(QEMU_IS_ALIGNED(end_offset, s->cluster_size) ||
1961 end_offset == bs->total_sectors << BDRV_SECTOR_BITS);
1963 nb_clusters = size_to_clusters(s, bytes);
1965 s->cache_discards = true;
1967 /* Each L2 slice is handled by its own loop iteration */
1968 while (nb_clusters > 0) {
1969 cleared = discard_in_l2_slice(bs, offset, nb_clusters, type,
1970 full_discard);
1971 if (cleared < 0) {
1972 ret = cleared;
1973 goto fail;
1976 nb_clusters -= cleared;
1977 offset += (cleared * s->cluster_size);
1980 ret = 0;
1981 fail:
1982 s->cache_discards = false;
1983 qcow2_process_discards(bs, ret);
1985 return ret;
1989 * This zeroes as many clusters of nb_clusters as possible at once (i.e.
1990 * all clusters in the same L2 slice) and returns the number of zeroed
1991 * clusters.
1993 static int zero_in_l2_slice(BlockDriverState *bs, uint64_t offset,
1994 uint64_t nb_clusters, int flags)
1996 BDRVQcow2State *s = bs->opaque;
1997 uint64_t *l2_slice;
1998 int l2_index;
1999 int ret;
2000 int i;
2002 ret = get_cluster_table(bs, offset, &l2_slice, &l2_index);
2003 if (ret < 0) {
2004 return ret;
2007 /* Limit nb_clusters to one L2 slice */
2008 nb_clusters = MIN(nb_clusters, s->l2_slice_size - l2_index);
2009 assert(nb_clusters <= INT_MAX);
2011 for (i = 0; i < nb_clusters; i++) {
2012 uint64_t old_l2_entry = get_l2_entry(s, l2_slice, l2_index + i);
2013 uint64_t old_l2_bitmap = get_l2_bitmap(s, l2_slice, l2_index + i);
2014 QCow2ClusterType type = qcow2_get_cluster_type(bs, old_l2_entry);
2015 bool unmap = (type == QCOW2_CLUSTER_COMPRESSED) ||
2016 ((flags & BDRV_REQ_MAY_UNMAP) && qcow2_cluster_is_allocated(type));
2017 uint64_t new_l2_entry = unmap ? 0 : old_l2_entry;
2018 uint64_t new_l2_bitmap = old_l2_bitmap;
2020 if (has_subclusters(s)) {
2021 new_l2_bitmap = QCOW_L2_BITMAP_ALL_ZEROES;
2022 } else {
2023 new_l2_entry |= QCOW_OFLAG_ZERO;
2026 if (old_l2_entry == new_l2_entry && old_l2_bitmap == new_l2_bitmap) {
2027 continue;
2030 /* First update L2 entries */
2031 qcow2_cache_entry_mark_dirty(s->l2_table_cache, l2_slice);
2032 set_l2_entry(s, l2_slice, l2_index + i, new_l2_entry);
2033 if (has_subclusters(s)) {
2034 set_l2_bitmap(s, l2_slice, l2_index + i, new_l2_bitmap);
2037 /* Then decrease the refcount */
2038 if (unmap) {
2039 qcow2_free_any_cluster(bs, old_l2_entry, QCOW2_DISCARD_REQUEST);
2043 qcow2_cache_put(s->l2_table_cache, (void **) &l2_slice);
2045 return nb_clusters;
2048 static int zero_l2_subclusters(BlockDriverState *bs, uint64_t offset,
2049 unsigned nb_subclusters)
2051 BDRVQcow2State *s = bs->opaque;
2052 uint64_t *l2_slice;
2053 uint64_t old_l2_bitmap, l2_bitmap;
2054 int l2_index, ret, sc = offset_to_sc_index(s, offset);
2056 /* For full clusters use zero_in_l2_slice() instead */
2057 assert(nb_subclusters > 0 && nb_subclusters < s->subclusters_per_cluster);
2058 assert(sc + nb_subclusters <= s->subclusters_per_cluster);
2059 assert(offset_into_subcluster(s, offset) == 0);
2061 ret = get_cluster_table(bs, offset, &l2_slice, &l2_index);
2062 if (ret < 0) {
2063 return ret;
2066 switch (qcow2_get_cluster_type(bs, get_l2_entry(s, l2_slice, l2_index))) {
2067 case QCOW2_CLUSTER_COMPRESSED:
2068 ret = -ENOTSUP; /* We cannot partially zeroize compressed clusters */
2069 goto out;
2070 case QCOW2_CLUSTER_NORMAL:
2071 case QCOW2_CLUSTER_UNALLOCATED:
2072 break;
2073 default:
2074 g_assert_not_reached();
2077 old_l2_bitmap = l2_bitmap = get_l2_bitmap(s, l2_slice, l2_index);
2079 l2_bitmap |= QCOW_OFLAG_SUB_ZERO_RANGE(sc, sc + nb_subclusters);
2080 l2_bitmap &= ~QCOW_OFLAG_SUB_ALLOC_RANGE(sc, sc + nb_subclusters);
2082 if (old_l2_bitmap != l2_bitmap) {
2083 set_l2_bitmap(s, l2_slice, l2_index, l2_bitmap);
2084 qcow2_cache_entry_mark_dirty(s->l2_table_cache, l2_slice);
2087 ret = 0;
2088 out:
2089 qcow2_cache_put(s->l2_table_cache, (void **) &l2_slice);
2091 return ret;
2094 int qcow2_subcluster_zeroize(BlockDriverState *bs, uint64_t offset,
2095 uint64_t bytes, int flags)
2097 BDRVQcow2State *s = bs->opaque;
2098 uint64_t end_offset = offset + bytes;
2099 uint64_t nb_clusters;
2100 unsigned head, tail;
2101 int64_t cleared;
2102 int ret;
2104 /* If we have to stay in sync with an external data file, zero out
2105 * s->data_file first. */
2106 if (data_file_is_raw(bs)) {
2107 assert(has_data_file(bs));
2108 ret = bdrv_co_pwrite_zeroes(s->data_file, offset, bytes, flags);
2109 if (ret < 0) {
2110 return ret;
2114 /* Caller must pass aligned values, except at image end */
2115 assert(offset_into_subcluster(s, offset) == 0);
2116 assert(offset_into_subcluster(s, end_offset) == 0 ||
2117 end_offset >= bs->total_sectors << BDRV_SECTOR_BITS);
2120 * The zero flag is only supported by version 3 and newer. However, if we
2121 * have no backing file, we can resort to discard in version 2.
2123 if (s->qcow_version < 3) {
2124 if (!bs->backing) {
2125 return qcow2_cluster_discard(bs, offset, bytes,
2126 QCOW2_DISCARD_REQUEST, false);
2128 return -ENOTSUP;
2131 head = MIN(end_offset, ROUND_UP(offset, s->cluster_size)) - offset;
2132 offset += head;
2134 tail = (end_offset >= bs->total_sectors << BDRV_SECTOR_BITS) ? 0 :
2135 end_offset - MAX(offset, start_of_cluster(s, end_offset));
2136 end_offset -= tail;
2138 s->cache_discards = true;
2140 if (head) {
2141 ret = zero_l2_subclusters(bs, offset - head,
2142 size_to_subclusters(s, head));
2143 if (ret < 0) {
2144 goto fail;
2148 /* Each L2 slice is handled by its own loop iteration */
2149 nb_clusters = size_to_clusters(s, end_offset - offset);
2151 while (nb_clusters > 0) {
2152 cleared = zero_in_l2_slice(bs, offset, nb_clusters, flags);
2153 if (cleared < 0) {
2154 ret = cleared;
2155 goto fail;
2158 nb_clusters -= cleared;
2159 offset += (cleared * s->cluster_size);
2162 if (tail) {
2163 ret = zero_l2_subclusters(bs, end_offset, size_to_subclusters(s, tail));
2164 if (ret < 0) {
2165 goto fail;
2169 ret = 0;
2170 fail:
2171 s->cache_discards = false;
2172 qcow2_process_discards(bs, ret);
2174 return ret;
2178 * Expands all zero clusters in a specific L1 table (or deallocates them, for
2179 * non-backed non-pre-allocated zero clusters).
2181 * l1_entries and *visited_l1_entries are used to keep track of progress for
2182 * status_cb(). l1_entries contains the total number of L1 entries and
2183 * *visited_l1_entries counts all visited L1 entries.
2185 static int expand_zero_clusters_in_l1(BlockDriverState *bs, uint64_t *l1_table,
2186 int l1_size, int64_t *visited_l1_entries,
2187 int64_t l1_entries,
2188 BlockDriverAmendStatusCB *status_cb,
2189 void *cb_opaque)
2191 BDRVQcow2State *s = bs->opaque;
2192 bool is_active_l1 = (l1_table == s->l1_table);
2193 uint64_t *l2_slice = NULL;
2194 unsigned slice, slice_size2, n_slices;
2195 int ret;
2196 int i, j;
2198 /* qcow2_downgrade() is not allowed in images with subclusters */
2199 assert(!has_subclusters(s));
2201 slice_size2 = s->l2_slice_size * l2_entry_size(s);
2202 n_slices = s->cluster_size / slice_size2;
2204 if (!is_active_l1) {
2205 /* inactive L2 tables require a buffer to be stored in when loading
2206 * them from disk */
2207 l2_slice = qemu_try_blockalign(bs->file->bs, slice_size2);
2208 if (l2_slice == NULL) {
2209 return -ENOMEM;
2213 for (i = 0; i < l1_size; i++) {
2214 uint64_t l2_offset = l1_table[i] & L1E_OFFSET_MASK;
2215 uint64_t l2_refcount;
2217 if (!l2_offset) {
2218 /* unallocated */
2219 (*visited_l1_entries)++;
2220 if (status_cb) {
2221 status_cb(bs, *visited_l1_entries, l1_entries, cb_opaque);
2223 continue;
2226 if (offset_into_cluster(s, l2_offset)) {
2227 qcow2_signal_corruption(bs, true, -1, -1, "L2 table offset %#"
2228 PRIx64 " unaligned (L1 index: %#x)",
2229 l2_offset, i);
2230 ret = -EIO;
2231 goto fail;
2234 ret = qcow2_get_refcount(bs, l2_offset >> s->cluster_bits,
2235 &l2_refcount);
2236 if (ret < 0) {
2237 goto fail;
2240 for (slice = 0; slice < n_slices; slice++) {
2241 uint64_t slice_offset = l2_offset + slice * slice_size2;
2242 bool l2_dirty = false;
2243 if (is_active_l1) {
2244 /* get active L2 tables from cache */
2245 ret = qcow2_cache_get(bs, s->l2_table_cache, slice_offset,
2246 (void **)&l2_slice);
2247 } else {
2248 /* load inactive L2 tables from disk */
2249 ret = bdrv_pread(bs->file, slice_offset, l2_slice, slice_size2);
2251 if (ret < 0) {
2252 goto fail;
2255 for (j = 0; j < s->l2_slice_size; j++) {
2256 uint64_t l2_entry = get_l2_entry(s, l2_slice, j);
2257 int64_t offset = l2_entry & L2E_OFFSET_MASK;
2258 QCow2ClusterType cluster_type =
2259 qcow2_get_cluster_type(bs, l2_entry);
2261 if (cluster_type != QCOW2_CLUSTER_ZERO_PLAIN &&
2262 cluster_type != QCOW2_CLUSTER_ZERO_ALLOC) {
2263 continue;
2266 if (cluster_type == QCOW2_CLUSTER_ZERO_PLAIN) {
2267 if (!bs->backing) {
2269 * not backed; therefore we can simply deallocate the
2270 * cluster. No need to call set_l2_bitmap(), this
2271 * function doesn't support images with subclusters.
2273 set_l2_entry(s, l2_slice, j, 0);
2274 l2_dirty = true;
2275 continue;
2278 offset = qcow2_alloc_clusters(bs, s->cluster_size);
2279 if (offset < 0) {
2280 ret = offset;
2281 goto fail;
2284 /* The offset must fit in the offset field */
2285 assert((offset & L2E_OFFSET_MASK) == offset);
2287 if (l2_refcount > 1) {
2288 /* For shared L2 tables, set the refcount accordingly
2289 * (it is already 1 and needs to be l2_refcount) */
2290 ret = qcow2_update_cluster_refcount(
2291 bs, offset >> s->cluster_bits,
2292 refcount_diff(1, l2_refcount), false,
2293 QCOW2_DISCARD_OTHER);
2294 if (ret < 0) {
2295 qcow2_free_clusters(bs, offset, s->cluster_size,
2296 QCOW2_DISCARD_OTHER);
2297 goto fail;
2302 if (offset_into_cluster(s, offset)) {
2303 int l2_index = slice * s->l2_slice_size + j;
2304 qcow2_signal_corruption(
2305 bs, true, -1, -1,
2306 "Cluster allocation offset "
2307 "%#" PRIx64 " unaligned (L2 offset: %#"
2308 PRIx64 ", L2 index: %#x)", offset,
2309 l2_offset, l2_index);
2310 if (cluster_type == QCOW2_CLUSTER_ZERO_PLAIN) {
2311 qcow2_free_clusters(bs, offset, s->cluster_size,
2312 QCOW2_DISCARD_ALWAYS);
2314 ret = -EIO;
2315 goto fail;
2318 ret = qcow2_pre_write_overlap_check(bs, 0, offset,
2319 s->cluster_size, true);
2320 if (ret < 0) {
2321 if (cluster_type == QCOW2_CLUSTER_ZERO_PLAIN) {
2322 qcow2_free_clusters(bs, offset, s->cluster_size,
2323 QCOW2_DISCARD_ALWAYS);
2325 goto fail;
2328 ret = bdrv_pwrite_zeroes(s->data_file, offset,
2329 s->cluster_size, 0);
2330 if (ret < 0) {
2331 if (cluster_type == QCOW2_CLUSTER_ZERO_PLAIN) {
2332 qcow2_free_clusters(bs, offset, s->cluster_size,
2333 QCOW2_DISCARD_ALWAYS);
2335 goto fail;
2338 if (l2_refcount == 1) {
2339 set_l2_entry(s, l2_slice, j, offset | QCOW_OFLAG_COPIED);
2340 } else {
2341 set_l2_entry(s, l2_slice, j, offset);
2344 * No need to call set_l2_bitmap() after set_l2_entry() because
2345 * this function doesn't support images with subclusters.
2347 l2_dirty = true;
2350 if (is_active_l1) {
2351 if (l2_dirty) {
2352 qcow2_cache_entry_mark_dirty(s->l2_table_cache, l2_slice);
2353 qcow2_cache_depends_on_flush(s->l2_table_cache);
2355 qcow2_cache_put(s->l2_table_cache, (void **) &l2_slice);
2356 } else {
2357 if (l2_dirty) {
2358 ret = qcow2_pre_write_overlap_check(
2359 bs, QCOW2_OL_INACTIVE_L2 | QCOW2_OL_ACTIVE_L2,
2360 slice_offset, slice_size2, false);
2361 if (ret < 0) {
2362 goto fail;
2365 ret = bdrv_pwrite(bs->file, slice_offset,
2366 l2_slice, slice_size2);
2367 if (ret < 0) {
2368 goto fail;
2374 (*visited_l1_entries)++;
2375 if (status_cb) {
2376 status_cb(bs, *visited_l1_entries, l1_entries, cb_opaque);
2380 ret = 0;
2382 fail:
2383 if (l2_slice) {
2384 if (!is_active_l1) {
2385 qemu_vfree(l2_slice);
2386 } else {
2387 qcow2_cache_put(s->l2_table_cache, (void **) &l2_slice);
2390 return ret;
2394 * For backed images, expands all zero clusters on the image. For non-backed
2395 * images, deallocates all non-pre-allocated zero clusters (and claims the
2396 * allocation for pre-allocated ones). This is important for downgrading to a
2397 * qcow2 version which doesn't yet support metadata zero clusters.
2399 int qcow2_expand_zero_clusters(BlockDriverState *bs,
2400 BlockDriverAmendStatusCB *status_cb,
2401 void *cb_opaque)
2403 BDRVQcow2State *s = bs->opaque;
2404 uint64_t *l1_table = NULL;
2405 int64_t l1_entries = 0, visited_l1_entries = 0;
2406 int ret;
2407 int i, j;
2409 if (status_cb) {
2410 l1_entries = s->l1_size;
2411 for (i = 0; i < s->nb_snapshots; i++) {
2412 l1_entries += s->snapshots[i].l1_size;
2416 ret = expand_zero_clusters_in_l1(bs, s->l1_table, s->l1_size,
2417 &visited_l1_entries, l1_entries,
2418 status_cb, cb_opaque);
2419 if (ret < 0) {
2420 goto fail;
2423 /* Inactive L1 tables may point to active L2 tables - therefore it is
2424 * necessary to flush the L2 table cache before trying to access the L2
2425 * tables pointed to by inactive L1 entries (else we might try to expand
2426 * zero clusters that have already been expanded); furthermore, it is also
2427 * necessary to empty the L2 table cache, since it may contain tables which
2428 * are now going to be modified directly on disk, bypassing the cache.
2429 * qcow2_cache_empty() does both for us. */
2430 ret = qcow2_cache_empty(bs, s->l2_table_cache);
2431 if (ret < 0) {
2432 goto fail;
2435 for (i = 0; i < s->nb_snapshots; i++) {
2436 int l1_size2;
2437 uint64_t *new_l1_table;
2438 Error *local_err = NULL;
2440 ret = qcow2_validate_table(bs, s->snapshots[i].l1_table_offset,
2441 s->snapshots[i].l1_size, L1E_SIZE,
2442 QCOW_MAX_L1_SIZE, "Snapshot L1 table",
2443 &local_err);
2444 if (ret < 0) {
2445 error_report_err(local_err);
2446 goto fail;
2449 l1_size2 = s->snapshots[i].l1_size * L1E_SIZE;
2450 new_l1_table = g_try_realloc(l1_table, l1_size2);
2452 if (!new_l1_table) {
2453 ret = -ENOMEM;
2454 goto fail;
2457 l1_table = new_l1_table;
2459 ret = bdrv_pread(bs->file, s->snapshots[i].l1_table_offset,
2460 l1_table, l1_size2);
2461 if (ret < 0) {
2462 goto fail;
2465 for (j = 0; j < s->snapshots[i].l1_size; j++) {
2466 be64_to_cpus(&l1_table[j]);
2469 ret = expand_zero_clusters_in_l1(bs, l1_table, s->snapshots[i].l1_size,
2470 &visited_l1_entries, l1_entries,
2471 status_cb, cb_opaque);
2472 if (ret < 0) {
2473 goto fail;
2477 ret = 0;
2479 fail:
2480 g_free(l1_table);
2481 return ret;
2484 void qcow2_parse_compressed_l2_entry(BlockDriverState *bs, uint64_t l2_entry,
2485 uint64_t *coffset, int *csize)
2487 BDRVQcow2State *s = bs->opaque;
2488 int nb_csectors;
2490 assert(qcow2_get_cluster_type(bs, l2_entry) == QCOW2_CLUSTER_COMPRESSED);
2492 *coffset = l2_entry & s->cluster_offset_mask;
2494 nb_csectors = ((l2_entry >> s->csize_shift) & s->csize_mask) + 1;
2495 *csize = nb_csectors * QCOW2_COMPRESSED_SECTOR_SIZE -
2496 (*coffset & (QCOW2_COMPRESSED_SECTOR_SIZE - 1));