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