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