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