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