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