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