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