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