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