]> git.proxmox.com Git - mirror_qemu.git/blame - block/qcow2-cluster.c
docs: Document share-rw property more thoroughly
[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
a3f1afb4 320 qcow2_cache_put(bs, 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);
72e80b89 327 qcow2_cache_entry_mark_dirty(bs, 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
HR
347 if (l2_table != NULL) {
348 qcow2_cache_put(bs, s->l2_table_cache, (void**) table);
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
KW
542
543 l1_index = offset >> l1_bits;
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
29c1a730
KW
622 qcow2_cache_put(bs, s->l2_table_cache, (void**) &l2_table);
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:
640 qcow2_cache_put(bs, s->l2_table_cache, (void **)&l2_table);
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 *
650 * the l2 table offset in the qcow2 file and the cluster index
651 * in the l2 table are given to the caller.
652 *
1e3e8f1a 653 * Returns 0 on success, -errno in failure case
45aba42f 654 */
45aba42f
KW
655static int get_cluster_table(BlockDriverState *bs, uint64_t offset,
656 uint64_t **new_l2_table,
45aba42f
KW
657 int *new_l2_index)
658{
ff99129a 659 BDRVQcow2State *s = bs->opaque;
2cf7cfa1
KW
660 unsigned int l2_index;
661 uint64_t l1_index, l2_offset;
c46e1167 662 uint64_t *l2_table = NULL;
80ee15a6 663 int ret;
45aba42f 664
b6af0975 665 /* seek to the l2 offset in the l1 table */
45aba42f
KW
666
667 l1_index = offset >> (s->l2_bits + s->cluster_bits);
668 if (l1_index >= s->l1_size) {
72893756 669 ret = qcow2_grow_l1_table(bs, l1_index + 1, false);
1e3e8f1a
KW
670 if (ret < 0) {
671 return ret;
672 }
45aba42f 673 }
8e37f681 674
2cf7cfa1 675 assert(l1_index < s->l1_size);
8e37f681 676 l2_offset = s->l1_table[l1_index] & L1E_OFFSET_MASK;
a97c67ee
HR
677 if (offset_into_cluster(s, l2_offset)) {
678 qcow2_signal_corruption(bs, true, -1, -1, "L2 table offset %#" PRIx64
679 " unaligned (L1 index: %#" PRIx64 ")",
680 l2_offset, l1_index);
681 return -EIO;
682 }
45aba42f
KW
683
684 /* seek the l2 table of the given l2 offset */
685
8e37f681 686 if (s->l1_table[l1_index] & QCOW_OFLAG_COPIED) {
45aba42f 687 /* load the l2 table in memory */
55c17e98
KW
688 ret = l2_load(bs, l2_offset, &l2_table);
689 if (ret < 0) {
690 return ret;
1e3e8f1a 691 }
45aba42f 692 } else {
16fde5f2 693 /* First allocate a new L2 table (and do COW if needed) */
c46e1167
KW
694 ret = l2_allocate(bs, l1_index, &l2_table);
695 if (ret < 0) {
696 return ret;
1e3e8f1a 697 }
16fde5f2
KW
698
699 /* Then decrease the refcount of the old table */
700 if (l2_offset) {
6cfcb9b8
KW
701 qcow2_free_clusters(bs, l2_offset, s->l2_size * sizeof(uint64_t),
702 QCOW2_DISCARD_OTHER);
16fde5f2 703 }
45aba42f
KW
704 }
705
706 /* find the cluster offset for the given disk offset */
707
24990c5b 708 l2_index = offset_to_l2_index(s, offset);
45aba42f
KW
709
710 *new_l2_table = l2_table;
45aba42f
KW
711 *new_l2_index = l2_index;
712
1e3e8f1a 713 return 0;
45aba42f
KW
714}
715
716/*
717 * alloc_compressed_cluster_offset
718 *
719 * For a given offset of the disk image, return cluster offset in
720 * qcow2 file.
721 *
722 * If the offset is not found, allocate a new compressed cluster.
723 *
724 * Return the cluster offset if successful,
725 * Return 0, otherwise.
726 *
727 */
728
ed6ccf0f
KW
729uint64_t qcow2_alloc_compressed_cluster_offset(BlockDriverState *bs,
730 uint64_t offset,
731 int compressed_size)
45aba42f 732{
ff99129a 733 BDRVQcow2State *s = bs->opaque;
45aba42f 734 int l2_index, ret;
3948d1d4 735 uint64_t *l2_table;
f4f0d391 736 int64_t cluster_offset;
45aba42f
KW
737 int nb_csectors;
738
3948d1d4 739 ret = get_cluster_table(bs, offset, &l2_table, &l2_index);
1e3e8f1a 740 if (ret < 0) {
45aba42f 741 return 0;
1e3e8f1a 742 }
45aba42f 743
b0b6862e
KW
744 /* Compression can't overwrite anything. Fail if the cluster was already
745 * allocated. */
45aba42f 746 cluster_offset = be64_to_cpu(l2_table[l2_index]);
b0b6862e 747 if (cluster_offset & L2E_OFFSET_MASK) {
8f1efd00
KW
748 qcow2_cache_put(bs, s->l2_table_cache, (void**) &l2_table);
749 return 0;
750 }
45aba42f 751
ed6ccf0f 752 cluster_offset = qcow2_alloc_bytes(bs, compressed_size);
5d757b56 753 if (cluster_offset < 0) {
29c1a730 754 qcow2_cache_put(bs, s->l2_table_cache, (void**) &l2_table);
5d757b56
KW
755 return 0;
756 }
757
45aba42f
KW
758 nb_csectors = ((cluster_offset + compressed_size - 1) >> 9) -
759 (cluster_offset >> 9);
760
761 cluster_offset |= QCOW_OFLAG_COMPRESSED |
762 ((uint64_t)nb_csectors << s->csize_shift);
763
764 /* update L2 table */
765
766 /* compressed clusters never have the copied flag */
767
66f82cee 768 BLKDBG_EVENT(bs->file, BLKDBG_L2_UPDATE_COMPRESSED);
72e80b89 769 qcow2_cache_entry_mark_dirty(bs, s->l2_table_cache, l2_table);
45aba42f 770 l2_table[l2_index] = cpu_to_be64(cluster_offset);
a3f1afb4 771 qcow2_cache_put(bs, s->l2_table_cache, (void **) &l2_table);
4c1612d9 772
29c1a730 773 return cluster_offset;
4c1612d9
KW
774}
775
99450c6f 776static int perform_cow(BlockDriverState *bs, QCowL2Meta *m)
593fb83c 777{
ff99129a 778 BDRVQcow2State *s = bs->opaque;
99450c6f
AG
779 Qcow2COWRegion *start = &m->cow_start;
780 Qcow2COWRegion *end = &m->cow_end;
672f0f2c 781 unsigned buffer_size;
b3cf1c7c
AG
782 unsigned data_bytes = end->offset - (start->offset + start->nb_bytes);
783 bool merge_reads;
672f0f2c 784 uint8_t *start_buffer, *end_buffer;
86b862c4 785 QEMUIOVector qiov;
593fb83c
KW
786 int ret;
787
672f0f2c 788 assert(start->nb_bytes <= UINT_MAX - end->nb_bytes);
b3cf1c7c
AG
789 assert(start->nb_bytes + end->nb_bytes <= UINT_MAX - data_bytes);
790 assert(start->offset + start->nb_bytes <= end->offset);
ee22a9d8 791 assert(!m->data_qiov || m->data_qiov->size == data_bytes);
672f0f2c 792
99450c6f 793 if (start->nb_bytes == 0 && end->nb_bytes == 0) {
593fb83c
KW
794 return 0;
795 }
796
b3cf1c7c
AG
797 /* If we have to read both the start and end COW regions and the
798 * middle region is not too large then perform just one read
799 * operation */
800 merge_reads = start->nb_bytes && end->nb_bytes && data_bytes <= 16384;
801 if (merge_reads) {
802 buffer_size = start->nb_bytes + data_bytes + end->nb_bytes;
803 } else {
804 /* If we have to do two reads, add some padding in the middle
805 * if necessary to make sure that the end region is optimally
806 * aligned. */
807 size_t align = bdrv_opt_mem_align(bs);
808 assert(align > 0 && align <= UINT_MAX);
809 assert(QEMU_ALIGN_UP(start->nb_bytes, align) <=
810 UINT_MAX - end->nb_bytes);
811 buffer_size = QEMU_ALIGN_UP(start->nb_bytes, align) + end->nb_bytes;
812 }
813
814 /* Reserve a buffer large enough to store all the data that we're
815 * going to read */
672f0f2c
AG
816 start_buffer = qemu_try_blockalign(bs, buffer_size);
817 if (start_buffer == NULL) {
818 return -ENOMEM;
819 }
820 /* The part of the buffer where the end region is located */
821 end_buffer = start_buffer + buffer_size - end->nb_bytes;
822
ee22a9d8 823 qemu_iovec_init(&qiov, 2 + (m->data_qiov ? m->data_qiov->niov : 0));
86b862c4 824
593fb83c 825 qemu_co_mutex_unlock(&s->lock);
b3cf1c7c
AG
826 /* First we read the existing data from both COW regions. We
827 * either read the whole region in one go, or the start and end
828 * regions separately. */
829 if (merge_reads) {
86b862c4
AG
830 qemu_iovec_add(&qiov, start_buffer, buffer_size);
831 ret = do_perform_cow_read(bs, m->offset, start->offset, &qiov);
b3cf1c7c 832 } else {
86b862c4
AG
833 qemu_iovec_add(&qiov, start_buffer, start->nb_bytes);
834 ret = do_perform_cow_read(bs, m->offset, start->offset, &qiov);
b3cf1c7c
AG
835 if (ret < 0) {
836 goto fail;
837 }
672f0f2c 838
86b862c4
AG
839 qemu_iovec_reset(&qiov);
840 qemu_iovec_add(&qiov, end_buffer, end->nb_bytes);
841 ret = do_perform_cow_read(bs, m->offset, end->offset, &qiov);
b3cf1c7c 842 }
593fb83c 843 if (ret < 0) {
99450c6f 844 goto fail;
593fb83c
KW
845 }
846
672f0f2c
AG
847 /* Encrypt the data if necessary before writing it */
848 if (bs->encrypted) {
4652b8f3
DB
849 if (!do_perform_cow_encrypt(bs, m->offset, m->alloc_offset,
850 start->offset, start_buffer,
851 start->nb_bytes) ||
852 !do_perform_cow_encrypt(bs, m->offset, m->alloc_offset,
853 end->offset, end_buffer, end->nb_bytes)) {
672f0f2c
AG
854 ret = -EIO;
855 goto fail;
856 }
857 }
858
ee22a9d8
AG
859 /* And now we can write everything. If we have the guest data we
860 * can write everything in one single operation */
861 if (m->data_qiov) {
862 qemu_iovec_reset(&qiov);
863 if (start->nb_bytes) {
864 qemu_iovec_add(&qiov, start_buffer, start->nb_bytes);
865 }
866 qemu_iovec_concat(&qiov, m->data_qiov, 0, data_bytes);
867 if (end->nb_bytes) {
868 qemu_iovec_add(&qiov, end_buffer, end->nb_bytes);
869 }
870 /* NOTE: we have a write_aio blkdebug event here followed by
871 * a cow_write one in do_perform_cow_write(), but there's only
872 * one single I/O operation */
873 BLKDBG_EVENT(bs->file, BLKDBG_WRITE_AIO);
874 ret = do_perform_cow_write(bs, m->alloc_offset, start->offset, &qiov);
875 } else {
876 /* If there's no guest data then write both COW regions separately */
877 qemu_iovec_reset(&qiov);
878 qemu_iovec_add(&qiov, start_buffer, start->nb_bytes);
879 ret = do_perform_cow_write(bs, m->alloc_offset, start->offset, &qiov);
880 if (ret < 0) {
881 goto fail;
882 }
883
884 qemu_iovec_reset(&qiov);
885 qemu_iovec_add(&qiov, end_buffer, end->nb_bytes);
886 ret = do_perform_cow_write(bs, m->alloc_offset, end->offset, &qiov);
672f0f2c 887 }
99450c6f
AG
888
889fail:
890 qemu_co_mutex_lock(&s->lock);
891
593fb83c
KW
892 /*
893 * Before we update the L2 table to actually point to the new cluster, we
894 * need to be sure that the refcounts have been increased and COW was
895 * handled.
896 */
99450c6f
AG
897 if (ret == 0) {
898 qcow2_cache_depends_on_flush(s->l2_table_cache);
899 }
593fb83c 900
672f0f2c 901 qemu_vfree(start_buffer);
86b862c4 902 qemu_iovec_destroy(&qiov);
99450c6f 903 return ret;
593fb83c
KW
904}
905
148da7ea 906int qcow2_alloc_cluster_link_l2(BlockDriverState *bs, QCowL2Meta *m)
45aba42f 907{
ff99129a 908 BDRVQcow2State *s = bs->opaque;
45aba42f 909 int i, j = 0, l2_index, ret;
593fb83c 910 uint64_t *old_cluster, *l2_table;
250196f1 911 uint64_t cluster_offset = m->alloc_offset;
45aba42f 912
3cce16f4 913 trace_qcow2_cluster_link_l2(qemu_coroutine_self(), m->nb_clusters);
f50f88b9 914 assert(m->nb_clusters > 0);
45aba42f 915
5839e53b 916 old_cluster = g_try_new(uint64_t, m->nb_clusters);
de82815d
KW
917 if (old_cluster == NULL) {
918 ret = -ENOMEM;
919 goto err;
920 }
45aba42f
KW
921
922 /* copy content of unmodified sectors */
99450c6f 923 ret = perform_cow(bs, m);
593fb83c
KW
924 if (ret < 0) {
925 goto err;
29c1a730
KW
926 }
927
593fb83c 928 /* Update L2 table. */
74c4510a 929 if (s->use_lazy_refcounts) {
280d3735
KW
930 qcow2_mark_dirty(bs);
931 }
bfe8043e
SH
932 if (qcow2_need_accurate_refcounts(s)) {
933 qcow2_cache_set_dependency(bs, s->l2_table_cache,
934 s->refcount_block_cache);
935 }
280d3735 936
3948d1d4 937 ret = get_cluster_table(bs, m->offset, &l2_table, &l2_index);
1e3e8f1a 938 if (ret < 0) {
45aba42f 939 goto err;
1e3e8f1a 940 }
72e80b89 941 qcow2_cache_entry_mark_dirty(bs, s->l2_table_cache, l2_table);
45aba42f 942
c01dbccb 943 assert(l2_index + m->nb_clusters <= s->l2_size);
45aba42f
KW
944 for (i = 0; i < m->nb_clusters; i++) {
945 /* if two concurrent writes happen to the same unallocated cluster
aaa4d20b
KW
946 * each write allocates separate cluster and writes data concurrently.
947 * The first one to complete updates l2 table with pointer to its
948 * cluster the second one has to do RMW (which is done above by
949 * perform_cow()), update l2 table with its cluster pointer and free
950 * old cluster. This is what this loop does */
951 if (l2_table[l2_index + i] != 0) {
45aba42f 952 old_cluster[j++] = l2_table[l2_index + i];
aaa4d20b 953 }
45aba42f
KW
954
955 l2_table[l2_index + i] = cpu_to_be64((cluster_offset +
956 (i << s->cluster_bits)) | QCOW_OFLAG_COPIED);
957 }
958
9f8e668e 959
a3f1afb4 960 qcow2_cache_put(bs, s->l2_table_cache, (void **) &l2_table);
45aba42f 961
7ec5e6a4
KW
962 /*
963 * If this was a COW, we need to decrease the refcount of the old cluster.
6cfcb9b8
KW
964 *
965 * Don't discard clusters that reach a refcount of 0 (e.g. compressed
966 * clusters), the next write will reuse them anyway.
7ec5e6a4 967 */
564a6b69 968 if (!m->keep_old_clusters && j != 0) {
7ec5e6a4 969 for (i = 0; i < j; i++) {
6cfcb9b8
KW
970 qcow2_free_any_clusters(bs, be64_to_cpu(old_cluster[i]), 1,
971 QCOW2_DISCARD_NEVER);
7ec5e6a4
KW
972 }
973 }
45aba42f
KW
974
975 ret = 0;
976err:
7267c094 977 g_free(old_cluster);
45aba42f
KW
978 return ret;
979 }
980
bf319ece
KW
981/*
982 * Returns the number of contiguous clusters that can be used for an allocating
983 * write, but require COW to be performed (this includes yet unallocated space,
984 * which must copy from the backing file)
985 */
ff99129a 986static int count_cow_clusters(BDRVQcow2State *s, int nb_clusters,
bf319ece
KW
987 uint64_t *l2_table, int l2_index)
988{
143550a8 989 int i;
bf319ece 990
143550a8
KW
991 for (i = 0; i < nb_clusters; i++) {
992 uint64_t l2_entry = be64_to_cpu(l2_table[l2_index + i]);
3ef95218 993 QCow2ClusterType cluster_type = qcow2_get_cluster_type(l2_entry);
143550a8
KW
994
995 switch(cluster_type) {
996 case QCOW2_CLUSTER_NORMAL:
997 if (l2_entry & QCOW_OFLAG_COPIED) {
998 goto out;
999 }
bf319ece 1000 break;
143550a8
KW
1001 case QCOW2_CLUSTER_UNALLOCATED:
1002 case QCOW2_CLUSTER_COMPRESSED:
fdfab37d
EB
1003 case QCOW2_CLUSTER_ZERO_PLAIN:
1004 case QCOW2_CLUSTER_ZERO_ALLOC:
bf319ece 1005 break;
143550a8
KW
1006 default:
1007 abort();
1008 }
bf319ece
KW
1009 }
1010
143550a8 1011out:
bf319ece
KW
1012 assert(i <= nb_clusters);
1013 return i;
1014}
1015
250196f1 1016/*
226c3c26
KW
1017 * Check if there already is an AIO write request in flight which allocates
1018 * the same cluster. In this case we need to wait until the previous
1019 * request has completed and updated the L2 table accordingly.
65eb2e35
KW
1020 *
1021 * Returns:
1022 * 0 if there was no dependency. *cur_bytes indicates the number of
1023 * bytes from guest_offset that can be read before the next
1024 * dependency must be processed (or the request is complete)
1025 *
1026 * -EAGAIN if we had to wait for another request, previously gathered
1027 * information on cluster allocation may be invalid now. The caller
1028 * must start over anyway, so consider *cur_bytes undefined.
250196f1 1029 */
226c3c26 1030static int handle_dependencies(BlockDriverState *bs, uint64_t guest_offset,
ecdd5333 1031 uint64_t *cur_bytes, QCowL2Meta **m)
250196f1 1032{
ff99129a 1033 BDRVQcow2State *s = bs->opaque;
250196f1 1034 QCowL2Meta *old_alloc;
65eb2e35 1035 uint64_t bytes = *cur_bytes;
250196f1 1036
250196f1
KW
1037 QLIST_FOREACH(old_alloc, &s->cluster_allocs, next_in_flight) {
1038
65eb2e35
KW
1039 uint64_t start = guest_offset;
1040 uint64_t end = start + bytes;
1041 uint64_t old_start = l2meta_cow_start(old_alloc);
1042 uint64_t old_end = l2meta_cow_end(old_alloc);
250196f1 1043
d9d74f41 1044 if (end <= old_start || start >= old_end) {
250196f1
KW
1045 /* No intersection */
1046 } else {
1047 if (start < old_start) {
1048 /* Stop at the start of a running allocation */
65eb2e35 1049 bytes = old_start - start;
250196f1 1050 } else {
65eb2e35 1051 bytes = 0;
250196f1
KW
1052 }
1053
ecdd5333
KW
1054 /* Stop if already an l2meta exists. After yielding, it wouldn't
1055 * be valid any more, so we'd have to clean up the old L2Metas
1056 * and deal with requests depending on them before starting to
1057 * gather new ones. Not worth the trouble. */
1058 if (bytes == 0 && *m) {
1059 *cur_bytes = 0;
1060 return 0;
1061 }
1062
65eb2e35 1063 if (bytes == 0) {
250196f1
KW
1064 /* Wait for the dependency to complete. We need to recheck
1065 * the free/allocated clusters when we continue. */
1ace7cea 1066 qemu_co_queue_wait(&old_alloc->dependent_requests, &s->lock);
250196f1
KW
1067 return -EAGAIN;
1068 }
1069 }
1070 }
1071
65eb2e35
KW
1072 /* Make sure that existing clusters and new allocations are only used up to
1073 * the next dependency if we shortened the request above */
1074 *cur_bytes = bytes;
250196f1 1075
226c3c26
KW
1076 return 0;
1077}
1078
0af729ec
KW
1079/*
1080 * Checks how many already allocated clusters that don't require a copy on
1081 * write there are at the given guest_offset (up to *bytes). If
1082 * *host_offset is not zero, only physically contiguous clusters beginning at
1083 * this host offset are counted.
1084 *
411d62b0
KW
1085 * Note that guest_offset may not be cluster aligned. In this case, the
1086 * returned *host_offset points to exact byte referenced by guest_offset and
1087 * therefore isn't cluster aligned as well.
0af729ec
KW
1088 *
1089 * Returns:
1090 * 0: if no allocated clusters are available at the given offset.
1091 * *bytes is normally unchanged. It is set to 0 if the cluster
1092 * is allocated and doesn't need COW, but doesn't have the right
1093 * physical offset.
1094 *
1095 * 1: if allocated clusters that don't require a COW are available at
1096 * the requested offset. *bytes may have decreased and describes
1097 * the length of the area that can be written to.
1098 *
1099 * -errno: in error cases
0af729ec
KW
1100 */
1101static int handle_copied(BlockDriverState *bs, uint64_t guest_offset,
c53ede9f 1102 uint64_t *host_offset, uint64_t *bytes, QCowL2Meta **m)
0af729ec 1103{
ff99129a 1104 BDRVQcow2State *s = bs->opaque;
0af729ec
KW
1105 int l2_index;
1106 uint64_t cluster_offset;
1107 uint64_t *l2_table;
b6d36def 1108 uint64_t nb_clusters;
c53ede9f 1109 unsigned int keep_clusters;
a3f1afb4 1110 int ret;
0af729ec
KW
1111
1112 trace_qcow2_handle_copied(qemu_coroutine_self(), guest_offset, *host_offset,
1113 *bytes);
0af729ec 1114
411d62b0
KW
1115 assert(*host_offset == 0 || offset_into_cluster(s, guest_offset)
1116 == offset_into_cluster(s, *host_offset));
1117
acb0467f
KW
1118 /*
1119 * Calculate the number of clusters to look for. We stop at L2 table
1120 * boundaries to keep things simple.
1121 */
1122 nb_clusters =
1123 size_to_clusters(s, offset_into_cluster(s, guest_offset) + *bytes);
1124
1125 l2_index = offset_to_l2_index(s, guest_offset);
1126 nb_clusters = MIN(nb_clusters, s->l2_size - l2_index);
b6d36def 1127 assert(nb_clusters <= INT_MAX);
acb0467f 1128
0af729ec
KW
1129 /* Find L2 entry for the first involved cluster */
1130 ret = get_cluster_table(bs, guest_offset, &l2_table, &l2_index);
1131 if (ret < 0) {
1132 return ret;
1133 }
1134
1135 cluster_offset = be64_to_cpu(l2_table[l2_index]);
1136
1137 /* Check how many clusters are already allocated and don't need COW */
1138 if (qcow2_get_cluster_type(cluster_offset) == QCOW2_CLUSTER_NORMAL
1139 && (cluster_offset & QCOW_OFLAG_COPIED))
1140 {
e62daaf6
KW
1141 /* If a specific host_offset is required, check it */
1142 bool offset_matches =
1143 (cluster_offset & L2E_OFFSET_MASK) == *host_offset;
1144
a97c67ee
HR
1145 if (offset_into_cluster(s, cluster_offset & L2E_OFFSET_MASK)) {
1146 qcow2_signal_corruption(bs, true, -1, -1, "Data cluster offset "
1147 "%#llx unaligned (guest offset: %#" PRIx64
1148 ")", cluster_offset & L2E_OFFSET_MASK,
1149 guest_offset);
1150 ret = -EIO;
1151 goto out;
1152 }
1153
e62daaf6
KW
1154 if (*host_offset != 0 && !offset_matches) {
1155 *bytes = 0;
1156 ret = 0;
1157 goto out;
1158 }
1159
0af729ec 1160 /* We keep all QCOW_OFLAG_COPIED clusters */
c53ede9f 1161 keep_clusters =
acb0467f 1162 count_contiguous_clusters(nb_clusters, s->cluster_size,
61653008 1163 &l2_table[l2_index],
0af729ec 1164 QCOW_OFLAG_COPIED | QCOW_OFLAG_ZERO);
c53ede9f
KW
1165 assert(keep_clusters <= nb_clusters);
1166
1167 *bytes = MIN(*bytes,
1168 keep_clusters * s->cluster_size
1169 - offset_into_cluster(s, guest_offset));
0af729ec
KW
1170
1171 ret = 1;
1172 } else {
0af729ec
KW
1173 ret = 0;
1174 }
1175
0af729ec 1176 /* Cleanup */
e62daaf6 1177out:
a3f1afb4 1178 qcow2_cache_put(bs, s->l2_table_cache, (void **) &l2_table);
0af729ec 1179
e62daaf6
KW
1180 /* Only return a host offset if we actually made progress. Otherwise we
1181 * would make requirements for handle_alloc() that it can't fulfill */
a97c67ee 1182 if (ret > 0) {
411d62b0
KW
1183 *host_offset = (cluster_offset & L2E_OFFSET_MASK)
1184 + offset_into_cluster(s, guest_offset);
e62daaf6
KW
1185 }
1186
0af729ec
KW
1187 return ret;
1188}
1189
226c3c26
KW
1190/*
1191 * Allocates new clusters for the given guest_offset.
1192 *
1193 * At most *nb_clusters are allocated, and on return *nb_clusters is updated to
1194 * contain the number of clusters that have been allocated and are contiguous
1195 * in the image file.
1196 *
1197 * If *host_offset is non-zero, it specifies the offset in the image file at
1198 * which the new clusters must start. *nb_clusters can be 0 on return in this
1199 * case if the cluster at host_offset is already in use. If *host_offset is
1200 * zero, the clusters can be allocated anywhere in the image file.
1201 *
1202 * *host_offset is updated to contain the offset into the image file at which
1203 * the first allocated cluster starts.
1204 *
1205 * Return 0 on success and -errno in error cases. -EAGAIN means that the
1206 * function has been waiting for another request and the allocation must be
1207 * restarted, but the whole request should not be failed.
1208 */
1209static int do_alloc_cluster_offset(BlockDriverState *bs, uint64_t guest_offset,
b6d36def 1210 uint64_t *host_offset, uint64_t *nb_clusters)
226c3c26 1211{
ff99129a 1212 BDRVQcow2State *s = bs->opaque;
226c3c26
KW
1213
1214 trace_qcow2_do_alloc_clusters_offset(qemu_coroutine_self(), guest_offset,
1215 *host_offset, *nb_clusters);
1216
250196f1
KW
1217 /* Allocate new clusters */
1218 trace_qcow2_cluster_alloc_phys(qemu_coroutine_self());
1219 if (*host_offset == 0) {
df021791
KW
1220 int64_t cluster_offset =
1221 qcow2_alloc_clusters(bs, *nb_clusters * s->cluster_size);
1222 if (cluster_offset < 0) {
1223 return cluster_offset;
1224 }
1225 *host_offset = cluster_offset;
1226 return 0;
250196f1 1227 } else {
b6d36def 1228 int64_t ret = qcow2_alloc_clusters_at(bs, *host_offset, *nb_clusters);
df021791
KW
1229 if (ret < 0) {
1230 return ret;
1231 }
1232 *nb_clusters = ret;
1233 return 0;
250196f1 1234 }
250196f1
KW
1235}
1236
10f0ed8b
KW
1237/*
1238 * Allocates new clusters for an area that either is yet unallocated or needs a
1239 * copy on write. If *host_offset is non-zero, clusters are only allocated if
1240 * the new allocation can match the specified host offset.
1241 *
411d62b0
KW
1242 * Note that guest_offset may not be cluster aligned. In this case, the
1243 * returned *host_offset points to exact byte referenced by guest_offset and
1244 * therefore isn't cluster aligned as well.
10f0ed8b
KW
1245 *
1246 * Returns:
1247 * 0: if no clusters could be allocated. *bytes is set to 0,
1248 * *host_offset is left unchanged.
1249 *
1250 * 1: if new clusters were allocated. *bytes may be decreased if the
1251 * new allocation doesn't cover all of the requested area.
1252 * *host_offset is updated to contain the host offset of the first
1253 * newly allocated cluster.
1254 *
1255 * -errno: in error cases
10f0ed8b
KW
1256 */
1257static int handle_alloc(BlockDriverState *bs, uint64_t guest_offset,
c37f4cd7 1258 uint64_t *host_offset, uint64_t *bytes, QCowL2Meta **m)
10f0ed8b 1259{
ff99129a 1260 BDRVQcow2State *s = bs->opaque;
10f0ed8b
KW
1261 int l2_index;
1262 uint64_t *l2_table;
1263 uint64_t entry;
b6d36def 1264 uint64_t nb_clusters;
10f0ed8b 1265 int ret;
564a6b69 1266 bool keep_old_clusters = false;
10f0ed8b 1267
564a6b69 1268 uint64_t alloc_cluster_offset = 0;
10f0ed8b
KW
1269
1270 trace_qcow2_handle_alloc(qemu_coroutine_self(), guest_offset, *host_offset,
1271 *bytes);
1272 assert(*bytes > 0);
1273
f5bc6350
KW
1274 /*
1275 * Calculate the number of clusters to look for. We stop at L2 table
1276 * boundaries to keep things simple.
1277 */
c37f4cd7
KW
1278 nb_clusters =
1279 size_to_clusters(s, offset_into_cluster(s, guest_offset) + *bytes);
1280
f5bc6350 1281 l2_index = offset_to_l2_index(s, guest_offset);
c37f4cd7 1282 nb_clusters = MIN(nb_clusters, s->l2_size - l2_index);
b6d36def 1283 assert(nb_clusters <= INT_MAX);
f5bc6350 1284
10f0ed8b
KW
1285 /* Find L2 entry for the first involved cluster */
1286 ret = get_cluster_table(bs, guest_offset, &l2_table, &l2_index);
1287 if (ret < 0) {
1288 return ret;
1289 }
1290
3b8e2e26 1291 entry = be64_to_cpu(l2_table[l2_index]);
10f0ed8b
KW
1292
1293 /* For the moment, overwrite compressed clusters one by one */
1294 if (entry & QCOW_OFLAG_COMPRESSED) {
1295 nb_clusters = 1;
1296 } else {
3b8e2e26 1297 nb_clusters = count_cow_clusters(s, nb_clusters, l2_table, l2_index);
10f0ed8b
KW
1298 }
1299
ecdd5333
KW
1300 /* This function is only called when there were no non-COW clusters, so if
1301 * we can't find any unallocated or COW clusters either, something is
1302 * wrong with our code. */
1303 assert(nb_clusters > 0);
1304
fdfab37d
EB
1305 if (qcow2_get_cluster_type(entry) == QCOW2_CLUSTER_ZERO_ALLOC &&
1306 (entry & QCOW_OFLAG_COPIED) &&
564a6b69
HR
1307 (!*host_offset ||
1308 start_of_cluster(s, *host_offset) == (entry & L2E_OFFSET_MASK)))
1309 {
93bbaf03
HR
1310 int preallocated_nb_clusters;
1311
1312 if (offset_into_cluster(s, entry & L2E_OFFSET_MASK)) {
1313 qcow2_signal_corruption(bs, true, -1, -1, "Preallocated zero "
1314 "cluster offset %#llx unaligned (guest "
1315 "offset: %#" PRIx64 ")",
1316 entry & L2E_OFFSET_MASK, guest_offset);
1317 ret = -EIO;
1318 goto fail;
1319 }
1320
564a6b69
HR
1321 /* Try to reuse preallocated zero clusters; contiguous normal clusters
1322 * would be fine, too, but count_cow_clusters() above has limited
1323 * nb_clusters already to a range of COW clusters */
93bbaf03 1324 preallocated_nb_clusters =
564a6b69
HR
1325 count_contiguous_clusters(nb_clusters, s->cluster_size,
1326 &l2_table[l2_index], QCOW_OFLAG_COPIED);
1327 assert(preallocated_nb_clusters > 0);
10f0ed8b 1328
564a6b69
HR
1329 nb_clusters = preallocated_nb_clusters;
1330 alloc_cluster_offset = entry & L2E_OFFSET_MASK;
10f0ed8b 1331
564a6b69
HR
1332 /* We want to reuse these clusters, so qcow2_alloc_cluster_link_l2()
1333 * should not free them. */
1334 keep_old_clusters = true;
10f0ed8b
KW
1335 }
1336
564a6b69
HR
1337 qcow2_cache_put(bs, s->l2_table_cache, (void **) &l2_table);
1338
ff52aab2 1339 if (!alloc_cluster_offset) {
564a6b69
HR
1340 /* Allocate, if necessary at a given offset in the image file */
1341 alloc_cluster_offset = start_of_cluster(s, *host_offset);
1342 ret = do_alloc_cluster_offset(bs, guest_offset, &alloc_cluster_offset,
1343 &nb_clusters);
1344 if (ret < 0) {
1345 goto fail;
1346 }
1347
1348 /* Can't extend contiguous allocation */
1349 if (nb_clusters == 0) {
1350 *bytes = 0;
1351 return 0;
1352 }
1353
1354 /* !*host_offset would overwrite the image header and is reserved for
1355 * "no host offset preferred". If 0 was a valid host offset, it'd
1356 * trigger the following overlap check; do that now to avoid having an
1357 * invalid value in *host_offset. */
1358 if (!alloc_cluster_offset) {
1359 ret = qcow2_pre_write_overlap_check(bs, 0, alloc_cluster_offset,
1360 nb_clusters * s->cluster_size);
1361 assert(ret < 0);
1362 goto fail;
1363 }
ff52aab2
HR
1364 }
1365
83baa9a4
KW
1366 /*
1367 * Save info needed for meta data update.
1368 *
85567393 1369 * requested_bytes: Number of bytes from the start of the first
83baa9a4
KW
1370 * newly allocated cluster to the end of the (possibly shortened
1371 * before) write request.
1372 *
85567393 1373 * avail_bytes: Number of bytes from the start of the first
83baa9a4
KW
1374 * newly allocated to the end of the last newly allocated cluster.
1375 *
85567393 1376 * nb_bytes: The number of bytes from the start of the first
83baa9a4
KW
1377 * newly allocated cluster to the end of the area that the write
1378 * request actually writes to (excluding COW at the end)
1379 */
85567393
KW
1380 uint64_t requested_bytes = *bytes + offset_into_cluster(s, guest_offset);
1381 int avail_bytes = MIN(INT_MAX, nb_clusters << s->cluster_bits);
1382 int nb_bytes = MIN(requested_bytes, avail_bytes);
88c6588c 1383 QCowL2Meta *old_m = *m;
83baa9a4 1384
83baa9a4
KW
1385 *m = g_malloc0(sizeof(**m));
1386
1387 **m = (QCowL2Meta) {
88c6588c
KW
1388 .next = old_m,
1389
411d62b0 1390 .alloc_offset = alloc_cluster_offset,
83baa9a4
KW
1391 .offset = start_of_cluster(s, guest_offset),
1392 .nb_clusters = nb_clusters,
83baa9a4 1393
564a6b69
HR
1394 .keep_old_clusters = keep_old_clusters,
1395
83baa9a4
KW
1396 .cow_start = {
1397 .offset = 0,
85567393 1398 .nb_bytes = offset_into_cluster(s, guest_offset),
83baa9a4
KW
1399 },
1400 .cow_end = {
85567393
KW
1401 .offset = nb_bytes,
1402 .nb_bytes = avail_bytes - nb_bytes,
83baa9a4
KW
1403 },
1404 };
1405 qemu_co_queue_init(&(*m)->dependent_requests);
1406 QLIST_INSERT_HEAD(&s->cluster_allocs, *m, next_in_flight);
1407
411d62b0 1408 *host_offset = alloc_cluster_offset + offset_into_cluster(s, guest_offset);
85567393 1409 *bytes = MIN(*bytes, nb_bytes - offset_into_cluster(s, guest_offset));
83baa9a4
KW
1410 assert(*bytes != 0);
1411
10f0ed8b
KW
1412 return 1;
1413
1414fail:
1415 if (*m && (*m)->nb_clusters > 0) {
1416 QLIST_REMOVE(*m, next_in_flight);
1417 }
1418 return ret;
1419}
1420
45aba42f
KW
1421/*
1422 * alloc_cluster_offset
1423 *
250196f1
KW
1424 * For a given offset on the virtual disk, find the cluster offset in qcow2
1425 * file. If the offset is not found, allocate a new cluster.
45aba42f 1426 *
250196f1 1427 * If the cluster was already allocated, m->nb_clusters is set to 0 and
a7912369 1428 * other fields in m are meaningless.
148da7ea
KW
1429 *
1430 * If the cluster is newly allocated, m->nb_clusters is set to the number of
68d100e9
KW
1431 * contiguous clusters that have been allocated. In this case, the other
1432 * fields of m are valid and contain information about the first allocated
1433 * cluster.
45aba42f 1434 *
68d100e9
KW
1435 * If the request conflicts with another write request in flight, the coroutine
1436 * is queued and will be reentered when the dependency has completed.
148da7ea
KW
1437 *
1438 * Return 0 on success and -errno in error cases
45aba42f 1439 */
f4f0d391 1440int qcow2_alloc_cluster_offset(BlockDriverState *bs, uint64_t offset,
d46a0bb2
KW
1441 unsigned int *bytes, uint64_t *host_offset,
1442 QCowL2Meta **m)
45aba42f 1443{
ff99129a 1444 BDRVQcow2State *s = bs->opaque;
710c2496 1445 uint64_t start, remaining;
250196f1 1446 uint64_t cluster_offset;
65eb2e35 1447 uint64_t cur_bytes;
710c2496 1448 int ret;
45aba42f 1449
d46a0bb2 1450 trace_qcow2_alloc_clusters_offset(qemu_coroutine_self(), offset, *bytes);
710c2496 1451
72424114 1452again:
16f0587e 1453 start = offset;
d46a0bb2 1454 remaining = *bytes;
0af729ec
KW
1455 cluster_offset = 0;
1456 *host_offset = 0;
ecdd5333
KW
1457 cur_bytes = 0;
1458 *m = NULL;
0af729ec 1459
2c3b32d2 1460 while (true) {
ecdd5333
KW
1461
1462 if (!*host_offset) {
1463 *host_offset = start_of_cluster(s, cluster_offset);
1464 }
1465
1466 assert(remaining >= cur_bytes);
1467
1468 start += cur_bytes;
1469 remaining -= cur_bytes;
1470 cluster_offset += cur_bytes;
1471
1472 if (remaining == 0) {
1473 break;
1474 }
1475
1476 cur_bytes = remaining;
1477
2c3b32d2
KW
1478 /*
1479 * Now start gathering as many contiguous clusters as possible:
1480 *
1481 * 1. Check for overlaps with in-flight allocations
1482 *
1483 * a) Overlap not in the first cluster -> shorten this request and
1484 * let the caller handle the rest in its next loop iteration.
1485 *
1486 * b) Real overlaps of two requests. Yield and restart the search
1487 * for contiguous clusters (the situation could have changed
1488 * while we were sleeping)
1489 *
1490 * c) TODO: Request starts in the same cluster as the in-flight
1491 * allocation ends. Shorten the COW of the in-fight allocation,
1492 * set cluster_offset to write to the same cluster and set up
1493 * the right synchronisation between the in-flight request and
1494 * the new one.
1495 */
ecdd5333 1496 ret = handle_dependencies(bs, start, &cur_bytes, m);
2c3b32d2 1497 if (ret == -EAGAIN) {
ecdd5333
KW
1498 /* Currently handle_dependencies() doesn't yield if we already had
1499 * an allocation. If it did, we would have to clean up the L2Meta
1500 * structs before starting over. */
1501 assert(*m == NULL);
2c3b32d2
KW
1502 goto again;
1503 } else if (ret < 0) {
1504 return ret;
ecdd5333
KW
1505 } else if (cur_bytes == 0) {
1506 break;
2c3b32d2
KW
1507 } else {
1508 /* handle_dependencies() may have decreased cur_bytes (shortened
1509 * the allocations below) so that the next dependency is processed
1510 * correctly during the next loop iteration. */
0af729ec 1511 }
710c2496 1512
2c3b32d2
KW
1513 /*
1514 * 2. Count contiguous COPIED clusters.
1515 */
1516 ret = handle_copied(bs, start, &cluster_offset, &cur_bytes, m);
1517 if (ret < 0) {
1518 return ret;
1519 } else if (ret) {
ecdd5333 1520 continue;
2c3b32d2
KW
1521 } else if (cur_bytes == 0) {
1522 break;
1523 }
060bee89 1524
2c3b32d2
KW
1525 /*
1526 * 3. If the request still hasn't completed, allocate new clusters,
1527 * considering any cluster_offset of steps 1c or 2.
1528 */
1529 ret = handle_alloc(bs, start, &cluster_offset, &cur_bytes, m);
1530 if (ret < 0) {
1531 return ret;
1532 } else if (ret) {
ecdd5333 1533 continue;
2c3b32d2
KW
1534 } else {
1535 assert(cur_bytes == 0);
1536 break;
1537 }
f5bc6350 1538 }
10f0ed8b 1539
d46a0bb2
KW
1540 *bytes -= remaining;
1541 assert(*bytes > 0);
710c2496 1542 assert(*host_offset != 0);
45aba42f 1543
148da7ea 1544 return 0;
45aba42f
KW
1545}
1546
1547static int decompress_buffer(uint8_t *out_buf, int out_buf_size,
1548 const uint8_t *buf, int buf_size)
1549{
1550 z_stream strm1, *strm = &strm1;
1551 int ret, out_len;
1552
1553 memset(strm, 0, sizeof(*strm));
1554
1555 strm->next_in = (uint8_t *)buf;
1556 strm->avail_in = buf_size;
1557 strm->next_out = out_buf;
1558 strm->avail_out = out_buf_size;
1559
1560 ret = inflateInit2(strm, -12);
1561 if (ret != Z_OK)
1562 return -1;
1563 ret = inflate(strm, Z_FINISH);
1564 out_len = strm->next_out - out_buf;
1565 if ((ret != Z_STREAM_END && ret != Z_BUF_ERROR) ||
1566 out_len != out_buf_size) {
1567 inflateEnd(strm);
1568 return -1;
1569 }
1570 inflateEnd(strm);
1571 return 0;
1572}
1573
66f82cee 1574int qcow2_decompress_cluster(BlockDriverState *bs, uint64_t cluster_offset)
45aba42f 1575{
ff99129a 1576 BDRVQcow2State *s = bs->opaque;
45aba42f
KW
1577 int ret, csize, nb_csectors, sector_offset;
1578 uint64_t coffset;
1579
1580 coffset = cluster_offset & s->cluster_offset_mask;
1581 if (s->cluster_cache_offset != coffset) {
1582 nb_csectors = ((cluster_offset >> s->csize_shift) & s->csize_mask) + 1;
1583 sector_offset = coffset & 511;
1584 csize = nb_csectors * 512 - sector_offset;
3e4c7052
SH
1585
1586 /* Allocate buffers on first decompress operation, most images are
1587 * uncompressed and the memory overhead can be avoided. The buffers
1588 * are freed in .bdrv_close().
1589 */
1590 if (!s->cluster_data) {
1591 /* one more sector for decompressed data alignment */
1592 s->cluster_data = qemu_try_blockalign(bs->file->bs,
1593 QCOW_MAX_CRYPT_CLUSTERS * s->cluster_size + 512);
1594 if (!s->cluster_data) {
1595 return -ENOMEM;
1596 }
1597 }
1598 if (!s->cluster_cache) {
1599 s->cluster_cache = g_malloc(s->cluster_size);
1600 }
1601
66f82cee 1602 BLKDBG_EVENT(bs->file, BLKDBG_READ_COMPRESSED);
fbcbbf4e 1603 ret = bdrv_read(bs->file, coffset >> 9, s->cluster_data,
9a4f4c31 1604 nb_csectors);
45aba42f 1605 if (ret < 0) {
8af36488 1606 return ret;
45aba42f
KW
1607 }
1608 if (decompress_buffer(s->cluster_cache, s->cluster_size,
1609 s->cluster_data + sector_offset, csize) < 0) {
8af36488 1610 return -EIO;
45aba42f
KW
1611 }
1612 s->cluster_cache_offset = coffset;
1613 }
1614 return 0;
1615}
5ea929e3
KW
1616
1617/*
1618 * This discards as many clusters of nb_clusters as possible at once (i.e.
1619 * all clusters in the same L2 table) and returns the number of discarded
1620 * clusters.
1621 */
1622static int discard_single_l2(BlockDriverState *bs, uint64_t offset,
b6d36def
HR
1623 uint64_t nb_clusters, enum qcow2_discard_type type,
1624 bool full_discard)
5ea929e3 1625{
ff99129a 1626 BDRVQcow2State *s = bs->opaque;
3948d1d4 1627 uint64_t *l2_table;
5ea929e3
KW
1628 int l2_index;
1629 int ret;
1630 int i;
1631
3948d1d4 1632 ret = get_cluster_table(bs, offset, &l2_table, &l2_index);
5ea929e3
KW
1633 if (ret < 0) {
1634 return ret;
1635 }
1636
1637 /* Limit nb_clusters to one L2 table */
1638 nb_clusters = MIN(nb_clusters, s->l2_size - l2_index);
b6d36def 1639 assert(nb_clusters <= INT_MAX);
5ea929e3
KW
1640
1641 for (i = 0; i < nb_clusters; i++) {
c883db0d 1642 uint64_t old_l2_entry;
5ea929e3 1643
c883db0d 1644 old_l2_entry = be64_to_cpu(l2_table[l2_index + i]);
a71835a0
KW
1645
1646 /*
808c4b6f
HR
1647 * If full_discard is false, make sure that a discarded area reads back
1648 * as zeroes for v3 images (we cannot do it for v2 without actually
1649 * writing a zero-filled buffer). We can skip the operation if the
1650 * cluster is already marked as zero, or if it's unallocated and we
1651 * don't have a backing file.
a71835a0 1652 *
237d78f8 1653 * TODO We might want to use bdrv_block_status(bs) here, but we're
a71835a0 1654 * holding s->lock, so that doesn't work today.
808c4b6f
HR
1655 *
1656 * If full_discard is true, the sector should not read back as zeroes,
1657 * but rather fall through to the backing file.
a71835a0 1658 */
c883db0d 1659 switch (qcow2_get_cluster_type(old_l2_entry)) {
bbd995d8
EB
1660 case QCOW2_CLUSTER_UNALLOCATED:
1661 if (full_discard || !bs->backing) {
1662 continue;
1663 }
1664 break;
1665
fdfab37d
EB
1666 case QCOW2_CLUSTER_ZERO_PLAIN:
1667 if (!full_discard) {
bbd995d8
EB
1668 continue;
1669 }
1670 break;
1671
fdfab37d 1672 case QCOW2_CLUSTER_ZERO_ALLOC:
bbd995d8
EB
1673 case QCOW2_CLUSTER_NORMAL:
1674 case QCOW2_CLUSTER_COMPRESSED:
1675 break;
1676
1677 default:
1678 abort();
5ea929e3
KW
1679 }
1680
1681 /* First remove L2 entries */
72e80b89 1682 qcow2_cache_entry_mark_dirty(bs, s->l2_table_cache, l2_table);
808c4b6f 1683 if (!full_discard && s->qcow_version >= 3) {
a71835a0
KW
1684 l2_table[l2_index + i] = cpu_to_be64(QCOW_OFLAG_ZERO);
1685 } else {
1686 l2_table[l2_index + i] = cpu_to_be64(0);
1687 }
5ea929e3
KW
1688
1689 /* Then decrease the refcount */
c883db0d 1690 qcow2_free_any_clusters(bs, old_l2_entry, 1, type);
5ea929e3
KW
1691 }
1692
a3f1afb4 1693 qcow2_cache_put(bs, s->l2_table_cache, (void **) &l2_table);
5ea929e3
KW
1694
1695 return nb_clusters;
1696}
1697
d2cb36af
EB
1698int qcow2_cluster_discard(BlockDriverState *bs, uint64_t offset,
1699 uint64_t bytes, enum qcow2_discard_type type,
1700 bool full_discard)
5ea929e3 1701{
ff99129a 1702 BDRVQcow2State *s = bs->opaque;
d2cb36af 1703 uint64_t end_offset = offset + bytes;
b6d36def 1704 uint64_t nb_clusters;
d2cb36af 1705 int64_t cleared;
5ea929e3
KW
1706 int ret;
1707
f10ee139 1708 /* Caller must pass aligned values, except at image end */
0c1bd469 1709 assert(QEMU_IS_ALIGNED(offset, s->cluster_size));
f10ee139
EB
1710 assert(QEMU_IS_ALIGNED(end_offset, s->cluster_size) ||
1711 end_offset == bs->total_sectors << BDRV_SECTOR_BITS);
5ea929e3 1712
d2cb36af 1713 nb_clusters = size_to_clusters(s, bytes);
5ea929e3 1714
0b919fae
KW
1715 s->cache_discards = true;
1716
5ea929e3
KW
1717 /* Each L2 table is handled by its own loop iteration */
1718 while (nb_clusters > 0) {
d2cb36af
EB
1719 cleared = discard_single_l2(bs, offset, nb_clusters, type,
1720 full_discard);
1721 if (cleared < 0) {
1722 ret = cleared;
0b919fae 1723 goto fail;
5ea929e3
KW
1724 }
1725
d2cb36af
EB
1726 nb_clusters -= cleared;
1727 offset += (cleared * s->cluster_size);
5ea929e3
KW
1728 }
1729
0b919fae
KW
1730 ret = 0;
1731fail:
1732 s->cache_discards = false;
1733 qcow2_process_discards(bs, ret);
1734
1735 return ret;
5ea929e3 1736}
621f0589
KW
1737
1738/*
1739 * This zeroes as many clusters of nb_clusters as possible at once (i.e.
1740 * all clusters in the same L2 table) and returns the number of zeroed
1741 * clusters.
1742 */
1743static int zero_single_l2(BlockDriverState *bs, uint64_t offset,
170f4b2e 1744 uint64_t nb_clusters, int flags)
621f0589 1745{
ff99129a 1746 BDRVQcow2State *s = bs->opaque;
621f0589
KW
1747 uint64_t *l2_table;
1748 int l2_index;
1749 int ret;
1750 int i;
06cc5e2b 1751 bool unmap = !!(flags & BDRV_REQ_MAY_UNMAP);
621f0589
KW
1752
1753 ret = get_cluster_table(bs, offset, &l2_table, &l2_index);
1754 if (ret < 0) {
1755 return ret;
1756 }
1757
1758 /* Limit nb_clusters to one L2 table */
1759 nb_clusters = MIN(nb_clusters, s->l2_size - l2_index);
b6d36def 1760 assert(nb_clusters <= INT_MAX);
621f0589
KW
1761
1762 for (i = 0; i < nb_clusters; i++) {
1763 uint64_t old_offset;
06cc5e2b 1764 QCow2ClusterType cluster_type;
621f0589
KW
1765
1766 old_offset = be64_to_cpu(l2_table[l2_index + i]);
1767
06cc5e2b
EB
1768 /*
1769 * Minimize L2 changes if the cluster already reads back as
1770 * zeroes with correct allocation.
1771 */
1772 cluster_type = qcow2_get_cluster_type(old_offset);
1773 if (cluster_type == QCOW2_CLUSTER_ZERO_PLAIN ||
1774 (cluster_type == QCOW2_CLUSTER_ZERO_ALLOC && !unmap)) {
1775 continue;
1776 }
1777
72e80b89 1778 qcow2_cache_entry_mark_dirty(bs, s->l2_table_cache, l2_table);
06cc5e2b 1779 if (cluster_type == QCOW2_CLUSTER_COMPRESSED || unmap) {
621f0589 1780 l2_table[l2_index + i] = cpu_to_be64(QCOW_OFLAG_ZERO);
6cfcb9b8 1781 qcow2_free_any_clusters(bs, old_offset, 1, QCOW2_DISCARD_REQUEST);
621f0589
KW
1782 } else {
1783 l2_table[l2_index + i] |= cpu_to_be64(QCOW_OFLAG_ZERO);
1784 }
1785 }
1786
a3f1afb4 1787 qcow2_cache_put(bs, s->l2_table_cache, (void **) &l2_table);
621f0589
KW
1788
1789 return nb_clusters;
1790}
1791
d2cb36af
EB
1792int qcow2_cluster_zeroize(BlockDriverState *bs, uint64_t offset,
1793 uint64_t bytes, int flags)
621f0589 1794{
ff99129a 1795 BDRVQcow2State *s = bs->opaque;
d2cb36af 1796 uint64_t end_offset = offset + bytes;
b6d36def 1797 uint64_t nb_clusters;
d2cb36af 1798 int64_t cleared;
621f0589
KW
1799 int ret;
1800
f10ee139
EB
1801 /* Caller must pass aligned values, except at image end */
1802 assert(QEMU_IS_ALIGNED(offset, s->cluster_size));
1803 assert(QEMU_IS_ALIGNED(end_offset, s->cluster_size) ||
1804 end_offset == bs->total_sectors << BDRV_SECTOR_BITS);
1805
621f0589
KW
1806 /* The zero flag is only supported by version 3 and newer */
1807 if (s->qcow_version < 3) {
1808 return -ENOTSUP;
1809 }
1810
1811 /* Each L2 table is handled by its own loop iteration */
d2cb36af 1812 nb_clusters = size_to_clusters(s, bytes);
621f0589 1813
0b919fae
KW
1814 s->cache_discards = true;
1815
621f0589 1816 while (nb_clusters > 0) {
d2cb36af
EB
1817 cleared = zero_single_l2(bs, offset, nb_clusters, flags);
1818 if (cleared < 0) {
1819 ret = cleared;
0b919fae 1820 goto fail;
621f0589
KW
1821 }
1822
d2cb36af
EB
1823 nb_clusters -= cleared;
1824 offset += (cleared * s->cluster_size);
621f0589
KW
1825 }
1826
0b919fae
KW
1827 ret = 0;
1828fail:
1829 s->cache_discards = false;
1830 qcow2_process_discards(bs, ret);
1831
1832 return ret;
621f0589 1833}
32b6444d
HR
1834
1835/*
1836 * Expands all zero clusters in a specific L1 table (or deallocates them, for
1837 * non-backed non-pre-allocated zero clusters).
1838 *
4057a2b2
HR
1839 * l1_entries and *visited_l1_entries are used to keep track of progress for
1840 * status_cb(). l1_entries contains the total number of L1 entries and
1841 * *visited_l1_entries counts all visited L1 entries.
32b6444d
HR
1842 */
1843static int expand_zero_clusters_in_l1(BlockDriverState *bs, uint64_t *l1_table,
ecf58777 1844 int l1_size, int64_t *visited_l1_entries,
4057a2b2 1845 int64_t l1_entries,
8b13976d
HR
1846 BlockDriverAmendStatusCB *status_cb,
1847 void *cb_opaque)
32b6444d 1848{
ff99129a 1849 BDRVQcow2State *s = bs->opaque;
32b6444d
HR
1850 bool is_active_l1 = (l1_table == s->l1_table);
1851 uint64_t *l2_table = NULL;
1852 int ret;
1853 int i, j;
1854
1855 if (!is_active_l1) {
1856 /* inactive L2 tables require a buffer to be stored in when loading
1857 * them from disk */
9a4f4c31 1858 l2_table = qemu_try_blockalign(bs->file->bs, s->cluster_size);
de82815d
KW
1859 if (l2_table == NULL) {
1860 return -ENOMEM;
1861 }
32b6444d
HR
1862 }
1863
1864 for (i = 0; i < l1_size; i++) {
1865 uint64_t l2_offset = l1_table[i] & L1E_OFFSET_MASK;
1866 bool l2_dirty = false;
0e06528e 1867 uint64_t l2_refcount;
32b6444d
HR
1868
1869 if (!l2_offset) {
1870 /* unallocated */
4057a2b2
HR
1871 (*visited_l1_entries)++;
1872 if (status_cb) {
8b13976d 1873 status_cb(bs, *visited_l1_entries, l1_entries, cb_opaque);
4057a2b2 1874 }
32b6444d
HR
1875 continue;
1876 }
1877
8dd93d93
HR
1878 if (offset_into_cluster(s, l2_offset)) {
1879 qcow2_signal_corruption(bs, true, -1, -1, "L2 table offset %#"
1880 PRIx64 " unaligned (L1 index: %#x)",
1881 l2_offset, i);
1882 ret = -EIO;
1883 goto fail;
1884 }
1885
32b6444d
HR
1886 if (is_active_l1) {
1887 /* get active L2 tables from cache */
1888 ret = qcow2_cache_get(bs, s->l2_table_cache, l2_offset,
1889 (void **)&l2_table);
1890 } else {
1891 /* load inactive L2 tables from disk */
fbcbbf4e 1892 ret = bdrv_read(bs->file, l2_offset / BDRV_SECTOR_SIZE,
9a4f4c31 1893 (void *)l2_table, s->cluster_sectors);
32b6444d
HR
1894 }
1895 if (ret < 0) {
1896 goto fail;
1897 }
1898
7324c10f
HR
1899 ret = qcow2_get_refcount(bs, l2_offset >> s->cluster_bits,
1900 &l2_refcount);
1901 if (ret < 0) {
ecf58777
HR
1902 goto fail;
1903 }
1904
32b6444d
HR
1905 for (j = 0; j < s->l2_size; j++) {
1906 uint64_t l2_entry = be64_to_cpu(l2_table[j]);
ecf58777 1907 int64_t offset = l2_entry & L2E_OFFSET_MASK;
3ef95218 1908 QCow2ClusterType cluster_type = qcow2_get_cluster_type(l2_entry);
32b6444d 1909
fdfab37d
EB
1910 if (cluster_type != QCOW2_CLUSTER_ZERO_PLAIN &&
1911 cluster_type != QCOW2_CLUSTER_ZERO_ALLOC) {
32b6444d
HR
1912 continue;
1913 }
1914
fdfab37d 1915 if (cluster_type == QCOW2_CLUSTER_ZERO_PLAIN) {
760e0063 1916 if (!bs->backing) {
32b6444d
HR
1917 /* not backed; therefore we can simply deallocate the
1918 * cluster */
1919 l2_table[j] = 0;
1920 l2_dirty = true;
1921 continue;
1922 }
1923
1924 offset = qcow2_alloc_clusters(bs, s->cluster_size);
1925 if (offset < 0) {
1926 ret = offset;
1927 goto fail;
1928 }
ecf58777
HR
1929
1930 if (l2_refcount > 1) {
1931 /* For shared L2 tables, set the refcount accordingly (it is
1932 * already 1 and needs to be l2_refcount) */
1933 ret = qcow2_update_cluster_refcount(bs,
2aabe7c7
HR
1934 offset >> s->cluster_bits,
1935 refcount_diff(1, l2_refcount), false,
ecf58777
HR
1936 QCOW2_DISCARD_OTHER);
1937 if (ret < 0) {
1938 qcow2_free_clusters(bs, offset, s->cluster_size,
1939 QCOW2_DISCARD_OTHER);
1940 goto fail;
1941 }
1942 }
32b6444d
HR
1943 }
1944
8dd93d93 1945 if (offset_into_cluster(s, offset)) {
bcb07dba
EB
1946 qcow2_signal_corruption(bs, true, -1, -1,
1947 "Cluster allocation offset "
8dd93d93
HR
1948 "%#" PRIx64 " unaligned (L2 offset: %#"
1949 PRIx64 ", L2 index: %#x)", offset,
1950 l2_offset, j);
fdfab37d 1951 if (cluster_type == QCOW2_CLUSTER_ZERO_PLAIN) {
8dd93d93
HR
1952 qcow2_free_clusters(bs, offset, s->cluster_size,
1953 QCOW2_DISCARD_ALWAYS);
1954 }
1955 ret = -EIO;
1956 goto fail;
1957 }
1958
231bb267 1959 ret = qcow2_pre_write_overlap_check(bs, 0, offset, s->cluster_size);
32b6444d 1960 if (ret < 0) {
fdfab37d 1961 if (cluster_type == QCOW2_CLUSTER_ZERO_PLAIN) {
320c7066
HR
1962 qcow2_free_clusters(bs, offset, s->cluster_size,
1963 QCOW2_DISCARD_ALWAYS);
1964 }
32b6444d
HR
1965 goto fail;
1966 }
1967
720ff280 1968 ret = bdrv_pwrite_zeroes(bs->file, offset, s->cluster_size, 0);
32b6444d 1969 if (ret < 0) {
fdfab37d 1970 if (cluster_type == QCOW2_CLUSTER_ZERO_PLAIN) {
320c7066
HR
1971 qcow2_free_clusters(bs, offset, s->cluster_size,
1972 QCOW2_DISCARD_ALWAYS);
1973 }
32b6444d
HR
1974 goto fail;
1975 }
1976
ecf58777
HR
1977 if (l2_refcount == 1) {
1978 l2_table[j] = cpu_to_be64(offset | QCOW_OFLAG_COPIED);
1979 } else {
1980 l2_table[j] = cpu_to_be64(offset);
e390cf5a 1981 }
ecf58777 1982 l2_dirty = true;
32b6444d
HR
1983 }
1984
1985 if (is_active_l1) {
1986 if (l2_dirty) {
72e80b89 1987 qcow2_cache_entry_mark_dirty(bs, s->l2_table_cache, l2_table);
32b6444d
HR
1988 qcow2_cache_depends_on_flush(s->l2_table_cache);
1989 }
a3f1afb4 1990 qcow2_cache_put(bs, s->l2_table_cache, (void **) &l2_table);
32b6444d
HR
1991 } else {
1992 if (l2_dirty) {
231bb267
HR
1993 ret = qcow2_pre_write_overlap_check(bs,
1994 QCOW2_OL_INACTIVE_L2 | QCOW2_OL_ACTIVE_L2, l2_offset,
32b6444d
HR
1995 s->cluster_size);
1996 if (ret < 0) {
1997 goto fail;
1998 }
1999
18d51c4b 2000 ret = bdrv_write(bs->file, l2_offset / BDRV_SECTOR_SIZE,
9a4f4c31 2001 (void *)l2_table, s->cluster_sectors);
32b6444d
HR
2002 if (ret < 0) {
2003 goto fail;
2004 }
2005 }
2006 }
4057a2b2
HR
2007
2008 (*visited_l1_entries)++;
2009 if (status_cb) {
8b13976d 2010 status_cb(bs, *visited_l1_entries, l1_entries, cb_opaque);
4057a2b2 2011 }
32b6444d
HR
2012 }
2013
2014 ret = 0;
2015
2016fail:
2017 if (l2_table) {
2018 if (!is_active_l1) {
2019 qemu_vfree(l2_table);
2020 } else {
a3f1afb4 2021 qcow2_cache_put(bs, s->l2_table_cache, (void **) &l2_table);
32b6444d
HR
2022 }
2023 }
2024 return ret;
2025}
2026
2027/*
2028 * For backed images, expands all zero clusters on the image. For non-backed
2029 * images, deallocates all non-pre-allocated zero clusters (and claims the
2030 * allocation for pre-allocated ones). This is important for downgrading to a
2031 * qcow2 version which doesn't yet support metadata zero clusters.
2032 */
4057a2b2 2033int qcow2_expand_zero_clusters(BlockDriverState *bs,
8b13976d
HR
2034 BlockDriverAmendStatusCB *status_cb,
2035 void *cb_opaque)
32b6444d 2036{
ff99129a 2037 BDRVQcow2State *s = bs->opaque;
32b6444d 2038 uint64_t *l1_table = NULL;
4057a2b2 2039 int64_t l1_entries = 0, visited_l1_entries = 0;
32b6444d
HR
2040 int ret;
2041 int i, j;
2042
4057a2b2
HR
2043 if (status_cb) {
2044 l1_entries = s->l1_size;
2045 for (i = 0; i < s->nb_snapshots; i++) {
2046 l1_entries += s->snapshots[i].l1_size;
2047 }
2048 }
2049
32b6444d 2050 ret = expand_zero_clusters_in_l1(bs, s->l1_table, s->l1_size,
4057a2b2 2051 &visited_l1_entries, l1_entries,
8b13976d 2052 status_cb, cb_opaque);
32b6444d
HR
2053 if (ret < 0) {
2054 goto fail;
2055 }
2056
2057 /* Inactive L1 tables may point to active L2 tables - therefore it is
2058 * necessary to flush the L2 table cache before trying to access the L2
2059 * tables pointed to by inactive L1 entries (else we might try to expand
2060 * zero clusters that have already been expanded); furthermore, it is also
2061 * necessary to empty the L2 table cache, since it may contain tables which
2062 * are now going to be modified directly on disk, bypassing the cache.
2063 * qcow2_cache_empty() does both for us. */
2064 ret = qcow2_cache_empty(bs, s->l2_table_cache);
2065 if (ret < 0) {
2066 goto fail;
2067 }
2068
2069 for (i = 0; i < s->nb_snapshots; i++) {
d737b78c
LV
2070 int l1_sectors = DIV_ROUND_UP(s->snapshots[i].l1_size *
2071 sizeof(uint64_t), BDRV_SECTOR_SIZE);
32b6444d
HR
2072
2073 l1_table = g_realloc(l1_table, l1_sectors * BDRV_SECTOR_SIZE);
2074
fbcbbf4e 2075 ret = bdrv_read(bs->file,
9a4f4c31
KW
2076 s->snapshots[i].l1_table_offset / BDRV_SECTOR_SIZE,
2077 (void *)l1_table, l1_sectors);
32b6444d
HR
2078 if (ret < 0) {
2079 goto fail;
2080 }
2081
2082 for (j = 0; j < s->snapshots[i].l1_size; j++) {
2083 be64_to_cpus(&l1_table[j]);
2084 }
2085
2086 ret = expand_zero_clusters_in_l1(bs, l1_table, s->snapshots[i].l1_size,
4057a2b2 2087 &visited_l1_entries, l1_entries,
8b13976d 2088 status_cb, cb_opaque);
32b6444d
HR
2089 if (ret < 0) {
2090 goto fail;
2091 }
2092 }
2093
2094 ret = 0;
2095
2096fail:
32b6444d
HR
2097 g_free(l1_table);
2098 return ret;
2099}