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