]> git.proxmox.com Git - qemu.git/blob - block/qcow2.c
Merge remote-tracking branch 'kwolf/for-anthony' into staging
[qemu.git] / block / qcow2.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 #include "qemu-common.h"
25 #include "block_int.h"
26 #include "module.h"
27 #include <zlib.h>
28 #include "aes.h"
29 #include "block/qcow2.h"
30 #include "qemu-error.h"
31 #include "qerror.h"
32 #include "trace.h"
33
34 /*
35 Differences with QCOW:
36
37 - Support for multiple incremental snapshots.
38 - Memory management by reference counts.
39 - Clusters which have a reference count of one have the bit
40 QCOW_OFLAG_COPIED to optimize write performance.
41 - Size of compressed clusters is stored in sectors to reduce bit usage
42 in the cluster offsets.
43 - Support for storing additional data (such as the VM state) in the
44 snapshots.
45 - If a backing store is used, the cluster size is not constrained
46 (could be backported to QCOW).
47 - L2 tables have always a size of one cluster.
48 */
49
50
51 typedef struct {
52 uint32_t magic;
53 uint32_t len;
54 } QCowExtension;
55 #define QCOW2_EXT_MAGIC_END 0
56 #define QCOW2_EXT_MAGIC_BACKING_FORMAT 0xE2792ACA
57 #define QCOW2_EXT_MAGIC_FEATURE_TABLE 0x6803f857
58
59 static int qcow2_probe(const uint8_t *buf, int buf_size, const char *filename)
60 {
61 const QCowHeader *cow_header = (const void *)buf;
62
63 if (buf_size >= sizeof(QCowHeader) &&
64 be32_to_cpu(cow_header->magic) == QCOW_MAGIC &&
65 be32_to_cpu(cow_header->version) >= 2)
66 return 100;
67 else
68 return 0;
69 }
70
71
72 /*
73 * read qcow2 extension and fill bs
74 * start reading from start_offset
75 * finish reading upon magic of value 0 or when end_offset reached
76 * unknown magic is skipped (future extension this version knows nothing about)
77 * return 0 upon success, non-0 otherwise
78 */
79 static int qcow2_read_extensions(BlockDriverState *bs, uint64_t start_offset,
80 uint64_t end_offset, void **p_feature_table)
81 {
82 BDRVQcowState *s = bs->opaque;
83 QCowExtension ext;
84 uint64_t offset;
85 int ret;
86
87 #ifdef DEBUG_EXT
88 printf("qcow2_read_extensions: start=%ld end=%ld\n", start_offset, end_offset);
89 #endif
90 offset = start_offset;
91 while (offset < end_offset) {
92
93 #ifdef DEBUG_EXT
94 /* Sanity check */
95 if (offset > s->cluster_size)
96 printf("qcow2_read_extension: suspicious offset %lu\n", offset);
97
98 printf("attempting to read extended header in offset %lu\n", offset);
99 #endif
100
101 if (bdrv_pread(bs->file, offset, &ext, sizeof(ext)) != sizeof(ext)) {
102 fprintf(stderr, "qcow2_read_extension: ERROR: "
103 "pread fail from offset %" PRIu64 "\n",
104 offset);
105 return 1;
106 }
107 be32_to_cpus(&ext.magic);
108 be32_to_cpus(&ext.len);
109 offset += sizeof(ext);
110 #ifdef DEBUG_EXT
111 printf("ext.magic = 0x%x\n", ext.magic);
112 #endif
113 if (ext.len > end_offset - offset) {
114 error_report("Header extension too large");
115 return -EINVAL;
116 }
117
118 switch (ext.magic) {
119 case QCOW2_EXT_MAGIC_END:
120 return 0;
121
122 case QCOW2_EXT_MAGIC_BACKING_FORMAT:
123 if (ext.len >= sizeof(bs->backing_format)) {
124 fprintf(stderr, "ERROR: ext_backing_format: len=%u too large"
125 " (>=%zu)\n",
126 ext.len, sizeof(bs->backing_format));
127 return 2;
128 }
129 if (bdrv_pread(bs->file, offset , bs->backing_format,
130 ext.len) != ext.len)
131 return 3;
132 bs->backing_format[ext.len] = '\0';
133 #ifdef DEBUG_EXT
134 printf("Qcow2: Got format extension %s\n", bs->backing_format);
135 #endif
136 break;
137
138 case QCOW2_EXT_MAGIC_FEATURE_TABLE:
139 if (p_feature_table != NULL) {
140 void* feature_table = g_malloc0(ext.len + 2 * sizeof(Qcow2Feature));
141 ret = bdrv_pread(bs->file, offset , feature_table, ext.len);
142 if (ret < 0) {
143 return ret;
144 }
145
146 *p_feature_table = feature_table;
147 }
148 break;
149
150 default:
151 /* unknown magic - save it in case we need to rewrite the header */
152 {
153 Qcow2UnknownHeaderExtension *uext;
154
155 uext = g_malloc0(sizeof(*uext) + ext.len);
156 uext->magic = ext.magic;
157 uext->len = ext.len;
158 QLIST_INSERT_HEAD(&s->unknown_header_ext, uext, next);
159
160 ret = bdrv_pread(bs->file, offset , uext->data, uext->len);
161 if (ret < 0) {
162 return ret;
163 }
164 }
165 break;
166 }
167
168 offset += ((ext.len + 7) & ~7);
169 }
170
171 return 0;
172 }
173
174 static void cleanup_unknown_header_ext(BlockDriverState *bs)
175 {
176 BDRVQcowState *s = bs->opaque;
177 Qcow2UnknownHeaderExtension *uext, *next;
178
179 QLIST_FOREACH_SAFE(uext, &s->unknown_header_ext, next, next) {
180 QLIST_REMOVE(uext, next);
181 g_free(uext);
182 }
183 }
184
185 static void GCC_FMT_ATTR(2, 3) report_unsupported(BlockDriverState *bs,
186 const char *fmt, ...)
187 {
188 char msg[64];
189 va_list ap;
190
191 va_start(ap, fmt);
192 vsnprintf(msg, sizeof(msg), fmt, ap);
193 va_end(ap);
194
195 qerror_report(QERR_UNKNOWN_BLOCK_FORMAT_FEATURE,
196 bs->device_name, "qcow2", msg);
197 }
198
199 static void report_unsupported_feature(BlockDriverState *bs,
200 Qcow2Feature *table, uint64_t mask)
201 {
202 while (table && table->name[0] != '\0') {
203 if (table->type == QCOW2_FEAT_TYPE_INCOMPATIBLE) {
204 if (mask & (1 << table->bit)) {
205 report_unsupported(bs, "%.46s",table->name);
206 mask &= ~(1 << table->bit);
207 }
208 }
209 table++;
210 }
211
212 if (mask) {
213 report_unsupported(bs, "Unknown incompatible feature: %" PRIx64, mask);
214 }
215 }
216
217 /*
218 * Sets the dirty bit and flushes afterwards if necessary.
219 *
220 * The incompatible_features bit is only set if the image file header was
221 * updated successfully. Therefore it is not required to check the return
222 * value of this function.
223 */
224 static int qcow2_mark_dirty(BlockDriverState *bs)
225 {
226 BDRVQcowState *s = bs->opaque;
227 uint64_t val;
228 int ret;
229
230 assert(s->qcow_version >= 3);
231
232 if (s->incompatible_features & QCOW2_INCOMPAT_DIRTY) {
233 return 0; /* already dirty */
234 }
235
236 val = cpu_to_be64(s->incompatible_features | QCOW2_INCOMPAT_DIRTY);
237 ret = bdrv_pwrite(bs->file, offsetof(QCowHeader, incompatible_features),
238 &val, sizeof(val));
239 if (ret < 0) {
240 return ret;
241 }
242 ret = bdrv_flush(bs->file);
243 if (ret < 0) {
244 return ret;
245 }
246
247 /* Only treat image as dirty if the header was updated successfully */
248 s->incompatible_features |= QCOW2_INCOMPAT_DIRTY;
249 return 0;
250 }
251
252 /*
253 * Clears the dirty bit and flushes before if necessary. Only call this
254 * function when there are no pending requests, it does not guard against
255 * concurrent requests dirtying the image.
256 */
257 static int qcow2_mark_clean(BlockDriverState *bs)
258 {
259 BDRVQcowState *s = bs->opaque;
260
261 if (s->incompatible_features & QCOW2_INCOMPAT_DIRTY) {
262 int ret = bdrv_flush(bs);
263 if (ret < 0) {
264 return ret;
265 }
266
267 s->incompatible_features &= ~QCOW2_INCOMPAT_DIRTY;
268 return qcow2_update_header(bs);
269 }
270 return 0;
271 }
272
273 static int qcow2_open(BlockDriverState *bs, int flags)
274 {
275 BDRVQcowState *s = bs->opaque;
276 int len, i, ret = 0;
277 QCowHeader header;
278 uint64_t ext_end;
279
280 ret = bdrv_pread(bs->file, 0, &header, sizeof(header));
281 if (ret < 0) {
282 goto fail;
283 }
284 be32_to_cpus(&header.magic);
285 be32_to_cpus(&header.version);
286 be64_to_cpus(&header.backing_file_offset);
287 be32_to_cpus(&header.backing_file_size);
288 be64_to_cpus(&header.size);
289 be32_to_cpus(&header.cluster_bits);
290 be32_to_cpus(&header.crypt_method);
291 be64_to_cpus(&header.l1_table_offset);
292 be32_to_cpus(&header.l1_size);
293 be64_to_cpus(&header.refcount_table_offset);
294 be32_to_cpus(&header.refcount_table_clusters);
295 be64_to_cpus(&header.snapshots_offset);
296 be32_to_cpus(&header.nb_snapshots);
297
298 if (header.magic != QCOW_MAGIC) {
299 ret = -EINVAL;
300 goto fail;
301 }
302 if (header.version < 2 || header.version > 3) {
303 report_unsupported(bs, "QCOW version %d", header.version);
304 ret = -ENOTSUP;
305 goto fail;
306 }
307
308 s->qcow_version = header.version;
309
310 /* Initialise version 3 header fields */
311 if (header.version == 2) {
312 header.incompatible_features = 0;
313 header.compatible_features = 0;
314 header.autoclear_features = 0;
315 header.refcount_order = 4;
316 header.header_length = 72;
317 } else {
318 be64_to_cpus(&header.incompatible_features);
319 be64_to_cpus(&header.compatible_features);
320 be64_to_cpus(&header.autoclear_features);
321 be32_to_cpus(&header.refcount_order);
322 be32_to_cpus(&header.header_length);
323 }
324
325 if (header.header_length > sizeof(header)) {
326 s->unknown_header_fields_size = header.header_length - sizeof(header);
327 s->unknown_header_fields = g_malloc(s->unknown_header_fields_size);
328 ret = bdrv_pread(bs->file, sizeof(header), s->unknown_header_fields,
329 s->unknown_header_fields_size);
330 if (ret < 0) {
331 goto fail;
332 }
333 }
334
335 if (header.backing_file_offset) {
336 ext_end = header.backing_file_offset;
337 } else {
338 ext_end = 1 << header.cluster_bits;
339 }
340
341 /* Handle feature bits */
342 s->incompatible_features = header.incompatible_features;
343 s->compatible_features = header.compatible_features;
344 s->autoclear_features = header.autoclear_features;
345
346 if (s->incompatible_features & ~QCOW2_INCOMPAT_MASK) {
347 void *feature_table = NULL;
348 qcow2_read_extensions(bs, header.header_length, ext_end,
349 &feature_table);
350 report_unsupported_feature(bs, feature_table,
351 s->incompatible_features &
352 ~QCOW2_INCOMPAT_MASK);
353 ret = -ENOTSUP;
354 goto fail;
355 }
356
357 /* Check support for various header values */
358 if (header.refcount_order != 4) {
359 report_unsupported(bs, "%d bit reference counts",
360 1 << header.refcount_order);
361 ret = -ENOTSUP;
362 goto fail;
363 }
364
365 if (header.cluster_bits < MIN_CLUSTER_BITS ||
366 header.cluster_bits > MAX_CLUSTER_BITS) {
367 ret = -EINVAL;
368 goto fail;
369 }
370 if (header.crypt_method > QCOW_CRYPT_AES) {
371 ret = -EINVAL;
372 goto fail;
373 }
374 s->crypt_method_header = header.crypt_method;
375 if (s->crypt_method_header) {
376 bs->encrypted = 1;
377 }
378 s->cluster_bits = header.cluster_bits;
379 s->cluster_size = 1 << s->cluster_bits;
380 s->cluster_sectors = 1 << (s->cluster_bits - 9);
381 s->l2_bits = s->cluster_bits - 3; /* L2 is always one cluster */
382 s->l2_size = 1 << s->l2_bits;
383 bs->total_sectors = header.size / 512;
384 s->csize_shift = (62 - (s->cluster_bits - 8));
385 s->csize_mask = (1 << (s->cluster_bits - 8)) - 1;
386 s->cluster_offset_mask = (1LL << s->csize_shift) - 1;
387 s->refcount_table_offset = header.refcount_table_offset;
388 s->refcount_table_size =
389 header.refcount_table_clusters << (s->cluster_bits - 3);
390
391 s->snapshots_offset = header.snapshots_offset;
392 s->nb_snapshots = header.nb_snapshots;
393
394 /* read the level 1 table */
395 s->l1_size = header.l1_size;
396 s->l1_vm_state_index = size_to_l1(s, header.size);
397 /* the L1 table must contain at least enough entries to put
398 header.size bytes */
399 if (s->l1_size < s->l1_vm_state_index) {
400 ret = -EINVAL;
401 goto fail;
402 }
403 s->l1_table_offset = header.l1_table_offset;
404 if (s->l1_size > 0) {
405 s->l1_table = g_malloc0(
406 align_offset(s->l1_size * sizeof(uint64_t), 512));
407 ret = bdrv_pread(bs->file, s->l1_table_offset, s->l1_table,
408 s->l1_size * sizeof(uint64_t));
409 if (ret < 0) {
410 goto fail;
411 }
412 for(i = 0;i < s->l1_size; i++) {
413 be64_to_cpus(&s->l1_table[i]);
414 }
415 }
416
417 /* alloc L2 table/refcount block cache */
418 s->l2_table_cache = qcow2_cache_create(bs, L2_CACHE_SIZE);
419 s->refcount_block_cache = qcow2_cache_create(bs, REFCOUNT_CACHE_SIZE);
420
421 s->cluster_cache = g_malloc(s->cluster_size);
422 /* one more sector for decompressed data alignment */
423 s->cluster_data = qemu_blockalign(bs, QCOW_MAX_CRYPT_CLUSTERS * s->cluster_size
424 + 512);
425 s->cluster_cache_offset = -1;
426 s->flags = flags;
427
428 ret = qcow2_refcount_init(bs);
429 if (ret != 0) {
430 goto fail;
431 }
432
433 QLIST_INIT(&s->cluster_allocs);
434
435 /* read qcow2 extensions */
436 if (qcow2_read_extensions(bs, header.header_length, ext_end, NULL)) {
437 ret = -EINVAL;
438 goto fail;
439 }
440
441 /* read the backing file name */
442 if (header.backing_file_offset != 0) {
443 len = header.backing_file_size;
444 if (len > 1023) {
445 len = 1023;
446 }
447 ret = bdrv_pread(bs->file, header.backing_file_offset,
448 bs->backing_file, len);
449 if (ret < 0) {
450 goto fail;
451 }
452 bs->backing_file[len] = '\0';
453 }
454
455 ret = qcow2_read_snapshots(bs);
456 if (ret < 0) {
457 goto fail;
458 }
459
460 /* Clear unknown autoclear feature bits */
461 if (!bs->read_only && s->autoclear_features != 0) {
462 s->autoclear_features = 0;
463 ret = qcow2_update_header(bs);
464 if (ret < 0) {
465 goto fail;
466 }
467 }
468
469 /* Initialise locks */
470 qemu_co_mutex_init(&s->lock);
471
472 /* Repair image if dirty */
473 if ((s->incompatible_features & QCOW2_INCOMPAT_DIRTY) &&
474 !bs->read_only) {
475 BdrvCheckResult result = {0};
476
477 ret = qcow2_check_refcounts(bs, &result, BDRV_FIX_ERRORS);
478 if (ret < 0) {
479 goto fail;
480 }
481
482 ret = qcow2_mark_clean(bs);
483 if (ret < 0) {
484 goto fail;
485 }
486 }
487
488 #ifdef DEBUG_ALLOC
489 {
490 BdrvCheckResult result = {0};
491 qcow2_check_refcounts(bs, &result, 0);
492 }
493 #endif
494 return ret;
495
496 fail:
497 g_free(s->unknown_header_fields);
498 cleanup_unknown_header_ext(bs);
499 qcow2_free_snapshots(bs);
500 qcow2_refcount_close(bs);
501 g_free(s->l1_table);
502 if (s->l2_table_cache) {
503 qcow2_cache_destroy(bs, s->l2_table_cache);
504 }
505 g_free(s->cluster_cache);
506 qemu_vfree(s->cluster_data);
507 return ret;
508 }
509
510 static int qcow2_set_key(BlockDriverState *bs, const char *key)
511 {
512 BDRVQcowState *s = bs->opaque;
513 uint8_t keybuf[16];
514 int len, i;
515
516 memset(keybuf, 0, 16);
517 len = strlen(key);
518 if (len > 16)
519 len = 16;
520 /* XXX: we could compress the chars to 7 bits to increase
521 entropy */
522 for(i = 0;i < len;i++) {
523 keybuf[i] = key[i];
524 }
525 s->crypt_method = s->crypt_method_header;
526
527 if (AES_set_encrypt_key(keybuf, 128, &s->aes_encrypt_key) != 0)
528 return -1;
529 if (AES_set_decrypt_key(keybuf, 128, &s->aes_decrypt_key) != 0)
530 return -1;
531 #if 0
532 /* test */
533 {
534 uint8_t in[16];
535 uint8_t out[16];
536 uint8_t tmp[16];
537 for(i=0;i<16;i++)
538 in[i] = i;
539 AES_encrypt(in, tmp, &s->aes_encrypt_key);
540 AES_decrypt(tmp, out, &s->aes_decrypt_key);
541 for(i = 0; i < 16; i++)
542 printf(" %02x", tmp[i]);
543 printf("\n");
544 for(i = 0; i < 16; i++)
545 printf(" %02x", out[i]);
546 printf("\n");
547 }
548 #endif
549 return 0;
550 }
551
552 static int coroutine_fn qcow2_co_is_allocated(BlockDriverState *bs,
553 int64_t sector_num, int nb_sectors, int *pnum)
554 {
555 BDRVQcowState *s = bs->opaque;
556 uint64_t cluster_offset;
557 int ret;
558
559 *pnum = nb_sectors;
560 /* FIXME We can get errors here, but the bdrv_co_is_allocated interface
561 * can't pass them on today */
562 qemu_co_mutex_lock(&s->lock);
563 ret = qcow2_get_cluster_offset(bs, sector_num << 9, pnum, &cluster_offset);
564 qemu_co_mutex_unlock(&s->lock);
565 if (ret < 0) {
566 *pnum = 0;
567 }
568
569 return (cluster_offset != 0);
570 }
571
572 /* handle reading after the end of the backing file */
573 int qcow2_backing_read1(BlockDriverState *bs, QEMUIOVector *qiov,
574 int64_t sector_num, int nb_sectors)
575 {
576 int n1;
577 if ((sector_num + nb_sectors) <= bs->total_sectors)
578 return nb_sectors;
579 if (sector_num >= bs->total_sectors)
580 n1 = 0;
581 else
582 n1 = bs->total_sectors - sector_num;
583
584 qemu_iovec_memset(qiov, 512 * n1, 0, 512 * (nb_sectors - n1));
585
586 return n1;
587 }
588
589 static coroutine_fn int qcow2_co_readv(BlockDriverState *bs, int64_t sector_num,
590 int remaining_sectors, QEMUIOVector *qiov)
591 {
592 BDRVQcowState *s = bs->opaque;
593 int index_in_cluster, n1;
594 int ret;
595 int cur_nr_sectors; /* number of sectors in current iteration */
596 uint64_t cluster_offset = 0;
597 uint64_t bytes_done = 0;
598 QEMUIOVector hd_qiov;
599 uint8_t *cluster_data = NULL;
600
601 qemu_iovec_init(&hd_qiov, qiov->niov);
602
603 qemu_co_mutex_lock(&s->lock);
604
605 while (remaining_sectors != 0) {
606
607 /* prepare next request */
608 cur_nr_sectors = remaining_sectors;
609 if (s->crypt_method) {
610 cur_nr_sectors = MIN(cur_nr_sectors,
611 QCOW_MAX_CRYPT_CLUSTERS * s->cluster_sectors);
612 }
613
614 ret = qcow2_get_cluster_offset(bs, sector_num << 9,
615 &cur_nr_sectors, &cluster_offset);
616 if (ret < 0) {
617 goto fail;
618 }
619
620 index_in_cluster = sector_num & (s->cluster_sectors - 1);
621
622 qemu_iovec_reset(&hd_qiov);
623 qemu_iovec_concat(&hd_qiov, qiov, bytes_done,
624 cur_nr_sectors * 512);
625
626 switch (ret) {
627 case QCOW2_CLUSTER_UNALLOCATED:
628
629 if (bs->backing_hd) {
630 /* read from the base image */
631 n1 = qcow2_backing_read1(bs->backing_hd, &hd_qiov,
632 sector_num, cur_nr_sectors);
633 if (n1 > 0) {
634 BLKDBG_EVENT(bs->file, BLKDBG_READ_BACKING_AIO);
635 qemu_co_mutex_unlock(&s->lock);
636 ret = bdrv_co_readv(bs->backing_hd, sector_num,
637 n1, &hd_qiov);
638 qemu_co_mutex_lock(&s->lock);
639 if (ret < 0) {
640 goto fail;
641 }
642 }
643 } else {
644 /* Note: in this case, no need to wait */
645 qemu_iovec_memset(&hd_qiov, 0, 0, 512 * cur_nr_sectors);
646 }
647 break;
648
649 case QCOW2_CLUSTER_ZERO:
650 if (s->qcow_version < 3) {
651 ret = -EIO;
652 goto fail;
653 }
654 qemu_iovec_memset(&hd_qiov, 0, 0, 512 * cur_nr_sectors);
655 break;
656
657 case QCOW2_CLUSTER_COMPRESSED:
658 /* add AIO support for compressed blocks ? */
659 ret = qcow2_decompress_cluster(bs, cluster_offset);
660 if (ret < 0) {
661 goto fail;
662 }
663
664 qemu_iovec_from_buf(&hd_qiov, 0,
665 s->cluster_cache + index_in_cluster * 512,
666 512 * cur_nr_sectors);
667 break;
668
669 case QCOW2_CLUSTER_NORMAL:
670 if ((cluster_offset & 511) != 0) {
671 ret = -EIO;
672 goto fail;
673 }
674
675 if (s->crypt_method) {
676 /*
677 * For encrypted images, read everything into a temporary
678 * contiguous buffer on which the AES functions can work.
679 */
680 if (!cluster_data) {
681 cluster_data =
682 qemu_blockalign(bs, QCOW_MAX_CRYPT_CLUSTERS * s->cluster_size);
683 }
684
685 assert(cur_nr_sectors <=
686 QCOW_MAX_CRYPT_CLUSTERS * s->cluster_sectors);
687 qemu_iovec_reset(&hd_qiov);
688 qemu_iovec_add(&hd_qiov, cluster_data,
689 512 * cur_nr_sectors);
690 }
691
692 BLKDBG_EVENT(bs->file, BLKDBG_READ_AIO);
693 qemu_co_mutex_unlock(&s->lock);
694 ret = bdrv_co_readv(bs->file,
695 (cluster_offset >> 9) + index_in_cluster,
696 cur_nr_sectors, &hd_qiov);
697 qemu_co_mutex_lock(&s->lock);
698 if (ret < 0) {
699 goto fail;
700 }
701 if (s->crypt_method) {
702 qcow2_encrypt_sectors(s, sector_num, cluster_data,
703 cluster_data, cur_nr_sectors, 0, &s->aes_decrypt_key);
704 qemu_iovec_from_buf(qiov, bytes_done,
705 cluster_data, 512 * cur_nr_sectors);
706 }
707 break;
708
709 default:
710 g_assert_not_reached();
711 ret = -EIO;
712 goto fail;
713 }
714
715 remaining_sectors -= cur_nr_sectors;
716 sector_num += cur_nr_sectors;
717 bytes_done += cur_nr_sectors * 512;
718 }
719 ret = 0;
720
721 fail:
722 qemu_co_mutex_unlock(&s->lock);
723
724 qemu_iovec_destroy(&hd_qiov);
725 qemu_vfree(cluster_data);
726
727 return ret;
728 }
729
730 static void run_dependent_requests(BDRVQcowState *s, QCowL2Meta *m)
731 {
732 /* Take the request off the list of running requests */
733 if (m->nb_clusters != 0) {
734 QLIST_REMOVE(m, next_in_flight);
735 }
736
737 /* Restart all dependent requests */
738 if (!qemu_co_queue_empty(&m->dependent_requests)) {
739 qemu_co_mutex_unlock(&s->lock);
740 qemu_co_queue_restart_all(&m->dependent_requests);
741 qemu_co_mutex_lock(&s->lock);
742 }
743 }
744
745 static coroutine_fn int qcow2_co_writev(BlockDriverState *bs,
746 int64_t sector_num,
747 int remaining_sectors,
748 QEMUIOVector *qiov)
749 {
750 BDRVQcowState *s = bs->opaque;
751 int index_in_cluster;
752 int n_end;
753 int ret;
754 int cur_nr_sectors; /* number of sectors in current iteration */
755 uint64_t cluster_offset;
756 QEMUIOVector hd_qiov;
757 uint64_t bytes_done = 0;
758 uint8_t *cluster_data = NULL;
759 QCowL2Meta l2meta = {
760 .nb_clusters = 0,
761 };
762
763 trace_qcow2_writev_start_req(qemu_coroutine_self(), sector_num,
764 remaining_sectors);
765
766 qemu_co_queue_init(&l2meta.dependent_requests);
767
768 qemu_iovec_init(&hd_qiov, qiov->niov);
769
770 s->cluster_cache_offset = -1; /* disable compressed cache */
771
772 qemu_co_mutex_lock(&s->lock);
773
774 while (remaining_sectors != 0) {
775
776 trace_qcow2_writev_start_part(qemu_coroutine_self());
777 index_in_cluster = sector_num & (s->cluster_sectors - 1);
778 n_end = index_in_cluster + remaining_sectors;
779 if (s->crypt_method &&
780 n_end > QCOW_MAX_CRYPT_CLUSTERS * s->cluster_sectors) {
781 n_end = QCOW_MAX_CRYPT_CLUSTERS * s->cluster_sectors;
782 }
783
784 ret = qcow2_alloc_cluster_offset(bs, sector_num << 9,
785 index_in_cluster, n_end, &cur_nr_sectors, &l2meta);
786 if (ret < 0) {
787 goto fail;
788 }
789
790 if (l2meta.nb_clusters > 0 &&
791 (s->compatible_features & QCOW2_COMPAT_LAZY_REFCOUNTS)) {
792 qcow2_mark_dirty(bs);
793 }
794
795 cluster_offset = l2meta.cluster_offset;
796 assert((cluster_offset & 511) == 0);
797
798 qemu_iovec_reset(&hd_qiov);
799 qemu_iovec_concat(&hd_qiov, qiov, bytes_done,
800 cur_nr_sectors * 512);
801
802 if (s->crypt_method) {
803 if (!cluster_data) {
804 cluster_data = qemu_blockalign(bs, QCOW_MAX_CRYPT_CLUSTERS *
805 s->cluster_size);
806 }
807
808 assert(hd_qiov.size <=
809 QCOW_MAX_CRYPT_CLUSTERS * s->cluster_size);
810 qemu_iovec_to_buf(&hd_qiov, 0, cluster_data, hd_qiov.size);
811
812 qcow2_encrypt_sectors(s, sector_num, cluster_data,
813 cluster_data, cur_nr_sectors, 1, &s->aes_encrypt_key);
814
815 qemu_iovec_reset(&hd_qiov);
816 qemu_iovec_add(&hd_qiov, cluster_data,
817 cur_nr_sectors * 512);
818 }
819
820 BLKDBG_EVENT(bs->file, BLKDBG_WRITE_AIO);
821 qemu_co_mutex_unlock(&s->lock);
822 trace_qcow2_writev_data(qemu_coroutine_self(),
823 (cluster_offset >> 9) + index_in_cluster);
824 ret = bdrv_co_writev(bs->file,
825 (cluster_offset >> 9) + index_in_cluster,
826 cur_nr_sectors, &hd_qiov);
827 qemu_co_mutex_lock(&s->lock);
828 if (ret < 0) {
829 goto fail;
830 }
831
832 ret = qcow2_alloc_cluster_link_l2(bs, &l2meta);
833 if (ret < 0) {
834 goto fail;
835 }
836
837 run_dependent_requests(s, &l2meta);
838
839 remaining_sectors -= cur_nr_sectors;
840 sector_num += cur_nr_sectors;
841 bytes_done += cur_nr_sectors * 512;
842 trace_qcow2_writev_done_part(qemu_coroutine_self(), cur_nr_sectors);
843 }
844 ret = 0;
845
846 fail:
847 run_dependent_requests(s, &l2meta);
848
849 qemu_co_mutex_unlock(&s->lock);
850
851 qemu_iovec_destroy(&hd_qiov);
852 qemu_vfree(cluster_data);
853 trace_qcow2_writev_done_req(qemu_coroutine_self(), ret);
854
855 return ret;
856 }
857
858 static void qcow2_close(BlockDriverState *bs)
859 {
860 BDRVQcowState *s = bs->opaque;
861 g_free(s->l1_table);
862
863 qcow2_cache_flush(bs, s->l2_table_cache);
864 qcow2_cache_flush(bs, s->refcount_block_cache);
865
866 qcow2_mark_clean(bs);
867
868 qcow2_cache_destroy(bs, s->l2_table_cache);
869 qcow2_cache_destroy(bs, s->refcount_block_cache);
870
871 g_free(s->unknown_header_fields);
872 cleanup_unknown_header_ext(bs);
873
874 g_free(s->cluster_cache);
875 qemu_vfree(s->cluster_data);
876 qcow2_refcount_close(bs);
877 qcow2_free_snapshots(bs);
878 }
879
880 static void qcow2_invalidate_cache(BlockDriverState *bs)
881 {
882 BDRVQcowState *s = bs->opaque;
883 int flags = s->flags;
884 AES_KEY aes_encrypt_key;
885 AES_KEY aes_decrypt_key;
886 uint32_t crypt_method = 0;
887
888 /*
889 * Backing files are read-only which makes all of their metadata immutable,
890 * that means we don't have to worry about reopening them here.
891 */
892
893 if (s->crypt_method) {
894 crypt_method = s->crypt_method;
895 memcpy(&aes_encrypt_key, &s->aes_encrypt_key, sizeof(aes_encrypt_key));
896 memcpy(&aes_decrypt_key, &s->aes_decrypt_key, sizeof(aes_decrypt_key));
897 }
898
899 qcow2_close(bs);
900
901 memset(s, 0, sizeof(BDRVQcowState));
902 qcow2_open(bs, flags);
903
904 if (crypt_method) {
905 s->crypt_method = crypt_method;
906 memcpy(&s->aes_encrypt_key, &aes_encrypt_key, sizeof(aes_encrypt_key));
907 memcpy(&s->aes_decrypt_key, &aes_decrypt_key, sizeof(aes_decrypt_key));
908 }
909 }
910
911 static size_t header_ext_add(char *buf, uint32_t magic, const void *s,
912 size_t len, size_t buflen)
913 {
914 QCowExtension *ext_backing_fmt = (QCowExtension*) buf;
915 size_t ext_len = sizeof(QCowExtension) + ((len + 7) & ~7);
916
917 if (buflen < ext_len) {
918 return -ENOSPC;
919 }
920
921 *ext_backing_fmt = (QCowExtension) {
922 .magic = cpu_to_be32(magic),
923 .len = cpu_to_be32(len),
924 };
925 memcpy(buf + sizeof(QCowExtension), s, len);
926
927 return ext_len;
928 }
929
930 /*
931 * Updates the qcow2 header, including the variable length parts of it, i.e.
932 * the backing file name and all extensions. qcow2 was not designed to allow
933 * such changes, so if we run out of space (we can only use the first cluster)
934 * this function may fail.
935 *
936 * Returns 0 on success, -errno in error cases.
937 */
938 int qcow2_update_header(BlockDriverState *bs)
939 {
940 BDRVQcowState *s = bs->opaque;
941 QCowHeader *header;
942 char *buf;
943 size_t buflen = s->cluster_size;
944 int ret;
945 uint64_t total_size;
946 uint32_t refcount_table_clusters;
947 size_t header_length;
948 Qcow2UnknownHeaderExtension *uext;
949
950 buf = qemu_blockalign(bs, buflen);
951
952 /* Header structure */
953 header = (QCowHeader*) buf;
954
955 if (buflen < sizeof(*header)) {
956 ret = -ENOSPC;
957 goto fail;
958 }
959
960 header_length = sizeof(*header) + s->unknown_header_fields_size;
961 total_size = bs->total_sectors * BDRV_SECTOR_SIZE;
962 refcount_table_clusters = s->refcount_table_size >> (s->cluster_bits - 3);
963
964 *header = (QCowHeader) {
965 /* Version 2 fields */
966 .magic = cpu_to_be32(QCOW_MAGIC),
967 .version = cpu_to_be32(s->qcow_version),
968 .backing_file_offset = 0,
969 .backing_file_size = 0,
970 .cluster_bits = cpu_to_be32(s->cluster_bits),
971 .size = cpu_to_be64(total_size),
972 .crypt_method = cpu_to_be32(s->crypt_method_header),
973 .l1_size = cpu_to_be32(s->l1_size),
974 .l1_table_offset = cpu_to_be64(s->l1_table_offset),
975 .refcount_table_offset = cpu_to_be64(s->refcount_table_offset),
976 .refcount_table_clusters = cpu_to_be32(refcount_table_clusters),
977 .nb_snapshots = cpu_to_be32(s->nb_snapshots),
978 .snapshots_offset = cpu_to_be64(s->snapshots_offset),
979
980 /* Version 3 fields */
981 .incompatible_features = cpu_to_be64(s->incompatible_features),
982 .compatible_features = cpu_to_be64(s->compatible_features),
983 .autoclear_features = cpu_to_be64(s->autoclear_features),
984 .refcount_order = cpu_to_be32(3 + REFCOUNT_SHIFT),
985 .header_length = cpu_to_be32(header_length),
986 };
987
988 /* For older versions, write a shorter header */
989 switch (s->qcow_version) {
990 case 2:
991 ret = offsetof(QCowHeader, incompatible_features);
992 break;
993 case 3:
994 ret = sizeof(*header);
995 break;
996 default:
997 ret = -EINVAL;
998 goto fail;
999 }
1000
1001 buf += ret;
1002 buflen -= ret;
1003 memset(buf, 0, buflen);
1004
1005 /* Preserve any unknown field in the header */
1006 if (s->unknown_header_fields_size) {
1007 if (buflen < s->unknown_header_fields_size) {
1008 ret = -ENOSPC;
1009 goto fail;
1010 }
1011
1012 memcpy(buf, s->unknown_header_fields, s->unknown_header_fields_size);
1013 buf += s->unknown_header_fields_size;
1014 buflen -= s->unknown_header_fields_size;
1015 }
1016
1017 /* Backing file format header extension */
1018 if (*bs->backing_format) {
1019 ret = header_ext_add(buf, QCOW2_EXT_MAGIC_BACKING_FORMAT,
1020 bs->backing_format, strlen(bs->backing_format),
1021 buflen);
1022 if (ret < 0) {
1023 goto fail;
1024 }
1025
1026 buf += ret;
1027 buflen -= ret;
1028 }
1029
1030 /* Feature table */
1031 Qcow2Feature features[] = {
1032 {
1033 .type = QCOW2_FEAT_TYPE_INCOMPATIBLE,
1034 .bit = QCOW2_INCOMPAT_DIRTY_BITNR,
1035 .name = "dirty bit",
1036 },
1037 {
1038 .type = QCOW2_FEAT_TYPE_COMPATIBLE,
1039 .bit = QCOW2_COMPAT_LAZY_REFCOUNTS_BITNR,
1040 .name = "lazy refcounts",
1041 },
1042 };
1043
1044 ret = header_ext_add(buf, QCOW2_EXT_MAGIC_FEATURE_TABLE,
1045 features, sizeof(features), buflen);
1046 if (ret < 0) {
1047 goto fail;
1048 }
1049 buf += ret;
1050 buflen -= ret;
1051
1052 /* Keep unknown header extensions */
1053 QLIST_FOREACH(uext, &s->unknown_header_ext, next) {
1054 ret = header_ext_add(buf, uext->magic, uext->data, uext->len, buflen);
1055 if (ret < 0) {
1056 goto fail;
1057 }
1058
1059 buf += ret;
1060 buflen -= ret;
1061 }
1062
1063 /* End of header extensions */
1064 ret = header_ext_add(buf, QCOW2_EXT_MAGIC_END, NULL, 0, buflen);
1065 if (ret < 0) {
1066 goto fail;
1067 }
1068
1069 buf += ret;
1070 buflen -= ret;
1071
1072 /* Backing file name */
1073 if (*bs->backing_file) {
1074 size_t backing_file_len = strlen(bs->backing_file);
1075
1076 if (buflen < backing_file_len) {
1077 ret = -ENOSPC;
1078 goto fail;
1079 }
1080
1081 strncpy(buf, bs->backing_file, buflen);
1082
1083 header->backing_file_offset = cpu_to_be64(buf - ((char*) header));
1084 header->backing_file_size = cpu_to_be32(backing_file_len);
1085 }
1086
1087 /* Write the new header */
1088 ret = bdrv_pwrite(bs->file, 0, header, s->cluster_size);
1089 if (ret < 0) {
1090 goto fail;
1091 }
1092
1093 ret = 0;
1094 fail:
1095 qemu_vfree(header);
1096 return ret;
1097 }
1098
1099 static int qcow2_change_backing_file(BlockDriverState *bs,
1100 const char *backing_file, const char *backing_fmt)
1101 {
1102 pstrcpy(bs->backing_file, sizeof(bs->backing_file), backing_file ?: "");
1103 pstrcpy(bs->backing_format, sizeof(bs->backing_format), backing_fmt ?: "");
1104
1105 return qcow2_update_header(bs);
1106 }
1107
1108 static int preallocate(BlockDriverState *bs)
1109 {
1110 uint64_t nb_sectors;
1111 uint64_t offset;
1112 int num;
1113 int ret;
1114 QCowL2Meta meta;
1115
1116 nb_sectors = bdrv_getlength(bs) >> 9;
1117 offset = 0;
1118 qemu_co_queue_init(&meta.dependent_requests);
1119 meta.cluster_offset = 0;
1120
1121 while (nb_sectors) {
1122 num = MIN(nb_sectors, INT_MAX >> 9);
1123 ret = qcow2_alloc_cluster_offset(bs, offset, 0, num, &num, &meta);
1124 if (ret < 0) {
1125 return ret;
1126 }
1127
1128 ret = qcow2_alloc_cluster_link_l2(bs, &meta);
1129 if (ret < 0) {
1130 qcow2_free_any_clusters(bs, meta.cluster_offset, meta.nb_clusters);
1131 return ret;
1132 }
1133
1134 /* There are no dependent requests, but we need to remove our request
1135 * from the list of in-flight requests */
1136 run_dependent_requests(bs->opaque, &meta);
1137
1138 /* TODO Preallocate data if requested */
1139
1140 nb_sectors -= num;
1141 offset += num << 9;
1142 }
1143
1144 /*
1145 * It is expected that the image file is large enough to actually contain
1146 * all of the allocated clusters (otherwise we get failing reads after
1147 * EOF). Extend the image to the last allocated sector.
1148 */
1149 if (meta.cluster_offset != 0) {
1150 uint8_t buf[512];
1151 memset(buf, 0, 512);
1152 ret = bdrv_write(bs->file, (meta.cluster_offset >> 9) + num - 1, buf, 1);
1153 if (ret < 0) {
1154 return ret;
1155 }
1156 }
1157
1158 return 0;
1159 }
1160
1161 static int qcow2_create2(const char *filename, int64_t total_size,
1162 const char *backing_file, const char *backing_format,
1163 int flags, size_t cluster_size, int prealloc,
1164 QEMUOptionParameter *options, int version)
1165 {
1166 /* Calculate cluster_bits */
1167 int cluster_bits;
1168 cluster_bits = ffs(cluster_size) - 1;
1169 if (cluster_bits < MIN_CLUSTER_BITS || cluster_bits > MAX_CLUSTER_BITS ||
1170 (1 << cluster_bits) != cluster_size)
1171 {
1172 error_report(
1173 "Cluster size must be a power of two between %d and %dk",
1174 1 << MIN_CLUSTER_BITS, 1 << (MAX_CLUSTER_BITS - 10));
1175 return -EINVAL;
1176 }
1177
1178 /*
1179 * Open the image file and write a minimal qcow2 header.
1180 *
1181 * We keep things simple and start with a zero-sized image. We also
1182 * do without refcount blocks or a L1 table for now. We'll fix the
1183 * inconsistency later.
1184 *
1185 * We do need a refcount table because growing the refcount table means
1186 * allocating two new refcount blocks - the seconds of which would be at
1187 * 2 GB for 64k clusters, and we don't want to have a 2 GB initial file
1188 * size for any qcow2 image.
1189 */
1190 BlockDriverState* bs;
1191 QCowHeader header;
1192 uint8_t* refcount_table;
1193 int ret;
1194
1195 ret = bdrv_create_file(filename, options);
1196 if (ret < 0) {
1197 return ret;
1198 }
1199
1200 ret = bdrv_file_open(&bs, filename, BDRV_O_RDWR);
1201 if (ret < 0) {
1202 return ret;
1203 }
1204
1205 /* Write the header */
1206 memset(&header, 0, sizeof(header));
1207 header.magic = cpu_to_be32(QCOW_MAGIC);
1208 header.version = cpu_to_be32(version);
1209 header.cluster_bits = cpu_to_be32(cluster_bits);
1210 header.size = cpu_to_be64(0);
1211 header.l1_table_offset = cpu_to_be64(0);
1212 header.l1_size = cpu_to_be32(0);
1213 header.refcount_table_offset = cpu_to_be64(cluster_size);
1214 header.refcount_table_clusters = cpu_to_be32(1);
1215 header.refcount_order = cpu_to_be32(3 + REFCOUNT_SHIFT);
1216 header.header_length = cpu_to_be32(sizeof(header));
1217
1218 if (flags & BLOCK_FLAG_ENCRYPT) {
1219 header.crypt_method = cpu_to_be32(QCOW_CRYPT_AES);
1220 } else {
1221 header.crypt_method = cpu_to_be32(QCOW_CRYPT_NONE);
1222 }
1223
1224 if (flags & BLOCK_FLAG_LAZY_REFCOUNTS) {
1225 header.compatible_features |=
1226 cpu_to_be64(QCOW2_COMPAT_LAZY_REFCOUNTS);
1227 }
1228
1229 ret = bdrv_pwrite(bs, 0, &header, sizeof(header));
1230 if (ret < 0) {
1231 goto out;
1232 }
1233
1234 /* Write an empty refcount table */
1235 refcount_table = g_malloc0(cluster_size);
1236 ret = bdrv_pwrite(bs, cluster_size, refcount_table, cluster_size);
1237 g_free(refcount_table);
1238
1239 if (ret < 0) {
1240 goto out;
1241 }
1242
1243 bdrv_close(bs);
1244
1245 /*
1246 * And now open the image and make it consistent first (i.e. increase the
1247 * refcount of the cluster that is occupied by the header and the refcount
1248 * table)
1249 */
1250 BlockDriver* drv = bdrv_find_format("qcow2");
1251 assert(drv != NULL);
1252 ret = bdrv_open(bs, filename,
1253 BDRV_O_RDWR | BDRV_O_CACHE_WB | BDRV_O_NO_FLUSH, drv);
1254 if (ret < 0) {
1255 goto out;
1256 }
1257
1258 ret = qcow2_alloc_clusters(bs, 2 * cluster_size);
1259 if (ret < 0) {
1260 goto out;
1261
1262 } else if (ret != 0) {
1263 error_report("Huh, first cluster in empty image is already in use?");
1264 abort();
1265 }
1266
1267 /* Okay, now that we have a valid image, let's give it the right size */
1268 ret = bdrv_truncate(bs, total_size * BDRV_SECTOR_SIZE);
1269 if (ret < 0) {
1270 goto out;
1271 }
1272
1273 /* Want a backing file? There you go.*/
1274 if (backing_file) {
1275 ret = bdrv_change_backing_file(bs, backing_file, backing_format);
1276 if (ret < 0) {
1277 goto out;
1278 }
1279 }
1280
1281 /* And if we're supposed to preallocate metadata, do that now */
1282 if (prealloc) {
1283 BDRVQcowState *s = bs->opaque;
1284 qemu_co_mutex_lock(&s->lock);
1285 ret = preallocate(bs);
1286 qemu_co_mutex_unlock(&s->lock);
1287 if (ret < 0) {
1288 goto out;
1289 }
1290 }
1291
1292 ret = 0;
1293 out:
1294 bdrv_delete(bs);
1295 return ret;
1296 }
1297
1298 static int qcow2_create(const char *filename, QEMUOptionParameter *options)
1299 {
1300 const char *backing_file = NULL;
1301 const char *backing_fmt = NULL;
1302 uint64_t sectors = 0;
1303 int flags = 0;
1304 size_t cluster_size = DEFAULT_CLUSTER_SIZE;
1305 int prealloc = 0;
1306 int version = 2;
1307
1308 /* Read out options */
1309 while (options && options->name) {
1310 if (!strcmp(options->name, BLOCK_OPT_SIZE)) {
1311 sectors = options->value.n / 512;
1312 } else if (!strcmp(options->name, BLOCK_OPT_BACKING_FILE)) {
1313 backing_file = options->value.s;
1314 } else if (!strcmp(options->name, BLOCK_OPT_BACKING_FMT)) {
1315 backing_fmt = options->value.s;
1316 } else if (!strcmp(options->name, BLOCK_OPT_ENCRYPT)) {
1317 flags |= options->value.n ? BLOCK_FLAG_ENCRYPT : 0;
1318 } else if (!strcmp(options->name, BLOCK_OPT_CLUSTER_SIZE)) {
1319 if (options->value.n) {
1320 cluster_size = options->value.n;
1321 }
1322 } else if (!strcmp(options->name, BLOCK_OPT_PREALLOC)) {
1323 if (!options->value.s || !strcmp(options->value.s, "off")) {
1324 prealloc = 0;
1325 } else if (!strcmp(options->value.s, "metadata")) {
1326 prealloc = 1;
1327 } else {
1328 fprintf(stderr, "Invalid preallocation mode: '%s'\n",
1329 options->value.s);
1330 return -EINVAL;
1331 }
1332 } else if (!strcmp(options->name, BLOCK_OPT_COMPAT_LEVEL)) {
1333 if (!options->value.s || !strcmp(options->value.s, "0.10")) {
1334 version = 2;
1335 } else if (!strcmp(options->value.s, "1.1")) {
1336 version = 3;
1337 } else {
1338 fprintf(stderr, "Invalid compatibility level: '%s'\n",
1339 options->value.s);
1340 return -EINVAL;
1341 }
1342 } else if (!strcmp(options->name, BLOCK_OPT_LAZY_REFCOUNTS)) {
1343 flags |= options->value.n ? BLOCK_FLAG_LAZY_REFCOUNTS : 0;
1344 }
1345 options++;
1346 }
1347
1348 if (backing_file && prealloc) {
1349 fprintf(stderr, "Backing file and preallocation cannot be used at "
1350 "the same time\n");
1351 return -EINVAL;
1352 }
1353
1354 if (version < 3 && (flags & BLOCK_FLAG_LAZY_REFCOUNTS)) {
1355 fprintf(stderr, "Lazy refcounts only supported with compatibility "
1356 "level 1.1 and above (use compat=1.1 or greater)\n");
1357 return -EINVAL;
1358 }
1359
1360 return qcow2_create2(filename, sectors, backing_file, backing_fmt, flags,
1361 cluster_size, prealloc, options, version);
1362 }
1363
1364 static int qcow2_make_empty(BlockDriverState *bs)
1365 {
1366 #if 0
1367 /* XXX: not correct */
1368 BDRVQcowState *s = bs->opaque;
1369 uint32_t l1_length = s->l1_size * sizeof(uint64_t);
1370 int ret;
1371
1372 memset(s->l1_table, 0, l1_length);
1373 if (bdrv_pwrite(bs->file, s->l1_table_offset, s->l1_table, l1_length) < 0)
1374 return -1;
1375 ret = bdrv_truncate(bs->file, s->l1_table_offset + l1_length);
1376 if (ret < 0)
1377 return ret;
1378
1379 l2_cache_reset(bs);
1380 #endif
1381 return 0;
1382 }
1383
1384 static coroutine_fn int qcow2_co_write_zeroes(BlockDriverState *bs,
1385 int64_t sector_num, int nb_sectors)
1386 {
1387 int ret;
1388 BDRVQcowState *s = bs->opaque;
1389
1390 /* Emulate misaligned zero writes */
1391 if (sector_num % s->cluster_sectors || nb_sectors % s->cluster_sectors) {
1392 return -ENOTSUP;
1393 }
1394
1395 /* Whatever is left can use real zero clusters */
1396 qemu_co_mutex_lock(&s->lock);
1397 ret = qcow2_zero_clusters(bs, sector_num << BDRV_SECTOR_BITS,
1398 nb_sectors);
1399 qemu_co_mutex_unlock(&s->lock);
1400
1401 return ret;
1402 }
1403
1404 static coroutine_fn int qcow2_co_discard(BlockDriverState *bs,
1405 int64_t sector_num, int nb_sectors)
1406 {
1407 int ret;
1408 BDRVQcowState *s = bs->opaque;
1409
1410 qemu_co_mutex_lock(&s->lock);
1411 ret = qcow2_discard_clusters(bs, sector_num << BDRV_SECTOR_BITS,
1412 nb_sectors);
1413 qemu_co_mutex_unlock(&s->lock);
1414 return ret;
1415 }
1416
1417 static int qcow2_truncate(BlockDriverState *bs, int64_t offset)
1418 {
1419 BDRVQcowState *s = bs->opaque;
1420 int ret, new_l1_size;
1421
1422 if (offset & 511) {
1423 error_report("The new size must be a multiple of 512");
1424 return -EINVAL;
1425 }
1426
1427 /* cannot proceed if image has snapshots */
1428 if (s->nb_snapshots) {
1429 error_report("Can't resize an image which has snapshots");
1430 return -ENOTSUP;
1431 }
1432
1433 /* shrinking is currently not supported */
1434 if (offset < bs->total_sectors * 512) {
1435 error_report("qcow2 doesn't support shrinking images yet");
1436 return -ENOTSUP;
1437 }
1438
1439 new_l1_size = size_to_l1(s, offset);
1440 ret = qcow2_grow_l1_table(bs, new_l1_size, true);
1441 if (ret < 0) {
1442 return ret;
1443 }
1444
1445 /* write updated header.size */
1446 offset = cpu_to_be64(offset);
1447 ret = bdrv_pwrite_sync(bs->file, offsetof(QCowHeader, size),
1448 &offset, sizeof(uint64_t));
1449 if (ret < 0) {
1450 return ret;
1451 }
1452
1453 s->l1_vm_state_index = new_l1_size;
1454 return 0;
1455 }
1456
1457 /* XXX: put compressed sectors first, then all the cluster aligned
1458 tables to avoid losing bytes in alignment */
1459 static int qcow2_write_compressed(BlockDriverState *bs, int64_t sector_num,
1460 const uint8_t *buf, int nb_sectors)
1461 {
1462 BDRVQcowState *s = bs->opaque;
1463 z_stream strm;
1464 int ret, out_len;
1465 uint8_t *out_buf;
1466 uint64_t cluster_offset;
1467
1468 if (nb_sectors == 0) {
1469 /* align end of file to a sector boundary to ease reading with
1470 sector based I/Os */
1471 cluster_offset = bdrv_getlength(bs->file);
1472 cluster_offset = (cluster_offset + 511) & ~511;
1473 bdrv_truncate(bs->file, cluster_offset);
1474 return 0;
1475 }
1476
1477 if (nb_sectors != s->cluster_sectors)
1478 return -EINVAL;
1479
1480 out_buf = g_malloc(s->cluster_size + (s->cluster_size / 1000) + 128);
1481
1482 /* best compression, small window, no zlib header */
1483 memset(&strm, 0, sizeof(strm));
1484 ret = deflateInit2(&strm, Z_DEFAULT_COMPRESSION,
1485 Z_DEFLATED, -12,
1486 9, Z_DEFAULT_STRATEGY);
1487 if (ret != 0) {
1488 ret = -EINVAL;
1489 goto fail;
1490 }
1491
1492 strm.avail_in = s->cluster_size;
1493 strm.next_in = (uint8_t *)buf;
1494 strm.avail_out = s->cluster_size;
1495 strm.next_out = out_buf;
1496
1497 ret = deflate(&strm, Z_FINISH);
1498 if (ret != Z_STREAM_END && ret != Z_OK) {
1499 deflateEnd(&strm);
1500 ret = -EINVAL;
1501 goto fail;
1502 }
1503 out_len = strm.next_out - out_buf;
1504
1505 deflateEnd(&strm);
1506
1507 if (ret != Z_STREAM_END || out_len >= s->cluster_size) {
1508 /* could not compress: write normal cluster */
1509 ret = bdrv_write(bs, sector_num, buf, s->cluster_sectors);
1510 if (ret < 0) {
1511 goto fail;
1512 }
1513 } else {
1514 cluster_offset = qcow2_alloc_compressed_cluster_offset(bs,
1515 sector_num << 9, out_len);
1516 if (!cluster_offset) {
1517 ret = -EIO;
1518 goto fail;
1519 }
1520 cluster_offset &= s->cluster_offset_mask;
1521 BLKDBG_EVENT(bs->file, BLKDBG_WRITE_COMPRESSED);
1522 ret = bdrv_pwrite(bs->file, cluster_offset, out_buf, out_len);
1523 if (ret < 0) {
1524 goto fail;
1525 }
1526 }
1527
1528 ret = 0;
1529 fail:
1530 g_free(out_buf);
1531 return ret;
1532 }
1533
1534 static coroutine_fn int qcow2_co_flush_to_os(BlockDriverState *bs)
1535 {
1536 BDRVQcowState *s = bs->opaque;
1537 int ret;
1538
1539 qemu_co_mutex_lock(&s->lock);
1540 ret = qcow2_cache_flush(bs, s->l2_table_cache);
1541 if (ret < 0) {
1542 qemu_co_mutex_unlock(&s->lock);
1543 return ret;
1544 }
1545
1546 if (qcow2_need_accurate_refcounts(s)) {
1547 ret = qcow2_cache_flush(bs, s->refcount_block_cache);
1548 if (ret < 0) {
1549 qemu_co_mutex_unlock(&s->lock);
1550 return ret;
1551 }
1552 }
1553 qemu_co_mutex_unlock(&s->lock);
1554
1555 return 0;
1556 }
1557
1558 static int64_t qcow2_vm_state_offset(BDRVQcowState *s)
1559 {
1560 return (int64_t)s->l1_vm_state_index << (s->cluster_bits + s->l2_bits);
1561 }
1562
1563 static int qcow2_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
1564 {
1565 BDRVQcowState *s = bs->opaque;
1566 bdi->cluster_size = s->cluster_size;
1567 bdi->vm_state_offset = qcow2_vm_state_offset(s);
1568 return 0;
1569 }
1570
1571
1572 static int qcow2_check(BlockDriverState *bs, BdrvCheckResult *result,
1573 BdrvCheckMode fix)
1574 {
1575 return qcow2_check_refcounts(bs, result, fix);
1576 }
1577
1578 #if 0
1579 static void dump_refcounts(BlockDriverState *bs)
1580 {
1581 BDRVQcowState *s = bs->opaque;
1582 int64_t nb_clusters, k, k1, size;
1583 int refcount;
1584
1585 size = bdrv_getlength(bs->file);
1586 nb_clusters = size_to_clusters(s, size);
1587 for(k = 0; k < nb_clusters;) {
1588 k1 = k;
1589 refcount = get_refcount(bs, k);
1590 k++;
1591 while (k < nb_clusters && get_refcount(bs, k) == refcount)
1592 k++;
1593 printf("%" PRId64 ": refcount=%d nb=%" PRId64 "\n", k, refcount,
1594 k - k1);
1595 }
1596 }
1597 #endif
1598
1599 static int qcow2_save_vmstate(BlockDriverState *bs, const uint8_t *buf,
1600 int64_t pos, int size)
1601 {
1602 BDRVQcowState *s = bs->opaque;
1603 int growable = bs->growable;
1604 int ret;
1605
1606 BLKDBG_EVENT(bs->file, BLKDBG_VMSTATE_SAVE);
1607 bs->growable = 1;
1608 ret = bdrv_pwrite(bs, qcow2_vm_state_offset(s) + pos, buf, size);
1609 bs->growable = growable;
1610
1611 return ret;
1612 }
1613
1614 static int qcow2_load_vmstate(BlockDriverState *bs, uint8_t *buf,
1615 int64_t pos, int size)
1616 {
1617 BDRVQcowState *s = bs->opaque;
1618 int growable = bs->growable;
1619 int ret;
1620
1621 BLKDBG_EVENT(bs->file, BLKDBG_VMSTATE_LOAD);
1622 bs->growable = 1;
1623 ret = bdrv_pread(bs, qcow2_vm_state_offset(s) + pos, buf, size);
1624 bs->growable = growable;
1625
1626 return ret;
1627 }
1628
1629 static QEMUOptionParameter qcow2_create_options[] = {
1630 {
1631 .name = BLOCK_OPT_SIZE,
1632 .type = OPT_SIZE,
1633 .help = "Virtual disk size"
1634 },
1635 {
1636 .name = BLOCK_OPT_COMPAT_LEVEL,
1637 .type = OPT_STRING,
1638 .help = "Compatibility level (0.10 or 1.1)"
1639 },
1640 {
1641 .name = BLOCK_OPT_BACKING_FILE,
1642 .type = OPT_STRING,
1643 .help = "File name of a base image"
1644 },
1645 {
1646 .name = BLOCK_OPT_BACKING_FMT,
1647 .type = OPT_STRING,
1648 .help = "Image format of the base image"
1649 },
1650 {
1651 .name = BLOCK_OPT_ENCRYPT,
1652 .type = OPT_FLAG,
1653 .help = "Encrypt the image"
1654 },
1655 {
1656 .name = BLOCK_OPT_CLUSTER_SIZE,
1657 .type = OPT_SIZE,
1658 .help = "qcow2 cluster size",
1659 .value = { .n = DEFAULT_CLUSTER_SIZE },
1660 },
1661 {
1662 .name = BLOCK_OPT_PREALLOC,
1663 .type = OPT_STRING,
1664 .help = "Preallocation mode (allowed values: off, metadata)"
1665 },
1666 {
1667 .name = BLOCK_OPT_LAZY_REFCOUNTS,
1668 .type = OPT_FLAG,
1669 .help = "Postpone refcount updates",
1670 },
1671 { NULL }
1672 };
1673
1674 static BlockDriver bdrv_qcow2 = {
1675 .format_name = "qcow2",
1676 .instance_size = sizeof(BDRVQcowState),
1677 .bdrv_probe = qcow2_probe,
1678 .bdrv_open = qcow2_open,
1679 .bdrv_close = qcow2_close,
1680 .bdrv_create = qcow2_create,
1681 .bdrv_co_is_allocated = qcow2_co_is_allocated,
1682 .bdrv_set_key = qcow2_set_key,
1683 .bdrv_make_empty = qcow2_make_empty,
1684
1685 .bdrv_co_readv = qcow2_co_readv,
1686 .bdrv_co_writev = qcow2_co_writev,
1687 .bdrv_co_flush_to_os = qcow2_co_flush_to_os,
1688
1689 .bdrv_co_write_zeroes = qcow2_co_write_zeroes,
1690 .bdrv_co_discard = qcow2_co_discard,
1691 .bdrv_truncate = qcow2_truncate,
1692 .bdrv_write_compressed = qcow2_write_compressed,
1693
1694 .bdrv_snapshot_create = qcow2_snapshot_create,
1695 .bdrv_snapshot_goto = qcow2_snapshot_goto,
1696 .bdrv_snapshot_delete = qcow2_snapshot_delete,
1697 .bdrv_snapshot_list = qcow2_snapshot_list,
1698 .bdrv_snapshot_load_tmp = qcow2_snapshot_load_tmp,
1699 .bdrv_get_info = qcow2_get_info,
1700
1701 .bdrv_save_vmstate = qcow2_save_vmstate,
1702 .bdrv_load_vmstate = qcow2_load_vmstate,
1703
1704 .bdrv_change_backing_file = qcow2_change_backing_file,
1705
1706 .bdrv_invalidate_cache = qcow2_invalidate_cache,
1707
1708 .create_options = qcow2_create_options,
1709 .bdrv_check = qcow2_check,
1710 };
1711
1712 static void bdrv_qcow2_init(void)
1713 {
1714 bdrv_register(&bdrv_qcow2);
1715 }
1716
1717 block_init(bdrv_qcow2_init);