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