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