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