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