xref: /openbmc/qemu/block/qcow.c (revision 82c4f87e)
1 /*
2  * Block driver for the QCOW format
3  *
4  * Copyright (c) 2004-2006 Fabrice Bellard
5  *
6  * Permission is hereby granted, free of charge, to any person obtaining a copy
7  * of this software and associated documentation files (the "Software"), to deal
8  * in the Software without restriction, including without limitation the rights
9  * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10  * copies of the Software, and to permit persons to whom the Software is
11  * furnished to do so, subject to the following conditions:
12  *
13  * The above copyright notice and this permission notice shall be included in
14  * all copies or substantial portions of the Software.
15  *
16  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22  * THE SOFTWARE.
23  */
24 
25 #include "qemu/osdep.h"
26 #include "qapi/error.h"
27 #include "qemu/error-report.h"
28 #include "block/block_int.h"
29 #include "block/qdict.h"
30 #include "sysemu/block-backend.h"
31 #include "qemu/module.h"
32 #include "qemu/option.h"
33 #include "qemu/bswap.h"
34 #include <zlib.h>
35 #include "qapi/qmp/qdict.h"
36 #include "qapi/qmp/qstring.h"
37 #include "qapi/qobject-input-visitor.h"
38 #include "qapi/qapi-visit-block-core.h"
39 #include "crypto/block.h"
40 #include "migration/blocker.h"
41 #include "crypto.h"
42 
43 /**************************************************************/
44 /* QEMU COW block driver with compression and encryption support */
45 
46 #define QCOW_MAGIC (('Q' << 24) | ('F' << 16) | ('I' << 8) | 0xfb)
47 #define QCOW_VERSION 1
48 
49 #define QCOW_CRYPT_NONE 0
50 #define QCOW_CRYPT_AES  1
51 
52 #define QCOW_OFLAG_COMPRESSED (1LL << 63)
53 
54 typedef struct QCowHeader {
55     uint32_t magic;
56     uint32_t version;
57     uint64_t backing_file_offset;
58     uint32_t backing_file_size;
59     uint32_t mtime;
60     uint64_t size; /* in bytes */
61     uint8_t cluster_bits;
62     uint8_t l2_bits;
63     uint16_t padding;
64     uint32_t crypt_method;
65     uint64_t l1_table_offset;
66 } QEMU_PACKED QCowHeader;
67 
68 #define L2_CACHE_SIZE 16
69 
70 typedef struct BDRVQcowState {
71     int cluster_bits;
72     int cluster_size;
73     int cluster_sectors;
74     int l2_bits;
75     int l2_size;
76     unsigned int l1_size;
77     uint64_t cluster_offset_mask;
78     uint64_t l1_table_offset;
79     uint64_t *l1_table;
80     uint64_t *l2_cache;
81     uint64_t l2_cache_offsets[L2_CACHE_SIZE];
82     uint32_t l2_cache_counts[L2_CACHE_SIZE];
83     uint8_t *cluster_cache;
84     uint8_t *cluster_data;
85     uint64_t cluster_cache_offset;
86     QCryptoBlock *crypto; /* Disk encryption format driver */
87     uint32_t crypt_method_header;
88     CoMutex lock;
89     Error *migration_blocker;
90 } BDRVQcowState;
91 
92 static QemuOptsList qcow_create_opts;
93 
94 static int decompress_cluster(BlockDriverState *bs, uint64_t cluster_offset);
95 
96 static int qcow_probe(const uint8_t *buf, int buf_size, const char *filename)
97 {
98     const QCowHeader *cow_header = (const void *)buf;
99 
100     if (buf_size >= sizeof(QCowHeader) &&
101         be32_to_cpu(cow_header->magic) == QCOW_MAGIC &&
102         be32_to_cpu(cow_header->version) == QCOW_VERSION)
103         return 100;
104     else
105         return 0;
106 }
107 
108 static QemuOptsList qcow_runtime_opts = {
109     .name = "qcow",
110     .head = QTAILQ_HEAD_INITIALIZER(qcow_runtime_opts.head),
111     .desc = {
112         BLOCK_CRYPTO_OPT_DEF_QCOW_KEY_SECRET("encrypt."),
113         { /* end of list */ }
114     },
115 };
116 
117 static int qcow_open(BlockDriverState *bs, QDict *options, int flags,
118                      Error **errp)
119 {
120     BDRVQcowState *s = bs->opaque;
121     unsigned int len, i, shift;
122     int ret;
123     QCowHeader header;
124     Error *local_err = NULL;
125     QCryptoBlockOpenOptions *crypto_opts = NULL;
126     unsigned int cflags = 0;
127     QDict *encryptopts = NULL;
128     const char *encryptfmt;
129 
130     qdict_extract_subqdict(options, &encryptopts, "encrypt.");
131     encryptfmt = qdict_get_try_str(encryptopts, "format");
132 
133     bs->file = bdrv_open_child(NULL, options, "file", bs, &child_file,
134                                false, errp);
135     if (!bs->file) {
136         ret = -EINVAL;
137         goto fail;
138     }
139 
140     ret = bdrv_pread(bs->file, 0, &header, sizeof(header));
141     if (ret < 0) {
142         goto fail;
143     }
144     be32_to_cpus(&header.magic);
145     be32_to_cpus(&header.version);
146     be64_to_cpus(&header.backing_file_offset);
147     be32_to_cpus(&header.backing_file_size);
148     be32_to_cpus(&header.mtime);
149     be64_to_cpus(&header.size);
150     be32_to_cpus(&header.crypt_method);
151     be64_to_cpus(&header.l1_table_offset);
152 
153     if (header.magic != QCOW_MAGIC) {
154         error_setg(errp, "Image not in qcow format");
155         ret = -EINVAL;
156         goto fail;
157     }
158     if (header.version != QCOW_VERSION) {
159         error_setg(errp, "Unsupported qcow version %" PRIu32, header.version);
160         ret = -ENOTSUP;
161         goto fail;
162     }
163 
164     if (header.size <= 1) {
165         error_setg(errp, "Image size is too small (must be at least 2 bytes)");
166         ret = -EINVAL;
167         goto fail;
168     }
169     if (header.cluster_bits < 9 || header.cluster_bits > 16) {
170         error_setg(errp, "Cluster size must be between 512 and 64k");
171         ret = -EINVAL;
172         goto fail;
173     }
174 
175     /* l2_bits specifies number of entries; storing a uint64_t in each entry,
176      * so bytes = num_entries << 3. */
177     if (header.l2_bits < 9 - 3 || header.l2_bits > 16 - 3) {
178         error_setg(errp, "L2 table size must be between 512 and 64k");
179         ret = -EINVAL;
180         goto fail;
181     }
182 
183     s->crypt_method_header = header.crypt_method;
184     if (s->crypt_method_header) {
185         if (bdrv_uses_whitelist() &&
186             s->crypt_method_header == QCOW_CRYPT_AES) {
187             error_setg(errp,
188                        "Use of AES-CBC encrypted qcow images is no longer "
189                        "supported in system emulators");
190             error_append_hint(errp,
191                               "You can use 'qemu-img convert' to convert your "
192                               "image to an alternative supported format, such "
193                               "as unencrypted qcow, or raw with the LUKS "
194                               "format instead.\n");
195             ret = -ENOSYS;
196             goto fail;
197         }
198         if (s->crypt_method_header == QCOW_CRYPT_AES) {
199             if (encryptfmt && !g_str_equal(encryptfmt, "aes")) {
200                 error_setg(errp,
201                            "Header reported 'aes' encryption format but "
202                            "options specify '%s'", encryptfmt);
203                 ret = -EINVAL;
204                 goto fail;
205             }
206             qdict_del(encryptopts, "format");
207             crypto_opts = block_crypto_open_opts_init(
208                 Q_CRYPTO_BLOCK_FORMAT_QCOW, encryptopts, errp);
209             if (!crypto_opts) {
210                 ret = -EINVAL;
211                 goto fail;
212             }
213 
214             if (flags & BDRV_O_NO_IO) {
215                 cflags |= QCRYPTO_BLOCK_OPEN_NO_IO;
216             }
217             s->crypto = qcrypto_block_open(crypto_opts, "encrypt.",
218                                            NULL, NULL, cflags, errp);
219             if (!s->crypto) {
220                 ret = -EINVAL;
221                 goto fail;
222             }
223         } else {
224             error_setg(errp, "invalid encryption method in qcow header");
225             ret = -EINVAL;
226             goto fail;
227         }
228         bs->encrypted = true;
229     } else {
230         if (encryptfmt) {
231             error_setg(errp, "No encryption in image header, but options "
232                        "specified format '%s'", encryptfmt);
233             ret = -EINVAL;
234             goto fail;
235         }
236     }
237     s->cluster_bits = header.cluster_bits;
238     s->cluster_size = 1 << s->cluster_bits;
239     s->cluster_sectors = 1 << (s->cluster_bits - 9);
240     s->l2_bits = header.l2_bits;
241     s->l2_size = 1 << s->l2_bits;
242     bs->total_sectors = header.size / 512;
243     s->cluster_offset_mask = (1LL << (63 - s->cluster_bits)) - 1;
244 
245     /* read the level 1 table */
246     shift = s->cluster_bits + s->l2_bits;
247     if (header.size > UINT64_MAX - (1LL << shift)) {
248         error_setg(errp, "Image too large");
249         ret = -EINVAL;
250         goto fail;
251     } else {
252         uint64_t l1_size = (header.size + (1LL << shift) - 1) >> shift;
253         if (l1_size > INT_MAX / sizeof(uint64_t)) {
254             error_setg(errp, "Image too large");
255             ret = -EINVAL;
256             goto fail;
257         }
258         s->l1_size = l1_size;
259     }
260 
261     s->l1_table_offset = header.l1_table_offset;
262     s->l1_table = g_try_new(uint64_t, s->l1_size);
263     if (s->l1_table == NULL) {
264         error_setg(errp, "Could not allocate memory for L1 table");
265         ret = -ENOMEM;
266         goto fail;
267     }
268 
269     ret = bdrv_pread(bs->file, s->l1_table_offset, s->l1_table,
270                s->l1_size * sizeof(uint64_t));
271     if (ret < 0) {
272         goto fail;
273     }
274 
275     for(i = 0;i < s->l1_size; i++) {
276         be64_to_cpus(&s->l1_table[i]);
277     }
278 
279     /* alloc L2 cache (max. 64k * 16 * 8 = 8 MB) */
280     s->l2_cache =
281         qemu_try_blockalign(bs->file->bs,
282                             s->l2_size * L2_CACHE_SIZE * sizeof(uint64_t));
283     if (s->l2_cache == NULL) {
284         error_setg(errp, "Could not allocate L2 table cache");
285         ret = -ENOMEM;
286         goto fail;
287     }
288     s->cluster_cache = g_malloc(s->cluster_size);
289     s->cluster_data = g_malloc(s->cluster_size);
290     s->cluster_cache_offset = -1;
291 
292     /* read the backing file name */
293     if (header.backing_file_offset != 0) {
294         len = header.backing_file_size;
295         if (len > 1023 || len >= sizeof(bs->backing_file)) {
296             error_setg(errp, "Backing file name too long");
297             ret = -EINVAL;
298             goto fail;
299         }
300         ret = bdrv_pread(bs->file, header.backing_file_offset,
301                    bs->backing_file, len);
302         if (ret < 0) {
303             goto fail;
304         }
305         bs->backing_file[len] = '\0';
306     }
307 
308     /* Disable migration when qcow images are used */
309     error_setg(&s->migration_blocker, "The qcow format used by node '%s' "
310                "does not support live migration",
311                bdrv_get_device_or_node_name(bs));
312     ret = migrate_add_blocker(s->migration_blocker, &local_err);
313     if (local_err) {
314         error_propagate(errp, local_err);
315         error_free(s->migration_blocker);
316         goto fail;
317     }
318 
319     qobject_unref(encryptopts);
320     qapi_free_QCryptoBlockOpenOptions(crypto_opts);
321     qemu_co_mutex_init(&s->lock);
322     return 0;
323 
324  fail:
325     g_free(s->l1_table);
326     qemu_vfree(s->l2_cache);
327     g_free(s->cluster_cache);
328     g_free(s->cluster_data);
329     qcrypto_block_free(s->crypto);
330     qobject_unref(encryptopts);
331     qapi_free_QCryptoBlockOpenOptions(crypto_opts);
332     return ret;
333 }
334 
335 
336 /* We have nothing to do for QCOW reopen, stubs just return
337  * success */
338 static int qcow_reopen_prepare(BDRVReopenState *state,
339                                BlockReopenQueue *queue, Error **errp)
340 {
341     return 0;
342 }
343 
344 
345 /* 'allocate' is:
346  *
347  * 0 to not allocate.
348  *
349  * 1 to allocate a normal cluster (for sector indexes 'n_start' to
350  * 'n_end')
351  *
352  * 2 to allocate a compressed cluster of size
353  * 'compressed_size'. 'compressed_size' must be > 0 and <
354  * cluster_size
355  *
356  * return 0 if not allocated, 1 if *result is assigned, and negative
357  * errno on failure.
358  */
359 static int get_cluster_offset(BlockDriverState *bs,
360                               uint64_t offset, int allocate,
361                               int compressed_size,
362                               int n_start, int n_end, uint64_t *result)
363 {
364     BDRVQcowState *s = bs->opaque;
365     int min_index, i, j, l1_index, l2_index, ret;
366     int64_t l2_offset;
367     uint64_t *l2_table, cluster_offset, tmp;
368     uint32_t min_count;
369     int new_l2_table;
370 
371     *result = 0;
372     l1_index = offset >> (s->l2_bits + s->cluster_bits);
373     l2_offset = s->l1_table[l1_index];
374     new_l2_table = 0;
375     if (!l2_offset) {
376         if (!allocate)
377             return 0;
378         /* allocate a new l2 entry */
379         l2_offset = bdrv_getlength(bs->file->bs);
380         if (l2_offset < 0) {
381             return l2_offset;
382         }
383         /* round to cluster size */
384         l2_offset = QEMU_ALIGN_UP(l2_offset, s->cluster_size);
385         /* update the L1 entry */
386         s->l1_table[l1_index] = l2_offset;
387         tmp = cpu_to_be64(l2_offset);
388         BLKDBG_EVENT(bs->file, BLKDBG_L1_UPDATE);
389         ret = bdrv_pwrite_sync(bs->file,
390                                s->l1_table_offset + l1_index * sizeof(tmp),
391                                &tmp, sizeof(tmp));
392         if (ret < 0) {
393             return ret;
394         }
395         new_l2_table = 1;
396     }
397     for(i = 0; i < L2_CACHE_SIZE; i++) {
398         if (l2_offset == s->l2_cache_offsets[i]) {
399             /* increment the hit count */
400             if (++s->l2_cache_counts[i] == 0xffffffff) {
401                 for(j = 0; j < L2_CACHE_SIZE; j++) {
402                     s->l2_cache_counts[j] >>= 1;
403                 }
404             }
405             l2_table = s->l2_cache + (i << s->l2_bits);
406             goto found;
407         }
408     }
409     /* not found: load a new entry in the least used one */
410     min_index = 0;
411     min_count = 0xffffffff;
412     for(i = 0; i < L2_CACHE_SIZE; i++) {
413         if (s->l2_cache_counts[i] < min_count) {
414             min_count = s->l2_cache_counts[i];
415             min_index = i;
416         }
417     }
418     l2_table = s->l2_cache + (min_index << s->l2_bits);
419     BLKDBG_EVENT(bs->file, BLKDBG_L2_LOAD);
420     if (new_l2_table) {
421         memset(l2_table, 0, s->l2_size * sizeof(uint64_t));
422         ret = bdrv_pwrite_sync(bs->file, l2_offset, l2_table,
423                                s->l2_size * sizeof(uint64_t));
424         if (ret < 0) {
425             return ret;
426         }
427     } else {
428         ret = bdrv_pread(bs->file, l2_offset, l2_table,
429                          s->l2_size * sizeof(uint64_t));
430         if (ret < 0) {
431             return ret;
432         }
433     }
434     s->l2_cache_offsets[min_index] = l2_offset;
435     s->l2_cache_counts[min_index] = 1;
436  found:
437     l2_index = (offset >> s->cluster_bits) & (s->l2_size - 1);
438     cluster_offset = be64_to_cpu(l2_table[l2_index]);
439     if (!cluster_offset ||
440         ((cluster_offset & QCOW_OFLAG_COMPRESSED) && allocate == 1)) {
441         if (!allocate)
442             return 0;
443         BLKDBG_EVENT(bs->file, BLKDBG_CLUSTER_ALLOC);
444         /* allocate a new cluster */
445         if ((cluster_offset & QCOW_OFLAG_COMPRESSED) &&
446             (n_end - n_start) < s->cluster_sectors) {
447             /* if the cluster is already compressed, we must
448                decompress it in the case it is not completely
449                overwritten */
450             if (decompress_cluster(bs, cluster_offset) < 0) {
451                 return -EIO;
452             }
453             cluster_offset = bdrv_getlength(bs->file->bs);
454             if ((int64_t) cluster_offset < 0) {
455                 return cluster_offset;
456             }
457             cluster_offset = QEMU_ALIGN_UP(cluster_offset, s->cluster_size);
458             /* write the cluster content */
459             BLKDBG_EVENT(bs->file, BLKDBG_WRITE_AIO);
460             ret = bdrv_pwrite(bs->file, cluster_offset, s->cluster_cache,
461                               s->cluster_size);
462             if (ret < 0) {
463                 return ret;
464             }
465         } else {
466             cluster_offset = bdrv_getlength(bs->file->bs);
467             if ((int64_t) cluster_offset < 0) {
468                 return cluster_offset;
469             }
470             if (allocate == 1) {
471                 /* round to cluster size */
472                 cluster_offset = QEMU_ALIGN_UP(cluster_offset, s->cluster_size);
473                 if (cluster_offset + s->cluster_size > INT64_MAX) {
474                     return -E2BIG;
475                 }
476                 ret = bdrv_truncate(bs->file, cluster_offset + s->cluster_size,
477                                     PREALLOC_MODE_OFF, NULL);
478                 if (ret < 0) {
479                     return ret;
480                 }
481                 /* if encrypted, we must initialize the cluster
482                    content which won't be written */
483                 if (bs->encrypted &&
484                     (n_end - n_start) < s->cluster_sectors) {
485                     uint64_t start_sect;
486                     assert(s->crypto);
487                     start_sect = (offset & ~(s->cluster_size - 1)) >> 9;
488                     for(i = 0; i < s->cluster_sectors; i++) {
489                         if (i < n_start || i >= n_end) {
490                             memset(s->cluster_data, 0x00, 512);
491                             if (qcrypto_block_encrypt(s->crypto,
492                                                       (start_sect + i) *
493                                                       BDRV_SECTOR_SIZE,
494                                                       s->cluster_data,
495                                                       BDRV_SECTOR_SIZE,
496                                                       NULL) < 0) {
497                                 return -EIO;
498                             }
499                             BLKDBG_EVENT(bs->file, BLKDBG_WRITE_AIO);
500                             ret = bdrv_pwrite(bs->file,
501                                               cluster_offset + i * 512,
502                                               s->cluster_data, 512);
503                             if (ret < 0) {
504                                 return ret;
505                             }
506                         }
507                     }
508                 }
509             } else if (allocate == 2) {
510                 cluster_offset |= QCOW_OFLAG_COMPRESSED |
511                     (uint64_t)compressed_size << (63 - s->cluster_bits);
512             }
513         }
514         /* update L2 table */
515         tmp = cpu_to_be64(cluster_offset);
516         l2_table[l2_index] = tmp;
517         if (allocate == 2) {
518             BLKDBG_EVENT(bs->file, BLKDBG_L2_UPDATE_COMPRESSED);
519         } else {
520             BLKDBG_EVENT(bs->file, BLKDBG_L2_UPDATE);
521         }
522         ret = bdrv_pwrite_sync(bs->file, l2_offset + l2_index * sizeof(tmp),
523                                &tmp, sizeof(tmp));
524         if (ret < 0) {
525             return ret;
526         }
527     }
528     *result = cluster_offset;
529     return 1;
530 }
531 
532 static int coroutine_fn qcow_co_block_status(BlockDriverState *bs,
533                                              bool want_zero,
534                                              int64_t offset, int64_t bytes,
535                                              int64_t *pnum, int64_t *map,
536                                              BlockDriverState **file)
537 {
538     BDRVQcowState *s = bs->opaque;
539     int index_in_cluster, ret;
540     int64_t n;
541     uint64_t cluster_offset;
542 
543     qemu_co_mutex_lock(&s->lock);
544     ret = get_cluster_offset(bs, offset, 0, 0, 0, 0, &cluster_offset);
545     qemu_co_mutex_unlock(&s->lock);
546     if (ret < 0) {
547         return ret;
548     }
549     index_in_cluster = offset & (s->cluster_size - 1);
550     n = s->cluster_size - index_in_cluster;
551     if (n > bytes) {
552         n = bytes;
553     }
554     *pnum = n;
555     if (!cluster_offset) {
556         return 0;
557     }
558     if ((cluster_offset & QCOW_OFLAG_COMPRESSED) || s->crypto) {
559         return BDRV_BLOCK_DATA;
560     }
561     *map = cluster_offset | index_in_cluster;
562     *file = bs->file->bs;
563     return BDRV_BLOCK_DATA | BDRV_BLOCK_OFFSET_VALID;
564 }
565 
566 static int decompress_buffer(uint8_t *out_buf, int out_buf_size,
567                              const uint8_t *buf, int buf_size)
568 {
569     z_stream strm1, *strm = &strm1;
570     int ret, out_len;
571 
572     memset(strm, 0, sizeof(*strm));
573 
574     strm->next_in = (uint8_t *)buf;
575     strm->avail_in = buf_size;
576     strm->next_out = out_buf;
577     strm->avail_out = out_buf_size;
578 
579     ret = inflateInit2(strm, -12);
580     if (ret != Z_OK)
581         return -1;
582     ret = inflate(strm, Z_FINISH);
583     out_len = strm->next_out - out_buf;
584     if ((ret != Z_STREAM_END && ret != Z_BUF_ERROR) ||
585         out_len != out_buf_size) {
586         inflateEnd(strm);
587         return -1;
588     }
589     inflateEnd(strm);
590     return 0;
591 }
592 
593 static int decompress_cluster(BlockDriverState *bs, uint64_t cluster_offset)
594 {
595     BDRVQcowState *s = bs->opaque;
596     int ret, csize;
597     uint64_t coffset;
598 
599     coffset = cluster_offset & s->cluster_offset_mask;
600     if (s->cluster_cache_offset != coffset) {
601         csize = cluster_offset >> (63 - s->cluster_bits);
602         csize &= (s->cluster_size - 1);
603         BLKDBG_EVENT(bs->file, BLKDBG_READ_COMPRESSED);
604         ret = bdrv_pread(bs->file, coffset, s->cluster_data, csize);
605         if (ret != csize)
606             return -1;
607         if (decompress_buffer(s->cluster_cache, s->cluster_size,
608                               s->cluster_data, csize) < 0) {
609             return -1;
610         }
611         s->cluster_cache_offset = coffset;
612     }
613     return 0;
614 }
615 
616 static coroutine_fn int qcow_co_readv(BlockDriverState *bs, int64_t sector_num,
617                          int nb_sectors, QEMUIOVector *qiov)
618 {
619     BDRVQcowState *s = bs->opaque;
620     int index_in_cluster;
621     int ret = 0, n;
622     uint64_t cluster_offset;
623     struct iovec hd_iov;
624     QEMUIOVector hd_qiov;
625     uint8_t *buf;
626     void *orig_buf;
627 
628     if (qiov->niov > 1) {
629         buf = orig_buf = qemu_try_blockalign(bs, qiov->size);
630         if (buf == NULL) {
631             return -ENOMEM;
632         }
633     } else {
634         orig_buf = NULL;
635         buf = (uint8_t *)qiov->iov->iov_base;
636     }
637 
638     qemu_co_mutex_lock(&s->lock);
639 
640     while (nb_sectors != 0) {
641         /* prepare next request */
642         ret = get_cluster_offset(bs, sector_num << 9,
643                                  0, 0, 0, 0, &cluster_offset);
644         if (ret < 0) {
645             break;
646         }
647         index_in_cluster = sector_num & (s->cluster_sectors - 1);
648         n = s->cluster_sectors - index_in_cluster;
649         if (n > nb_sectors) {
650             n = nb_sectors;
651         }
652 
653         if (!cluster_offset) {
654             if (bs->backing) {
655                 /* read from the base image */
656                 hd_iov.iov_base = (void *)buf;
657                 hd_iov.iov_len = n * 512;
658                 qemu_iovec_init_external(&hd_qiov, &hd_iov, 1);
659                 qemu_co_mutex_unlock(&s->lock);
660                 /* qcow2 emits this on bs->file instead of bs->backing */
661                 BLKDBG_EVENT(bs->file, BLKDBG_READ_BACKING_AIO);
662                 ret = bdrv_co_readv(bs->backing, sector_num, n, &hd_qiov);
663                 qemu_co_mutex_lock(&s->lock);
664                 if (ret < 0) {
665                     break;
666                 }
667             } else {
668                 /* Note: in this case, no need to wait */
669                 memset(buf, 0, 512 * n);
670             }
671         } else if (cluster_offset & QCOW_OFLAG_COMPRESSED) {
672             /* add AIO support for compressed blocks ? */
673             if (decompress_cluster(bs, cluster_offset) < 0) {
674                 ret = -EIO;
675                 break;
676             }
677             memcpy(buf,
678                    s->cluster_cache + index_in_cluster * 512, 512 * n);
679         } else {
680             if ((cluster_offset & 511) != 0) {
681                 ret = -EIO;
682                 break;
683             }
684             hd_iov.iov_base = (void *)buf;
685             hd_iov.iov_len = n * 512;
686             qemu_iovec_init_external(&hd_qiov, &hd_iov, 1);
687             qemu_co_mutex_unlock(&s->lock);
688             BLKDBG_EVENT(bs->file, BLKDBG_READ_AIO);
689             ret = bdrv_co_readv(bs->file,
690                                 (cluster_offset >> 9) + index_in_cluster,
691                                 n, &hd_qiov);
692             qemu_co_mutex_lock(&s->lock);
693             if (ret < 0) {
694                 break;
695             }
696             if (bs->encrypted) {
697                 assert(s->crypto);
698                 if (qcrypto_block_decrypt(s->crypto,
699                                           sector_num * BDRV_SECTOR_SIZE, buf,
700                                           n * BDRV_SECTOR_SIZE, NULL) < 0) {
701                     ret = -EIO;
702                     break;
703                 }
704             }
705         }
706         ret = 0;
707 
708         nb_sectors -= n;
709         sector_num += n;
710         buf += n * 512;
711     }
712 
713     qemu_co_mutex_unlock(&s->lock);
714 
715     if (qiov->niov > 1) {
716         qemu_iovec_from_buf(qiov, 0, orig_buf, qiov->size);
717         qemu_vfree(orig_buf);
718     }
719 
720     return ret;
721 }
722 
723 static coroutine_fn int qcow_co_writev(BlockDriverState *bs, int64_t sector_num,
724                                        int nb_sectors, QEMUIOVector *qiov,
725                                        int flags)
726 {
727     BDRVQcowState *s = bs->opaque;
728     int index_in_cluster;
729     uint64_t cluster_offset;
730     int ret = 0, n;
731     struct iovec hd_iov;
732     QEMUIOVector hd_qiov;
733     uint8_t *buf;
734     void *orig_buf;
735 
736     assert(!flags);
737     s->cluster_cache_offset = -1; /* disable compressed cache */
738 
739     /* We must always copy the iov when encrypting, so we
740      * don't modify the original data buffer during encryption */
741     if (bs->encrypted || qiov->niov > 1) {
742         buf = orig_buf = qemu_try_blockalign(bs, qiov->size);
743         if (buf == NULL) {
744             return -ENOMEM;
745         }
746         qemu_iovec_to_buf(qiov, 0, buf, qiov->size);
747     } else {
748         orig_buf = NULL;
749         buf = (uint8_t *)qiov->iov->iov_base;
750     }
751 
752     qemu_co_mutex_lock(&s->lock);
753 
754     while (nb_sectors != 0) {
755 
756         index_in_cluster = sector_num & (s->cluster_sectors - 1);
757         n = s->cluster_sectors - index_in_cluster;
758         if (n > nb_sectors) {
759             n = nb_sectors;
760         }
761         ret = get_cluster_offset(bs, sector_num << 9, 1, 0,
762                                  index_in_cluster,
763                                  index_in_cluster + n, &cluster_offset);
764         if (ret < 0) {
765             break;
766         }
767         if (!cluster_offset || (cluster_offset & 511) != 0) {
768             ret = -EIO;
769             break;
770         }
771         if (bs->encrypted) {
772             assert(s->crypto);
773             if (qcrypto_block_encrypt(s->crypto, sector_num * BDRV_SECTOR_SIZE,
774                                       buf, n * BDRV_SECTOR_SIZE, NULL) < 0) {
775                 ret = -EIO;
776                 break;
777             }
778         }
779 
780         hd_iov.iov_base = (void *)buf;
781         hd_iov.iov_len = n * 512;
782         qemu_iovec_init_external(&hd_qiov, &hd_iov, 1);
783         qemu_co_mutex_unlock(&s->lock);
784         BLKDBG_EVENT(bs->file, BLKDBG_WRITE_AIO);
785         ret = bdrv_co_writev(bs->file,
786                              (cluster_offset >> 9) + index_in_cluster,
787                              n, &hd_qiov);
788         qemu_co_mutex_lock(&s->lock);
789         if (ret < 0) {
790             break;
791         }
792         ret = 0;
793 
794         nb_sectors -= n;
795         sector_num += n;
796         buf += n * 512;
797     }
798     qemu_co_mutex_unlock(&s->lock);
799 
800     qemu_vfree(orig_buf);
801 
802     return ret;
803 }
804 
805 static void qcow_close(BlockDriverState *bs)
806 {
807     BDRVQcowState *s = bs->opaque;
808 
809     qcrypto_block_free(s->crypto);
810     s->crypto = NULL;
811     g_free(s->l1_table);
812     qemu_vfree(s->l2_cache);
813     g_free(s->cluster_cache);
814     g_free(s->cluster_data);
815 
816     migrate_del_blocker(s->migration_blocker);
817     error_free(s->migration_blocker);
818 }
819 
820 static int coroutine_fn qcow_co_create(BlockdevCreateOptions *opts,
821                                        Error **errp)
822 {
823     BlockdevCreateOptionsQcow *qcow_opts;
824     int header_size, backing_filename_len, l1_size, shift, i;
825     QCowHeader header;
826     uint8_t *tmp;
827     int64_t total_size = 0;
828     int ret;
829     BlockDriverState *bs;
830     BlockBackend *qcow_blk;
831     QCryptoBlock *crypto = NULL;
832 
833     assert(opts->driver == BLOCKDEV_DRIVER_QCOW);
834     qcow_opts = &opts->u.qcow;
835 
836     /* Sanity checks */
837     total_size = qcow_opts->size;
838     if (total_size == 0) {
839         error_setg(errp, "Image size is too small, cannot be zero length");
840         return -EINVAL;
841     }
842 
843     if (qcow_opts->has_encrypt &&
844         qcow_opts->encrypt->format != Q_CRYPTO_BLOCK_FORMAT_QCOW)
845     {
846         error_setg(errp, "Unsupported encryption format");
847         return -EINVAL;
848     }
849 
850     /* Create BlockBackend to write to the image */
851     bs = bdrv_open_blockdev_ref(qcow_opts->file, errp);
852     if (bs == NULL) {
853         return -EIO;
854     }
855 
856     qcow_blk = blk_new(BLK_PERM_WRITE | BLK_PERM_RESIZE, BLK_PERM_ALL);
857     ret = blk_insert_bs(qcow_blk, bs, errp);
858     if (ret < 0) {
859         goto exit;
860     }
861     blk_set_allow_write_beyond_eof(qcow_blk, true);
862 
863     /* Create image format */
864     ret = blk_truncate(qcow_blk, 0, PREALLOC_MODE_OFF, errp);
865     if (ret < 0) {
866         goto exit;
867     }
868 
869     memset(&header, 0, sizeof(header));
870     header.magic = cpu_to_be32(QCOW_MAGIC);
871     header.version = cpu_to_be32(QCOW_VERSION);
872     header.size = cpu_to_be64(total_size);
873     header_size = sizeof(header);
874     backing_filename_len = 0;
875     if (qcow_opts->has_backing_file) {
876         if (strcmp(qcow_opts->backing_file, "fat:")) {
877             header.backing_file_offset = cpu_to_be64(header_size);
878             backing_filename_len = strlen(qcow_opts->backing_file);
879             header.backing_file_size = cpu_to_be32(backing_filename_len);
880             header_size += backing_filename_len;
881         } else {
882             /* special backing file for vvfat */
883             qcow_opts->has_backing_file = false;
884         }
885         header.cluster_bits = 9; /* 512 byte cluster to avoid copying
886                                     unmodified sectors */
887         header.l2_bits = 12; /* 32 KB L2 tables */
888     } else {
889         header.cluster_bits = 12; /* 4 KB clusters */
890         header.l2_bits = 9; /* 4 KB L2 tables */
891     }
892     header_size = (header_size + 7) & ~7;
893     shift = header.cluster_bits + header.l2_bits;
894     l1_size = (total_size + (1LL << shift) - 1) >> shift;
895 
896     header.l1_table_offset = cpu_to_be64(header_size);
897 
898     if (qcow_opts->has_encrypt) {
899         header.crypt_method = cpu_to_be32(QCOW_CRYPT_AES);
900 
901         crypto = qcrypto_block_create(qcow_opts->encrypt, "encrypt.",
902                                       NULL, NULL, NULL, errp);
903         if (!crypto) {
904             ret = -EINVAL;
905             goto exit;
906         }
907     } else {
908         header.crypt_method = cpu_to_be32(QCOW_CRYPT_NONE);
909     }
910 
911     /* write all the data */
912     ret = blk_pwrite(qcow_blk, 0, &header, sizeof(header), 0);
913     if (ret != sizeof(header)) {
914         goto exit;
915     }
916 
917     if (qcow_opts->has_backing_file) {
918         ret = blk_pwrite(qcow_blk, sizeof(header),
919                          qcow_opts->backing_file, backing_filename_len, 0);
920         if (ret != backing_filename_len) {
921             goto exit;
922         }
923     }
924 
925     tmp = g_malloc0(BDRV_SECTOR_SIZE);
926     for (i = 0; i < DIV_ROUND_UP(sizeof(uint64_t) * l1_size, BDRV_SECTOR_SIZE);
927          i++) {
928         ret = blk_pwrite(qcow_blk, header_size + BDRV_SECTOR_SIZE * i,
929                          tmp, BDRV_SECTOR_SIZE, 0);
930         if (ret != BDRV_SECTOR_SIZE) {
931             g_free(tmp);
932             goto exit;
933         }
934     }
935 
936     g_free(tmp);
937     ret = 0;
938 exit:
939     blk_unref(qcow_blk);
940     qcrypto_block_free(crypto);
941     return ret;
942 }
943 
944 static int coroutine_fn qcow_co_create_opts(const char *filename,
945                                             QemuOpts *opts, Error **errp)
946 {
947     BlockdevCreateOptions *create_options = NULL;
948     BlockDriverState *bs = NULL;
949     QDict *qdict;
950     Visitor *v;
951     const char *val;
952     Error *local_err = NULL;
953     int ret;
954 
955     static const QDictRenames opt_renames[] = {
956         { BLOCK_OPT_BACKING_FILE,       "backing-file" },
957         { BLOCK_OPT_ENCRYPT,            BLOCK_OPT_ENCRYPT_FORMAT },
958         { NULL, NULL },
959     };
960 
961     /* Parse options and convert legacy syntax */
962     qdict = qemu_opts_to_qdict_filtered(opts, NULL, &qcow_create_opts, true);
963 
964     val = qdict_get_try_str(qdict, BLOCK_OPT_ENCRYPT);
965     if (val && !strcmp(val, "on")) {
966         qdict_put_str(qdict, BLOCK_OPT_ENCRYPT, "qcow");
967     } else if (val && !strcmp(val, "off")) {
968         qdict_del(qdict, BLOCK_OPT_ENCRYPT);
969     }
970 
971     val = qdict_get_try_str(qdict, BLOCK_OPT_ENCRYPT_FORMAT);
972     if (val && !strcmp(val, "aes")) {
973         qdict_put_str(qdict, BLOCK_OPT_ENCRYPT_FORMAT, "qcow");
974     }
975 
976     if (!qdict_rename_keys(qdict, opt_renames, errp)) {
977         ret = -EINVAL;
978         goto fail;
979     }
980 
981     /* Create and open the file (protocol layer) */
982     ret = bdrv_create_file(filename, opts, &local_err);
983     if (ret < 0) {
984         error_propagate(errp, local_err);
985         goto fail;
986     }
987 
988     bs = bdrv_open(filename, NULL, NULL,
989                    BDRV_O_RDWR | BDRV_O_RESIZE | BDRV_O_PROTOCOL, errp);
990     if (bs == NULL) {
991         ret = -EIO;
992         goto fail;
993     }
994 
995     /* Now get the QAPI type BlockdevCreateOptions */
996     qdict_put_str(qdict, "driver", "qcow");
997     qdict_put_str(qdict, "file", bs->node_name);
998 
999     v = qobject_input_visitor_new_flat_confused(qdict, errp);
1000     if (!v) {
1001         ret = -EINVAL;
1002         goto fail;
1003     }
1004 
1005     visit_type_BlockdevCreateOptions(v, NULL, &create_options, &local_err);
1006     visit_free(v);
1007 
1008     if (local_err) {
1009         error_propagate(errp, local_err);
1010         ret = -EINVAL;
1011         goto fail;
1012     }
1013 
1014     /* Silently round up size */
1015     assert(create_options->driver == BLOCKDEV_DRIVER_QCOW);
1016     create_options->u.qcow.size =
1017         ROUND_UP(create_options->u.qcow.size, BDRV_SECTOR_SIZE);
1018 
1019     /* Create the qcow image (format layer) */
1020     ret = qcow_co_create(create_options, errp);
1021     if (ret < 0) {
1022         goto fail;
1023     }
1024 
1025     ret = 0;
1026 fail:
1027     qobject_unref(qdict);
1028     bdrv_unref(bs);
1029     qapi_free_BlockdevCreateOptions(create_options);
1030     return ret;
1031 }
1032 
1033 static int qcow_make_empty(BlockDriverState *bs)
1034 {
1035     BDRVQcowState *s = bs->opaque;
1036     uint32_t l1_length = s->l1_size * sizeof(uint64_t);
1037     int ret;
1038 
1039     memset(s->l1_table, 0, l1_length);
1040     if (bdrv_pwrite_sync(bs->file, s->l1_table_offset, s->l1_table,
1041             l1_length) < 0)
1042         return -1;
1043     ret = bdrv_truncate(bs->file, s->l1_table_offset + l1_length,
1044                         PREALLOC_MODE_OFF, NULL);
1045     if (ret < 0)
1046         return ret;
1047 
1048     memset(s->l2_cache, 0, s->l2_size * L2_CACHE_SIZE * sizeof(uint64_t));
1049     memset(s->l2_cache_offsets, 0, L2_CACHE_SIZE * sizeof(uint64_t));
1050     memset(s->l2_cache_counts, 0, L2_CACHE_SIZE * sizeof(uint32_t));
1051 
1052     return 0;
1053 }
1054 
1055 /* XXX: put compressed sectors first, then all the cluster aligned
1056    tables to avoid losing bytes in alignment */
1057 static coroutine_fn int
1058 qcow_co_pwritev_compressed(BlockDriverState *bs, uint64_t offset,
1059                            uint64_t bytes, QEMUIOVector *qiov)
1060 {
1061     BDRVQcowState *s = bs->opaque;
1062     QEMUIOVector hd_qiov;
1063     struct iovec iov;
1064     z_stream strm;
1065     int ret, out_len;
1066     uint8_t *buf, *out_buf;
1067     uint64_t cluster_offset;
1068 
1069     buf = qemu_blockalign(bs, s->cluster_size);
1070     if (bytes != s->cluster_size) {
1071         if (bytes > s->cluster_size ||
1072             offset + bytes != bs->total_sectors << BDRV_SECTOR_BITS)
1073         {
1074             qemu_vfree(buf);
1075             return -EINVAL;
1076         }
1077         /* Zero-pad last write if image size is not cluster aligned */
1078         memset(buf + bytes, 0, s->cluster_size - bytes);
1079     }
1080     qemu_iovec_to_buf(qiov, 0, buf, qiov->size);
1081 
1082     out_buf = g_malloc(s->cluster_size);
1083 
1084     /* best compression, small window, no zlib header */
1085     memset(&strm, 0, sizeof(strm));
1086     ret = deflateInit2(&strm, Z_DEFAULT_COMPRESSION,
1087                        Z_DEFLATED, -12,
1088                        9, Z_DEFAULT_STRATEGY);
1089     if (ret != 0) {
1090         ret = -EINVAL;
1091         goto fail;
1092     }
1093 
1094     strm.avail_in = s->cluster_size;
1095     strm.next_in = (uint8_t *)buf;
1096     strm.avail_out = s->cluster_size;
1097     strm.next_out = out_buf;
1098 
1099     ret = deflate(&strm, Z_FINISH);
1100     if (ret != Z_STREAM_END && ret != Z_OK) {
1101         deflateEnd(&strm);
1102         ret = -EINVAL;
1103         goto fail;
1104     }
1105     out_len = strm.next_out - out_buf;
1106 
1107     deflateEnd(&strm);
1108 
1109     if (ret != Z_STREAM_END || out_len >= s->cluster_size) {
1110         /* could not compress: write normal cluster */
1111         ret = qcow_co_writev(bs, offset >> BDRV_SECTOR_BITS,
1112                              bytes >> BDRV_SECTOR_BITS, qiov, 0);
1113         if (ret < 0) {
1114             goto fail;
1115         }
1116         goto success;
1117     }
1118     qemu_co_mutex_lock(&s->lock);
1119     ret = get_cluster_offset(bs, offset, 2, out_len, 0, 0, &cluster_offset);
1120     qemu_co_mutex_unlock(&s->lock);
1121     if (ret < 0) {
1122         goto fail;
1123     }
1124     if (cluster_offset == 0) {
1125         ret = -EIO;
1126         goto fail;
1127     }
1128     cluster_offset &= s->cluster_offset_mask;
1129 
1130     iov = (struct iovec) {
1131         .iov_base   = out_buf,
1132         .iov_len    = out_len,
1133     };
1134     qemu_iovec_init_external(&hd_qiov, &iov, 1);
1135     BLKDBG_EVENT(bs->file, BLKDBG_WRITE_COMPRESSED);
1136     ret = bdrv_co_pwritev(bs->file, cluster_offset, out_len, &hd_qiov, 0);
1137     if (ret < 0) {
1138         goto fail;
1139     }
1140 success:
1141     ret = 0;
1142 fail:
1143     qemu_vfree(buf);
1144     g_free(out_buf);
1145     return ret;
1146 }
1147 
1148 static int qcow_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
1149 {
1150     BDRVQcowState *s = bs->opaque;
1151     bdi->cluster_size = s->cluster_size;
1152     return 0;
1153 }
1154 
1155 static QemuOptsList qcow_create_opts = {
1156     .name = "qcow-create-opts",
1157     .head = QTAILQ_HEAD_INITIALIZER(qcow_create_opts.head),
1158     .desc = {
1159         {
1160             .name = BLOCK_OPT_SIZE,
1161             .type = QEMU_OPT_SIZE,
1162             .help = "Virtual disk size"
1163         },
1164         {
1165             .name = BLOCK_OPT_BACKING_FILE,
1166             .type = QEMU_OPT_STRING,
1167             .help = "File name of a base image"
1168         },
1169         {
1170             .name = BLOCK_OPT_ENCRYPT,
1171             .type = QEMU_OPT_BOOL,
1172             .help = "Encrypt the image with format 'aes'. (Deprecated "
1173                     "in favor of " BLOCK_OPT_ENCRYPT_FORMAT "=aes)",
1174         },
1175         {
1176             .name = BLOCK_OPT_ENCRYPT_FORMAT,
1177             .type = QEMU_OPT_STRING,
1178             .help = "Encrypt the image, format choices: 'aes'",
1179         },
1180         BLOCK_CRYPTO_OPT_DEF_QCOW_KEY_SECRET("encrypt."),
1181         { /* end of list */ }
1182     }
1183 };
1184 
1185 static BlockDriver bdrv_qcow = {
1186     .format_name	= "qcow",
1187     .instance_size	= sizeof(BDRVQcowState),
1188     .bdrv_probe		= qcow_probe,
1189     .bdrv_open		= qcow_open,
1190     .bdrv_close		= qcow_close,
1191     .bdrv_child_perm        = bdrv_format_default_perms,
1192     .bdrv_reopen_prepare    = qcow_reopen_prepare,
1193     .bdrv_co_create         = qcow_co_create,
1194     .bdrv_co_create_opts    = qcow_co_create_opts,
1195     .bdrv_has_zero_init     = bdrv_has_zero_init_1,
1196     .supports_backing       = true,
1197 
1198     .bdrv_co_readv          = qcow_co_readv,
1199     .bdrv_co_writev         = qcow_co_writev,
1200     .bdrv_co_block_status   = qcow_co_block_status,
1201 
1202     .bdrv_make_empty        = qcow_make_empty,
1203     .bdrv_co_pwritev_compressed = qcow_co_pwritev_compressed,
1204     .bdrv_get_info          = qcow_get_info,
1205 
1206     .create_opts            = &qcow_create_opts,
1207 };
1208 
1209 static void bdrv_qcow_init(void)
1210 {
1211     bdrv_register(&bdrv_qcow);
1212 }
1213 
1214 block_init(bdrv_qcow_init);
1215