qcow2: Free allocated L2 cluster on error
[qemu.git] / block / qcow2-cluster.c
blob0fd26bb4ccfd3f4666db669848fe7121f59417c5
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 <zlib.h>
27 #include "qemu-common.h"
28 #include "block/block_int.h"
29 #include "block/qcow2.h"
30 #include "trace.h"
32 int qcow2_grow_l1_table(BlockDriverState *bs, uint64_t min_size,
33 bool exact_size)
35 BDRVQcowState *s = bs->opaque;
36 int new_l1_size2, ret, i;
37 uint64_t *new_l1_table;
38 int64_t old_l1_table_offset, old_l1_size;
39 int64_t new_l1_table_offset, new_l1_size;
40 uint8_t data[12];
42 if (min_size <= s->l1_size)
43 return 0;
45 if (exact_size) {
46 new_l1_size = min_size;
47 } else {
48 /* Bump size up to reduce the number of times we have to grow */
49 new_l1_size = s->l1_size;
50 if (new_l1_size == 0) {
51 new_l1_size = 1;
53 while (min_size > new_l1_size) {
54 new_l1_size = (new_l1_size * 3 + 1) / 2;
58 if (new_l1_size > INT_MAX) {
59 return -EFBIG;
62 #ifdef DEBUG_ALLOC2
63 fprintf(stderr, "grow l1_table from %d to %" PRId64 "\n",
64 s->l1_size, new_l1_size);
65 #endif
67 new_l1_size2 = sizeof(uint64_t) * new_l1_size;
68 new_l1_table = g_malloc0(align_offset(new_l1_size2, 512));
69 memcpy(new_l1_table, s->l1_table, s->l1_size * sizeof(uint64_t));
71 /* write new table (align to cluster) */
72 BLKDBG_EVENT(bs->file, BLKDBG_L1_GROW_ALLOC_TABLE);
73 new_l1_table_offset = qcow2_alloc_clusters(bs, new_l1_size2);
74 if (new_l1_table_offset < 0) {
75 g_free(new_l1_table);
76 return new_l1_table_offset;
79 ret = qcow2_cache_flush(bs, s->refcount_block_cache);
80 if (ret < 0) {
81 goto fail;
84 /* the L1 position has not yet been updated, so these clusters must
85 * indeed be completely free */
86 ret = qcow2_pre_write_overlap_check(bs, QCOW2_OL_DEFAULT,
87 new_l1_table_offset, new_l1_size2);
88 if (ret < 0) {
89 goto fail;
92 BLKDBG_EVENT(bs->file, BLKDBG_L1_GROW_WRITE_TABLE);
93 for(i = 0; i < s->l1_size; i++)
94 new_l1_table[i] = cpu_to_be64(new_l1_table[i]);
95 ret = bdrv_pwrite_sync(bs->file, new_l1_table_offset, new_l1_table, new_l1_size2);
96 if (ret < 0)
97 goto fail;
98 for(i = 0; i < s->l1_size; i++)
99 new_l1_table[i] = be64_to_cpu(new_l1_table[i]);
101 /* set new table */
102 BLKDBG_EVENT(bs->file, BLKDBG_L1_GROW_ACTIVATE_TABLE);
103 cpu_to_be32w((uint32_t*)data, new_l1_size);
104 cpu_to_be64wu((uint64_t*)(data + 4), new_l1_table_offset);
105 ret = bdrv_pwrite_sync(bs->file, offsetof(QCowHeader, l1_size), data,sizeof(data));
106 if (ret < 0) {
107 goto fail;
109 g_free(s->l1_table);
110 old_l1_table_offset = s->l1_table_offset;
111 s->l1_table_offset = new_l1_table_offset;
112 s->l1_table = new_l1_table;
113 old_l1_size = s->l1_size;
114 s->l1_size = new_l1_size;
115 qcow2_free_clusters(bs, old_l1_table_offset, old_l1_size * sizeof(uint64_t),
116 QCOW2_DISCARD_OTHER);
117 return 0;
118 fail:
119 g_free(new_l1_table);
120 qcow2_free_clusters(bs, new_l1_table_offset, new_l1_size2,
121 QCOW2_DISCARD_OTHER);
122 return ret;
126 * l2_load
128 * Loads a L2 table into memory. If the table is in the cache, the cache
129 * is used; otherwise the L2 table is loaded from the image file.
131 * Returns a pointer to the L2 table on success, or NULL if the read from
132 * the image file failed.
135 static int l2_load(BlockDriverState *bs, uint64_t l2_offset,
136 uint64_t **l2_table)
138 BDRVQcowState *s = bs->opaque;
139 int ret;
141 ret = qcow2_cache_get(bs, s->l2_table_cache, l2_offset, (void**) l2_table);
143 return ret;
147 * Writes one sector of the L1 table to the disk (can't update single entries
148 * and we really don't want bdrv_pread to perform a read-modify-write)
150 #define L1_ENTRIES_PER_SECTOR (512 / 8)
151 int qcow2_write_l1_entry(BlockDriverState *bs, int l1_index)
153 BDRVQcowState *s = bs->opaque;
154 uint64_t buf[L1_ENTRIES_PER_SECTOR];
155 int l1_start_index;
156 int i, ret;
158 l1_start_index = l1_index & ~(L1_ENTRIES_PER_SECTOR - 1);
159 for (i = 0; i < L1_ENTRIES_PER_SECTOR; i++) {
160 buf[i] = cpu_to_be64(s->l1_table[l1_start_index + i]);
163 ret = qcow2_pre_write_overlap_check(bs,
164 QCOW2_OL_DEFAULT & ~QCOW2_OL_ACTIVE_L1,
165 s->l1_table_offset + 8 * l1_start_index, sizeof(buf));
166 if (ret < 0) {
167 return ret;
170 BLKDBG_EVENT(bs->file, BLKDBG_L1_UPDATE);
171 ret = bdrv_pwrite_sync(bs->file, s->l1_table_offset + 8 * l1_start_index,
172 buf, sizeof(buf));
173 if (ret < 0) {
174 return ret;
177 return 0;
181 * l2_allocate
183 * Allocate a new l2 entry in the file. If l1_index points to an already
184 * used entry in the L2 table (i.e. we are doing a copy on write for the L2
185 * table) copy the contents of the old L2 table into the newly allocated one.
186 * Otherwise the new table is initialized with zeros.
190 static int l2_allocate(BlockDriverState *bs, int l1_index, uint64_t **table)
192 BDRVQcowState *s = bs->opaque;
193 uint64_t old_l2_offset;
194 uint64_t *l2_table = NULL;
195 int64_t l2_offset;
196 int ret;
198 old_l2_offset = s->l1_table[l1_index];
200 trace_qcow2_l2_allocate(bs, l1_index);
202 /* allocate a new l2 entry */
204 l2_offset = qcow2_alloc_clusters(bs, s->l2_size * sizeof(uint64_t));
205 if (l2_offset < 0) {
206 ret = l2_offset;
207 goto fail;
210 ret = qcow2_cache_flush(bs, s->refcount_block_cache);
211 if (ret < 0) {
212 goto fail;
215 /* allocate a new entry in the l2 cache */
217 trace_qcow2_l2_allocate_get_empty(bs, l1_index);
218 ret = qcow2_cache_get_empty(bs, s->l2_table_cache, l2_offset, (void**) table);
219 if (ret < 0) {
220 goto fail;
223 l2_table = *table;
225 if ((old_l2_offset & L1E_OFFSET_MASK) == 0) {
226 /* if there was no old l2 table, clear the new table */
227 memset(l2_table, 0, s->l2_size * sizeof(uint64_t));
228 } else {
229 uint64_t* old_table;
231 /* if there was an old l2 table, read it from the disk */
232 BLKDBG_EVENT(bs->file, BLKDBG_L2_ALLOC_COW_READ);
233 ret = qcow2_cache_get(bs, s->l2_table_cache,
234 old_l2_offset & L1E_OFFSET_MASK,
235 (void**) &old_table);
236 if (ret < 0) {
237 goto fail;
240 memcpy(l2_table, old_table, s->cluster_size);
242 ret = qcow2_cache_put(bs, s->l2_table_cache, (void**) &old_table);
243 if (ret < 0) {
244 goto fail;
248 /* write the l2 table to the file */
249 BLKDBG_EVENT(bs->file, BLKDBG_L2_ALLOC_WRITE);
251 trace_qcow2_l2_allocate_write_l2(bs, l1_index);
252 qcow2_cache_entry_mark_dirty(s->l2_table_cache, l2_table);
253 ret = qcow2_cache_flush(bs, s->l2_table_cache);
254 if (ret < 0) {
255 goto fail;
258 /* update the L1 entry */
259 trace_qcow2_l2_allocate_write_l1(bs, l1_index);
260 s->l1_table[l1_index] = l2_offset | QCOW_OFLAG_COPIED;
261 ret = qcow2_write_l1_entry(bs, l1_index);
262 if (ret < 0) {
263 goto fail;
266 *table = l2_table;
267 trace_qcow2_l2_allocate_done(bs, l1_index, 0);
268 return 0;
270 fail:
271 trace_qcow2_l2_allocate_done(bs, l1_index, ret);
272 if (l2_table != NULL) {
273 qcow2_cache_put(bs, s->l2_table_cache, (void**) table);
275 s->l1_table[l1_index] = old_l2_offset;
276 if (l2_offset > 0) {
277 qcow2_free_clusters(bs, l2_offset, s->l2_size * sizeof(uint64_t),
278 QCOW2_DISCARD_ALWAYS);
280 return ret;
284 * Checks how many clusters in a given L2 table are contiguous in the image
285 * file. As soon as one of the flags in the bitmask stop_flags changes compared
286 * to the first cluster, the search is stopped and the cluster is not counted
287 * as contiguous. (This allows it, for example, to stop at the first compressed
288 * cluster which may require a different handling)
290 static int count_contiguous_clusters(uint64_t nb_clusters, int cluster_size,
291 uint64_t *l2_table, uint64_t stop_flags)
293 int i;
294 uint64_t mask = stop_flags | L2E_OFFSET_MASK | QCOW2_CLUSTER_COMPRESSED;
295 uint64_t first_entry = be64_to_cpu(l2_table[0]);
296 uint64_t offset = first_entry & mask;
298 if (!offset)
299 return 0;
301 assert(qcow2_get_cluster_type(first_entry) != QCOW2_CLUSTER_COMPRESSED);
303 for (i = 0; i < nb_clusters; i++) {
304 uint64_t l2_entry = be64_to_cpu(l2_table[i]) & mask;
305 if (offset + (uint64_t) i * cluster_size != l2_entry) {
306 break;
310 return i;
313 static int count_contiguous_free_clusters(uint64_t nb_clusters, uint64_t *l2_table)
315 int i;
317 for (i = 0; i < nb_clusters; i++) {
318 int type = qcow2_get_cluster_type(be64_to_cpu(l2_table[i]));
320 if (type != QCOW2_CLUSTER_UNALLOCATED) {
321 break;
325 return i;
328 /* The crypt function is compatible with the linux cryptoloop
329 algorithm for < 4 GB images. NOTE: out_buf == in_buf is
330 supported */
331 void qcow2_encrypt_sectors(BDRVQcowState *s, int64_t sector_num,
332 uint8_t *out_buf, const uint8_t *in_buf,
333 int nb_sectors, int enc,
334 const AES_KEY *key)
336 union {
337 uint64_t ll[2];
338 uint8_t b[16];
339 } ivec;
340 int i;
342 for(i = 0; i < nb_sectors; i++) {
343 ivec.ll[0] = cpu_to_le64(sector_num);
344 ivec.ll[1] = 0;
345 AES_cbc_encrypt(in_buf, out_buf, 512, key,
346 ivec.b, enc);
347 sector_num++;
348 in_buf += 512;
349 out_buf += 512;
353 static int coroutine_fn copy_sectors(BlockDriverState *bs,
354 uint64_t start_sect,
355 uint64_t cluster_offset,
356 int n_start, int n_end)
358 BDRVQcowState *s = bs->opaque;
359 QEMUIOVector qiov;
360 struct iovec iov;
361 int n, ret;
364 * If this is the last cluster and it is only partially used, we must only
365 * copy until the end of the image, or bdrv_check_request will fail for the
366 * bdrv_read/write calls below.
368 if (start_sect + n_end > bs->total_sectors) {
369 n_end = bs->total_sectors - start_sect;
372 n = n_end - n_start;
373 if (n <= 0) {
374 return 0;
377 iov.iov_len = n * BDRV_SECTOR_SIZE;
378 iov.iov_base = qemu_blockalign(bs, iov.iov_len);
380 qemu_iovec_init_external(&qiov, &iov, 1);
382 BLKDBG_EVENT(bs->file, BLKDBG_COW_READ);
384 /* Call .bdrv_co_readv() directly instead of using the public block-layer
385 * interface. This avoids double I/O throttling and request tracking,
386 * which can lead to deadlock when block layer copy-on-read is enabled.
388 ret = bs->drv->bdrv_co_readv(bs, start_sect + n_start, n, &qiov);
389 if (ret < 0) {
390 goto out;
393 if (s->crypt_method) {
394 qcow2_encrypt_sectors(s, start_sect + n_start,
395 iov.iov_base, iov.iov_base, n, 1,
396 &s->aes_encrypt_key);
399 ret = qcow2_pre_write_overlap_check(bs, QCOW2_OL_DEFAULT,
400 cluster_offset + n_start * BDRV_SECTOR_SIZE, n * BDRV_SECTOR_SIZE);
401 if (ret < 0) {
402 goto out;
405 BLKDBG_EVENT(bs->file, BLKDBG_COW_WRITE);
406 ret = bdrv_co_writev(bs->file, (cluster_offset >> 9) + n_start, n, &qiov);
407 if (ret < 0) {
408 goto out;
411 ret = 0;
412 out:
413 qemu_vfree(iov.iov_base);
414 return ret;
419 * get_cluster_offset
421 * For a given offset of the disk image, find the cluster offset in
422 * qcow2 file. The offset is stored in *cluster_offset.
424 * on entry, *num is the number of contiguous sectors we'd like to
425 * access following offset.
427 * on exit, *num is the number of contiguous sectors we can read.
429 * Returns the cluster type (QCOW2_CLUSTER_*) on success, -errno in error
430 * cases.
432 int qcow2_get_cluster_offset(BlockDriverState *bs, uint64_t offset,
433 int *num, uint64_t *cluster_offset)
435 BDRVQcowState *s = bs->opaque;
436 unsigned int l2_index;
437 uint64_t l1_index, l2_offset, *l2_table;
438 int l1_bits, c;
439 unsigned int index_in_cluster, nb_clusters;
440 uint64_t nb_available, nb_needed;
441 int ret;
443 index_in_cluster = (offset >> 9) & (s->cluster_sectors - 1);
444 nb_needed = *num + index_in_cluster;
446 l1_bits = s->l2_bits + s->cluster_bits;
448 /* compute how many bytes there are between the offset and
449 * the end of the l1 entry
452 nb_available = (1ULL << l1_bits) - (offset & ((1ULL << l1_bits) - 1));
454 /* compute the number of available sectors */
456 nb_available = (nb_available >> 9) + index_in_cluster;
458 if (nb_needed > nb_available) {
459 nb_needed = nb_available;
462 *cluster_offset = 0;
464 /* seek the the l2 offset in the l1 table */
466 l1_index = offset >> l1_bits;
467 if (l1_index >= s->l1_size) {
468 ret = QCOW2_CLUSTER_UNALLOCATED;
469 goto out;
472 l2_offset = s->l1_table[l1_index] & L1E_OFFSET_MASK;
473 if (!l2_offset) {
474 ret = QCOW2_CLUSTER_UNALLOCATED;
475 goto out;
478 /* load the l2 table in memory */
480 ret = l2_load(bs, l2_offset, &l2_table);
481 if (ret < 0) {
482 return ret;
485 /* find the cluster offset for the given disk offset */
487 l2_index = (offset >> s->cluster_bits) & (s->l2_size - 1);
488 *cluster_offset = be64_to_cpu(l2_table[l2_index]);
489 nb_clusters = size_to_clusters(s, nb_needed << 9);
491 ret = qcow2_get_cluster_type(*cluster_offset);
492 switch (ret) {
493 case QCOW2_CLUSTER_COMPRESSED:
494 /* Compressed clusters can only be processed one by one */
495 c = 1;
496 *cluster_offset &= L2E_COMPRESSED_OFFSET_SIZE_MASK;
497 break;
498 case QCOW2_CLUSTER_ZERO:
499 if (s->qcow_version < 3) {
500 return -EIO;
502 c = count_contiguous_clusters(nb_clusters, s->cluster_size,
503 &l2_table[l2_index], QCOW_OFLAG_ZERO);
504 *cluster_offset = 0;
505 break;
506 case QCOW2_CLUSTER_UNALLOCATED:
507 /* how many empty clusters ? */
508 c = count_contiguous_free_clusters(nb_clusters, &l2_table[l2_index]);
509 *cluster_offset = 0;
510 break;
511 case QCOW2_CLUSTER_NORMAL:
512 /* how many allocated clusters ? */
513 c = count_contiguous_clusters(nb_clusters, s->cluster_size,
514 &l2_table[l2_index], QCOW_OFLAG_ZERO);
515 *cluster_offset &= L2E_OFFSET_MASK;
516 break;
517 default:
518 abort();
521 qcow2_cache_put(bs, s->l2_table_cache, (void**) &l2_table);
523 nb_available = (c * s->cluster_sectors);
525 out:
526 if (nb_available > nb_needed)
527 nb_available = nb_needed;
529 *num = nb_available - index_in_cluster;
531 return ret;
535 * get_cluster_table
537 * for a given disk offset, load (and allocate if needed)
538 * the l2 table.
540 * the l2 table offset in the qcow2 file and the cluster index
541 * in the l2 table are given to the caller.
543 * Returns 0 on success, -errno in failure case
545 static int get_cluster_table(BlockDriverState *bs, uint64_t offset,
546 uint64_t **new_l2_table,
547 int *new_l2_index)
549 BDRVQcowState *s = bs->opaque;
550 unsigned int l2_index;
551 uint64_t l1_index, l2_offset;
552 uint64_t *l2_table = NULL;
553 int ret;
555 /* seek the the l2 offset in the l1 table */
557 l1_index = offset >> (s->l2_bits + s->cluster_bits);
558 if (l1_index >= s->l1_size) {
559 ret = qcow2_grow_l1_table(bs, l1_index + 1, false);
560 if (ret < 0) {
561 return ret;
565 assert(l1_index < s->l1_size);
566 l2_offset = s->l1_table[l1_index] & L1E_OFFSET_MASK;
568 /* seek the l2 table of the given l2 offset */
570 if (s->l1_table[l1_index] & QCOW_OFLAG_COPIED) {
571 /* load the l2 table in memory */
572 ret = l2_load(bs, l2_offset, &l2_table);
573 if (ret < 0) {
574 return ret;
576 } else {
577 /* First allocate a new L2 table (and do COW if needed) */
578 ret = l2_allocate(bs, l1_index, &l2_table);
579 if (ret < 0) {
580 return ret;
583 /* Then decrease the refcount of the old table */
584 if (l2_offset) {
585 qcow2_free_clusters(bs, l2_offset, s->l2_size * sizeof(uint64_t),
586 QCOW2_DISCARD_OTHER);
590 /* find the cluster offset for the given disk offset */
592 l2_index = (offset >> s->cluster_bits) & (s->l2_size - 1);
594 *new_l2_table = l2_table;
595 *new_l2_index = l2_index;
597 return 0;
601 * alloc_compressed_cluster_offset
603 * For a given offset of the disk image, return cluster offset in
604 * qcow2 file.
606 * If the offset is not found, allocate a new compressed cluster.
608 * Return the cluster offset if successful,
609 * Return 0, otherwise.
613 uint64_t qcow2_alloc_compressed_cluster_offset(BlockDriverState *bs,
614 uint64_t offset,
615 int compressed_size)
617 BDRVQcowState *s = bs->opaque;
618 int l2_index, ret;
619 uint64_t *l2_table;
620 int64_t cluster_offset;
621 int nb_csectors;
623 ret = get_cluster_table(bs, offset, &l2_table, &l2_index);
624 if (ret < 0) {
625 return 0;
628 /* Compression can't overwrite anything. Fail if the cluster was already
629 * allocated. */
630 cluster_offset = be64_to_cpu(l2_table[l2_index]);
631 if (cluster_offset & L2E_OFFSET_MASK) {
632 qcow2_cache_put(bs, s->l2_table_cache, (void**) &l2_table);
633 return 0;
636 cluster_offset = qcow2_alloc_bytes(bs, compressed_size);
637 if (cluster_offset < 0) {
638 qcow2_cache_put(bs, s->l2_table_cache, (void**) &l2_table);
639 return 0;
642 nb_csectors = ((cluster_offset + compressed_size - 1) >> 9) -
643 (cluster_offset >> 9);
645 cluster_offset |= QCOW_OFLAG_COMPRESSED |
646 ((uint64_t)nb_csectors << s->csize_shift);
648 /* update L2 table */
650 /* compressed clusters never have the copied flag */
652 BLKDBG_EVENT(bs->file, BLKDBG_L2_UPDATE_COMPRESSED);
653 qcow2_cache_entry_mark_dirty(s->l2_table_cache, l2_table);
654 l2_table[l2_index] = cpu_to_be64(cluster_offset);
655 ret = qcow2_cache_put(bs, s->l2_table_cache, (void**) &l2_table);
656 if (ret < 0) {
657 return 0;
660 return cluster_offset;
663 static int perform_cow(BlockDriverState *bs, QCowL2Meta *m, Qcow2COWRegion *r)
665 BDRVQcowState *s = bs->opaque;
666 int ret;
668 if (r->nb_sectors == 0) {
669 return 0;
672 qemu_co_mutex_unlock(&s->lock);
673 ret = copy_sectors(bs, m->offset / BDRV_SECTOR_SIZE, m->alloc_offset,
674 r->offset / BDRV_SECTOR_SIZE,
675 r->offset / BDRV_SECTOR_SIZE + r->nb_sectors);
676 qemu_co_mutex_lock(&s->lock);
678 if (ret < 0) {
679 return ret;
683 * Before we update the L2 table to actually point to the new cluster, we
684 * need to be sure that the refcounts have been increased and COW was
685 * handled.
687 qcow2_cache_depends_on_flush(s->l2_table_cache);
689 return 0;
692 int qcow2_alloc_cluster_link_l2(BlockDriverState *bs, QCowL2Meta *m)
694 BDRVQcowState *s = bs->opaque;
695 int i, j = 0, l2_index, ret;
696 uint64_t *old_cluster, *l2_table;
697 uint64_t cluster_offset = m->alloc_offset;
699 trace_qcow2_cluster_link_l2(qemu_coroutine_self(), m->nb_clusters);
700 assert(m->nb_clusters > 0);
702 old_cluster = g_malloc(m->nb_clusters * sizeof(uint64_t));
704 /* copy content of unmodified sectors */
705 ret = perform_cow(bs, m, &m->cow_start);
706 if (ret < 0) {
707 goto err;
710 ret = perform_cow(bs, m, &m->cow_end);
711 if (ret < 0) {
712 goto err;
715 /* Update L2 table. */
716 if (s->use_lazy_refcounts) {
717 qcow2_mark_dirty(bs);
719 if (qcow2_need_accurate_refcounts(s)) {
720 qcow2_cache_set_dependency(bs, s->l2_table_cache,
721 s->refcount_block_cache);
724 ret = get_cluster_table(bs, m->offset, &l2_table, &l2_index);
725 if (ret < 0) {
726 goto err;
728 qcow2_cache_entry_mark_dirty(s->l2_table_cache, l2_table);
730 assert(l2_index + m->nb_clusters <= s->l2_size);
731 for (i = 0; i < m->nb_clusters; i++) {
732 /* if two concurrent writes happen to the same unallocated cluster
733 * each write allocates separate cluster and writes data concurrently.
734 * The first one to complete updates l2 table with pointer to its
735 * cluster the second one has to do RMW (which is done above by
736 * copy_sectors()), update l2 table with its cluster pointer and free
737 * old cluster. This is what this loop does */
738 if(l2_table[l2_index + i] != 0)
739 old_cluster[j++] = l2_table[l2_index + i];
741 l2_table[l2_index + i] = cpu_to_be64((cluster_offset +
742 (i << s->cluster_bits)) | QCOW_OFLAG_COPIED);
746 ret = qcow2_cache_put(bs, s->l2_table_cache, (void**) &l2_table);
747 if (ret < 0) {
748 goto err;
752 * If this was a COW, we need to decrease the refcount of the old cluster.
753 * Also flush bs->file to get the right order for L2 and refcount update.
755 * Don't discard clusters that reach a refcount of 0 (e.g. compressed
756 * clusters), the next write will reuse them anyway.
758 if (j != 0) {
759 for (i = 0; i < j; i++) {
760 qcow2_free_any_clusters(bs, be64_to_cpu(old_cluster[i]), 1,
761 QCOW2_DISCARD_NEVER);
765 ret = 0;
766 err:
767 g_free(old_cluster);
768 return ret;
772 * Returns the number of contiguous clusters that can be used for an allocating
773 * write, but require COW to be performed (this includes yet unallocated space,
774 * which must copy from the backing file)
776 static int count_cow_clusters(BDRVQcowState *s, int nb_clusters,
777 uint64_t *l2_table, int l2_index)
779 int i;
781 for (i = 0; i < nb_clusters; i++) {
782 uint64_t l2_entry = be64_to_cpu(l2_table[l2_index + i]);
783 int cluster_type = qcow2_get_cluster_type(l2_entry);
785 switch(cluster_type) {
786 case QCOW2_CLUSTER_NORMAL:
787 if (l2_entry & QCOW_OFLAG_COPIED) {
788 goto out;
790 break;
791 case QCOW2_CLUSTER_UNALLOCATED:
792 case QCOW2_CLUSTER_COMPRESSED:
793 case QCOW2_CLUSTER_ZERO:
794 break;
795 default:
796 abort();
800 out:
801 assert(i <= nb_clusters);
802 return i;
806 * Check if there already is an AIO write request in flight which allocates
807 * the same cluster. In this case we need to wait until the previous
808 * request has completed and updated the L2 table accordingly.
810 * Returns:
811 * 0 if there was no dependency. *cur_bytes indicates the number of
812 * bytes from guest_offset that can be read before the next
813 * dependency must be processed (or the request is complete)
815 * -EAGAIN if we had to wait for another request, previously gathered
816 * information on cluster allocation may be invalid now. The caller
817 * must start over anyway, so consider *cur_bytes undefined.
819 static int handle_dependencies(BlockDriverState *bs, uint64_t guest_offset,
820 uint64_t *cur_bytes, QCowL2Meta **m)
822 BDRVQcowState *s = bs->opaque;
823 QCowL2Meta *old_alloc;
824 uint64_t bytes = *cur_bytes;
826 QLIST_FOREACH(old_alloc, &s->cluster_allocs, next_in_flight) {
828 uint64_t start = guest_offset;
829 uint64_t end = start + bytes;
830 uint64_t old_start = l2meta_cow_start(old_alloc);
831 uint64_t old_end = l2meta_cow_end(old_alloc);
833 if (end <= old_start || start >= old_end) {
834 /* No intersection */
835 } else {
836 if (start < old_start) {
837 /* Stop at the start of a running allocation */
838 bytes = old_start - start;
839 } else {
840 bytes = 0;
843 /* Stop if already an l2meta exists. After yielding, it wouldn't
844 * be valid any more, so we'd have to clean up the old L2Metas
845 * and deal with requests depending on them before starting to
846 * gather new ones. Not worth the trouble. */
847 if (bytes == 0 && *m) {
848 *cur_bytes = 0;
849 return 0;
852 if (bytes == 0) {
853 /* Wait for the dependency to complete. We need to recheck
854 * the free/allocated clusters when we continue. */
855 qemu_co_mutex_unlock(&s->lock);
856 qemu_co_queue_wait(&old_alloc->dependent_requests);
857 qemu_co_mutex_lock(&s->lock);
858 return -EAGAIN;
863 /* Make sure that existing clusters and new allocations are only used up to
864 * the next dependency if we shortened the request above */
865 *cur_bytes = bytes;
867 return 0;
871 * Checks how many already allocated clusters that don't require a copy on
872 * write there are at the given guest_offset (up to *bytes). If
873 * *host_offset is not zero, only physically contiguous clusters beginning at
874 * this host offset are counted.
876 * Note that guest_offset may not be cluster aligned. In this case, the
877 * returned *host_offset points to exact byte referenced by guest_offset and
878 * therefore isn't cluster aligned as well.
880 * Returns:
881 * 0: if no allocated clusters are available at the given offset.
882 * *bytes is normally unchanged. It is set to 0 if the cluster
883 * is allocated and doesn't need COW, but doesn't have the right
884 * physical offset.
886 * 1: if allocated clusters that don't require a COW are available at
887 * the requested offset. *bytes may have decreased and describes
888 * the length of the area that can be written to.
890 * -errno: in error cases
892 static int handle_copied(BlockDriverState *bs, uint64_t guest_offset,
893 uint64_t *host_offset, uint64_t *bytes, QCowL2Meta **m)
895 BDRVQcowState *s = bs->opaque;
896 int l2_index;
897 uint64_t cluster_offset;
898 uint64_t *l2_table;
899 unsigned int nb_clusters;
900 unsigned int keep_clusters;
901 int ret, pret;
903 trace_qcow2_handle_copied(qemu_coroutine_self(), guest_offset, *host_offset,
904 *bytes);
906 assert(*host_offset == 0 || offset_into_cluster(s, guest_offset)
907 == offset_into_cluster(s, *host_offset));
910 * Calculate the number of clusters to look for. We stop at L2 table
911 * boundaries to keep things simple.
913 nb_clusters =
914 size_to_clusters(s, offset_into_cluster(s, guest_offset) + *bytes);
916 l2_index = offset_to_l2_index(s, guest_offset);
917 nb_clusters = MIN(nb_clusters, s->l2_size - l2_index);
919 /* Find L2 entry for the first involved cluster */
920 ret = get_cluster_table(bs, guest_offset, &l2_table, &l2_index);
921 if (ret < 0) {
922 return ret;
925 cluster_offset = be64_to_cpu(l2_table[l2_index]);
927 /* Check how many clusters are already allocated and don't need COW */
928 if (qcow2_get_cluster_type(cluster_offset) == QCOW2_CLUSTER_NORMAL
929 && (cluster_offset & QCOW_OFLAG_COPIED))
931 /* If a specific host_offset is required, check it */
932 bool offset_matches =
933 (cluster_offset & L2E_OFFSET_MASK) == *host_offset;
935 if (*host_offset != 0 && !offset_matches) {
936 *bytes = 0;
937 ret = 0;
938 goto out;
941 /* We keep all QCOW_OFLAG_COPIED clusters */
942 keep_clusters =
943 count_contiguous_clusters(nb_clusters, s->cluster_size,
944 &l2_table[l2_index],
945 QCOW_OFLAG_COPIED | QCOW_OFLAG_ZERO);
946 assert(keep_clusters <= nb_clusters);
948 *bytes = MIN(*bytes,
949 keep_clusters * s->cluster_size
950 - offset_into_cluster(s, guest_offset));
952 ret = 1;
953 } else {
954 ret = 0;
957 /* Cleanup */
958 out:
959 pret = qcow2_cache_put(bs, s->l2_table_cache, (void**) &l2_table);
960 if (pret < 0) {
961 return pret;
964 /* Only return a host offset if we actually made progress. Otherwise we
965 * would make requirements for handle_alloc() that it can't fulfill */
966 if (ret) {
967 *host_offset = (cluster_offset & L2E_OFFSET_MASK)
968 + offset_into_cluster(s, guest_offset);
971 return ret;
975 * Allocates new clusters for the given guest_offset.
977 * At most *nb_clusters are allocated, and on return *nb_clusters is updated to
978 * contain the number of clusters that have been allocated and are contiguous
979 * in the image file.
981 * If *host_offset is non-zero, it specifies the offset in the image file at
982 * which the new clusters must start. *nb_clusters can be 0 on return in this
983 * case if the cluster at host_offset is already in use. If *host_offset is
984 * zero, the clusters can be allocated anywhere in the image file.
986 * *host_offset is updated to contain the offset into the image file at which
987 * the first allocated cluster starts.
989 * Return 0 on success and -errno in error cases. -EAGAIN means that the
990 * function has been waiting for another request and the allocation must be
991 * restarted, but the whole request should not be failed.
993 static int do_alloc_cluster_offset(BlockDriverState *bs, uint64_t guest_offset,
994 uint64_t *host_offset, unsigned int *nb_clusters)
996 BDRVQcowState *s = bs->opaque;
998 trace_qcow2_do_alloc_clusters_offset(qemu_coroutine_self(), guest_offset,
999 *host_offset, *nb_clusters);
1001 /* Allocate new clusters */
1002 trace_qcow2_cluster_alloc_phys(qemu_coroutine_self());
1003 if (*host_offset == 0) {
1004 int64_t cluster_offset =
1005 qcow2_alloc_clusters(bs, *nb_clusters * s->cluster_size);
1006 if (cluster_offset < 0) {
1007 return cluster_offset;
1009 *host_offset = cluster_offset;
1010 return 0;
1011 } else {
1012 int ret = qcow2_alloc_clusters_at(bs, *host_offset, *nb_clusters);
1013 if (ret < 0) {
1014 return ret;
1016 *nb_clusters = ret;
1017 return 0;
1022 * Allocates new clusters for an area that either is yet unallocated or needs a
1023 * copy on write. If *host_offset is non-zero, clusters are only allocated if
1024 * the new allocation can match the specified host offset.
1026 * Note that guest_offset may not be cluster aligned. In this case, the
1027 * returned *host_offset points to exact byte referenced by guest_offset and
1028 * therefore isn't cluster aligned as well.
1030 * Returns:
1031 * 0: if no clusters could be allocated. *bytes is set to 0,
1032 * *host_offset is left unchanged.
1034 * 1: if new clusters were allocated. *bytes may be decreased if the
1035 * new allocation doesn't cover all of the requested area.
1036 * *host_offset is updated to contain the host offset of the first
1037 * newly allocated cluster.
1039 * -errno: in error cases
1041 static int handle_alloc(BlockDriverState *bs, uint64_t guest_offset,
1042 uint64_t *host_offset, uint64_t *bytes, QCowL2Meta **m)
1044 BDRVQcowState *s = bs->opaque;
1045 int l2_index;
1046 uint64_t *l2_table;
1047 uint64_t entry;
1048 unsigned int nb_clusters;
1049 int ret;
1051 uint64_t alloc_cluster_offset;
1053 trace_qcow2_handle_alloc(qemu_coroutine_self(), guest_offset, *host_offset,
1054 *bytes);
1055 assert(*bytes > 0);
1058 * Calculate the number of clusters to look for. We stop at L2 table
1059 * boundaries to keep things simple.
1061 nb_clusters =
1062 size_to_clusters(s, offset_into_cluster(s, guest_offset) + *bytes);
1064 l2_index = offset_to_l2_index(s, guest_offset);
1065 nb_clusters = MIN(nb_clusters, s->l2_size - l2_index);
1067 /* Find L2 entry for the first involved cluster */
1068 ret = get_cluster_table(bs, guest_offset, &l2_table, &l2_index);
1069 if (ret < 0) {
1070 return ret;
1073 entry = be64_to_cpu(l2_table[l2_index]);
1075 /* For the moment, overwrite compressed clusters one by one */
1076 if (entry & QCOW_OFLAG_COMPRESSED) {
1077 nb_clusters = 1;
1078 } else {
1079 nb_clusters = count_cow_clusters(s, nb_clusters, l2_table, l2_index);
1082 /* This function is only called when there were no non-COW clusters, so if
1083 * we can't find any unallocated or COW clusters either, something is
1084 * wrong with our code. */
1085 assert(nb_clusters > 0);
1087 ret = qcow2_cache_put(bs, s->l2_table_cache, (void**) &l2_table);
1088 if (ret < 0) {
1089 return ret;
1092 /* Allocate, if necessary at a given offset in the image file */
1093 alloc_cluster_offset = start_of_cluster(s, *host_offset);
1094 ret = do_alloc_cluster_offset(bs, guest_offset, &alloc_cluster_offset,
1095 &nb_clusters);
1096 if (ret < 0) {
1097 goto fail;
1100 /* Can't extend contiguous allocation */
1101 if (nb_clusters == 0) {
1102 *bytes = 0;
1103 return 0;
1107 * Save info needed for meta data update.
1109 * requested_sectors: Number of sectors from the start of the first
1110 * newly allocated cluster to the end of the (possibly shortened
1111 * before) write request.
1113 * avail_sectors: Number of sectors from the start of the first
1114 * newly allocated to the end of the last newly allocated cluster.
1116 * nb_sectors: The number of sectors from the start of the first
1117 * newly allocated cluster to the end of the area that the write
1118 * request actually writes to (excluding COW at the end)
1120 int requested_sectors =
1121 (*bytes + offset_into_cluster(s, guest_offset))
1122 >> BDRV_SECTOR_BITS;
1123 int avail_sectors = nb_clusters
1124 << (s->cluster_bits - BDRV_SECTOR_BITS);
1125 int alloc_n_start = offset_into_cluster(s, guest_offset)
1126 >> BDRV_SECTOR_BITS;
1127 int nb_sectors = MIN(requested_sectors, avail_sectors);
1128 QCowL2Meta *old_m = *m;
1130 *m = g_malloc0(sizeof(**m));
1132 **m = (QCowL2Meta) {
1133 .next = old_m,
1135 .alloc_offset = alloc_cluster_offset,
1136 .offset = start_of_cluster(s, guest_offset),
1137 .nb_clusters = nb_clusters,
1138 .nb_available = nb_sectors,
1140 .cow_start = {
1141 .offset = 0,
1142 .nb_sectors = alloc_n_start,
1144 .cow_end = {
1145 .offset = nb_sectors * BDRV_SECTOR_SIZE,
1146 .nb_sectors = avail_sectors - nb_sectors,
1149 qemu_co_queue_init(&(*m)->dependent_requests);
1150 QLIST_INSERT_HEAD(&s->cluster_allocs, *m, next_in_flight);
1152 *host_offset = alloc_cluster_offset + offset_into_cluster(s, guest_offset);
1153 *bytes = MIN(*bytes, (nb_sectors * BDRV_SECTOR_SIZE)
1154 - offset_into_cluster(s, guest_offset));
1155 assert(*bytes != 0);
1157 return 1;
1159 fail:
1160 if (*m && (*m)->nb_clusters > 0) {
1161 QLIST_REMOVE(*m, next_in_flight);
1163 return ret;
1167 * alloc_cluster_offset
1169 * For a given offset on the virtual disk, find the cluster offset in qcow2
1170 * file. If the offset is not found, allocate a new cluster.
1172 * If the cluster was already allocated, m->nb_clusters is set to 0 and
1173 * other fields in m are meaningless.
1175 * If the cluster is newly allocated, m->nb_clusters is set to the number of
1176 * contiguous clusters that have been allocated. In this case, the other
1177 * fields of m are valid and contain information about the first allocated
1178 * cluster.
1180 * If the request conflicts with another write request in flight, the coroutine
1181 * is queued and will be reentered when the dependency has completed.
1183 * Return 0 on success and -errno in error cases
1185 int qcow2_alloc_cluster_offset(BlockDriverState *bs, uint64_t offset,
1186 int n_start, int n_end, int *num, uint64_t *host_offset, QCowL2Meta **m)
1188 BDRVQcowState *s = bs->opaque;
1189 uint64_t start, remaining;
1190 uint64_t cluster_offset;
1191 uint64_t cur_bytes;
1192 int ret;
1194 trace_qcow2_alloc_clusters_offset(qemu_coroutine_self(), offset,
1195 n_start, n_end);
1197 assert(n_start * BDRV_SECTOR_SIZE == offset_into_cluster(s, offset));
1198 offset = start_of_cluster(s, offset);
1200 again:
1201 start = offset + (n_start << BDRV_SECTOR_BITS);
1202 remaining = (n_end - n_start) << BDRV_SECTOR_BITS;
1203 cluster_offset = 0;
1204 *host_offset = 0;
1205 cur_bytes = 0;
1206 *m = NULL;
1208 while (true) {
1210 if (!*host_offset) {
1211 *host_offset = start_of_cluster(s, cluster_offset);
1214 assert(remaining >= cur_bytes);
1216 start += cur_bytes;
1217 remaining -= cur_bytes;
1218 cluster_offset += cur_bytes;
1220 if (remaining == 0) {
1221 break;
1224 cur_bytes = remaining;
1227 * Now start gathering as many contiguous clusters as possible:
1229 * 1. Check for overlaps with in-flight allocations
1231 * a) Overlap not in the first cluster -> shorten this request and
1232 * let the caller handle the rest in its next loop iteration.
1234 * b) Real overlaps of two requests. Yield and restart the search
1235 * for contiguous clusters (the situation could have changed
1236 * while we were sleeping)
1238 * c) TODO: Request starts in the same cluster as the in-flight
1239 * allocation ends. Shorten the COW of the in-fight allocation,
1240 * set cluster_offset to write to the same cluster and set up
1241 * the right synchronisation between the in-flight request and
1242 * the new one.
1244 ret = handle_dependencies(bs, start, &cur_bytes, m);
1245 if (ret == -EAGAIN) {
1246 /* Currently handle_dependencies() doesn't yield if we already had
1247 * an allocation. If it did, we would have to clean up the L2Meta
1248 * structs before starting over. */
1249 assert(*m == NULL);
1250 goto again;
1251 } else if (ret < 0) {
1252 return ret;
1253 } else if (cur_bytes == 0) {
1254 break;
1255 } else {
1256 /* handle_dependencies() may have decreased cur_bytes (shortened
1257 * the allocations below) so that the next dependency is processed
1258 * correctly during the next loop iteration. */
1262 * 2. Count contiguous COPIED clusters.
1264 ret = handle_copied(bs, start, &cluster_offset, &cur_bytes, m);
1265 if (ret < 0) {
1266 return ret;
1267 } else if (ret) {
1268 continue;
1269 } else if (cur_bytes == 0) {
1270 break;
1274 * 3. If the request still hasn't completed, allocate new clusters,
1275 * considering any cluster_offset of steps 1c or 2.
1277 ret = handle_alloc(bs, start, &cluster_offset, &cur_bytes, m);
1278 if (ret < 0) {
1279 return ret;
1280 } else if (ret) {
1281 continue;
1282 } else {
1283 assert(cur_bytes == 0);
1284 break;
1288 *num = (n_end - n_start) - (remaining >> BDRV_SECTOR_BITS);
1289 assert(*num > 0);
1290 assert(*host_offset != 0);
1292 return 0;
1295 static int decompress_buffer(uint8_t *out_buf, int out_buf_size,
1296 const uint8_t *buf, int buf_size)
1298 z_stream strm1, *strm = &strm1;
1299 int ret, out_len;
1301 memset(strm, 0, sizeof(*strm));
1303 strm->next_in = (uint8_t *)buf;
1304 strm->avail_in = buf_size;
1305 strm->next_out = out_buf;
1306 strm->avail_out = out_buf_size;
1308 ret = inflateInit2(strm, -12);
1309 if (ret != Z_OK)
1310 return -1;
1311 ret = inflate(strm, Z_FINISH);
1312 out_len = strm->next_out - out_buf;
1313 if ((ret != Z_STREAM_END && ret != Z_BUF_ERROR) ||
1314 out_len != out_buf_size) {
1315 inflateEnd(strm);
1316 return -1;
1318 inflateEnd(strm);
1319 return 0;
1322 int qcow2_decompress_cluster(BlockDriverState *bs, uint64_t cluster_offset)
1324 BDRVQcowState *s = bs->opaque;
1325 int ret, csize, nb_csectors, sector_offset;
1326 uint64_t coffset;
1328 coffset = cluster_offset & s->cluster_offset_mask;
1329 if (s->cluster_cache_offset != coffset) {
1330 nb_csectors = ((cluster_offset >> s->csize_shift) & s->csize_mask) + 1;
1331 sector_offset = coffset & 511;
1332 csize = nb_csectors * 512 - sector_offset;
1333 BLKDBG_EVENT(bs->file, BLKDBG_READ_COMPRESSED);
1334 ret = bdrv_read(bs->file, coffset >> 9, s->cluster_data, nb_csectors);
1335 if (ret < 0) {
1336 return ret;
1338 if (decompress_buffer(s->cluster_cache, s->cluster_size,
1339 s->cluster_data + sector_offset, csize) < 0) {
1340 return -EIO;
1342 s->cluster_cache_offset = coffset;
1344 return 0;
1348 * This discards as many clusters of nb_clusters as possible at once (i.e.
1349 * all clusters in the same L2 table) and returns the number of discarded
1350 * clusters.
1352 static int discard_single_l2(BlockDriverState *bs, uint64_t offset,
1353 unsigned int nb_clusters, enum qcow2_discard_type type)
1355 BDRVQcowState *s = bs->opaque;
1356 uint64_t *l2_table;
1357 int l2_index;
1358 int ret;
1359 int i;
1361 ret = get_cluster_table(bs, offset, &l2_table, &l2_index);
1362 if (ret < 0) {
1363 return ret;
1366 /* Limit nb_clusters to one L2 table */
1367 nb_clusters = MIN(nb_clusters, s->l2_size - l2_index);
1369 for (i = 0; i < nb_clusters; i++) {
1370 uint64_t old_offset;
1372 old_offset = be64_to_cpu(l2_table[l2_index + i]);
1373 if ((old_offset & L2E_OFFSET_MASK) == 0) {
1374 continue;
1377 /* First remove L2 entries */
1378 qcow2_cache_entry_mark_dirty(s->l2_table_cache, l2_table);
1379 l2_table[l2_index + i] = cpu_to_be64(0);
1381 /* Then decrease the refcount */
1382 qcow2_free_any_clusters(bs, old_offset, 1, type);
1385 ret = qcow2_cache_put(bs, s->l2_table_cache, (void**) &l2_table);
1386 if (ret < 0) {
1387 return ret;
1390 return nb_clusters;
1393 int qcow2_discard_clusters(BlockDriverState *bs, uint64_t offset,
1394 int nb_sectors, enum qcow2_discard_type type)
1396 BDRVQcowState *s = bs->opaque;
1397 uint64_t end_offset;
1398 unsigned int nb_clusters;
1399 int ret;
1401 end_offset = offset + (nb_sectors << BDRV_SECTOR_BITS);
1403 /* Round start up and end down */
1404 offset = align_offset(offset, s->cluster_size);
1405 end_offset &= ~(s->cluster_size - 1);
1407 if (offset > end_offset) {
1408 return 0;
1411 nb_clusters = size_to_clusters(s, end_offset - offset);
1413 s->cache_discards = true;
1415 /* Each L2 table is handled by its own loop iteration */
1416 while (nb_clusters > 0) {
1417 ret = discard_single_l2(bs, offset, nb_clusters, type);
1418 if (ret < 0) {
1419 goto fail;
1422 nb_clusters -= ret;
1423 offset += (ret * s->cluster_size);
1426 ret = 0;
1427 fail:
1428 s->cache_discards = false;
1429 qcow2_process_discards(bs, ret);
1431 return ret;
1435 * This zeroes as many clusters of nb_clusters as possible at once (i.e.
1436 * all clusters in the same L2 table) and returns the number of zeroed
1437 * clusters.
1439 static int zero_single_l2(BlockDriverState *bs, uint64_t offset,
1440 unsigned int nb_clusters)
1442 BDRVQcowState *s = bs->opaque;
1443 uint64_t *l2_table;
1444 int l2_index;
1445 int ret;
1446 int i;
1448 ret = get_cluster_table(bs, offset, &l2_table, &l2_index);
1449 if (ret < 0) {
1450 return ret;
1453 /* Limit nb_clusters to one L2 table */
1454 nb_clusters = MIN(nb_clusters, s->l2_size - l2_index);
1456 for (i = 0; i < nb_clusters; i++) {
1457 uint64_t old_offset;
1459 old_offset = be64_to_cpu(l2_table[l2_index + i]);
1461 /* Update L2 entries */
1462 qcow2_cache_entry_mark_dirty(s->l2_table_cache, l2_table);
1463 if (old_offset & QCOW_OFLAG_COMPRESSED) {
1464 l2_table[l2_index + i] = cpu_to_be64(QCOW_OFLAG_ZERO);
1465 qcow2_free_any_clusters(bs, old_offset, 1, QCOW2_DISCARD_REQUEST);
1466 } else {
1467 l2_table[l2_index + i] |= cpu_to_be64(QCOW_OFLAG_ZERO);
1471 ret = qcow2_cache_put(bs, s->l2_table_cache, (void**) &l2_table);
1472 if (ret < 0) {
1473 return ret;
1476 return nb_clusters;
1479 int qcow2_zero_clusters(BlockDriverState *bs, uint64_t offset, int nb_sectors)
1481 BDRVQcowState *s = bs->opaque;
1482 unsigned int nb_clusters;
1483 int ret;
1485 /* The zero flag is only supported by version 3 and newer */
1486 if (s->qcow_version < 3) {
1487 return -ENOTSUP;
1490 /* Each L2 table is handled by its own loop iteration */
1491 nb_clusters = size_to_clusters(s, nb_sectors << BDRV_SECTOR_BITS);
1493 s->cache_discards = true;
1495 while (nb_clusters > 0) {
1496 ret = zero_single_l2(bs, offset, nb_clusters);
1497 if (ret < 0) {
1498 goto fail;
1501 nb_clusters -= ret;
1502 offset += (ret * s->cluster_size);
1505 ret = 0;
1506 fail:
1507 s->cache_discards = false;
1508 qcow2_process_discards(bs, ret);
1510 return ret;
1514 * Expands all zero clusters in a specific L1 table (or deallocates them, for
1515 * non-backed non-pre-allocated zero clusters).
1517 * expanded_clusters is a bitmap where every bit corresponds to one cluster in
1518 * the image file; a bit gets set if the corresponding cluster has been used for
1519 * zero expansion (i.e., has been filled with zeroes and is referenced from an
1520 * L2 table). nb_clusters contains the total cluster count of the image file,
1521 * i.e., the number of bits in expanded_clusters.
1523 static int expand_zero_clusters_in_l1(BlockDriverState *bs, uint64_t *l1_table,
1524 int l1_size, uint8_t **expanded_clusters,
1525 uint64_t *nb_clusters)
1527 BDRVQcowState *s = bs->opaque;
1528 bool is_active_l1 = (l1_table == s->l1_table);
1529 uint64_t *l2_table = NULL;
1530 int ret;
1531 int i, j;
1533 if (!is_active_l1) {
1534 /* inactive L2 tables require a buffer to be stored in when loading
1535 * them from disk */
1536 l2_table = qemu_blockalign(bs, s->cluster_size);
1539 for (i = 0; i < l1_size; i++) {
1540 uint64_t l2_offset = l1_table[i] & L1E_OFFSET_MASK;
1541 bool l2_dirty = false;
1543 if (!l2_offset) {
1544 /* unallocated */
1545 continue;
1548 if (is_active_l1) {
1549 /* get active L2 tables from cache */
1550 ret = qcow2_cache_get(bs, s->l2_table_cache, l2_offset,
1551 (void **)&l2_table);
1552 } else {
1553 /* load inactive L2 tables from disk */
1554 ret = bdrv_read(bs->file, l2_offset / BDRV_SECTOR_SIZE,
1555 (void *)l2_table, s->cluster_sectors);
1557 if (ret < 0) {
1558 goto fail;
1561 for (j = 0; j < s->l2_size; j++) {
1562 uint64_t l2_entry = be64_to_cpu(l2_table[j]);
1563 int64_t offset = l2_entry & L2E_OFFSET_MASK, cluster_index;
1564 int cluster_type = qcow2_get_cluster_type(l2_entry);
1565 bool preallocated = offset != 0;
1567 if (cluster_type == QCOW2_CLUSTER_NORMAL) {
1568 cluster_index = offset >> s->cluster_bits;
1569 assert((cluster_index >= 0) && (cluster_index < *nb_clusters));
1570 if ((*expanded_clusters)[cluster_index / 8] &
1571 (1 << (cluster_index % 8))) {
1572 /* Probably a shared L2 table; this cluster was a zero
1573 * cluster which has been expanded, its refcount
1574 * therefore most likely requires an update. */
1575 ret = qcow2_update_cluster_refcount(bs, cluster_index, 1,
1576 QCOW2_DISCARD_NEVER);
1577 if (ret < 0) {
1578 goto fail;
1580 /* Since we just increased the refcount, the COPIED flag may
1581 * no longer be set. */
1582 l2_table[j] = cpu_to_be64(l2_entry & ~QCOW_OFLAG_COPIED);
1583 l2_dirty = true;
1585 continue;
1587 else if (qcow2_get_cluster_type(l2_entry) != QCOW2_CLUSTER_ZERO) {
1588 continue;
1591 if (!preallocated) {
1592 if (!bs->backing_hd) {
1593 /* not backed; therefore we can simply deallocate the
1594 * cluster */
1595 l2_table[j] = 0;
1596 l2_dirty = true;
1597 continue;
1600 offset = qcow2_alloc_clusters(bs, s->cluster_size);
1601 if (offset < 0) {
1602 ret = offset;
1603 goto fail;
1607 ret = qcow2_pre_write_overlap_check(bs, QCOW2_OL_DEFAULT,
1608 offset, s->cluster_size);
1609 if (ret < 0) {
1610 if (!preallocated) {
1611 qcow2_free_clusters(bs, offset, s->cluster_size,
1612 QCOW2_DISCARD_ALWAYS);
1614 goto fail;
1617 ret = bdrv_write_zeroes(bs->file, offset / BDRV_SECTOR_SIZE,
1618 s->cluster_sectors);
1619 if (ret < 0) {
1620 if (!preallocated) {
1621 qcow2_free_clusters(bs, offset, s->cluster_size,
1622 QCOW2_DISCARD_ALWAYS);
1624 goto fail;
1627 l2_table[j] = cpu_to_be64(offset | QCOW_OFLAG_COPIED);
1628 l2_dirty = true;
1630 cluster_index = offset >> s->cluster_bits;
1632 if (cluster_index >= *nb_clusters) {
1633 uint64_t old_bitmap_size = (*nb_clusters + 7) / 8;
1634 uint64_t new_bitmap_size;
1635 /* The offset may lie beyond the old end of the underlying image
1636 * file for growable files only */
1637 assert(bs->file->growable);
1638 *nb_clusters = size_to_clusters(s, bs->file->total_sectors *
1639 BDRV_SECTOR_SIZE);
1640 new_bitmap_size = (*nb_clusters + 7) / 8;
1641 *expanded_clusters = g_realloc(*expanded_clusters,
1642 new_bitmap_size);
1643 /* clear the newly allocated space */
1644 memset(&(*expanded_clusters)[old_bitmap_size], 0,
1645 new_bitmap_size - old_bitmap_size);
1648 assert((cluster_index >= 0) && (cluster_index < *nb_clusters));
1649 (*expanded_clusters)[cluster_index / 8] |= 1 << (cluster_index % 8);
1652 if (is_active_l1) {
1653 if (l2_dirty) {
1654 qcow2_cache_entry_mark_dirty(s->l2_table_cache, l2_table);
1655 qcow2_cache_depends_on_flush(s->l2_table_cache);
1657 ret = qcow2_cache_put(bs, s->l2_table_cache, (void **)&l2_table);
1658 if (ret < 0) {
1659 l2_table = NULL;
1660 goto fail;
1662 } else {
1663 if (l2_dirty) {
1664 ret = qcow2_pre_write_overlap_check(bs, QCOW2_OL_DEFAULT &
1665 ~(QCOW2_OL_INACTIVE_L2 | QCOW2_OL_ACTIVE_L2), l2_offset,
1666 s->cluster_size);
1667 if (ret < 0) {
1668 goto fail;
1671 ret = bdrv_write(bs->file, l2_offset / BDRV_SECTOR_SIZE,
1672 (void *)l2_table, s->cluster_sectors);
1673 if (ret < 0) {
1674 goto fail;
1680 ret = 0;
1682 fail:
1683 if (l2_table) {
1684 if (!is_active_l1) {
1685 qemu_vfree(l2_table);
1686 } else {
1687 if (ret < 0) {
1688 qcow2_cache_put(bs, s->l2_table_cache, (void **)&l2_table);
1689 } else {
1690 ret = qcow2_cache_put(bs, s->l2_table_cache,
1691 (void **)&l2_table);
1695 return ret;
1699 * For backed images, expands all zero clusters on the image. For non-backed
1700 * images, deallocates all non-pre-allocated zero clusters (and claims the
1701 * allocation for pre-allocated ones). This is important for downgrading to a
1702 * qcow2 version which doesn't yet support metadata zero clusters.
1704 int qcow2_expand_zero_clusters(BlockDriverState *bs)
1706 BDRVQcowState *s = bs->opaque;
1707 uint64_t *l1_table = NULL;
1708 uint64_t nb_clusters;
1709 uint8_t *expanded_clusters;
1710 int ret;
1711 int i, j;
1713 nb_clusters = size_to_clusters(s, bs->file->total_sectors *
1714 BDRV_SECTOR_SIZE);
1715 expanded_clusters = g_malloc0((nb_clusters + 7) / 8);
1717 ret = expand_zero_clusters_in_l1(bs, s->l1_table, s->l1_size,
1718 &expanded_clusters, &nb_clusters);
1719 if (ret < 0) {
1720 goto fail;
1723 /* Inactive L1 tables may point to active L2 tables - therefore it is
1724 * necessary to flush the L2 table cache before trying to access the L2
1725 * tables pointed to by inactive L1 entries (else we might try to expand
1726 * zero clusters that have already been expanded); furthermore, it is also
1727 * necessary to empty the L2 table cache, since it may contain tables which
1728 * are now going to be modified directly on disk, bypassing the cache.
1729 * qcow2_cache_empty() does both for us. */
1730 ret = qcow2_cache_empty(bs, s->l2_table_cache);
1731 if (ret < 0) {
1732 goto fail;
1735 for (i = 0; i < s->nb_snapshots; i++) {
1736 int l1_sectors = (s->snapshots[i].l1_size * sizeof(uint64_t) +
1737 BDRV_SECTOR_SIZE - 1) / BDRV_SECTOR_SIZE;
1739 l1_table = g_realloc(l1_table, l1_sectors * BDRV_SECTOR_SIZE);
1741 ret = bdrv_read(bs->file, s->snapshots[i].l1_table_offset /
1742 BDRV_SECTOR_SIZE, (void *)l1_table, l1_sectors);
1743 if (ret < 0) {
1744 goto fail;
1747 for (j = 0; j < s->snapshots[i].l1_size; j++) {
1748 be64_to_cpus(&l1_table[j]);
1751 ret = expand_zero_clusters_in_l1(bs, l1_table, s->snapshots[i].l1_size,
1752 &expanded_clusters, &nb_clusters);
1753 if (ret < 0) {
1754 goto fail;
1758 ret = 0;
1760 fail:
1761 g_free(expanded_clusters);
1762 g_free(l1_table);
1763 return ret;