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