Update OpenBIOS images
[qemu.git] / block / qcow2-cluster.c
blob39323ace387da30882e7ec7203e4b4d8c5ac5749
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 new_l1_table_offset, new_l1_size;
39 uint8_t data[12];
41 if (min_size <= s->l1_size)
42 return 0;
44 if (exact_size) {
45 new_l1_size = min_size;
46 } else {
47 /* Bump size up to reduce the number of times we have to grow */
48 new_l1_size = s->l1_size;
49 if (new_l1_size == 0) {
50 new_l1_size = 1;
52 while (min_size > new_l1_size) {
53 new_l1_size = (new_l1_size * 3 + 1) / 2;
57 if (new_l1_size > INT_MAX) {
58 return -EFBIG;
61 #ifdef DEBUG_ALLOC2
62 fprintf(stderr, "grow l1_table from %d to %" PRId64 "\n",
63 s->l1_size, new_l1_size);
64 #endif
66 new_l1_size2 = sizeof(uint64_t) * new_l1_size;
67 new_l1_table = g_malloc0(align_offset(new_l1_size2, 512));
68 memcpy(new_l1_table, s->l1_table, s->l1_size * sizeof(uint64_t));
70 /* write new table (align to cluster) */
71 BLKDBG_EVENT(bs->file, BLKDBG_L1_GROW_ALLOC_TABLE);
72 new_l1_table_offset = qcow2_alloc_clusters(bs, new_l1_size2);
73 if (new_l1_table_offset < 0) {
74 g_free(new_l1_table);
75 return new_l1_table_offset;
78 ret = qcow2_cache_flush(bs, s->refcount_block_cache);
79 if (ret < 0) {
80 goto fail;
83 /* the L1 position has not yet been updated, so these clusters must
84 * indeed be completely free */
85 ret = qcow2_pre_write_overlap_check(bs, QCOW2_OL_DEFAULT,
86 new_l1_table_offset, new_l1_size2);
87 if (ret < 0) {
88 goto fail;
91 BLKDBG_EVENT(bs->file, BLKDBG_L1_GROW_WRITE_TABLE);
92 for(i = 0; i < s->l1_size; i++)
93 new_l1_table[i] = cpu_to_be64(new_l1_table[i]);
94 ret = bdrv_pwrite_sync(bs->file, new_l1_table_offset, new_l1_table, new_l1_size2);
95 if (ret < 0)
96 goto fail;
97 for(i = 0; i < s->l1_size; i++)
98 new_l1_table[i] = be64_to_cpu(new_l1_table[i]);
100 /* set new table */
101 BLKDBG_EVENT(bs->file, BLKDBG_L1_GROW_ACTIVATE_TABLE);
102 cpu_to_be32w((uint32_t*)data, new_l1_size);
103 cpu_to_be64wu((uint64_t*)(data + 4), new_l1_table_offset);
104 ret = bdrv_pwrite_sync(bs->file, offsetof(QCowHeader, l1_size), data,sizeof(data));
105 if (ret < 0) {
106 goto fail;
108 g_free(s->l1_table);
109 qcow2_free_clusters(bs, s->l1_table_offset, s->l1_size * sizeof(uint64_t),
110 QCOW2_DISCARD_OTHER);
111 s->l1_table_offset = new_l1_table_offset;
112 s->l1_table = new_l1_table;
113 s->l1_size = new_l1_size;
114 return 0;
115 fail:
116 g_free(new_l1_table);
117 qcow2_free_clusters(bs, new_l1_table_offset, new_l1_size2,
118 QCOW2_DISCARD_OTHER);
119 return ret;
123 * l2_load
125 * Loads a L2 table into memory. If the table is in the cache, the cache
126 * is used; otherwise the L2 table is loaded from the image file.
128 * Returns a pointer to the L2 table on success, or NULL if the read from
129 * the image file failed.
132 static int l2_load(BlockDriverState *bs, uint64_t l2_offset,
133 uint64_t **l2_table)
135 BDRVQcowState *s = bs->opaque;
136 int ret;
138 ret = qcow2_cache_get(bs, s->l2_table_cache, l2_offset, (void**) l2_table);
140 return ret;
144 * Writes one sector of the L1 table to the disk (can't update single entries
145 * and we really don't want bdrv_pread to perform a read-modify-write)
147 #define L1_ENTRIES_PER_SECTOR (512 / 8)
148 int qcow2_write_l1_entry(BlockDriverState *bs, int l1_index)
150 BDRVQcowState *s = bs->opaque;
151 uint64_t buf[L1_ENTRIES_PER_SECTOR];
152 int l1_start_index;
153 int i, ret;
155 l1_start_index = l1_index & ~(L1_ENTRIES_PER_SECTOR - 1);
156 for (i = 0; i < L1_ENTRIES_PER_SECTOR; i++) {
157 buf[i] = cpu_to_be64(s->l1_table[l1_start_index + i]);
160 ret = qcow2_pre_write_overlap_check(bs,
161 QCOW2_OL_DEFAULT & ~QCOW2_OL_ACTIVE_L1,
162 s->l1_table_offset + 8 * l1_start_index, sizeof(buf));
163 if (ret < 0) {
164 return ret;
167 BLKDBG_EVENT(bs->file, BLKDBG_L1_UPDATE);
168 ret = bdrv_pwrite_sync(bs->file, s->l1_table_offset + 8 * l1_start_index,
169 buf, sizeof(buf));
170 if (ret < 0) {
171 return ret;
174 return 0;
178 * l2_allocate
180 * Allocate a new l2 entry in the file. If l1_index points to an already
181 * used entry in the L2 table (i.e. we are doing a copy on write for the L2
182 * table) copy the contents of the old L2 table into the newly allocated one.
183 * Otherwise the new table is initialized with zeros.
187 static int l2_allocate(BlockDriverState *bs, int l1_index, uint64_t **table)
189 BDRVQcowState *s = bs->opaque;
190 uint64_t old_l2_offset;
191 uint64_t *l2_table = NULL;
192 int64_t l2_offset;
193 int ret;
195 old_l2_offset = s->l1_table[l1_index];
197 trace_qcow2_l2_allocate(bs, l1_index);
199 /* allocate a new l2 entry */
201 l2_offset = qcow2_alloc_clusters(bs, s->l2_size * sizeof(uint64_t));
202 if (l2_offset < 0) {
203 ret = l2_offset;
204 goto fail;
207 ret = qcow2_cache_flush(bs, s->refcount_block_cache);
208 if (ret < 0) {
209 goto fail;
212 /* allocate a new entry in the l2 cache */
214 trace_qcow2_l2_allocate_get_empty(bs, l1_index);
215 ret = qcow2_cache_get_empty(bs, s->l2_table_cache, l2_offset, (void**) table);
216 if (ret < 0) {
217 goto fail;
220 l2_table = *table;
222 if ((old_l2_offset & L1E_OFFSET_MASK) == 0) {
223 /* if there was no old l2 table, clear the new table */
224 memset(l2_table, 0, s->l2_size * sizeof(uint64_t));
225 } else {
226 uint64_t* old_table;
228 /* if there was an old l2 table, read it from the disk */
229 BLKDBG_EVENT(bs->file, BLKDBG_L2_ALLOC_COW_READ);
230 ret = qcow2_cache_get(bs, s->l2_table_cache,
231 old_l2_offset & L1E_OFFSET_MASK,
232 (void**) &old_table);
233 if (ret < 0) {
234 goto fail;
237 memcpy(l2_table, old_table, s->cluster_size);
239 ret = qcow2_cache_put(bs, s->l2_table_cache, (void**) &old_table);
240 if (ret < 0) {
241 goto fail;
245 /* write the l2 table to the file */
246 BLKDBG_EVENT(bs->file, BLKDBG_L2_ALLOC_WRITE);
248 trace_qcow2_l2_allocate_write_l2(bs, l1_index);
249 qcow2_cache_entry_mark_dirty(s->l2_table_cache, l2_table);
250 ret = qcow2_cache_flush(bs, s->l2_table_cache);
251 if (ret < 0) {
252 goto fail;
255 /* update the L1 entry */
256 trace_qcow2_l2_allocate_write_l1(bs, l1_index);
257 s->l1_table[l1_index] = l2_offset | QCOW_OFLAG_COPIED;
258 ret = qcow2_write_l1_entry(bs, l1_index);
259 if (ret < 0) {
260 goto fail;
263 *table = l2_table;
264 trace_qcow2_l2_allocate_done(bs, l1_index, 0);
265 return 0;
267 fail:
268 trace_qcow2_l2_allocate_done(bs, l1_index, ret);
269 if (l2_table != NULL) {
270 qcow2_cache_put(bs, s->l2_table_cache, (void**) table);
272 s->l1_table[l1_index] = old_l2_offset;
273 return ret;
277 * Checks how many clusters in a given L2 table are contiguous in the image
278 * file. As soon as one of the flags in the bitmask stop_flags changes compared
279 * to the first cluster, the search is stopped and the cluster is not counted
280 * as contiguous. (This allows it, for example, to stop at the first compressed
281 * cluster which may require a different handling)
283 static int count_contiguous_clusters(uint64_t nb_clusters, int cluster_size,
284 uint64_t *l2_table, uint64_t stop_flags)
286 int i;
287 uint64_t mask = stop_flags | L2E_OFFSET_MASK | QCOW2_CLUSTER_COMPRESSED;
288 uint64_t first_entry = be64_to_cpu(l2_table[0]);
289 uint64_t offset = first_entry & mask;
291 if (!offset)
292 return 0;
294 assert(qcow2_get_cluster_type(first_entry) != QCOW2_CLUSTER_COMPRESSED);
296 for (i = 0; i < nb_clusters; i++) {
297 uint64_t l2_entry = be64_to_cpu(l2_table[i]) & mask;
298 if (offset + (uint64_t) i * cluster_size != l2_entry) {
299 break;
303 return i;
306 static int count_contiguous_free_clusters(uint64_t nb_clusters, uint64_t *l2_table)
308 int i;
310 for (i = 0; i < nb_clusters; i++) {
311 int type = qcow2_get_cluster_type(be64_to_cpu(l2_table[i]));
313 if (type != QCOW2_CLUSTER_UNALLOCATED) {
314 break;
318 return i;
321 /* The crypt function is compatible with the linux cryptoloop
322 algorithm for < 4 GB images. NOTE: out_buf == in_buf is
323 supported */
324 void qcow2_encrypt_sectors(BDRVQcowState *s, int64_t sector_num,
325 uint8_t *out_buf, const uint8_t *in_buf,
326 int nb_sectors, int enc,
327 const AES_KEY *key)
329 union {
330 uint64_t ll[2];
331 uint8_t b[16];
332 } ivec;
333 int i;
335 for(i = 0; i < nb_sectors; i++) {
336 ivec.ll[0] = cpu_to_le64(sector_num);
337 ivec.ll[1] = 0;
338 AES_cbc_encrypt(in_buf, out_buf, 512, key,
339 ivec.b, enc);
340 sector_num++;
341 in_buf += 512;
342 out_buf += 512;
346 static int coroutine_fn copy_sectors(BlockDriverState *bs,
347 uint64_t start_sect,
348 uint64_t cluster_offset,
349 int n_start, int n_end)
351 BDRVQcowState *s = bs->opaque;
352 QEMUIOVector qiov;
353 struct iovec iov;
354 int n, ret;
357 * If this is the last cluster and it is only partially used, we must only
358 * copy until the end of the image, or bdrv_check_request will fail for the
359 * bdrv_read/write calls below.
361 if (start_sect + n_end > bs->total_sectors) {
362 n_end = bs->total_sectors - start_sect;
365 n = n_end - n_start;
366 if (n <= 0) {
367 return 0;
370 iov.iov_len = n * BDRV_SECTOR_SIZE;
371 iov.iov_base = qemu_blockalign(bs, iov.iov_len);
373 qemu_iovec_init_external(&qiov, &iov, 1);
375 BLKDBG_EVENT(bs->file, BLKDBG_COW_READ);
377 /* Call .bdrv_co_readv() directly instead of using the public block-layer
378 * interface. This avoids double I/O throttling and request tracking,
379 * which can lead to deadlock when block layer copy-on-read is enabled.
381 ret = bs->drv->bdrv_co_readv(bs, start_sect + n_start, n, &qiov);
382 if (ret < 0) {
383 goto out;
386 if (s->crypt_method) {
387 qcow2_encrypt_sectors(s, start_sect + n_start,
388 iov.iov_base, iov.iov_base, n, 1,
389 &s->aes_encrypt_key);
392 ret = qcow2_pre_write_overlap_check(bs, QCOW2_OL_DEFAULT,
393 cluster_offset + n_start * BDRV_SECTOR_SIZE, n * BDRV_SECTOR_SIZE);
394 if (ret < 0) {
395 goto out;
398 BLKDBG_EVENT(bs->file, BLKDBG_COW_WRITE);
399 ret = bdrv_co_writev(bs->file, (cluster_offset >> 9) + n_start, n, &qiov);
400 if (ret < 0) {
401 goto out;
404 ret = 0;
405 out:
406 qemu_vfree(iov.iov_base);
407 return ret;
412 * get_cluster_offset
414 * For a given offset of the disk image, find the cluster offset in
415 * qcow2 file. The offset is stored in *cluster_offset.
417 * on entry, *num is the number of contiguous sectors we'd like to
418 * access following offset.
420 * on exit, *num is the number of contiguous sectors we can read.
422 * Returns the cluster type (QCOW2_CLUSTER_*) on success, -errno in error
423 * cases.
425 int qcow2_get_cluster_offset(BlockDriverState *bs, uint64_t offset,
426 int *num, uint64_t *cluster_offset)
428 BDRVQcowState *s = bs->opaque;
429 unsigned int l2_index;
430 uint64_t l1_index, l2_offset, *l2_table;
431 int l1_bits, c;
432 unsigned int index_in_cluster, nb_clusters;
433 uint64_t nb_available, nb_needed;
434 int ret;
436 index_in_cluster = (offset >> 9) & (s->cluster_sectors - 1);
437 nb_needed = *num + index_in_cluster;
439 l1_bits = s->l2_bits + s->cluster_bits;
441 /* compute how many bytes there are between the offset and
442 * the end of the l1 entry
445 nb_available = (1ULL << l1_bits) - (offset & ((1ULL << l1_bits) - 1));
447 /* compute the number of available sectors */
449 nb_available = (nb_available >> 9) + index_in_cluster;
451 if (nb_needed > nb_available) {
452 nb_needed = nb_available;
455 *cluster_offset = 0;
457 /* seek the the l2 offset in the l1 table */
459 l1_index = offset >> l1_bits;
460 if (l1_index >= s->l1_size) {
461 ret = QCOW2_CLUSTER_UNALLOCATED;
462 goto out;
465 l2_offset = s->l1_table[l1_index] & L1E_OFFSET_MASK;
466 if (!l2_offset) {
467 ret = QCOW2_CLUSTER_UNALLOCATED;
468 goto out;
471 /* load the l2 table in memory */
473 ret = l2_load(bs, l2_offset, &l2_table);
474 if (ret < 0) {
475 return ret;
478 /* find the cluster offset for the given disk offset */
480 l2_index = (offset >> s->cluster_bits) & (s->l2_size - 1);
481 *cluster_offset = be64_to_cpu(l2_table[l2_index]);
482 nb_clusters = size_to_clusters(s, nb_needed << 9);
484 ret = qcow2_get_cluster_type(*cluster_offset);
485 switch (ret) {
486 case QCOW2_CLUSTER_COMPRESSED:
487 /* Compressed clusters can only be processed one by one */
488 c = 1;
489 *cluster_offset &= L2E_COMPRESSED_OFFSET_SIZE_MASK;
490 break;
491 case QCOW2_CLUSTER_ZERO:
492 if (s->qcow_version < 3) {
493 return -EIO;
495 c = count_contiguous_clusters(nb_clusters, s->cluster_size,
496 &l2_table[l2_index], QCOW_OFLAG_ZERO);
497 *cluster_offset = 0;
498 break;
499 case QCOW2_CLUSTER_UNALLOCATED:
500 /* how many empty clusters ? */
501 c = count_contiguous_free_clusters(nb_clusters, &l2_table[l2_index]);
502 *cluster_offset = 0;
503 break;
504 case QCOW2_CLUSTER_NORMAL:
505 /* how many allocated clusters ? */
506 c = count_contiguous_clusters(nb_clusters, s->cluster_size,
507 &l2_table[l2_index], QCOW_OFLAG_ZERO);
508 *cluster_offset &= L2E_OFFSET_MASK;
509 break;
510 default:
511 abort();
514 qcow2_cache_put(bs, s->l2_table_cache, (void**) &l2_table);
516 nb_available = (c * s->cluster_sectors);
518 out:
519 if (nb_available > nb_needed)
520 nb_available = nb_needed;
522 *num = nb_available - index_in_cluster;
524 return ret;
528 * get_cluster_table
530 * for a given disk offset, load (and allocate if needed)
531 * the l2 table.
533 * the l2 table offset in the qcow2 file and the cluster index
534 * in the l2 table are given to the caller.
536 * Returns 0 on success, -errno in failure case
538 static int get_cluster_table(BlockDriverState *bs, uint64_t offset,
539 uint64_t **new_l2_table,
540 int *new_l2_index)
542 BDRVQcowState *s = bs->opaque;
543 unsigned int l2_index;
544 uint64_t l1_index, l2_offset;
545 uint64_t *l2_table = NULL;
546 int ret;
548 /* seek the the l2 offset in the l1 table */
550 l1_index = offset >> (s->l2_bits + s->cluster_bits);
551 if (l1_index >= s->l1_size) {
552 ret = qcow2_grow_l1_table(bs, l1_index + 1, false);
553 if (ret < 0) {
554 return ret;
558 assert(l1_index < s->l1_size);
559 l2_offset = s->l1_table[l1_index] & L1E_OFFSET_MASK;
561 /* seek the l2 table of the given l2 offset */
563 if (s->l1_table[l1_index] & QCOW_OFLAG_COPIED) {
564 /* load the l2 table in memory */
565 ret = l2_load(bs, l2_offset, &l2_table);
566 if (ret < 0) {
567 return ret;
569 } else {
570 /* First allocate a new L2 table (and do COW if needed) */
571 ret = l2_allocate(bs, l1_index, &l2_table);
572 if (ret < 0) {
573 return ret;
576 /* Then decrease the refcount of the old table */
577 if (l2_offset) {
578 qcow2_free_clusters(bs, l2_offset, s->l2_size * sizeof(uint64_t),
579 QCOW2_DISCARD_OTHER);
583 /* find the cluster offset for the given disk offset */
585 l2_index = (offset >> s->cluster_bits) & (s->l2_size - 1);
587 *new_l2_table = l2_table;
588 *new_l2_index = l2_index;
590 return 0;
594 * alloc_compressed_cluster_offset
596 * For a given offset of the disk image, return cluster offset in
597 * qcow2 file.
599 * If the offset is not found, allocate a new compressed cluster.
601 * Return the cluster offset if successful,
602 * Return 0, otherwise.
606 uint64_t qcow2_alloc_compressed_cluster_offset(BlockDriverState *bs,
607 uint64_t offset,
608 int compressed_size)
610 BDRVQcowState *s = bs->opaque;
611 int l2_index, ret;
612 uint64_t *l2_table;
613 int64_t cluster_offset;
614 int nb_csectors;
616 ret = get_cluster_table(bs, offset, &l2_table, &l2_index);
617 if (ret < 0) {
618 return 0;
621 /* Compression can't overwrite anything. Fail if the cluster was already
622 * allocated. */
623 cluster_offset = be64_to_cpu(l2_table[l2_index]);
624 if (cluster_offset & L2E_OFFSET_MASK) {
625 qcow2_cache_put(bs, s->l2_table_cache, (void**) &l2_table);
626 return 0;
629 cluster_offset = qcow2_alloc_bytes(bs, compressed_size);
630 if (cluster_offset < 0) {
631 qcow2_cache_put(bs, s->l2_table_cache, (void**) &l2_table);
632 return 0;
635 nb_csectors = ((cluster_offset + compressed_size - 1) >> 9) -
636 (cluster_offset >> 9);
638 cluster_offset |= QCOW_OFLAG_COMPRESSED |
639 ((uint64_t)nb_csectors << s->csize_shift);
641 /* update L2 table */
643 /* compressed clusters never have the copied flag */
645 BLKDBG_EVENT(bs->file, BLKDBG_L2_UPDATE_COMPRESSED);
646 qcow2_cache_entry_mark_dirty(s->l2_table_cache, l2_table);
647 l2_table[l2_index] = cpu_to_be64(cluster_offset);
648 ret = qcow2_cache_put(bs, s->l2_table_cache, (void**) &l2_table);
649 if (ret < 0) {
650 return 0;
653 return cluster_offset;
656 static int perform_cow(BlockDriverState *bs, QCowL2Meta *m, Qcow2COWRegion *r)
658 BDRVQcowState *s = bs->opaque;
659 int ret;
661 if (r->nb_sectors == 0) {
662 return 0;
665 qemu_co_mutex_unlock(&s->lock);
666 ret = copy_sectors(bs, m->offset / BDRV_SECTOR_SIZE, m->alloc_offset,
667 r->offset / BDRV_SECTOR_SIZE,
668 r->offset / BDRV_SECTOR_SIZE + r->nb_sectors);
669 qemu_co_mutex_lock(&s->lock);
671 if (ret < 0) {
672 return ret;
676 * Before we update the L2 table to actually point to the new cluster, we
677 * need to be sure that the refcounts have been increased and COW was
678 * handled.
680 qcow2_cache_depends_on_flush(s->l2_table_cache);
682 return 0;
685 int qcow2_alloc_cluster_link_l2(BlockDriverState *bs, QCowL2Meta *m)
687 BDRVQcowState *s = bs->opaque;
688 int i, j = 0, l2_index, ret;
689 uint64_t *old_cluster, *l2_table;
690 uint64_t cluster_offset = m->alloc_offset;
692 trace_qcow2_cluster_link_l2(qemu_coroutine_self(), m->nb_clusters);
693 assert(m->nb_clusters > 0);
695 old_cluster = g_malloc(m->nb_clusters * sizeof(uint64_t));
697 /* copy content of unmodified sectors */
698 ret = perform_cow(bs, m, &m->cow_start);
699 if (ret < 0) {
700 goto err;
703 ret = perform_cow(bs, m, &m->cow_end);
704 if (ret < 0) {
705 goto err;
708 /* Update L2 table. */
709 if (s->use_lazy_refcounts) {
710 qcow2_mark_dirty(bs);
712 if (qcow2_need_accurate_refcounts(s)) {
713 qcow2_cache_set_dependency(bs, s->l2_table_cache,
714 s->refcount_block_cache);
717 ret = get_cluster_table(bs, m->offset, &l2_table, &l2_index);
718 if (ret < 0) {
719 goto err;
721 qcow2_cache_entry_mark_dirty(s->l2_table_cache, l2_table);
723 assert(l2_index + m->nb_clusters <= s->l2_size);
724 for (i = 0; i < m->nb_clusters; i++) {
725 /* if two concurrent writes happen to the same unallocated cluster
726 * each write allocates separate cluster and writes data concurrently.
727 * The first one to complete updates l2 table with pointer to its
728 * cluster the second one has to do RMW (which is done above by
729 * copy_sectors()), update l2 table with its cluster pointer and free
730 * old cluster. This is what this loop does */
731 if(l2_table[l2_index + i] != 0)
732 old_cluster[j++] = l2_table[l2_index + i];
734 l2_table[l2_index + i] = cpu_to_be64((cluster_offset +
735 (i << s->cluster_bits)) | QCOW_OFLAG_COPIED);
739 ret = qcow2_cache_put(bs, s->l2_table_cache, (void**) &l2_table);
740 if (ret < 0) {
741 goto err;
745 * If this was a COW, we need to decrease the refcount of the old cluster.
746 * Also flush bs->file to get the right order for L2 and refcount update.
748 * Don't discard clusters that reach a refcount of 0 (e.g. compressed
749 * clusters), the next write will reuse them anyway.
751 if (j != 0) {
752 for (i = 0; i < j; i++) {
753 qcow2_free_any_clusters(bs, be64_to_cpu(old_cluster[i]), 1,
754 QCOW2_DISCARD_NEVER);
758 ret = 0;
759 err:
760 g_free(old_cluster);
761 return ret;
765 * Returns the number of contiguous clusters that can be used for an allocating
766 * write, but require COW to be performed (this includes yet unallocated space,
767 * which must copy from the backing file)
769 static int count_cow_clusters(BDRVQcowState *s, int nb_clusters,
770 uint64_t *l2_table, int l2_index)
772 int i;
774 for (i = 0; i < nb_clusters; i++) {
775 uint64_t l2_entry = be64_to_cpu(l2_table[l2_index + i]);
776 int cluster_type = qcow2_get_cluster_type(l2_entry);
778 switch(cluster_type) {
779 case QCOW2_CLUSTER_NORMAL:
780 if (l2_entry & QCOW_OFLAG_COPIED) {
781 goto out;
783 break;
784 case QCOW2_CLUSTER_UNALLOCATED:
785 case QCOW2_CLUSTER_COMPRESSED:
786 case QCOW2_CLUSTER_ZERO:
787 break;
788 default:
789 abort();
793 out:
794 assert(i <= nb_clusters);
795 return i;
799 * Check if there already is an AIO write request in flight which allocates
800 * the same cluster. In this case we need to wait until the previous
801 * request has completed and updated the L2 table accordingly.
803 * Returns:
804 * 0 if there was no dependency. *cur_bytes indicates the number of
805 * bytes from guest_offset that can be read before the next
806 * dependency must be processed (or the request is complete)
808 * -EAGAIN if we had to wait for another request, previously gathered
809 * information on cluster allocation may be invalid now. The caller
810 * must start over anyway, so consider *cur_bytes undefined.
812 static int handle_dependencies(BlockDriverState *bs, uint64_t guest_offset,
813 uint64_t *cur_bytes, QCowL2Meta **m)
815 BDRVQcowState *s = bs->opaque;
816 QCowL2Meta *old_alloc;
817 uint64_t bytes = *cur_bytes;
819 QLIST_FOREACH(old_alloc, &s->cluster_allocs, next_in_flight) {
821 uint64_t start = guest_offset;
822 uint64_t end = start + bytes;
823 uint64_t old_start = l2meta_cow_start(old_alloc);
824 uint64_t old_end = l2meta_cow_end(old_alloc);
826 if (end <= old_start || start >= old_end) {
827 /* No intersection */
828 } else {
829 if (start < old_start) {
830 /* Stop at the start of a running allocation */
831 bytes = old_start - start;
832 } else {
833 bytes = 0;
836 /* Stop if already an l2meta exists. After yielding, it wouldn't
837 * be valid any more, so we'd have to clean up the old L2Metas
838 * and deal with requests depending on them before starting to
839 * gather new ones. Not worth the trouble. */
840 if (bytes == 0 && *m) {
841 *cur_bytes = 0;
842 return 0;
845 if (bytes == 0) {
846 /* Wait for the dependency to complete. We need to recheck
847 * the free/allocated clusters when we continue. */
848 qemu_co_mutex_unlock(&s->lock);
849 qemu_co_queue_wait(&old_alloc->dependent_requests);
850 qemu_co_mutex_lock(&s->lock);
851 return -EAGAIN;
856 /* Make sure that existing clusters and new allocations are only used up to
857 * the next dependency if we shortened the request above */
858 *cur_bytes = bytes;
860 return 0;
864 * Checks how many already allocated clusters that don't require a copy on
865 * write there are at the given guest_offset (up to *bytes). If
866 * *host_offset is not zero, only physically contiguous clusters beginning at
867 * this host offset are counted.
869 * Note that guest_offset may not be cluster aligned. In this case, the
870 * returned *host_offset points to exact byte referenced by guest_offset and
871 * therefore isn't cluster aligned as well.
873 * Returns:
874 * 0: if no allocated clusters are available at the given offset.
875 * *bytes is normally unchanged. It is set to 0 if the cluster
876 * is allocated and doesn't need COW, but doesn't have the right
877 * physical offset.
879 * 1: if allocated clusters that don't require a COW are available at
880 * the requested offset. *bytes may have decreased and describes
881 * the length of the area that can be written to.
883 * -errno: in error cases
885 static int handle_copied(BlockDriverState *bs, uint64_t guest_offset,
886 uint64_t *host_offset, uint64_t *bytes, QCowL2Meta **m)
888 BDRVQcowState *s = bs->opaque;
889 int l2_index;
890 uint64_t cluster_offset;
891 uint64_t *l2_table;
892 unsigned int nb_clusters;
893 unsigned int keep_clusters;
894 int ret, pret;
896 trace_qcow2_handle_copied(qemu_coroutine_self(), guest_offset, *host_offset,
897 *bytes);
899 assert(*host_offset == 0 || offset_into_cluster(s, guest_offset)
900 == offset_into_cluster(s, *host_offset));
903 * Calculate the number of clusters to look for. We stop at L2 table
904 * boundaries to keep things simple.
906 nb_clusters =
907 size_to_clusters(s, offset_into_cluster(s, guest_offset) + *bytes);
909 l2_index = offset_to_l2_index(s, guest_offset);
910 nb_clusters = MIN(nb_clusters, s->l2_size - l2_index);
912 /* Find L2 entry for the first involved cluster */
913 ret = get_cluster_table(bs, guest_offset, &l2_table, &l2_index);
914 if (ret < 0) {
915 return ret;
918 cluster_offset = be64_to_cpu(l2_table[l2_index]);
920 /* Check how many clusters are already allocated and don't need COW */
921 if (qcow2_get_cluster_type(cluster_offset) == QCOW2_CLUSTER_NORMAL
922 && (cluster_offset & QCOW_OFLAG_COPIED))
924 /* If a specific host_offset is required, check it */
925 bool offset_matches =
926 (cluster_offset & L2E_OFFSET_MASK) == *host_offset;
928 if (*host_offset != 0 && !offset_matches) {
929 *bytes = 0;
930 ret = 0;
931 goto out;
934 /* We keep all QCOW_OFLAG_COPIED clusters */
935 keep_clusters =
936 count_contiguous_clusters(nb_clusters, s->cluster_size,
937 &l2_table[l2_index],
938 QCOW_OFLAG_COPIED | QCOW_OFLAG_ZERO);
939 assert(keep_clusters <= nb_clusters);
941 *bytes = MIN(*bytes,
942 keep_clusters * s->cluster_size
943 - offset_into_cluster(s, guest_offset));
945 ret = 1;
946 } else {
947 ret = 0;
950 /* Cleanup */
951 out:
952 pret = qcow2_cache_put(bs, s->l2_table_cache, (void**) &l2_table);
953 if (pret < 0) {
954 return pret;
957 /* Only return a host offset if we actually made progress. Otherwise we
958 * would make requirements for handle_alloc() that it can't fulfill */
959 if (ret) {
960 *host_offset = (cluster_offset & L2E_OFFSET_MASK)
961 + offset_into_cluster(s, guest_offset);
964 return ret;
968 * Allocates new clusters for the given guest_offset.
970 * At most *nb_clusters are allocated, and on return *nb_clusters is updated to
971 * contain the number of clusters that have been allocated and are contiguous
972 * in the image file.
974 * If *host_offset is non-zero, it specifies the offset in the image file at
975 * which the new clusters must start. *nb_clusters can be 0 on return in this
976 * case if the cluster at host_offset is already in use. If *host_offset is
977 * zero, the clusters can be allocated anywhere in the image file.
979 * *host_offset is updated to contain the offset into the image file at which
980 * the first allocated cluster starts.
982 * Return 0 on success and -errno in error cases. -EAGAIN means that the
983 * function has been waiting for another request and the allocation must be
984 * restarted, but the whole request should not be failed.
986 static int do_alloc_cluster_offset(BlockDriverState *bs, uint64_t guest_offset,
987 uint64_t *host_offset, unsigned int *nb_clusters)
989 BDRVQcowState *s = bs->opaque;
991 trace_qcow2_do_alloc_clusters_offset(qemu_coroutine_self(), guest_offset,
992 *host_offset, *nb_clusters);
994 /* Allocate new clusters */
995 trace_qcow2_cluster_alloc_phys(qemu_coroutine_self());
996 if (*host_offset == 0) {
997 int64_t cluster_offset =
998 qcow2_alloc_clusters(bs, *nb_clusters * s->cluster_size);
999 if (cluster_offset < 0) {
1000 return cluster_offset;
1002 *host_offset = cluster_offset;
1003 return 0;
1004 } else {
1005 int ret = qcow2_alloc_clusters_at(bs, *host_offset, *nb_clusters);
1006 if (ret < 0) {
1007 return ret;
1009 *nb_clusters = ret;
1010 return 0;
1015 * Allocates new clusters for an area that either is yet unallocated or needs a
1016 * copy on write. If *host_offset is non-zero, clusters are only allocated if
1017 * the new allocation can match the specified host offset.
1019 * Note that guest_offset may not be cluster aligned. In this case, the
1020 * returned *host_offset points to exact byte referenced by guest_offset and
1021 * therefore isn't cluster aligned as well.
1023 * Returns:
1024 * 0: if no clusters could be allocated. *bytes is set to 0,
1025 * *host_offset is left unchanged.
1027 * 1: if new clusters were allocated. *bytes may be decreased if the
1028 * new allocation doesn't cover all of the requested area.
1029 * *host_offset is updated to contain the host offset of the first
1030 * newly allocated cluster.
1032 * -errno: in error cases
1034 static int handle_alloc(BlockDriverState *bs, uint64_t guest_offset,
1035 uint64_t *host_offset, uint64_t *bytes, QCowL2Meta **m)
1037 BDRVQcowState *s = bs->opaque;
1038 int l2_index;
1039 uint64_t *l2_table;
1040 uint64_t entry;
1041 unsigned int nb_clusters;
1042 int ret;
1044 uint64_t alloc_cluster_offset;
1046 trace_qcow2_handle_alloc(qemu_coroutine_self(), guest_offset, *host_offset,
1047 *bytes);
1048 assert(*bytes > 0);
1051 * Calculate the number of clusters to look for. We stop at L2 table
1052 * boundaries to keep things simple.
1054 nb_clusters =
1055 size_to_clusters(s, offset_into_cluster(s, guest_offset) + *bytes);
1057 l2_index = offset_to_l2_index(s, guest_offset);
1058 nb_clusters = MIN(nb_clusters, s->l2_size - l2_index);
1060 /* Find L2 entry for the first involved cluster */
1061 ret = get_cluster_table(bs, guest_offset, &l2_table, &l2_index);
1062 if (ret < 0) {
1063 return ret;
1066 entry = be64_to_cpu(l2_table[l2_index]);
1068 /* For the moment, overwrite compressed clusters one by one */
1069 if (entry & QCOW_OFLAG_COMPRESSED) {
1070 nb_clusters = 1;
1071 } else {
1072 nb_clusters = count_cow_clusters(s, nb_clusters, l2_table, l2_index);
1075 /* This function is only called when there were no non-COW clusters, so if
1076 * we can't find any unallocated or COW clusters either, something is
1077 * wrong with our code. */
1078 assert(nb_clusters > 0);
1080 ret = qcow2_cache_put(bs, s->l2_table_cache, (void**) &l2_table);
1081 if (ret < 0) {
1082 return ret;
1085 /* Allocate, if necessary at a given offset in the image file */
1086 alloc_cluster_offset = start_of_cluster(s, *host_offset);
1087 ret = do_alloc_cluster_offset(bs, guest_offset, &alloc_cluster_offset,
1088 &nb_clusters);
1089 if (ret < 0) {
1090 goto fail;
1093 /* Can't extend contiguous allocation */
1094 if (nb_clusters == 0) {
1095 *bytes = 0;
1096 return 0;
1100 * Save info needed for meta data update.
1102 * requested_sectors: Number of sectors from the start of the first
1103 * newly allocated cluster to the end of the (possibly shortened
1104 * before) write request.
1106 * avail_sectors: Number of sectors from the start of the first
1107 * newly allocated to the end of the last newly allocated cluster.
1109 * nb_sectors: The number of sectors from the start of the first
1110 * newly allocated cluster to the end of the area that the write
1111 * request actually writes to (excluding COW at the end)
1113 int requested_sectors =
1114 (*bytes + offset_into_cluster(s, guest_offset))
1115 >> BDRV_SECTOR_BITS;
1116 int avail_sectors = nb_clusters
1117 << (s->cluster_bits - BDRV_SECTOR_BITS);
1118 int alloc_n_start = offset_into_cluster(s, guest_offset)
1119 >> BDRV_SECTOR_BITS;
1120 int nb_sectors = MIN(requested_sectors, avail_sectors);
1121 QCowL2Meta *old_m = *m;
1123 *m = g_malloc0(sizeof(**m));
1125 **m = (QCowL2Meta) {
1126 .next = old_m,
1128 .alloc_offset = alloc_cluster_offset,
1129 .offset = start_of_cluster(s, guest_offset),
1130 .nb_clusters = nb_clusters,
1131 .nb_available = nb_sectors,
1133 .cow_start = {
1134 .offset = 0,
1135 .nb_sectors = alloc_n_start,
1137 .cow_end = {
1138 .offset = nb_sectors * BDRV_SECTOR_SIZE,
1139 .nb_sectors = avail_sectors - nb_sectors,
1142 qemu_co_queue_init(&(*m)->dependent_requests);
1143 QLIST_INSERT_HEAD(&s->cluster_allocs, *m, next_in_flight);
1145 *host_offset = alloc_cluster_offset + offset_into_cluster(s, guest_offset);
1146 *bytes = MIN(*bytes, (nb_sectors * BDRV_SECTOR_SIZE)
1147 - offset_into_cluster(s, guest_offset));
1148 assert(*bytes != 0);
1150 return 1;
1152 fail:
1153 if (*m && (*m)->nb_clusters > 0) {
1154 QLIST_REMOVE(*m, next_in_flight);
1156 return ret;
1160 * alloc_cluster_offset
1162 * For a given offset on the virtual disk, find the cluster offset in qcow2
1163 * file. If the offset is not found, allocate a new cluster.
1165 * If the cluster was already allocated, m->nb_clusters is set to 0 and
1166 * other fields in m are meaningless.
1168 * If the cluster is newly allocated, m->nb_clusters is set to the number of
1169 * contiguous clusters that have been allocated. In this case, the other
1170 * fields of m are valid and contain information about the first allocated
1171 * cluster.
1173 * If the request conflicts with another write request in flight, the coroutine
1174 * is queued and will be reentered when the dependency has completed.
1176 * Return 0 on success and -errno in error cases
1178 int qcow2_alloc_cluster_offset(BlockDriverState *bs, uint64_t offset,
1179 int n_start, int n_end, int *num, uint64_t *host_offset, QCowL2Meta **m)
1181 BDRVQcowState *s = bs->opaque;
1182 uint64_t start, remaining;
1183 uint64_t cluster_offset;
1184 uint64_t cur_bytes;
1185 int ret;
1187 trace_qcow2_alloc_clusters_offset(qemu_coroutine_self(), offset,
1188 n_start, n_end);
1190 assert(n_start * BDRV_SECTOR_SIZE == offset_into_cluster(s, offset));
1191 offset = start_of_cluster(s, offset);
1193 again:
1194 start = offset + (n_start << BDRV_SECTOR_BITS);
1195 remaining = (n_end - n_start) << BDRV_SECTOR_BITS;
1196 cluster_offset = 0;
1197 *host_offset = 0;
1198 cur_bytes = 0;
1199 *m = NULL;
1201 while (true) {
1203 if (!*host_offset) {
1204 *host_offset = start_of_cluster(s, cluster_offset);
1207 assert(remaining >= cur_bytes);
1209 start += cur_bytes;
1210 remaining -= cur_bytes;
1211 cluster_offset += cur_bytes;
1213 if (remaining == 0) {
1214 break;
1217 cur_bytes = remaining;
1220 * Now start gathering as many contiguous clusters as possible:
1222 * 1. Check for overlaps with in-flight allocations
1224 * a) Overlap not in the first cluster -> shorten this request and
1225 * let the caller handle the rest in its next loop iteration.
1227 * b) Real overlaps of two requests. Yield and restart the search
1228 * for contiguous clusters (the situation could have changed
1229 * while we were sleeping)
1231 * c) TODO: Request starts in the same cluster as the in-flight
1232 * allocation ends. Shorten the COW of the in-fight allocation,
1233 * set cluster_offset to write to the same cluster and set up
1234 * the right synchronisation between the in-flight request and
1235 * the new one.
1237 ret = handle_dependencies(bs, start, &cur_bytes, m);
1238 if (ret == -EAGAIN) {
1239 /* Currently handle_dependencies() doesn't yield if we already had
1240 * an allocation. If it did, we would have to clean up the L2Meta
1241 * structs before starting over. */
1242 assert(*m == NULL);
1243 goto again;
1244 } else if (ret < 0) {
1245 return ret;
1246 } else if (cur_bytes == 0) {
1247 break;
1248 } else {
1249 /* handle_dependencies() may have decreased cur_bytes (shortened
1250 * the allocations below) so that the next dependency is processed
1251 * correctly during the next loop iteration. */
1255 * 2. Count contiguous COPIED clusters.
1257 ret = handle_copied(bs, start, &cluster_offset, &cur_bytes, m);
1258 if (ret < 0) {
1259 return ret;
1260 } else if (ret) {
1261 continue;
1262 } else if (cur_bytes == 0) {
1263 break;
1267 * 3. If the request still hasn't completed, allocate new clusters,
1268 * considering any cluster_offset of steps 1c or 2.
1270 ret = handle_alloc(bs, start, &cluster_offset, &cur_bytes, m);
1271 if (ret < 0) {
1272 return ret;
1273 } else if (ret) {
1274 continue;
1275 } else {
1276 assert(cur_bytes == 0);
1277 break;
1281 *num = (n_end - n_start) - (remaining >> BDRV_SECTOR_BITS);
1282 assert(*num > 0);
1283 assert(*host_offset != 0);
1285 return 0;
1288 static int decompress_buffer(uint8_t *out_buf, int out_buf_size,
1289 const uint8_t *buf, int buf_size)
1291 z_stream strm1, *strm = &strm1;
1292 int ret, out_len;
1294 memset(strm, 0, sizeof(*strm));
1296 strm->next_in = (uint8_t *)buf;
1297 strm->avail_in = buf_size;
1298 strm->next_out = out_buf;
1299 strm->avail_out = out_buf_size;
1301 ret = inflateInit2(strm, -12);
1302 if (ret != Z_OK)
1303 return -1;
1304 ret = inflate(strm, Z_FINISH);
1305 out_len = strm->next_out - out_buf;
1306 if ((ret != Z_STREAM_END && ret != Z_BUF_ERROR) ||
1307 out_len != out_buf_size) {
1308 inflateEnd(strm);
1309 return -1;
1311 inflateEnd(strm);
1312 return 0;
1315 int qcow2_decompress_cluster(BlockDriverState *bs, uint64_t cluster_offset)
1317 BDRVQcowState *s = bs->opaque;
1318 int ret, csize, nb_csectors, sector_offset;
1319 uint64_t coffset;
1321 coffset = cluster_offset & s->cluster_offset_mask;
1322 if (s->cluster_cache_offset != coffset) {
1323 nb_csectors = ((cluster_offset >> s->csize_shift) & s->csize_mask) + 1;
1324 sector_offset = coffset & 511;
1325 csize = nb_csectors * 512 - sector_offset;
1326 BLKDBG_EVENT(bs->file, BLKDBG_READ_COMPRESSED);
1327 ret = bdrv_read(bs->file, coffset >> 9, s->cluster_data, nb_csectors);
1328 if (ret < 0) {
1329 return ret;
1331 if (decompress_buffer(s->cluster_cache, s->cluster_size,
1332 s->cluster_data + sector_offset, csize) < 0) {
1333 return -EIO;
1335 s->cluster_cache_offset = coffset;
1337 return 0;
1341 * This discards as many clusters of nb_clusters as possible at once (i.e.
1342 * all clusters in the same L2 table) and returns the number of discarded
1343 * clusters.
1345 static int discard_single_l2(BlockDriverState *bs, uint64_t offset,
1346 unsigned int nb_clusters, enum qcow2_discard_type type)
1348 BDRVQcowState *s = bs->opaque;
1349 uint64_t *l2_table;
1350 int l2_index;
1351 int ret;
1352 int i;
1354 ret = get_cluster_table(bs, offset, &l2_table, &l2_index);
1355 if (ret < 0) {
1356 return ret;
1359 /* Limit nb_clusters to one L2 table */
1360 nb_clusters = MIN(nb_clusters, s->l2_size - l2_index);
1362 for (i = 0; i < nb_clusters; i++) {
1363 uint64_t old_offset;
1365 old_offset = be64_to_cpu(l2_table[l2_index + i]);
1366 if ((old_offset & L2E_OFFSET_MASK) == 0) {
1367 continue;
1370 /* First remove L2 entries */
1371 qcow2_cache_entry_mark_dirty(s->l2_table_cache, l2_table);
1372 l2_table[l2_index + i] = cpu_to_be64(0);
1374 /* Then decrease the refcount */
1375 qcow2_free_any_clusters(bs, old_offset, 1, type);
1378 ret = qcow2_cache_put(bs, s->l2_table_cache, (void**) &l2_table);
1379 if (ret < 0) {
1380 return ret;
1383 return nb_clusters;
1386 int qcow2_discard_clusters(BlockDriverState *bs, uint64_t offset,
1387 int nb_sectors, enum qcow2_discard_type type)
1389 BDRVQcowState *s = bs->opaque;
1390 uint64_t end_offset;
1391 unsigned int nb_clusters;
1392 int ret;
1394 end_offset = offset + (nb_sectors << BDRV_SECTOR_BITS);
1396 /* Round start up and end down */
1397 offset = align_offset(offset, s->cluster_size);
1398 end_offset &= ~(s->cluster_size - 1);
1400 if (offset > end_offset) {
1401 return 0;
1404 nb_clusters = size_to_clusters(s, end_offset - offset);
1406 s->cache_discards = true;
1408 /* Each L2 table is handled by its own loop iteration */
1409 while (nb_clusters > 0) {
1410 ret = discard_single_l2(bs, offset, nb_clusters, type);
1411 if (ret < 0) {
1412 goto fail;
1415 nb_clusters -= ret;
1416 offset += (ret * s->cluster_size);
1419 ret = 0;
1420 fail:
1421 s->cache_discards = false;
1422 qcow2_process_discards(bs, ret);
1424 return ret;
1428 * This zeroes as many clusters of nb_clusters as possible at once (i.e.
1429 * all clusters in the same L2 table) and returns the number of zeroed
1430 * clusters.
1432 static int zero_single_l2(BlockDriverState *bs, uint64_t offset,
1433 unsigned int nb_clusters)
1435 BDRVQcowState *s = bs->opaque;
1436 uint64_t *l2_table;
1437 int l2_index;
1438 int ret;
1439 int i;
1441 ret = get_cluster_table(bs, offset, &l2_table, &l2_index);
1442 if (ret < 0) {
1443 return ret;
1446 /* Limit nb_clusters to one L2 table */
1447 nb_clusters = MIN(nb_clusters, s->l2_size - l2_index);
1449 for (i = 0; i < nb_clusters; i++) {
1450 uint64_t old_offset;
1452 old_offset = be64_to_cpu(l2_table[l2_index + i]);
1454 /* Update L2 entries */
1455 qcow2_cache_entry_mark_dirty(s->l2_table_cache, l2_table);
1456 if (old_offset & QCOW_OFLAG_COMPRESSED) {
1457 l2_table[l2_index + i] = cpu_to_be64(QCOW_OFLAG_ZERO);
1458 qcow2_free_any_clusters(bs, old_offset, 1, QCOW2_DISCARD_REQUEST);
1459 } else {
1460 l2_table[l2_index + i] |= cpu_to_be64(QCOW_OFLAG_ZERO);
1464 ret = qcow2_cache_put(bs, s->l2_table_cache, (void**) &l2_table);
1465 if (ret < 0) {
1466 return ret;
1469 return nb_clusters;
1472 int qcow2_zero_clusters(BlockDriverState *bs, uint64_t offset, int nb_sectors)
1474 BDRVQcowState *s = bs->opaque;
1475 unsigned int nb_clusters;
1476 int ret;
1478 /* The zero flag is only supported by version 3 and newer */
1479 if (s->qcow_version < 3) {
1480 return -ENOTSUP;
1483 /* Each L2 table is handled by its own loop iteration */
1484 nb_clusters = size_to_clusters(s, nb_sectors << BDRV_SECTOR_BITS);
1486 s->cache_discards = true;
1488 while (nb_clusters > 0) {
1489 ret = zero_single_l2(bs, offset, nb_clusters);
1490 if (ret < 0) {
1491 goto fail;
1494 nb_clusters -= ret;
1495 offset += (ret * s->cluster_size);
1498 ret = 0;
1499 fail:
1500 s->cache_discards = false;
1501 qcow2_process_discards(bs, ret);
1503 return ret;
1507 * Expands all zero clusters in a specific L1 table (or deallocates them, for
1508 * non-backed non-pre-allocated zero clusters).
1510 * expanded_clusters is a bitmap where every bit corresponds to one cluster in
1511 * the image file; a bit gets set if the corresponding cluster has been used for
1512 * zero expansion (i.e., has been filled with zeroes and is referenced from an
1513 * L2 table). nb_clusters contains the total cluster count of the image file,
1514 * i.e., the number of bits in expanded_clusters.
1516 static int expand_zero_clusters_in_l1(BlockDriverState *bs, uint64_t *l1_table,
1517 int l1_size, uint8_t **expanded_clusters,
1518 uint64_t *nb_clusters)
1520 BDRVQcowState *s = bs->opaque;
1521 bool is_active_l1 = (l1_table == s->l1_table);
1522 uint64_t *l2_table = NULL;
1523 int ret;
1524 int i, j;
1526 if (!is_active_l1) {
1527 /* inactive L2 tables require a buffer to be stored in when loading
1528 * them from disk */
1529 l2_table = qemu_blockalign(bs, s->cluster_size);
1532 for (i = 0; i < l1_size; i++) {
1533 uint64_t l2_offset = l1_table[i] & L1E_OFFSET_MASK;
1534 bool l2_dirty = false;
1536 if (!l2_offset) {
1537 /* unallocated */
1538 continue;
1541 if (is_active_l1) {
1542 /* get active L2 tables from cache */
1543 ret = qcow2_cache_get(bs, s->l2_table_cache, l2_offset,
1544 (void **)&l2_table);
1545 } else {
1546 /* load inactive L2 tables from disk */
1547 ret = bdrv_read(bs->file, l2_offset / BDRV_SECTOR_SIZE,
1548 (void *)l2_table, s->cluster_sectors);
1550 if (ret < 0) {
1551 goto fail;
1554 for (j = 0; j < s->l2_size; j++) {
1555 uint64_t l2_entry = be64_to_cpu(l2_table[j]);
1556 int64_t offset = l2_entry & L2E_OFFSET_MASK, cluster_index;
1557 int cluster_type = qcow2_get_cluster_type(l2_entry);
1558 bool preallocated = offset != 0;
1560 if (cluster_type == QCOW2_CLUSTER_NORMAL) {
1561 cluster_index = offset >> s->cluster_bits;
1562 assert((cluster_index >= 0) && (cluster_index < *nb_clusters));
1563 if ((*expanded_clusters)[cluster_index / 8] &
1564 (1 << (cluster_index % 8))) {
1565 /* Probably a shared L2 table; this cluster was a zero
1566 * cluster which has been expanded, its refcount
1567 * therefore most likely requires an update. */
1568 ret = qcow2_update_cluster_refcount(bs, cluster_index, 1,
1569 QCOW2_DISCARD_NEVER);
1570 if (ret < 0) {
1571 goto fail;
1573 /* Since we just increased the refcount, the COPIED flag may
1574 * no longer be set. */
1575 l2_table[j] = cpu_to_be64(l2_entry & ~QCOW_OFLAG_COPIED);
1576 l2_dirty = true;
1578 continue;
1580 else if (qcow2_get_cluster_type(l2_entry) != QCOW2_CLUSTER_ZERO) {
1581 continue;
1584 if (!preallocated) {
1585 if (!bs->backing_hd) {
1586 /* not backed; therefore we can simply deallocate the
1587 * cluster */
1588 l2_table[j] = 0;
1589 l2_dirty = true;
1590 continue;
1593 offset = qcow2_alloc_clusters(bs, s->cluster_size);
1594 if (offset < 0) {
1595 ret = offset;
1596 goto fail;
1600 ret = qcow2_pre_write_overlap_check(bs, QCOW2_OL_DEFAULT,
1601 offset, s->cluster_size);
1602 if (ret < 0) {
1603 if (!preallocated) {
1604 qcow2_free_clusters(bs, offset, s->cluster_size,
1605 QCOW2_DISCARD_ALWAYS);
1607 goto fail;
1610 ret = bdrv_write_zeroes(bs->file, offset / BDRV_SECTOR_SIZE,
1611 s->cluster_sectors);
1612 if (ret < 0) {
1613 if (!preallocated) {
1614 qcow2_free_clusters(bs, offset, s->cluster_size,
1615 QCOW2_DISCARD_ALWAYS);
1617 goto fail;
1620 l2_table[j] = cpu_to_be64(offset | QCOW_OFLAG_COPIED);
1621 l2_dirty = true;
1623 cluster_index = offset >> s->cluster_bits;
1625 if (cluster_index >= *nb_clusters) {
1626 uint64_t old_bitmap_size = (*nb_clusters + 7) / 8;
1627 uint64_t new_bitmap_size;
1628 /* The offset may lie beyond the old end of the underlying image
1629 * file for growable files only */
1630 assert(bs->file->growable);
1631 *nb_clusters = size_to_clusters(s, bs->file->total_sectors *
1632 BDRV_SECTOR_SIZE);
1633 new_bitmap_size = (*nb_clusters + 7) / 8;
1634 *expanded_clusters = g_realloc(*expanded_clusters,
1635 new_bitmap_size);
1636 /* clear the newly allocated space */
1637 memset(&(*expanded_clusters)[old_bitmap_size], 0,
1638 new_bitmap_size - old_bitmap_size);
1641 assert((cluster_index >= 0) && (cluster_index < *nb_clusters));
1642 (*expanded_clusters)[cluster_index / 8] |= 1 << (cluster_index % 8);
1645 if (is_active_l1) {
1646 if (l2_dirty) {
1647 qcow2_cache_entry_mark_dirty(s->l2_table_cache, l2_table);
1648 qcow2_cache_depends_on_flush(s->l2_table_cache);
1650 ret = qcow2_cache_put(bs, s->l2_table_cache, (void **)&l2_table);
1651 if (ret < 0) {
1652 l2_table = NULL;
1653 goto fail;
1655 } else {
1656 if (l2_dirty) {
1657 ret = qcow2_pre_write_overlap_check(bs, QCOW2_OL_DEFAULT &
1658 ~(QCOW2_OL_INACTIVE_L2 | QCOW2_OL_ACTIVE_L2), l2_offset,
1659 s->cluster_size);
1660 if (ret < 0) {
1661 goto fail;
1664 ret = bdrv_write(bs->file, l2_offset / BDRV_SECTOR_SIZE,
1665 (void *)l2_table, s->cluster_sectors);
1666 if (ret < 0) {
1667 goto fail;
1673 ret = 0;
1675 fail:
1676 if (l2_table) {
1677 if (!is_active_l1) {
1678 qemu_vfree(l2_table);
1679 } else {
1680 if (ret < 0) {
1681 qcow2_cache_put(bs, s->l2_table_cache, (void **)&l2_table);
1682 } else {
1683 ret = qcow2_cache_put(bs, s->l2_table_cache,
1684 (void **)&l2_table);
1688 return ret;
1692 * For backed images, expands all zero clusters on the image. For non-backed
1693 * images, deallocates all non-pre-allocated zero clusters (and claims the
1694 * allocation for pre-allocated ones). This is important for downgrading to a
1695 * qcow2 version which doesn't yet support metadata zero clusters.
1697 int qcow2_expand_zero_clusters(BlockDriverState *bs)
1699 BDRVQcowState *s = bs->opaque;
1700 uint64_t *l1_table = NULL;
1701 uint64_t nb_clusters;
1702 uint8_t *expanded_clusters;
1703 int ret;
1704 int i, j;
1706 nb_clusters = size_to_clusters(s, bs->file->total_sectors *
1707 BDRV_SECTOR_SIZE);
1708 expanded_clusters = g_malloc0((nb_clusters + 7) / 8);
1710 ret = expand_zero_clusters_in_l1(bs, s->l1_table, s->l1_size,
1711 &expanded_clusters, &nb_clusters);
1712 if (ret < 0) {
1713 goto fail;
1716 /* Inactive L1 tables may point to active L2 tables - therefore it is
1717 * necessary to flush the L2 table cache before trying to access the L2
1718 * tables pointed to by inactive L1 entries (else we might try to expand
1719 * zero clusters that have already been expanded); furthermore, it is also
1720 * necessary to empty the L2 table cache, since it may contain tables which
1721 * are now going to be modified directly on disk, bypassing the cache.
1722 * qcow2_cache_empty() does both for us. */
1723 ret = qcow2_cache_empty(bs, s->l2_table_cache);
1724 if (ret < 0) {
1725 goto fail;
1728 for (i = 0; i < s->nb_snapshots; i++) {
1729 int l1_sectors = (s->snapshots[i].l1_size * sizeof(uint64_t) +
1730 BDRV_SECTOR_SIZE - 1) / BDRV_SECTOR_SIZE;
1732 l1_table = g_realloc(l1_table, l1_sectors * BDRV_SECTOR_SIZE);
1734 ret = bdrv_read(bs->file, s->snapshots[i].l1_table_offset /
1735 BDRV_SECTOR_SIZE, (void *)l1_table, l1_sectors);
1736 if (ret < 0) {
1737 goto fail;
1740 for (j = 0; j < s->snapshots[i].l1_size; j++) {
1741 be64_to_cpus(&l1_table[j]);
1744 ret = expand_zero_clusters_in_l1(bs, l1_table, s->snapshots[i].l1_size,
1745 &expanded_clusters, &nb_clusters);
1746 if (ret < 0) {
1747 goto fail;
1751 ret = 0;
1753 fail:
1754 g_free(expanded_clusters);
1755 g_free(l1_table);
1756 return ret;