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