]> git.proxmox.com Git - mirror_qemu.git/blame - block/qcow2-cluster.c
qcow2: Make perform_cow() call do_perform_cow() twice
[mirror_qemu.git] / block / qcow2-cluster.c
CommitLineData
45aba42f
KW
1/*
2 * Block driver for the QCOW version 2 format
3 *
4 * Copyright (c) 2004-2006 Fabrice Bellard
5 *
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:
12 *
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
15 *
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.
23 */
24
80c71a24 25#include "qemu/osdep.h"
45aba42f
KW
26#include <zlib.h>
27
da34e65c 28#include "qapi/error.h"
45aba42f 29#include "qemu-common.h"
737e150e 30#include "block/block_int.h"
45aba42f 31#include "block/qcow2.h"
58369e22 32#include "qemu/bswap.h"
3cce16f4 33#include "trace.h"
45aba42f 34
2cf7cfa1
KW
35int qcow2_grow_l1_table(BlockDriverState *bs, uint64_t min_size,
36 bool exact_size)
45aba42f 37{
ff99129a 38 BDRVQcow2State *s = bs->opaque;
2cf7cfa1 39 int new_l1_size2, ret, i;
45aba42f 40 uint64_t *new_l1_table;
fda74f82 41 int64_t old_l1_table_offset, old_l1_size;
2cf7cfa1 42 int64_t new_l1_table_offset, new_l1_size;
45aba42f
KW
43 uint8_t data[12];
44
72893756 45 if (min_size <= s->l1_size)
45aba42f 46 return 0;
72893756 47
b93f9950
HR
48 /* Do a sanity check on min_size before trying to calculate new_l1_size
49 * (this prevents overflows during the while loop for the calculation of
50 * new_l1_size) */
51 if (min_size > INT_MAX / sizeof(uint64_t)) {
52 return -EFBIG;
53 }
54
72893756
SH
55 if (exact_size) {
56 new_l1_size = min_size;
57 } else {
58 /* Bump size up to reduce the number of times we have to grow */
59 new_l1_size = s->l1_size;
60 if (new_l1_size == 0) {
61 new_l1_size = 1;
62 }
63 while (min_size > new_l1_size) {
64 new_l1_size = (new_l1_size * 3 + 1) / 2;
65 }
45aba42f 66 }
72893756 67
84c26520
HR
68 QEMU_BUILD_BUG_ON(QCOW_MAX_L1_SIZE > INT_MAX);
69 if (new_l1_size > QCOW_MAX_L1_SIZE / sizeof(uint64_t)) {
2cf7cfa1
KW
70 return -EFBIG;
71 }
72
45aba42f 73#ifdef DEBUG_ALLOC2
2cf7cfa1
KW
74 fprintf(stderr, "grow l1_table from %d to %" PRId64 "\n",
75 s->l1_size, new_l1_size);
45aba42f
KW
76#endif
77
78 new_l1_size2 = sizeof(uint64_t) * new_l1_size;
9a4f4c31 79 new_l1_table = qemu_try_blockalign(bs->file->bs,
de82815d
KW
80 align_offset(new_l1_size2, 512));
81 if (new_l1_table == NULL) {
82 return -ENOMEM;
83 }
84 memset(new_l1_table, 0, align_offset(new_l1_size2, 512));
85
0647d47c
SH
86 if (s->l1_size) {
87 memcpy(new_l1_table, s->l1_table, s->l1_size * sizeof(uint64_t));
88 }
45aba42f
KW
89
90 /* write new table (align to cluster) */
66f82cee 91 BLKDBG_EVENT(bs->file, BLKDBG_L1_GROW_ALLOC_TABLE);
ed6ccf0f 92 new_l1_table_offset = qcow2_alloc_clusters(bs, new_l1_size2);
5d757b56 93 if (new_l1_table_offset < 0) {
de82815d 94 qemu_vfree(new_l1_table);
5d757b56
KW
95 return new_l1_table_offset;
96 }
29c1a730
KW
97
98 ret = qcow2_cache_flush(bs, s->refcount_block_cache);
99 if (ret < 0) {
80fa3341 100 goto fail;
29c1a730 101 }
45aba42f 102
cf93980e
HR
103 /* the L1 position has not yet been updated, so these clusters must
104 * indeed be completely free */
231bb267
HR
105 ret = qcow2_pre_write_overlap_check(bs, 0, new_l1_table_offset,
106 new_l1_size2);
cf93980e
HR
107 if (ret < 0) {
108 goto fail;
109 }
110
66f82cee 111 BLKDBG_EVENT(bs->file, BLKDBG_L1_GROW_WRITE_TABLE);
45aba42f
KW
112 for(i = 0; i < s->l1_size; i++)
113 new_l1_table[i] = cpu_to_be64(new_l1_table[i]);
d9ca2ea2 114 ret = bdrv_pwrite_sync(bs->file, new_l1_table_offset,
9a4f4c31 115 new_l1_table, new_l1_size2);
8b3b7206 116 if (ret < 0)
45aba42f
KW
117 goto fail;
118 for(i = 0; i < s->l1_size; i++)
119 new_l1_table[i] = be64_to_cpu(new_l1_table[i]);
120
121 /* set new table */
66f82cee 122 BLKDBG_EVENT(bs->file, BLKDBG_L1_GROW_ACTIVATE_TABLE);
f1f7a1dd 123 stl_be_p(data, new_l1_size);
e4ef9f46 124 stq_be_p(data + 4, new_l1_table_offset);
d9ca2ea2 125 ret = bdrv_pwrite_sync(bs->file, offsetof(QCowHeader, l1_size),
9a4f4c31 126 data, sizeof(data));
8b3b7206 127 if (ret < 0) {
45aba42f 128 goto fail;
fb8fa77c 129 }
de82815d 130 qemu_vfree(s->l1_table);
fda74f82 131 old_l1_table_offset = s->l1_table_offset;
45aba42f
KW
132 s->l1_table_offset = new_l1_table_offset;
133 s->l1_table = new_l1_table;
fda74f82 134 old_l1_size = s->l1_size;
45aba42f 135 s->l1_size = new_l1_size;
fda74f82
HR
136 qcow2_free_clusters(bs, old_l1_table_offset, old_l1_size * sizeof(uint64_t),
137 QCOW2_DISCARD_OTHER);
45aba42f
KW
138 return 0;
139 fail:
de82815d 140 qemu_vfree(new_l1_table);
6cfcb9b8
KW
141 qcow2_free_clusters(bs, new_l1_table_offset, new_l1_size2,
142 QCOW2_DISCARD_OTHER);
8b3b7206 143 return ret;
45aba42f
KW
144}
145
45aba42f
KW
146/*
147 * l2_load
148 *
149 * Loads a L2 table into memory. If the table is in the cache, the cache
150 * is used; otherwise the L2 table is loaded from the image file.
151 *
152 * Returns a pointer to the L2 table on success, or NULL if the read from
153 * the image file failed.
154 */
155
55c17e98
KW
156static int l2_load(BlockDriverState *bs, uint64_t l2_offset,
157 uint64_t **l2_table)
45aba42f 158{
ff99129a 159 BDRVQcow2State *s = bs->opaque;
45aba42f 160
9be38598
EH
161 return qcow2_cache_get(bs, s->l2_table_cache, l2_offset,
162 (void **)l2_table);
45aba42f
KW
163}
164
6583e3c7
KW
165/*
166 * Writes one sector of the L1 table to the disk (can't update single entries
167 * and we really don't want bdrv_pread to perform a read-modify-write)
168 */
169#define L1_ENTRIES_PER_SECTOR (512 / 8)
e23e400e 170int qcow2_write_l1_entry(BlockDriverState *bs, int l1_index)
6583e3c7 171{
ff99129a 172 BDRVQcow2State *s = bs->opaque;
a1391444 173 uint64_t buf[L1_ENTRIES_PER_SECTOR] = { 0 };
6583e3c7 174 int l1_start_index;
f7defcb6 175 int i, ret;
6583e3c7
KW
176
177 l1_start_index = l1_index & ~(L1_ENTRIES_PER_SECTOR - 1);
a1391444
HR
178 for (i = 0; i < L1_ENTRIES_PER_SECTOR && l1_start_index + i < s->l1_size;
179 i++)
180 {
6583e3c7
KW
181 buf[i] = cpu_to_be64(s->l1_table[l1_start_index + i]);
182 }
183
231bb267 184 ret = qcow2_pre_write_overlap_check(bs, QCOW2_OL_ACTIVE_L1,
cf93980e
HR
185 s->l1_table_offset + 8 * l1_start_index, sizeof(buf));
186 if (ret < 0) {
187 return ret;
188 }
189
66f82cee 190 BLKDBG_EVENT(bs->file, BLKDBG_L1_UPDATE);
d9ca2ea2 191 ret = bdrv_pwrite_sync(bs->file,
9a4f4c31
KW
192 s->l1_table_offset + 8 * l1_start_index,
193 buf, sizeof(buf));
f7defcb6
KW
194 if (ret < 0) {
195 return ret;
6583e3c7
KW
196 }
197
198 return 0;
199}
200
45aba42f
KW
201/*
202 * l2_allocate
203 *
204 * Allocate a new l2 entry in the file. If l1_index points to an already
205 * used entry in the L2 table (i.e. we are doing a copy on write for the L2
206 * table) copy the contents of the old L2 table into the newly allocated one.
207 * Otherwise the new table is initialized with zeros.
208 *
209 */
210
c46e1167 211static int l2_allocate(BlockDriverState *bs, int l1_index, uint64_t **table)
45aba42f 212{
ff99129a 213 BDRVQcow2State *s = bs->opaque;
6583e3c7 214 uint64_t old_l2_offset;
8585afd8 215 uint64_t *l2_table = NULL;
f4f0d391 216 int64_t l2_offset;
c46e1167 217 int ret;
45aba42f
KW
218
219 old_l2_offset = s->l1_table[l1_index];
220
3cce16f4
KW
221 trace_qcow2_l2_allocate(bs, l1_index);
222
45aba42f
KW
223 /* allocate a new l2 entry */
224
ed6ccf0f 225 l2_offset = qcow2_alloc_clusters(bs, s->l2_size * sizeof(uint64_t));
5d757b56 226 if (l2_offset < 0) {
be0b742e
HR
227 ret = l2_offset;
228 goto fail;
5d757b56 229 }
29c1a730
KW
230
231 ret = qcow2_cache_flush(bs, s->refcount_block_cache);
232 if (ret < 0) {
233 goto fail;
234 }
45aba42f 235
45aba42f
KW
236 /* allocate a new entry in the l2 cache */
237
3cce16f4 238 trace_qcow2_l2_allocate_get_empty(bs, l1_index);
29c1a730
KW
239 ret = qcow2_cache_get_empty(bs, s->l2_table_cache, l2_offset, (void**) table);
240 if (ret < 0) {
be0b742e 241 goto fail;
29c1a730
KW
242 }
243
244 l2_table = *table;
45aba42f 245
8e37f681 246 if ((old_l2_offset & L1E_OFFSET_MASK) == 0) {
45aba42f
KW
247 /* if there was no old l2 table, clear the new table */
248 memset(l2_table, 0, s->l2_size * sizeof(uint64_t));
249 } else {
29c1a730
KW
250 uint64_t* old_table;
251
45aba42f 252 /* if there was an old l2 table, read it from the disk */
66f82cee 253 BLKDBG_EVENT(bs->file, BLKDBG_L2_ALLOC_COW_READ);
8e37f681
KW
254 ret = qcow2_cache_get(bs, s->l2_table_cache,
255 old_l2_offset & L1E_OFFSET_MASK,
29c1a730
KW
256 (void**) &old_table);
257 if (ret < 0) {
258 goto fail;
259 }
260
261 memcpy(l2_table, old_table, s->cluster_size);
262
a3f1afb4 263 qcow2_cache_put(bs, s->l2_table_cache, (void **) &old_table);
45aba42f 264 }
29c1a730 265
45aba42f 266 /* write the l2 table to the file */
66f82cee 267 BLKDBG_EVENT(bs->file, BLKDBG_L2_ALLOC_WRITE);
29c1a730 268
3cce16f4 269 trace_qcow2_l2_allocate_write_l2(bs, l1_index);
72e80b89 270 qcow2_cache_entry_mark_dirty(bs, s->l2_table_cache, l2_table);
29c1a730 271 ret = qcow2_cache_flush(bs, s->l2_table_cache);
c46e1167 272 if (ret < 0) {
175e1152
KW
273 goto fail;
274 }
275
276 /* update the L1 entry */
3cce16f4 277 trace_qcow2_l2_allocate_write_l1(bs, l1_index);
175e1152 278 s->l1_table[l1_index] = l2_offset | QCOW_OFLAG_COPIED;
e23e400e 279 ret = qcow2_write_l1_entry(bs, l1_index);
175e1152
KW
280 if (ret < 0) {
281 goto fail;
c46e1167 282 }
45aba42f 283
c46e1167 284 *table = l2_table;
3cce16f4 285 trace_qcow2_l2_allocate_done(bs, l1_index, 0);
c46e1167 286 return 0;
175e1152
KW
287
288fail:
3cce16f4 289 trace_qcow2_l2_allocate_done(bs, l1_index, ret);
8585afd8
HR
290 if (l2_table != NULL) {
291 qcow2_cache_put(bs, s->l2_table_cache, (void**) table);
292 }
68dba0bf 293 s->l1_table[l1_index] = old_l2_offset;
e3b21ef9
HR
294 if (l2_offset > 0) {
295 qcow2_free_clusters(bs, l2_offset, s->l2_size * sizeof(uint64_t),
296 QCOW2_DISCARD_ALWAYS);
297 }
175e1152 298 return ret;
45aba42f
KW
299}
300
2bfcc4a0
KW
301/*
302 * Checks how many clusters in a given L2 table are contiguous in the image
303 * file. As soon as one of the flags in the bitmask stop_flags changes compared
304 * to the first cluster, the search is stopped and the cluster is not counted
305 * as contiguous. (This allows it, for example, to stop at the first compressed
306 * cluster which may require a different handling)
307 */
b6d36def 308static int count_contiguous_clusters(int nb_clusters, int cluster_size,
61653008 309 uint64_t *l2_table, uint64_t stop_flags)
45aba42f
KW
310{
311 int i;
3ef95218 312 QCow2ClusterType first_cluster_type;
78a52ad5 313 uint64_t mask = stop_flags | L2E_OFFSET_MASK | QCOW_OFLAG_COMPRESSED;
15684a47
HR
314 uint64_t first_entry = be64_to_cpu(l2_table[0]);
315 uint64_t offset = first_entry & mask;
45aba42f 316
564a6b69 317 if (!offset) {
45aba42f 318 return 0;
564a6b69 319 }
45aba42f 320
564a6b69
HR
321 /* must be allocated */
322 first_cluster_type = qcow2_get_cluster_type(first_entry);
323 assert(first_cluster_type == QCOW2_CLUSTER_NORMAL ||
fdfab37d 324 first_cluster_type == QCOW2_CLUSTER_ZERO_ALLOC);
15684a47 325
61653008 326 for (i = 0; i < nb_clusters; i++) {
2bfcc4a0
KW
327 uint64_t l2_entry = be64_to_cpu(l2_table[i]) & mask;
328 if (offset + (uint64_t) i * cluster_size != l2_entry) {
45aba42f 329 break;
2bfcc4a0
KW
330 }
331 }
45aba42f 332
61653008 333 return i;
45aba42f
KW
334}
335
4341df8a
EB
336/*
337 * Checks how many consecutive unallocated clusters in a given L2
338 * table have the same cluster type.
339 */
340static int count_contiguous_clusters_unallocated(int nb_clusters,
341 uint64_t *l2_table,
3ef95218 342 QCow2ClusterType wanted_type)
45aba42f 343{
2bfcc4a0
KW
344 int i;
345
fdfab37d 346 assert(wanted_type == QCOW2_CLUSTER_ZERO_PLAIN ||
4341df8a 347 wanted_type == QCOW2_CLUSTER_UNALLOCATED);
2bfcc4a0 348 for (i = 0; i < nb_clusters; i++) {
4341df8a 349 uint64_t entry = be64_to_cpu(l2_table[i]);
3ef95218 350 QCow2ClusterType type = qcow2_get_cluster_type(entry);
45aba42f 351
fdfab37d 352 if (type != wanted_type) {
2bfcc4a0
KW
353 break;
354 }
355 }
45aba42f
KW
356
357 return i;
358}
359
360/* The crypt function is compatible with the linux cryptoloop
361 algorithm for < 4 GB images. NOTE: out_buf == in_buf is
362 supported */
ff99129a 363int qcow2_encrypt_sectors(BDRVQcow2State *s, int64_t sector_num,
f6fa64f6
DB
364 uint8_t *out_buf, const uint8_t *in_buf,
365 int nb_sectors, bool enc,
366 Error **errp)
45aba42f
KW
367{
368 union {
369 uint64_t ll[2];
370 uint8_t b[16];
371 } ivec;
372 int i;
f6fa64f6 373 int ret;
45aba42f
KW
374
375 for(i = 0; i < nb_sectors; i++) {
376 ivec.ll[0] = cpu_to_le64(sector_num);
377 ivec.ll[1] = 0;
f6fa64f6
DB
378 if (qcrypto_cipher_setiv(s->cipher,
379 ivec.b, G_N_ELEMENTS(ivec.b),
380 errp) < 0) {
381 return -1;
382 }
383 if (enc) {
384 ret = qcrypto_cipher_encrypt(s->cipher,
385 in_buf,
386 out_buf,
387 512,
388 errp);
389 } else {
390 ret = qcrypto_cipher_decrypt(s->cipher,
391 in_buf,
392 out_buf,
393 512,
394 errp);
395 }
396 if (ret < 0) {
397 return -1;
398 }
45aba42f
KW
399 sector_num++;
400 in_buf += 512;
401 out_buf += 512;
402 }
f6fa64f6 403 return 0;
45aba42f
KW
404}
405
aaa4d20b
KW
406static int coroutine_fn do_perform_cow(BlockDriverState *bs,
407 uint64_t src_cluster_offset,
408 uint64_t cluster_offset,
e034f5bc
AG
409 unsigned offset_in_cluster,
410 unsigned bytes)
45aba42f 411{
ff99129a 412 BDRVQcow2State *s = bs->opaque;
aef4acb6
SH
413 QEMUIOVector qiov;
414 struct iovec iov;
aaa4d20b 415 int ret;
1b9f1491 416
99450c6f
AG
417 if (bytes == 0) {
418 return 0;
419 }
420
aaa4d20b 421 iov.iov_len = bytes;
de82815d
KW
422 iov.iov_base = qemu_try_blockalign(bs, iov.iov_len);
423 if (iov.iov_base == NULL) {
424 return -ENOMEM;
425 }
aef4acb6
SH
426
427 qemu_iovec_init_external(&qiov, &iov, 1);
1b9f1491 428
66f82cee 429 BLKDBG_EVENT(bs->file, BLKDBG_COW_READ);
aef4acb6 430
dba28555 431 if (!bs->drv) {
bd604369
KW
432 ret = -ENOMEDIUM;
433 goto out;
dba28555
HR
434 }
435
aef4acb6
SH
436 /* Call .bdrv_co_readv() directly instead of using the public block-layer
437 * interface. This avoids double I/O throttling and request tracking,
438 * which can lead to deadlock when block layer copy-on-read is enabled.
439 */
aaa4d20b
KW
440 ret = bs->drv->bdrv_co_preadv(bs, src_cluster_offset + offset_in_cluster,
441 bytes, &qiov, 0);
1b9f1491
KW
442 if (ret < 0) {
443 goto out;
444 }
445
8336aafa 446 if (bs->encrypted) {
bb9f8dd0 447 int64_t sector = (src_cluster_offset + offset_in_cluster)
aaa4d20b 448 >> BDRV_SECTOR_BITS;
f6fa64f6 449 assert(s->cipher);
aaa4d20b
KW
450 assert((offset_in_cluster & ~BDRV_SECTOR_MASK) == 0);
451 assert((bytes & ~BDRV_SECTOR_MASK) == 0);
452 if (qcow2_encrypt_sectors(s, sector, iov.iov_base, iov.iov_base,
026ac158 453 bytes >> BDRV_SECTOR_BITS, true, NULL) < 0) {
f6fa64f6 454 ret = -EIO;
f6fa64f6
DB
455 goto out;
456 }
45aba42f 457 }
1b9f1491 458
231bb267 459 ret = qcow2_pre_write_overlap_check(bs, 0,
aaa4d20b 460 cluster_offset + offset_in_cluster, bytes);
cf93980e
HR
461 if (ret < 0) {
462 goto out;
463 }
464
66f82cee 465 BLKDBG_EVENT(bs->file, BLKDBG_COW_WRITE);
a03ef88f 466 ret = bdrv_co_pwritev(bs->file, cluster_offset + offset_in_cluster,
aaa4d20b 467 bytes, &qiov, 0);
1b9f1491
KW
468 if (ret < 0) {
469 goto out;
470 }
471
472 ret = 0;
473out:
aef4acb6 474 qemu_vfree(iov.iov_base);
1b9f1491 475 return ret;
45aba42f
KW
476}
477
478
479/*
480 * get_cluster_offset
481 *
ecfe1863
KW
482 * For a given offset of the virtual disk, find the cluster type and offset in
483 * the qcow2 file. The offset is stored in *cluster_offset.
45aba42f 484 *
ecfe1863
KW
485 * On entry, *bytes is the maximum number of contiguous bytes starting at
486 * offset that we are interested in.
45aba42f 487 *
ecfe1863
KW
488 * On exit, *bytes is the number of bytes starting at offset that have the same
489 * cluster type and (if applicable) are stored contiguously in the image file.
490 * Compressed clusters are always returned one by one.
45aba42f 491 *
68d000a3
KW
492 * Returns the cluster type (QCOW2_CLUSTER_*) on success, -errno in error
493 * cases.
45aba42f 494 */
1c46efaa 495int qcow2_get_cluster_offset(BlockDriverState *bs, uint64_t offset,
ecfe1863 496 unsigned int *bytes, uint64_t *cluster_offset)
45aba42f 497{
ff99129a 498 BDRVQcow2State *s = bs->opaque;
2cf7cfa1
KW
499 unsigned int l2_index;
500 uint64_t l1_index, l2_offset, *l2_table;
45aba42f 501 int l1_bits, c;
c834cba9
HR
502 unsigned int offset_in_cluster;
503 uint64_t bytes_available, bytes_needed, nb_clusters;
3ef95218 504 QCow2ClusterType type;
55c17e98 505 int ret;
45aba42f 506
b2f65d6b 507 offset_in_cluster = offset_into_cluster(s, offset);
ecfe1863 508 bytes_needed = (uint64_t) *bytes + offset_in_cluster;
45aba42f 509
b2f65d6b 510 l1_bits = s->l2_bits + s->cluster_bits;
45aba42f 511
b2f65d6b
KW
512 /* compute how many bytes there are between the start of the cluster
513 * containing offset and the end of the l1 entry */
514 bytes_available = (1ULL << l1_bits) - (offset & ((1ULL << l1_bits) - 1))
515 + offset_in_cluster;
45aba42f 516
b2f65d6b
KW
517 if (bytes_needed > bytes_available) {
518 bytes_needed = bytes_available;
45aba42f
KW
519 }
520
1c46efaa 521 *cluster_offset = 0;
45aba42f 522
b6af0975 523 /* seek to the l2 offset in the l1 table */
45aba42f
KW
524
525 l1_index = offset >> l1_bits;
68d000a3 526 if (l1_index >= s->l1_size) {
3ef95218 527 type = QCOW2_CLUSTER_UNALLOCATED;
45aba42f 528 goto out;
68d000a3 529 }
45aba42f 530
68d000a3
KW
531 l2_offset = s->l1_table[l1_index] & L1E_OFFSET_MASK;
532 if (!l2_offset) {
3ef95218 533 type = QCOW2_CLUSTER_UNALLOCATED;
45aba42f 534 goto out;
68d000a3 535 }
45aba42f 536
a97c67ee
HR
537 if (offset_into_cluster(s, l2_offset)) {
538 qcow2_signal_corruption(bs, true, -1, -1, "L2 table offset %#" PRIx64
539 " unaligned (L1 index: %#" PRIx64 ")",
540 l2_offset, l1_index);
541 return -EIO;
542 }
543
45aba42f
KW
544 /* load the l2 table in memory */
545
55c17e98
KW
546 ret = l2_load(bs, l2_offset, &l2_table);
547 if (ret < 0) {
548 return ret;
1c46efaa 549 }
45aba42f
KW
550
551 /* find the cluster offset for the given disk offset */
552
553 l2_index = (offset >> s->cluster_bits) & (s->l2_size - 1);
1c46efaa 554 *cluster_offset = be64_to_cpu(l2_table[l2_index]);
b6d36def 555
b2f65d6b 556 nb_clusters = size_to_clusters(s, bytes_needed);
c834cba9
HR
557 /* bytes_needed <= *bytes + offset_in_cluster, both of which are unsigned
558 * integers; the minimum cluster size is 512, so this assertion is always
559 * true */
560 assert(nb_clusters <= INT_MAX);
45aba42f 561
3ef95218 562 type = qcow2_get_cluster_type(*cluster_offset);
fdfab37d
EB
563 if (s->qcow_version < 3 && (type == QCOW2_CLUSTER_ZERO_PLAIN ||
564 type == QCOW2_CLUSTER_ZERO_ALLOC)) {
565 qcow2_signal_corruption(bs, true, -1, -1, "Zero cluster entry found"
566 " in pre-v3 image (L2 offset: %#" PRIx64
567 ", L2 index: %#x)", l2_offset, l2_index);
568 ret = -EIO;
569 goto fail;
570 }
3ef95218 571 switch (type) {
68d000a3
KW
572 case QCOW2_CLUSTER_COMPRESSED:
573 /* Compressed clusters can only be processed one by one */
574 c = 1;
575 *cluster_offset &= L2E_COMPRESSED_OFFSET_SIZE_MASK;
576 break;
fdfab37d 577 case QCOW2_CLUSTER_ZERO_PLAIN:
68d000a3 578 case QCOW2_CLUSTER_UNALLOCATED:
45aba42f 579 /* how many empty clusters ? */
4341df8a 580 c = count_contiguous_clusters_unallocated(nb_clusters,
fdfab37d 581 &l2_table[l2_index], type);
68d000a3
KW
582 *cluster_offset = 0;
583 break;
fdfab37d 584 case QCOW2_CLUSTER_ZERO_ALLOC:
68d000a3 585 case QCOW2_CLUSTER_NORMAL:
45aba42f
KW
586 /* how many allocated clusters ? */
587 c = count_contiguous_clusters(nb_clusters, s->cluster_size,
fdfab37d 588 &l2_table[l2_index], QCOW_OFLAG_ZERO);
68d000a3 589 *cluster_offset &= L2E_OFFSET_MASK;
a97c67ee 590 if (offset_into_cluster(s, *cluster_offset)) {
fdfab37d
EB
591 qcow2_signal_corruption(bs, true, -1, -1,
592 "Cluster allocation offset %#"
a97c67ee
HR
593 PRIx64 " unaligned (L2 offset: %#" PRIx64
594 ", L2 index: %#x)", *cluster_offset,
595 l2_offset, l2_index);
596 ret = -EIO;
597 goto fail;
598 }
68d000a3 599 break;
1417d7e4
KW
600 default:
601 abort();
45aba42f
KW
602 }
603
29c1a730
KW
604 qcow2_cache_put(bs, s->l2_table_cache, (void**) &l2_table);
605
c834cba9 606 bytes_available = (int64_t)c * s->cluster_size;
68d000a3 607
45aba42f 608out:
b2f65d6b
KW
609 if (bytes_available > bytes_needed) {
610 bytes_available = bytes_needed;
611 }
45aba42f 612
c834cba9
HR
613 /* bytes_available <= bytes_needed <= *bytes + offset_in_cluster;
614 * subtracting offset_in_cluster will therefore definitely yield something
615 * not exceeding UINT_MAX */
616 assert(bytes_available - offset_in_cluster <= UINT_MAX);
ecfe1863 617 *bytes = bytes_available - offset_in_cluster;
45aba42f 618
3ef95218 619 return type;
a97c67ee
HR
620
621fail:
622 qcow2_cache_put(bs, s->l2_table_cache, (void **)&l2_table);
623 return ret;
45aba42f
KW
624}
625
626/*
627 * get_cluster_table
628 *
629 * for a given disk offset, load (and allocate if needed)
630 * the l2 table.
631 *
632 * the l2 table offset in the qcow2 file and the cluster index
633 * in the l2 table are given to the caller.
634 *
1e3e8f1a 635 * Returns 0 on success, -errno in failure case
45aba42f 636 */
45aba42f
KW
637static int get_cluster_table(BlockDriverState *bs, uint64_t offset,
638 uint64_t **new_l2_table,
45aba42f
KW
639 int *new_l2_index)
640{
ff99129a 641 BDRVQcow2State *s = bs->opaque;
2cf7cfa1
KW
642 unsigned int l2_index;
643 uint64_t l1_index, l2_offset;
c46e1167 644 uint64_t *l2_table = NULL;
80ee15a6 645 int ret;
45aba42f 646
b6af0975 647 /* seek to the l2 offset in the l1 table */
45aba42f
KW
648
649 l1_index = offset >> (s->l2_bits + s->cluster_bits);
650 if (l1_index >= s->l1_size) {
72893756 651 ret = qcow2_grow_l1_table(bs, l1_index + 1, false);
1e3e8f1a
KW
652 if (ret < 0) {
653 return ret;
654 }
45aba42f 655 }
8e37f681 656
2cf7cfa1 657 assert(l1_index < s->l1_size);
8e37f681 658 l2_offset = s->l1_table[l1_index] & L1E_OFFSET_MASK;
a97c67ee
HR
659 if (offset_into_cluster(s, l2_offset)) {
660 qcow2_signal_corruption(bs, true, -1, -1, "L2 table offset %#" PRIx64
661 " unaligned (L1 index: %#" PRIx64 ")",
662 l2_offset, l1_index);
663 return -EIO;
664 }
45aba42f
KW
665
666 /* seek the l2 table of the given l2 offset */
667
8e37f681 668 if (s->l1_table[l1_index] & QCOW_OFLAG_COPIED) {
45aba42f 669 /* load the l2 table in memory */
55c17e98
KW
670 ret = l2_load(bs, l2_offset, &l2_table);
671 if (ret < 0) {
672 return ret;
1e3e8f1a 673 }
45aba42f 674 } else {
16fde5f2 675 /* First allocate a new L2 table (and do COW if needed) */
c46e1167
KW
676 ret = l2_allocate(bs, l1_index, &l2_table);
677 if (ret < 0) {
678 return ret;
1e3e8f1a 679 }
16fde5f2
KW
680
681 /* Then decrease the refcount of the old table */
682 if (l2_offset) {
6cfcb9b8
KW
683 qcow2_free_clusters(bs, l2_offset, s->l2_size * sizeof(uint64_t),
684 QCOW2_DISCARD_OTHER);
16fde5f2 685 }
45aba42f
KW
686 }
687
688 /* find the cluster offset for the given disk offset */
689
690 l2_index = (offset >> s->cluster_bits) & (s->l2_size - 1);
691
692 *new_l2_table = l2_table;
45aba42f
KW
693 *new_l2_index = l2_index;
694
1e3e8f1a 695 return 0;
45aba42f
KW
696}
697
698/*
699 * alloc_compressed_cluster_offset
700 *
701 * For a given offset of the disk image, return cluster offset in
702 * qcow2 file.
703 *
704 * If the offset is not found, allocate a new compressed cluster.
705 *
706 * Return the cluster offset if successful,
707 * Return 0, otherwise.
708 *
709 */
710
ed6ccf0f
KW
711uint64_t qcow2_alloc_compressed_cluster_offset(BlockDriverState *bs,
712 uint64_t offset,
713 int compressed_size)
45aba42f 714{
ff99129a 715 BDRVQcow2State *s = bs->opaque;
45aba42f 716 int l2_index, ret;
3948d1d4 717 uint64_t *l2_table;
f4f0d391 718 int64_t cluster_offset;
45aba42f
KW
719 int nb_csectors;
720
3948d1d4 721 ret = get_cluster_table(bs, offset, &l2_table, &l2_index);
1e3e8f1a 722 if (ret < 0) {
45aba42f 723 return 0;
1e3e8f1a 724 }
45aba42f 725
b0b6862e
KW
726 /* Compression can't overwrite anything. Fail if the cluster was already
727 * allocated. */
45aba42f 728 cluster_offset = be64_to_cpu(l2_table[l2_index]);
b0b6862e 729 if (cluster_offset & L2E_OFFSET_MASK) {
8f1efd00
KW
730 qcow2_cache_put(bs, s->l2_table_cache, (void**) &l2_table);
731 return 0;
732 }
45aba42f 733
ed6ccf0f 734 cluster_offset = qcow2_alloc_bytes(bs, compressed_size);
5d757b56 735 if (cluster_offset < 0) {
29c1a730 736 qcow2_cache_put(bs, s->l2_table_cache, (void**) &l2_table);
5d757b56
KW
737 return 0;
738 }
739
45aba42f
KW
740 nb_csectors = ((cluster_offset + compressed_size - 1) >> 9) -
741 (cluster_offset >> 9);
742
743 cluster_offset |= QCOW_OFLAG_COMPRESSED |
744 ((uint64_t)nb_csectors << s->csize_shift);
745
746 /* update L2 table */
747
748 /* compressed clusters never have the copied flag */
749
66f82cee 750 BLKDBG_EVENT(bs->file, BLKDBG_L2_UPDATE_COMPRESSED);
72e80b89 751 qcow2_cache_entry_mark_dirty(bs, s->l2_table_cache, l2_table);
45aba42f 752 l2_table[l2_index] = cpu_to_be64(cluster_offset);
a3f1afb4 753 qcow2_cache_put(bs, s->l2_table_cache, (void **) &l2_table);
4c1612d9 754
29c1a730 755 return cluster_offset;
4c1612d9
KW
756}
757
99450c6f 758static int perform_cow(BlockDriverState *bs, QCowL2Meta *m)
593fb83c 759{
ff99129a 760 BDRVQcow2State *s = bs->opaque;
99450c6f
AG
761 Qcow2COWRegion *start = &m->cow_start;
762 Qcow2COWRegion *end = &m->cow_end;
593fb83c
KW
763 int ret;
764
99450c6f 765 if (start->nb_bytes == 0 && end->nb_bytes == 0) {
593fb83c
KW
766 return 0;
767 }
768
769 qemu_co_mutex_unlock(&s->lock);
99450c6f
AG
770 ret = do_perform_cow(bs, m->offset, m->alloc_offset,
771 start->offset, start->nb_bytes);
593fb83c 772 if (ret < 0) {
99450c6f 773 goto fail;
593fb83c
KW
774 }
775
99450c6f
AG
776 ret = do_perform_cow(bs, m->offset, m->alloc_offset,
777 end->offset, end->nb_bytes);
778
779fail:
780 qemu_co_mutex_lock(&s->lock);
781
593fb83c
KW
782 /*
783 * Before we update the L2 table to actually point to the new cluster, we
784 * need to be sure that the refcounts have been increased and COW was
785 * handled.
786 */
99450c6f
AG
787 if (ret == 0) {
788 qcow2_cache_depends_on_flush(s->l2_table_cache);
789 }
593fb83c 790
99450c6f 791 return ret;
593fb83c
KW
792}
793
148da7ea 794int qcow2_alloc_cluster_link_l2(BlockDriverState *bs, QCowL2Meta *m)
45aba42f 795{
ff99129a 796 BDRVQcow2State *s = bs->opaque;
45aba42f 797 int i, j = 0, l2_index, ret;
593fb83c 798 uint64_t *old_cluster, *l2_table;
250196f1 799 uint64_t cluster_offset = m->alloc_offset;
45aba42f 800
3cce16f4 801 trace_qcow2_cluster_link_l2(qemu_coroutine_self(), m->nb_clusters);
f50f88b9 802 assert(m->nb_clusters > 0);
45aba42f 803
5839e53b 804 old_cluster = g_try_new(uint64_t, m->nb_clusters);
de82815d
KW
805 if (old_cluster == NULL) {
806 ret = -ENOMEM;
807 goto err;
808 }
45aba42f
KW
809
810 /* copy content of unmodified sectors */
99450c6f 811 ret = perform_cow(bs, m);
593fb83c
KW
812 if (ret < 0) {
813 goto err;
29c1a730
KW
814 }
815
593fb83c 816 /* Update L2 table. */
74c4510a 817 if (s->use_lazy_refcounts) {
280d3735
KW
818 qcow2_mark_dirty(bs);
819 }
bfe8043e
SH
820 if (qcow2_need_accurate_refcounts(s)) {
821 qcow2_cache_set_dependency(bs, s->l2_table_cache,
822 s->refcount_block_cache);
823 }
280d3735 824
3948d1d4 825 ret = get_cluster_table(bs, m->offset, &l2_table, &l2_index);
1e3e8f1a 826 if (ret < 0) {
45aba42f 827 goto err;
1e3e8f1a 828 }
72e80b89 829 qcow2_cache_entry_mark_dirty(bs, s->l2_table_cache, l2_table);
45aba42f 830
c01dbccb 831 assert(l2_index + m->nb_clusters <= s->l2_size);
45aba42f
KW
832 for (i = 0; i < m->nb_clusters; i++) {
833 /* if two concurrent writes happen to the same unallocated cluster
aaa4d20b
KW
834 * each write allocates separate cluster and writes data concurrently.
835 * The first one to complete updates l2 table with pointer to its
836 * cluster the second one has to do RMW (which is done above by
837 * perform_cow()), update l2 table with its cluster pointer and free
838 * old cluster. This is what this loop does */
839 if (l2_table[l2_index + i] != 0) {
45aba42f 840 old_cluster[j++] = l2_table[l2_index + i];
aaa4d20b 841 }
45aba42f
KW
842
843 l2_table[l2_index + i] = cpu_to_be64((cluster_offset +
844 (i << s->cluster_bits)) | QCOW_OFLAG_COPIED);
845 }
846
9f8e668e 847
a3f1afb4 848 qcow2_cache_put(bs, s->l2_table_cache, (void **) &l2_table);
45aba42f 849
7ec5e6a4
KW
850 /*
851 * If this was a COW, we need to decrease the refcount of the old cluster.
6cfcb9b8
KW
852 *
853 * Don't discard clusters that reach a refcount of 0 (e.g. compressed
854 * clusters), the next write will reuse them anyway.
7ec5e6a4 855 */
564a6b69 856 if (!m->keep_old_clusters && j != 0) {
7ec5e6a4 857 for (i = 0; i < j; i++) {
6cfcb9b8
KW
858 qcow2_free_any_clusters(bs, be64_to_cpu(old_cluster[i]), 1,
859 QCOW2_DISCARD_NEVER);
7ec5e6a4
KW
860 }
861 }
45aba42f
KW
862
863 ret = 0;
864err:
7267c094 865 g_free(old_cluster);
45aba42f
KW
866 return ret;
867 }
868
bf319ece
KW
869/*
870 * Returns the number of contiguous clusters that can be used for an allocating
871 * write, but require COW to be performed (this includes yet unallocated space,
872 * which must copy from the backing file)
873 */
ff99129a 874static int count_cow_clusters(BDRVQcow2State *s, int nb_clusters,
bf319ece
KW
875 uint64_t *l2_table, int l2_index)
876{
143550a8 877 int i;
bf319ece 878
143550a8
KW
879 for (i = 0; i < nb_clusters; i++) {
880 uint64_t l2_entry = be64_to_cpu(l2_table[l2_index + i]);
3ef95218 881 QCow2ClusterType cluster_type = qcow2_get_cluster_type(l2_entry);
143550a8
KW
882
883 switch(cluster_type) {
884 case QCOW2_CLUSTER_NORMAL:
885 if (l2_entry & QCOW_OFLAG_COPIED) {
886 goto out;
887 }
bf319ece 888 break;
143550a8
KW
889 case QCOW2_CLUSTER_UNALLOCATED:
890 case QCOW2_CLUSTER_COMPRESSED:
fdfab37d
EB
891 case QCOW2_CLUSTER_ZERO_PLAIN:
892 case QCOW2_CLUSTER_ZERO_ALLOC:
bf319ece 893 break;
143550a8
KW
894 default:
895 abort();
896 }
bf319ece
KW
897 }
898
143550a8 899out:
bf319ece
KW
900 assert(i <= nb_clusters);
901 return i;
902}
903
250196f1 904/*
226c3c26
KW
905 * Check if there already is an AIO write request in flight which allocates
906 * the same cluster. In this case we need to wait until the previous
907 * request has completed and updated the L2 table accordingly.
65eb2e35
KW
908 *
909 * Returns:
910 * 0 if there was no dependency. *cur_bytes indicates the number of
911 * bytes from guest_offset that can be read before the next
912 * dependency must be processed (or the request is complete)
913 *
914 * -EAGAIN if we had to wait for another request, previously gathered
915 * information on cluster allocation may be invalid now. The caller
916 * must start over anyway, so consider *cur_bytes undefined.
250196f1 917 */
226c3c26 918static int handle_dependencies(BlockDriverState *bs, uint64_t guest_offset,
ecdd5333 919 uint64_t *cur_bytes, QCowL2Meta **m)
250196f1 920{
ff99129a 921 BDRVQcow2State *s = bs->opaque;
250196f1 922 QCowL2Meta *old_alloc;
65eb2e35 923 uint64_t bytes = *cur_bytes;
250196f1 924
250196f1
KW
925 QLIST_FOREACH(old_alloc, &s->cluster_allocs, next_in_flight) {
926
65eb2e35
KW
927 uint64_t start = guest_offset;
928 uint64_t end = start + bytes;
929 uint64_t old_start = l2meta_cow_start(old_alloc);
930 uint64_t old_end = l2meta_cow_end(old_alloc);
250196f1 931
d9d74f41 932 if (end <= old_start || start >= old_end) {
250196f1
KW
933 /* No intersection */
934 } else {
935 if (start < old_start) {
936 /* Stop at the start of a running allocation */
65eb2e35 937 bytes = old_start - start;
250196f1 938 } else {
65eb2e35 939 bytes = 0;
250196f1
KW
940 }
941
ecdd5333
KW
942 /* Stop if already an l2meta exists. After yielding, it wouldn't
943 * be valid any more, so we'd have to clean up the old L2Metas
944 * and deal with requests depending on them before starting to
945 * gather new ones. Not worth the trouble. */
946 if (bytes == 0 && *m) {
947 *cur_bytes = 0;
948 return 0;
949 }
950
65eb2e35 951 if (bytes == 0) {
250196f1
KW
952 /* Wait for the dependency to complete. We need to recheck
953 * the free/allocated clusters when we continue. */
1ace7cea 954 qemu_co_queue_wait(&old_alloc->dependent_requests, &s->lock);
250196f1
KW
955 return -EAGAIN;
956 }
957 }
958 }
959
65eb2e35
KW
960 /* Make sure that existing clusters and new allocations are only used up to
961 * the next dependency if we shortened the request above */
962 *cur_bytes = bytes;
250196f1 963
226c3c26
KW
964 return 0;
965}
966
0af729ec
KW
967/*
968 * Checks how many already allocated clusters that don't require a copy on
969 * write there are at the given guest_offset (up to *bytes). If
970 * *host_offset is not zero, only physically contiguous clusters beginning at
971 * this host offset are counted.
972 *
411d62b0
KW
973 * Note that guest_offset may not be cluster aligned. In this case, the
974 * returned *host_offset points to exact byte referenced by guest_offset and
975 * therefore isn't cluster aligned as well.
0af729ec
KW
976 *
977 * Returns:
978 * 0: if no allocated clusters are available at the given offset.
979 * *bytes is normally unchanged. It is set to 0 if the cluster
980 * is allocated and doesn't need COW, but doesn't have the right
981 * physical offset.
982 *
983 * 1: if allocated clusters that don't require a COW are available at
984 * the requested offset. *bytes may have decreased and describes
985 * the length of the area that can be written to.
986 *
987 * -errno: in error cases
0af729ec
KW
988 */
989static int handle_copied(BlockDriverState *bs, uint64_t guest_offset,
c53ede9f 990 uint64_t *host_offset, uint64_t *bytes, QCowL2Meta **m)
0af729ec 991{
ff99129a 992 BDRVQcow2State *s = bs->opaque;
0af729ec
KW
993 int l2_index;
994 uint64_t cluster_offset;
995 uint64_t *l2_table;
b6d36def 996 uint64_t nb_clusters;
c53ede9f 997 unsigned int keep_clusters;
a3f1afb4 998 int ret;
0af729ec
KW
999
1000 trace_qcow2_handle_copied(qemu_coroutine_self(), guest_offset, *host_offset,
1001 *bytes);
0af729ec 1002
411d62b0
KW
1003 assert(*host_offset == 0 || offset_into_cluster(s, guest_offset)
1004 == offset_into_cluster(s, *host_offset));
1005
acb0467f
KW
1006 /*
1007 * Calculate the number of clusters to look for. We stop at L2 table
1008 * boundaries to keep things simple.
1009 */
1010 nb_clusters =
1011 size_to_clusters(s, offset_into_cluster(s, guest_offset) + *bytes);
1012
1013 l2_index = offset_to_l2_index(s, guest_offset);
1014 nb_clusters = MIN(nb_clusters, s->l2_size - l2_index);
b6d36def 1015 assert(nb_clusters <= INT_MAX);
acb0467f 1016
0af729ec
KW
1017 /* Find L2 entry for the first involved cluster */
1018 ret = get_cluster_table(bs, guest_offset, &l2_table, &l2_index);
1019 if (ret < 0) {
1020 return ret;
1021 }
1022
1023 cluster_offset = be64_to_cpu(l2_table[l2_index]);
1024
1025 /* Check how many clusters are already allocated and don't need COW */
1026 if (qcow2_get_cluster_type(cluster_offset) == QCOW2_CLUSTER_NORMAL
1027 && (cluster_offset & QCOW_OFLAG_COPIED))
1028 {
e62daaf6
KW
1029 /* If a specific host_offset is required, check it */
1030 bool offset_matches =
1031 (cluster_offset & L2E_OFFSET_MASK) == *host_offset;
1032
a97c67ee
HR
1033 if (offset_into_cluster(s, cluster_offset & L2E_OFFSET_MASK)) {
1034 qcow2_signal_corruption(bs, true, -1, -1, "Data cluster offset "
1035 "%#llx unaligned (guest offset: %#" PRIx64
1036 ")", cluster_offset & L2E_OFFSET_MASK,
1037 guest_offset);
1038 ret = -EIO;
1039 goto out;
1040 }
1041
e62daaf6
KW
1042 if (*host_offset != 0 && !offset_matches) {
1043 *bytes = 0;
1044 ret = 0;
1045 goto out;
1046 }
1047
0af729ec 1048 /* We keep all QCOW_OFLAG_COPIED clusters */
c53ede9f 1049 keep_clusters =
acb0467f 1050 count_contiguous_clusters(nb_clusters, s->cluster_size,
61653008 1051 &l2_table[l2_index],
0af729ec 1052 QCOW_OFLAG_COPIED | QCOW_OFLAG_ZERO);
c53ede9f
KW
1053 assert(keep_clusters <= nb_clusters);
1054
1055 *bytes = MIN(*bytes,
1056 keep_clusters * s->cluster_size
1057 - offset_into_cluster(s, guest_offset));
0af729ec
KW
1058
1059 ret = 1;
1060 } else {
0af729ec
KW
1061 ret = 0;
1062 }
1063
0af729ec 1064 /* Cleanup */
e62daaf6 1065out:
a3f1afb4 1066 qcow2_cache_put(bs, s->l2_table_cache, (void **) &l2_table);
0af729ec 1067
e62daaf6
KW
1068 /* Only return a host offset if we actually made progress. Otherwise we
1069 * would make requirements for handle_alloc() that it can't fulfill */
a97c67ee 1070 if (ret > 0) {
411d62b0
KW
1071 *host_offset = (cluster_offset & L2E_OFFSET_MASK)
1072 + offset_into_cluster(s, guest_offset);
e62daaf6
KW
1073 }
1074
0af729ec
KW
1075 return ret;
1076}
1077
226c3c26
KW
1078/*
1079 * Allocates new clusters for the given guest_offset.
1080 *
1081 * At most *nb_clusters are allocated, and on return *nb_clusters is updated to
1082 * contain the number of clusters that have been allocated and are contiguous
1083 * in the image file.
1084 *
1085 * If *host_offset is non-zero, it specifies the offset in the image file at
1086 * which the new clusters must start. *nb_clusters can be 0 on return in this
1087 * case if the cluster at host_offset is already in use. If *host_offset is
1088 * zero, the clusters can be allocated anywhere in the image file.
1089 *
1090 * *host_offset is updated to contain the offset into the image file at which
1091 * the first allocated cluster starts.
1092 *
1093 * Return 0 on success and -errno in error cases. -EAGAIN means that the
1094 * function has been waiting for another request and the allocation must be
1095 * restarted, but the whole request should not be failed.
1096 */
1097static int do_alloc_cluster_offset(BlockDriverState *bs, uint64_t guest_offset,
b6d36def 1098 uint64_t *host_offset, uint64_t *nb_clusters)
226c3c26 1099{
ff99129a 1100 BDRVQcow2State *s = bs->opaque;
226c3c26
KW
1101
1102 trace_qcow2_do_alloc_clusters_offset(qemu_coroutine_self(), guest_offset,
1103 *host_offset, *nb_clusters);
1104
250196f1
KW
1105 /* Allocate new clusters */
1106 trace_qcow2_cluster_alloc_phys(qemu_coroutine_self());
1107 if (*host_offset == 0) {
df021791
KW
1108 int64_t cluster_offset =
1109 qcow2_alloc_clusters(bs, *nb_clusters * s->cluster_size);
1110 if (cluster_offset < 0) {
1111 return cluster_offset;
1112 }
1113 *host_offset = cluster_offset;
1114 return 0;
250196f1 1115 } else {
b6d36def 1116 int64_t ret = qcow2_alloc_clusters_at(bs, *host_offset, *nb_clusters);
df021791
KW
1117 if (ret < 0) {
1118 return ret;
1119 }
1120 *nb_clusters = ret;
1121 return 0;
250196f1 1122 }
250196f1
KW
1123}
1124
10f0ed8b
KW
1125/*
1126 * Allocates new clusters for an area that either is yet unallocated or needs a
1127 * copy on write. If *host_offset is non-zero, clusters are only allocated if
1128 * the new allocation can match the specified host offset.
1129 *
411d62b0
KW
1130 * Note that guest_offset may not be cluster aligned. In this case, the
1131 * returned *host_offset points to exact byte referenced by guest_offset and
1132 * therefore isn't cluster aligned as well.
10f0ed8b
KW
1133 *
1134 * Returns:
1135 * 0: if no clusters could be allocated. *bytes is set to 0,
1136 * *host_offset is left unchanged.
1137 *
1138 * 1: if new clusters were allocated. *bytes may be decreased if the
1139 * new allocation doesn't cover all of the requested area.
1140 * *host_offset is updated to contain the host offset of the first
1141 * newly allocated cluster.
1142 *
1143 * -errno: in error cases
10f0ed8b
KW
1144 */
1145static int handle_alloc(BlockDriverState *bs, uint64_t guest_offset,
c37f4cd7 1146 uint64_t *host_offset, uint64_t *bytes, QCowL2Meta **m)
10f0ed8b 1147{
ff99129a 1148 BDRVQcow2State *s = bs->opaque;
10f0ed8b
KW
1149 int l2_index;
1150 uint64_t *l2_table;
1151 uint64_t entry;
b6d36def 1152 uint64_t nb_clusters;
10f0ed8b 1153 int ret;
564a6b69 1154 bool keep_old_clusters = false;
10f0ed8b 1155
564a6b69 1156 uint64_t alloc_cluster_offset = 0;
10f0ed8b
KW
1157
1158 trace_qcow2_handle_alloc(qemu_coroutine_self(), guest_offset, *host_offset,
1159 *bytes);
1160 assert(*bytes > 0);
1161
f5bc6350
KW
1162 /*
1163 * Calculate the number of clusters to look for. We stop at L2 table
1164 * boundaries to keep things simple.
1165 */
c37f4cd7
KW
1166 nb_clusters =
1167 size_to_clusters(s, offset_into_cluster(s, guest_offset) + *bytes);
1168
f5bc6350 1169 l2_index = offset_to_l2_index(s, guest_offset);
c37f4cd7 1170 nb_clusters = MIN(nb_clusters, s->l2_size - l2_index);
b6d36def 1171 assert(nb_clusters <= INT_MAX);
f5bc6350 1172
10f0ed8b
KW
1173 /* Find L2 entry for the first involved cluster */
1174 ret = get_cluster_table(bs, guest_offset, &l2_table, &l2_index);
1175 if (ret < 0) {
1176 return ret;
1177 }
1178
3b8e2e26 1179 entry = be64_to_cpu(l2_table[l2_index]);
10f0ed8b
KW
1180
1181 /* For the moment, overwrite compressed clusters one by one */
1182 if (entry & QCOW_OFLAG_COMPRESSED) {
1183 nb_clusters = 1;
1184 } else {
3b8e2e26 1185 nb_clusters = count_cow_clusters(s, nb_clusters, l2_table, l2_index);
10f0ed8b
KW
1186 }
1187
ecdd5333
KW
1188 /* This function is only called when there were no non-COW clusters, so if
1189 * we can't find any unallocated or COW clusters either, something is
1190 * wrong with our code. */
1191 assert(nb_clusters > 0);
1192
fdfab37d
EB
1193 if (qcow2_get_cluster_type(entry) == QCOW2_CLUSTER_ZERO_ALLOC &&
1194 (entry & QCOW_OFLAG_COPIED) &&
564a6b69
HR
1195 (!*host_offset ||
1196 start_of_cluster(s, *host_offset) == (entry & L2E_OFFSET_MASK)))
1197 {
1198 /* Try to reuse preallocated zero clusters; contiguous normal clusters
1199 * would be fine, too, but count_cow_clusters() above has limited
1200 * nb_clusters already to a range of COW clusters */
1201 int preallocated_nb_clusters =
1202 count_contiguous_clusters(nb_clusters, s->cluster_size,
1203 &l2_table[l2_index], QCOW_OFLAG_COPIED);
1204 assert(preallocated_nb_clusters > 0);
10f0ed8b 1205
564a6b69
HR
1206 nb_clusters = preallocated_nb_clusters;
1207 alloc_cluster_offset = entry & L2E_OFFSET_MASK;
10f0ed8b 1208
564a6b69
HR
1209 /* We want to reuse these clusters, so qcow2_alloc_cluster_link_l2()
1210 * should not free them. */
1211 keep_old_clusters = true;
10f0ed8b
KW
1212 }
1213
564a6b69
HR
1214 qcow2_cache_put(bs, s->l2_table_cache, (void **) &l2_table);
1215
ff52aab2 1216 if (!alloc_cluster_offset) {
564a6b69
HR
1217 /* Allocate, if necessary at a given offset in the image file */
1218 alloc_cluster_offset = start_of_cluster(s, *host_offset);
1219 ret = do_alloc_cluster_offset(bs, guest_offset, &alloc_cluster_offset,
1220 &nb_clusters);
1221 if (ret < 0) {
1222 goto fail;
1223 }
1224
1225 /* Can't extend contiguous allocation */
1226 if (nb_clusters == 0) {
1227 *bytes = 0;
1228 return 0;
1229 }
1230
1231 /* !*host_offset would overwrite the image header and is reserved for
1232 * "no host offset preferred". If 0 was a valid host offset, it'd
1233 * trigger the following overlap check; do that now to avoid having an
1234 * invalid value in *host_offset. */
1235 if (!alloc_cluster_offset) {
1236 ret = qcow2_pre_write_overlap_check(bs, 0, alloc_cluster_offset,
1237 nb_clusters * s->cluster_size);
1238 assert(ret < 0);
1239 goto fail;
1240 }
ff52aab2
HR
1241 }
1242
83baa9a4
KW
1243 /*
1244 * Save info needed for meta data update.
1245 *
85567393 1246 * requested_bytes: Number of bytes from the start of the first
83baa9a4
KW
1247 * newly allocated cluster to the end of the (possibly shortened
1248 * before) write request.
1249 *
85567393 1250 * avail_bytes: Number of bytes from the start of the first
83baa9a4
KW
1251 * newly allocated to the end of the last newly allocated cluster.
1252 *
85567393 1253 * nb_bytes: The number of bytes from the start of the first
83baa9a4
KW
1254 * newly allocated cluster to the end of the area that the write
1255 * request actually writes to (excluding COW at the end)
1256 */
85567393
KW
1257 uint64_t requested_bytes = *bytes + offset_into_cluster(s, guest_offset);
1258 int avail_bytes = MIN(INT_MAX, nb_clusters << s->cluster_bits);
1259 int nb_bytes = MIN(requested_bytes, avail_bytes);
88c6588c 1260 QCowL2Meta *old_m = *m;
83baa9a4 1261
83baa9a4
KW
1262 *m = g_malloc0(sizeof(**m));
1263
1264 **m = (QCowL2Meta) {
88c6588c
KW
1265 .next = old_m,
1266
411d62b0 1267 .alloc_offset = alloc_cluster_offset,
83baa9a4
KW
1268 .offset = start_of_cluster(s, guest_offset),
1269 .nb_clusters = nb_clusters,
83baa9a4 1270
564a6b69
HR
1271 .keep_old_clusters = keep_old_clusters,
1272
83baa9a4
KW
1273 .cow_start = {
1274 .offset = 0,
85567393 1275 .nb_bytes = offset_into_cluster(s, guest_offset),
83baa9a4
KW
1276 },
1277 .cow_end = {
85567393
KW
1278 .offset = nb_bytes,
1279 .nb_bytes = avail_bytes - nb_bytes,
83baa9a4
KW
1280 },
1281 };
1282 qemu_co_queue_init(&(*m)->dependent_requests);
1283 QLIST_INSERT_HEAD(&s->cluster_allocs, *m, next_in_flight);
1284
411d62b0 1285 *host_offset = alloc_cluster_offset + offset_into_cluster(s, guest_offset);
85567393 1286 *bytes = MIN(*bytes, nb_bytes - offset_into_cluster(s, guest_offset));
83baa9a4
KW
1287 assert(*bytes != 0);
1288
10f0ed8b
KW
1289 return 1;
1290
1291fail:
1292 if (*m && (*m)->nb_clusters > 0) {
1293 QLIST_REMOVE(*m, next_in_flight);
1294 }
1295 return ret;
1296}
1297
45aba42f
KW
1298/*
1299 * alloc_cluster_offset
1300 *
250196f1
KW
1301 * For a given offset on the virtual disk, find the cluster offset in qcow2
1302 * file. If the offset is not found, allocate a new cluster.
45aba42f 1303 *
250196f1 1304 * If the cluster was already allocated, m->nb_clusters is set to 0 and
a7912369 1305 * other fields in m are meaningless.
148da7ea
KW
1306 *
1307 * If the cluster is newly allocated, m->nb_clusters is set to the number of
68d100e9
KW
1308 * contiguous clusters that have been allocated. In this case, the other
1309 * fields of m are valid and contain information about the first allocated
1310 * cluster.
45aba42f 1311 *
68d100e9
KW
1312 * If the request conflicts with another write request in flight, the coroutine
1313 * is queued and will be reentered when the dependency has completed.
148da7ea
KW
1314 *
1315 * Return 0 on success and -errno in error cases
45aba42f 1316 */
f4f0d391 1317int qcow2_alloc_cluster_offset(BlockDriverState *bs, uint64_t offset,
d46a0bb2
KW
1318 unsigned int *bytes, uint64_t *host_offset,
1319 QCowL2Meta **m)
45aba42f 1320{
ff99129a 1321 BDRVQcow2State *s = bs->opaque;
710c2496 1322 uint64_t start, remaining;
250196f1 1323 uint64_t cluster_offset;
65eb2e35 1324 uint64_t cur_bytes;
710c2496 1325 int ret;
45aba42f 1326
d46a0bb2 1327 trace_qcow2_alloc_clusters_offset(qemu_coroutine_self(), offset, *bytes);
710c2496 1328
72424114 1329again:
16f0587e 1330 start = offset;
d46a0bb2 1331 remaining = *bytes;
0af729ec
KW
1332 cluster_offset = 0;
1333 *host_offset = 0;
ecdd5333
KW
1334 cur_bytes = 0;
1335 *m = NULL;
0af729ec 1336
2c3b32d2 1337 while (true) {
ecdd5333
KW
1338
1339 if (!*host_offset) {
1340 *host_offset = start_of_cluster(s, cluster_offset);
1341 }
1342
1343 assert(remaining >= cur_bytes);
1344
1345 start += cur_bytes;
1346 remaining -= cur_bytes;
1347 cluster_offset += cur_bytes;
1348
1349 if (remaining == 0) {
1350 break;
1351 }
1352
1353 cur_bytes = remaining;
1354
2c3b32d2
KW
1355 /*
1356 * Now start gathering as many contiguous clusters as possible:
1357 *
1358 * 1. Check for overlaps with in-flight allocations
1359 *
1360 * a) Overlap not in the first cluster -> shorten this request and
1361 * let the caller handle the rest in its next loop iteration.
1362 *
1363 * b) Real overlaps of two requests. Yield and restart the search
1364 * for contiguous clusters (the situation could have changed
1365 * while we were sleeping)
1366 *
1367 * c) TODO: Request starts in the same cluster as the in-flight
1368 * allocation ends. Shorten the COW of the in-fight allocation,
1369 * set cluster_offset to write to the same cluster and set up
1370 * the right synchronisation between the in-flight request and
1371 * the new one.
1372 */
ecdd5333 1373 ret = handle_dependencies(bs, start, &cur_bytes, m);
2c3b32d2 1374 if (ret == -EAGAIN) {
ecdd5333
KW
1375 /* Currently handle_dependencies() doesn't yield if we already had
1376 * an allocation. If it did, we would have to clean up the L2Meta
1377 * structs before starting over. */
1378 assert(*m == NULL);
2c3b32d2
KW
1379 goto again;
1380 } else if (ret < 0) {
1381 return ret;
ecdd5333
KW
1382 } else if (cur_bytes == 0) {
1383 break;
2c3b32d2
KW
1384 } else {
1385 /* handle_dependencies() may have decreased cur_bytes (shortened
1386 * the allocations below) so that the next dependency is processed
1387 * correctly during the next loop iteration. */
0af729ec 1388 }
710c2496 1389
2c3b32d2
KW
1390 /*
1391 * 2. Count contiguous COPIED clusters.
1392 */
1393 ret = handle_copied(bs, start, &cluster_offset, &cur_bytes, m);
1394 if (ret < 0) {
1395 return ret;
1396 } else if (ret) {
ecdd5333 1397 continue;
2c3b32d2
KW
1398 } else if (cur_bytes == 0) {
1399 break;
1400 }
060bee89 1401
2c3b32d2
KW
1402 /*
1403 * 3. If the request still hasn't completed, allocate new clusters,
1404 * considering any cluster_offset of steps 1c or 2.
1405 */
1406 ret = handle_alloc(bs, start, &cluster_offset, &cur_bytes, m);
1407 if (ret < 0) {
1408 return ret;
1409 } else if (ret) {
ecdd5333 1410 continue;
2c3b32d2
KW
1411 } else {
1412 assert(cur_bytes == 0);
1413 break;
1414 }
f5bc6350 1415 }
10f0ed8b 1416
d46a0bb2
KW
1417 *bytes -= remaining;
1418 assert(*bytes > 0);
710c2496 1419 assert(*host_offset != 0);
45aba42f 1420
148da7ea 1421 return 0;
45aba42f
KW
1422}
1423
1424static int decompress_buffer(uint8_t *out_buf, int out_buf_size,
1425 const uint8_t *buf, int buf_size)
1426{
1427 z_stream strm1, *strm = &strm1;
1428 int ret, out_len;
1429
1430 memset(strm, 0, sizeof(*strm));
1431
1432 strm->next_in = (uint8_t *)buf;
1433 strm->avail_in = buf_size;
1434 strm->next_out = out_buf;
1435 strm->avail_out = out_buf_size;
1436
1437 ret = inflateInit2(strm, -12);
1438 if (ret != Z_OK)
1439 return -1;
1440 ret = inflate(strm, Z_FINISH);
1441 out_len = strm->next_out - out_buf;
1442 if ((ret != Z_STREAM_END && ret != Z_BUF_ERROR) ||
1443 out_len != out_buf_size) {
1444 inflateEnd(strm);
1445 return -1;
1446 }
1447 inflateEnd(strm);
1448 return 0;
1449}
1450
66f82cee 1451int qcow2_decompress_cluster(BlockDriverState *bs, uint64_t cluster_offset)
45aba42f 1452{
ff99129a 1453 BDRVQcow2State *s = bs->opaque;
45aba42f
KW
1454 int ret, csize, nb_csectors, sector_offset;
1455 uint64_t coffset;
1456
1457 coffset = cluster_offset & s->cluster_offset_mask;
1458 if (s->cluster_cache_offset != coffset) {
1459 nb_csectors = ((cluster_offset >> s->csize_shift) & s->csize_mask) + 1;
1460 sector_offset = coffset & 511;
1461 csize = nb_csectors * 512 - sector_offset;
66f82cee 1462 BLKDBG_EVENT(bs->file, BLKDBG_READ_COMPRESSED);
fbcbbf4e 1463 ret = bdrv_read(bs->file, coffset >> 9, s->cluster_data,
9a4f4c31 1464 nb_csectors);
45aba42f 1465 if (ret < 0) {
8af36488 1466 return ret;
45aba42f
KW
1467 }
1468 if (decompress_buffer(s->cluster_cache, s->cluster_size,
1469 s->cluster_data + sector_offset, csize) < 0) {
8af36488 1470 return -EIO;
45aba42f
KW
1471 }
1472 s->cluster_cache_offset = coffset;
1473 }
1474 return 0;
1475}
5ea929e3
KW
1476
1477/*
1478 * This discards as many clusters of nb_clusters as possible at once (i.e.
1479 * all clusters in the same L2 table) and returns the number of discarded
1480 * clusters.
1481 */
1482static int discard_single_l2(BlockDriverState *bs, uint64_t offset,
b6d36def
HR
1483 uint64_t nb_clusters, enum qcow2_discard_type type,
1484 bool full_discard)
5ea929e3 1485{
ff99129a 1486 BDRVQcow2State *s = bs->opaque;
3948d1d4 1487 uint64_t *l2_table;
5ea929e3
KW
1488 int l2_index;
1489 int ret;
1490 int i;
1491
3948d1d4 1492 ret = get_cluster_table(bs, offset, &l2_table, &l2_index);
5ea929e3
KW
1493 if (ret < 0) {
1494 return ret;
1495 }
1496
1497 /* Limit nb_clusters to one L2 table */
1498 nb_clusters = MIN(nb_clusters, s->l2_size - l2_index);
b6d36def 1499 assert(nb_clusters <= INT_MAX);
5ea929e3
KW
1500
1501 for (i = 0; i < nb_clusters; i++) {
c883db0d 1502 uint64_t old_l2_entry;
5ea929e3 1503
c883db0d 1504 old_l2_entry = be64_to_cpu(l2_table[l2_index + i]);
a71835a0
KW
1505
1506 /*
808c4b6f
HR
1507 * If full_discard is false, make sure that a discarded area reads back
1508 * as zeroes for v3 images (we cannot do it for v2 without actually
1509 * writing a zero-filled buffer). We can skip the operation if the
1510 * cluster is already marked as zero, or if it's unallocated and we
1511 * don't have a backing file.
a71835a0
KW
1512 *
1513 * TODO We might want to use bdrv_get_block_status(bs) here, but we're
1514 * holding s->lock, so that doesn't work today.
808c4b6f
HR
1515 *
1516 * If full_discard is true, the sector should not read back as zeroes,
1517 * but rather fall through to the backing file.
a71835a0 1518 */
c883db0d 1519 switch (qcow2_get_cluster_type(old_l2_entry)) {
bbd995d8
EB
1520 case QCOW2_CLUSTER_UNALLOCATED:
1521 if (full_discard || !bs->backing) {
1522 continue;
1523 }
1524 break;
1525
fdfab37d
EB
1526 case QCOW2_CLUSTER_ZERO_PLAIN:
1527 if (!full_discard) {
bbd995d8
EB
1528 continue;
1529 }
1530 break;
1531
fdfab37d 1532 case QCOW2_CLUSTER_ZERO_ALLOC:
bbd995d8
EB
1533 case QCOW2_CLUSTER_NORMAL:
1534 case QCOW2_CLUSTER_COMPRESSED:
1535 break;
1536
1537 default:
1538 abort();
5ea929e3
KW
1539 }
1540
1541 /* First remove L2 entries */
72e80b89 1542 qcow2_cache_entry_mark_dirty(bs, s->l2_table_cache, l2_table);
808c4b6f 1543 if (!full_discard && s->qcow_version >= 3) {
a71835a0
KW
1544 l2_table[l2_index + i] = cpu_to_be64(QCOW_OFLAG_ZERO);
1545 } else {
1546 l2_table[l2_index + i] = cpu_to_be64(0);
1547 }
5ea929e3
KW
1548
1549 /* Then decrease the refcount */
c883db0d 1550 qcow2_free_any_clusters(bs, old_l2_entry, 1, type);
5ea929e3
KW
1551 }
1552
a3f1afb4 1553 qcow2_cache_put(bs, s->l2_table_cache, (void **) &l2_table);
5ea929e3
KW
1554
1555 return nb_clusters;
1556}
1557
d2cb36af
EB
1558int qcow2_cluster_discard(BlockDriverState *bs, uint64_t offset,
1559 uint64_t bytes, enum qcow2_discard_type type,
1560 bool full_discard)
5ea929e3 1561{
ff99129a 1562 BDRVQcow2State *s = bs->opaque;
d2cb36af 1563 uint64_t end_offset = offset + bytes;
b6d36def 1564 uint64_t nb_clusters;
d2cb36af 1565 int64_t cleared;
5ea929e3
KW
1566 int ret;
1567
f10ee139 1568 /* Caller must pass aligned values, except at image end */
0c1bd469 1569 assert(QEMU_IS_ALIGNED(offset, s->cluster_size));
f10ee139
EB
1570 assert(QEMU_IS_ALIGNED(end_offset, s->cluster_size) ||
1571 end_offset == bs->total_sectors << BDRV_SECTOR_BITS);
5ea929e3 1572
d2cb36af 1573 nb_clusters = size_to_clusters(s, bytes);
5ea929e3 1574
0b919fae
KW
1575 s->cache_discards = true;
1576
5ea929e3
KW
1577 /* Each L2 table is handled by its own loop iteration */
1578 while (nb_clusters > 0) {
d2cb36af
EB
1579 cleared = discard_single_l2(bs, offset, nb_clusters, type,
1580 full_discard);
1581 if (cleared < 0) {
1582 ret = cleared;
0b919fae 1583 goto fail;
5ea929e3
KW
1584 }
1585
d2cb36af
EB
1586 nb_clusters -= cleared;
1587 offset += (cleared * s->cluster_size);
5ea929e3
KW
1588 }
1589
0b919fae
KW
1590 ret = 0;
1591fail:
1592 s->cache_discards = false;
1593 qcow2_process_discards(bs, ret);
1594
1595 return ret;
5ea929e3 1596}
621f0589
KW
1597
1598/*
1599 * This zeroes as many clusters of nb_clusters as possible at once (i.e.
1600 * all clusters in the same L2 table) and returns the number of zeroed
1601 * clusters.
1602 */
1603static int zero_single_l2(BlockDriverState *bs, uint64_t offset,
170f4b2e 1604 uint64_t nb_clusters, int flags)
621f0589 1605{
ff99129a 1606 BDRVQcow2State *s = bs->opaque;
621f0589
KW
1607 uint64_t *l2_table;
1608 int l2_index;
1609 int ret;
1610 int i;
06cc5e2b 1611 bool unmap = !!(flags & BDRV_REQ_MAY_UNMAP);
621f0589
KW
1612
1613 ret = get_cluster_table(bs, offset, &l2_table, &l2_index);
1614 if (ret < 0) {
1615 return ret;
1616 }
1617
1618 /* Limit nb_clusters to one L2 table */
1619 nb_clusters = MIN(nb_clusters, s->l2_size - l2_index);
b6d36def 1620 assert(nb_clusters <= INT_MAX);
621f0589
KW
1621
1622 for (i = 0; i < nb_clusters; i++) {
1623 uint64_t old_offset;
06cc5e2b 1624 QCow2ClusterType cluster_type;
621f0589
KW
1625
1626 old_offset = be64_to_cpu(l2_table[l2_index + i]);
1627
06cc5e2b
EB
1628 /*
1629 * Minimize L2 changes if the cluster already reads back as
1630 * zeroes with correct allocation.
1631 */
1632 cluster_type = qcow2_get_cluster_type(old_offset);
1633 if (cluster_type == QCOW2_CLUSTER_ZERO_PLAIN ||
1634 (cluster_type == QCOW2_CLUSTER_ZERO_ALLOC && !unmap)) {
1635 continue;
1636 }
1637
72e80b89 1638 qcow2_cache_entry_mark_dirty(bs, s->l2_table_cache, l2_table);
06cc5e2b 1639 if (cluster_type == QCOW2_CLUSTER_COMPRESSED || unmap) {
621f0589 1640 l2_table[l2_index + i] = cpu_to_be64(QCOW_OFLAG_ZERO);
6cfcb9b8 1641 qcow2_free_any_clusters(bs, old_offset, 1, QCOW2_DISCARD_REQUEST);
621f0589
KW
1642 } else {
1643 l2_table[l2_index + i] |= cpu_to_be64(QCOW_OFLAG_ZERO);
1644 }
1645 }
1646
a3f1afb4 1647 qcow2_cache_put(bs, s->l2_table_cache, (void **) &l2_table);
621f0589
KW
1648
1649 return nb_clusters;
1650}
1651
d2cb36af
EB
1652int qcow2_cluster_zeroize(BlockDriverState *bs, uint64_t offset,
1653 uint64_t bytes, int flags)
621f0589 1654{
ff99129a 1655 BDRVQcow2State *s = bs->opaque;
d2cb36af 1656 uint64_t end_offset = offset + bytes;
b6d36def 1657 uint64_t nb_clusters;
d2cb36af 1658 int64_t cleared;
621f0589
KW
1659 int ret;
1660
f10ee139
EB
1661 /* Caller must pass aligned values, except at image end */
1662 assert(QEMU_IS_ALIGNED(offset, s->cluster_size));
1663 assert(QEMU_IS_ALIGNED(end_offset, s->cluster_size) ||
1664 end_offset == bs->total_sectors << BDRV_SECTOR_BITS);
1665
621f0589
KW
1666 /* The zero flag is only supported by version 3 and newer */
1667 if (s->qcow_version < 3) {
1668 return -ENOTSUP;
1669 }
1670
1671 /* Each L2 table is handled by its own loop iteration */
d2cb36af 1672 nb_clusters = size_to_clusters(s, bytes);
621f0589 1673
0b919fae
KW
1674 s->cache_discards = true;
1675
621f0589 1676 while (nb_clusters > 0) {
d2cb36af
EB
1677 cleared = zero_single_l2(bs, offset, nb_clusters, flags);
1678 if (cleared < 0) {
1679 ret = cleared;
0b919fae 1680 goto fail;
621f0589
KW
1681 }
1682
d2cb36af
EB
1683 nb_clusters -= cleared;
1684 offset += (cleared * s->cluster_size);
621f0589
KW
1685 }
1686
0b919fae
KW
1687 ret = 0;
1688fail:
1689 s->cache_discards = false;
1690 qcow2_process_discards(bs, ret);
1691
1692 return ret;
621f0589 1693}
32b6444d
HR
1694
1695/*
1696 * Expands all zero clusters in a specific L1 table (or deallocates them, for
1697 * non-backed non-pre-allocated zero clusters).
1698 *
4057a2b2
HR
1699 * l1_entries and *visited_l1_entries are used to keep track of progress for
1700 * status_cb(). l1_entries contains the total number of L1 entries and
1701 * *visited_l1_entries counts all visited L1 entries.
32b6444d
HR
1702 */
1703static int expand_zero_clusters_in_l1(BlockDriverState *bs, uint64_t *l1_table,
ecf58777 1704 int l1_size, int64_t *visited_l1_entries,
4057a2b2 1705 int64_t l1_entries,
8b13976d
HR
1706 BlockDriverAmendStatusCB *status_cb,
1707 void *cb_opaque)
32b6444d 1708{
ff99129a 1709 BDRVQcow2State *s = bs->opaque;
32b6444d
HR
1710 bool is_active_l1 = (l1_table == s->l1_table);
1711 uint64_t *l2_table = NULL;
1712 int ret;
1713 int i, j;
1714
1715 if (!is_active_l1) {
1716 /* inactive L2 tables require a buffer to be stored in when loading
1717 * them from disk */
9a4f4c31 1718 l2_table = qemu_try_blockalign(bs->file->bs, s->cluster_size);
de82815d
KW
1719 if (l2_table == NULL) {
1720 return -ENOMEM;
1721 }
32b6444d
HR
1722 }
1723
1724 for (i = 0; i < l1_size; i++) {
1725 uint64_t l2_offset = l1_table[i] & L1E_OFFSET_MASK;
1726 bool l2_dirty = false;
0e06528e 1727 uint64_t l2_refcount;
32b6444d
HR
1728
1729 if (!l2_offset) {
1730 /* unallocated */
4057a2b2
HR
1731 (*visited_l1_entries)++;
1732 if (status_cb) {
8b13976d 1733 status_cb(bs, *visited_l1_entries, l1_entries, cb_opaque);
4057a2b2 1734 }
32b6444d
HR
1735 continue;
1736 }
1737
8dd93d93
HR
1738 if (offset_into_cluster(s, l2_offset)) {
1739 qcow2_signal_corruption(bs, true, -1, -1, "L2 table offset %#"
1740 PRIx64 " unaligned (L1 index: %#x)",
1741 l2_offset, i);
1742 ret = -EIO;
1743 goto fail;
1744 }
1745
32b6444d
HR
1746 if (is_active_l1) {
1747 /* get active L2 tables from cache */
1748 ret = qcow2_cache_get(bs, s->l2_table_cache, l2_offset,
1749 (void **)&l2_table);
1750 } else {
1751 /* load inactive L2 tables from disk */
fbcbbf4e 1752 ret = bdrv_read(bs->file, l2_offset / BDRV_SECTOR_SIZE,
9a4f4c31 1753 (void *)l2_table, s->cluster_sectors);
32b6444d
HR
1754 }
1755 if (ret < 0) {
1756 goto fail;
1757 }
1758
7324c10f
HR
1759 ret = qcow2_get_refcount(bs, l2_offset >> s->cluster_bits,
1760 &l2_refcount);
1761 if (ret < 0) {
ecf58777
HR
1762 goto fail;
1763 }
1764
32b6444d
HR
1765 for (j = 0; j < s->l2_size; j++) {
1766 uint64_t l2_entry = be64_to_cpu(l2_table[j]);
ecf58777 1767 int64_t offset = l2_entry & L2E_OFFSET_MASK;
3ef95218 1768 QCow2ClusterType cluster_type = qcow2_get_cluster_type(l2_entry);
32b6444d 1769
fdfab37d
EB
1770 if (cluster_type != QCOW2_CLUSTER_ZERO_PLAIN &&
1771 cluster_type != QCOW2_CLUSTER_ZERO_ALLOC) {
32b6444d
HR
1772 continue;
1773 }
1774
fdfab37d 1775 if (cluster_type == QCOW2_CLUSTER_ZERO_PLAIN) {
760e0063 1776 if (!bs->backing) {
32b6444d
HR
1777 /* not backed; therefore we can simply deallocate the
1778 * cluster */
1779 l2_table[j] = 0;
1780 l2_dirty = true;
1781 continue;
1782 }
1783
1784 offset = qcow2_alloc_clusters(bs, s->cluster_size);
1785 if (offset < 0) {
1786 ret = offset;
1787 goto fail;
1788 }
ecf58777
HR
1789
1790 if (l2_refcount > 1) {
1791 /* For shared L2 tables, set the refcount accordingly (it is
1792 * already 1 and needs to be l2_refcount) */
1793 ret = qcow2_update_cluster_refcount(bs,
2aabe7c7
HR
1794 offset >> s->cluster_bits,
1795 refcount_diff(1, l2_refcount), false,
ecf58777
HR
1796 QCOW2_DISCARD_OTHER);
1797 if (ret < 0) {
1798 qcow2_free_clusters(bs, offset, s->cluster_size,
1799 QCOW2_DISCARD_OTHER);
1800 goto fail;
1801 }
1802 }
32b6444d
HR
1803 }
1804
8dd93d93 1805 if (offset_into_cluster(s, offset)) {
bcb07dba
EB
1806 qcow2_signal_corruption(bs, true, -1, -1,
1807 "Cluster allocation offset "
8dd93d93
HR
1808 "%#" PRIx64 " unaligned (L2 offset: %#"
1809 PRIx64 ", L2 index: %#x)", offset,
1810 l2_offset, j);
fdfab37d 1811 if (cluster_type == QCOW2_CLUSTER_ZERO_PLAIN) {
8dd93d93
HR
1812 qcow2_free_clusters(bs, offset, s->cluster_size,
1813 QCOW2_DISCARD_ALWAYS);
1814 }
1815 ret = -EIO;
1816 goto fail;
1817 }
1818
231bb267 1819 ret = qcow2_pre_write_overlap_check(bs, 0, offset, s->cluster_size);
32b6444d 1820 if (ret < 0) {
fdfab37d 1821 if (cluster_type == QCOW2_CLUSTER_ZERO_PLAIN) {
320c7066
HR
1822 qcow2_free_clusters(bs, offset, s->cluster_size,
1823 QCOW2_DISCARD_ALWAYS);
1824 }
32b6444d
HR
1825 goto fail;
1826 }
1827
720ff280 1828 ret = bdrv_pwrite_zeroes(bs->file, offset, s->cluster_size, 0);
32b6444d 1829 if (ret < 0) {
fdfab37d 1830 if (cluster_type == QCOW2_CLUSTER_ZERO_PLAIN) {
320c7066
HR
1831 qcow2_free_clusters(bs, offset, s->cluster_size,
1832 QCOW2_DISCARD_ALWAYS);
1833 }
32b6444d
HR
1834 goto fail;
1835 }
1836
ecf58777
HR
1837 if (l2_refcount == 1) {
1838 l2_table[j] = cpu_to_be64(offset | QCOW_OFLAG_COPIED);
1839 } else {
1840 l2_table[j] = cpu_to_be64(offset);
e390cf5a 1841 }
ecf58777 1842 l2_dirty = true;
32b6444d
HR
1843 }
1844
1845 if (is_active_l1) {
1846 if (l2_dirty) {
72e80b89 1847 qcow2_cache_entry_mark_dirty(bs, s->l2_table_cache, l2_table);
32b6444d
HR
1848 qcow2_cache_depends_on_flush(s->l2_table_cache);
1849 }
a3f1afb4 1850 qcow2_cache_put(bs, s->l2_table_cache, (void **) &l2_table);
32b6444d
HR
1851 } else {
1852 if (l2_dirty) {
231bb267
HR
1853 ret = qcow2_pre_write_overlap_check(bs,
1854 QCOW2_OL_INACTIVE_L2 | QCOW2_OL_ACTIVE_L2, l2_offset,
32b6444d
HR
1855 s->cluster_size);
1856 if (ret < 0) {
1857 goto fail;
1858 }
1859
18d51c4b 1860 ret = bdrv_write(bs->file, l2_offset / BDRV_SECTOR_SIZE,
9a4f4c31 1861 (void *)l2_table, s->cluster_sectors);
32b6444d
HR
1862 if (ret < 0) {
1863 goto fail;
1864 }
1865 }
1866 }
4057a2b2
HR
1867
1868 (*visited_l1_entries)++;
1869 if (status_cb) {
8b13976d 1870 status_cb(bs, *visited_l1_entries, l1_entries, cb_opaque);
4057a2b2 1871 }
32b6444d
HR
1872 }
1873
1874 ret = 0;
1875
1876fail:
1877 if (l2_table) {
1878 if (!is_active_l1) {
1879 qemu_vfree(l2_table);
1880 } else {
a3f1afb4 1881 qcow2_cache_put(bs, s->l2_table_cache, (void **) &l2_table);
32b6444d
HR
1882 }
1883 }
1884 return ret;
1885}
1886
1887/*
1888 * For backed images, expands all zero clusters on the image. For non-backed
1889 * images, deallocates all non-pre-allocated zero clusters (and claims the
1890 * allocation for pre-allocated ones). This is important for downgrading to a
1891 * qcow2 version which doesn't yet support metadata zero clusters.
1892 */
4057a2b2 1893int qcow2_expand_zero_clusters(BlockDriverState *bs,
8b13976d
HR
1894 BlockDriverAmendStatusCB *status_cb,
1895 void *cb_opaque)
32b6444d 1896{
ff99129a 1897 BDRVQcow2State *s = bs->opaque;
32b6444d 1898 uint64_t *l1_table = NULL;
4057a2b2 1899 int64_t l1_entries = 0, visited_l1_entries = 0;
32b6444d
HR
1900 int ret;
1901 int i, j;
1902
4057a2b2
HR
1903 if (status_cb) {
1904 l1_entries = s->l1_size;
1905 for (i = 0; i < s->nb_snapshots; i++) {
1906 l1_entries += s->snapshots[i].l1_size;
1907 }
1908 }
1909
32b6444d 1910 ret = expand_zero_clusters_in_l1(bs, s->l1_table, s->l1_size,
4057a2b2 1911 &visited_l1_entries, l1_entries,
8b13976d 1912 status_cb, cb_opaque);
32b6444d
HR
1913 if (ret < 0) {
1914 goto fail;
1915 }
1916
1917 /* Inactive L1 tables may point to active L2 tables - therefore it is
1918 * necessary to flush the L2 table cache before trying to access the L2
1919 * tables pointed to by inactive L1 entries (else we might try to expand
1920 * zero clusters that have already been expanded); furthermore, it is also
1921 * necessary to empty the L2 table cache, since it may contain tables which
1922 * are now going to be modified directly on disk, bypassing the cache.
1923 * qcow2_cache_empty() does both for us. */
1924 ret = qcow2_cache_empty(bs, s->l2_table_cache);
1925 if (ret < 0) {
1926 goto fail;
1927 }
1928
1929 for (i = 0; i < s->nb_snapshots; i++) {
d737b78c
LV
1930 int l1_sectors = DIV_ROUND_UP(s->snapshots[i].l1_size *
1931 sizeof(uint64_t), BDRV_SECTOR_SIZE);
32b6444d
HR
1932
1933 l1_table = g_realloc(l1_table, l1_sectors * BDRV_SECTOR_SIZE);
1934
fbcbbf4e 1935 ret = bdrv_read(bs->file,
9a4f4c31
KW
1936 s->snapshots[i].l1_table_offset / BDRV_SECTOR_SIZE,
1937 (void *)l1_table, l1_sectors);
32b6444d
HR
1938 if (ret < 0) {
1939 goto fail;
1940 }
1941
1942 for (j = 0; j < s->snapshots[i].l1_size; j++) {
1943 be64_to_cpus(&l1_table[j]);
1944 }
1945
1946 ret = expand_zero_clusters_in_l1(bs, l1_table, s->snapshots[i].l1_size,
4057a2b2 1947 &visited_l1_entries, l1_entries,
8b13976d 1948 status_cb, cb_opaque);
32b6444d
HR
1949 if (ret < 0) {
1950 goto fail;
1951 }
1952 }
1953
1954 ret = 0;
1955
1956fail:
32b6444d
HR
1957 g_free(l1_table);
1958 return ret;
1959}