xref: /qemu/block/qcow.c (revision bf8d4924)
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 #include "qemu/osdep.h"
25 #include "qapi/error.h"
26 #include "qemu-common.h"
27 #include "qemu/error-report.h"
28 #include "block/block_int.h"
29 #include "sysemu/block-backend.h"
30 #include "qemu/module.h"
31 #include "qemu/bswap.h"
32 #include <zlib.h>
33 #include "qapi/qmp/qerror.h"
34 #include "crypto/cipher.h"
35 #include "migration/migration.h"
36 
37 /**************************************************************/
38 /* QEMU COW block driver with compression and encryption support */
39 
40 #define QCOW_MAGIC (('Q' << 24) | ('F' << 16) | ('I' << 8) | 0xfb)
41 #define QCOW_VERSION 1
42 
43 #define QCOW_CRYPT_NONE 0
44 #define QCOW_CRYPT_AES  1
45 
46 #define QCOW_OFLAG_COMPRESSED (1LL << 63)
47 
48 typedef struct QCowHeader {
49     uint32_t magic;
50     uint32_t version;
51     uint64_t backing_file_offset;
52     uint32_t backing_file_size;
53     uint32_t mtime;
54     uint64_t size; /* in bytes */
55     uint8_t cluster_bits;
56     uint8_t l2_bits;
57     uint16_t padding;
58     uint32_t crypt_method;
59     uint64_t l1_table_offset;
60 } QEMU_PACKED QCowHeader;
61 
62 #define L2_CACHE_SIZE 16
63 
64 typedef struct BDRVQcowState {
65     int cluster_bits;
66     int cluster_size;
67     int cluster_sectors;
68     int l2_bits;
69     int l2_size;
70     unsigned int l1_size;
71     uint64_t cluster_offset_mask;
72     uint64_t l1_table_offset;
73     uint64_t *l1_table;
74     uint64_t *l2_cache;
75     uint64_t l2_cache_offsets[L2_CACHE_SIZE];
76     uint32_t l2_cache_counts[L2_CACHE_SIZE];
77     uint8_t *cluster_cache;
78     uint8_t *cluster_data;
79     uint64_t cluster_cache_offset;
80     QCryptoCipher *cipher; /* NULL if no key yet */
81     uint32_t crypt_method_header;
82     CoMutex lock;
83     Error *migration_blocker;
84 } BDRVQcowState;
85 
86 static int decompress_cluster(BlockDriverState *bs, uint64_t cluster_offset);
87 
88 static int qcow_probe(const uint8_t *buf, int buf_size, const char *filename)
89 {
90     const QCowHeader *cow_header = (const void *)buf;
91 
92     if (buf_size >= sizeof(QCowHeader) &&
93         be32_to_cpu(cow_header->magic) == QCOW_MAGIC &&
94         be32_to_cpu(cow_header->version) == QCOW_VERSION)
95         return 100;
96     else
97         return 0;
98 }
99 
100 static int qcow_open(BlockDriverState *bs, QDict *options, int flags,
101                      Error **errp)
102 {
103     BDRVQcowState *s = bs->opaque;
104     unsigned int len, i, shift;
105     int ret;
106     QCowHeader header;
107 
108     ret = bdrv_pread(bs->file->bs, 0, &header, sizeof(header));
109     if (ret < 0) {
110         goto fail;
111     }
112     be32_to_cpus(&header.magic);
113     be32_to_cpus(&header.version);
114     be64_to_cpus(&header.backing_file_offset);
115     be32_to_cpus(&header.backing_file_size);
116     be32_to_cpus(&header.mtime);
117     be64_to_cpus(&header.size);
118     be32_to_cpus(&header.crypt_method);
119     be64_to_cpus(&header.l1_table_offset);
120 
121     if (header.magic != QCOW_MAGIC) {
122         error_setg(errp, "Image not in qcow format");
123         ret = -EINVAL;
124         goto fail;
125     }
126     if (header.version != QCOW_VERSION) {
127         error_setg(errp, "Unsupported qcow version %" PRIu32, header.version);
128         ret = -ENOTSUP;
129         goto fail;
130     }
131 
132     if (header.size <= 1) {
133         error_setg(errp, "Image size is too small (must be at least 2 bytes)");
134         ret = -EINVAL;
135         goto fail;
136     }
137     if (header.cluster_bits < 9 || header.cluster_bits > 16) {
138         error_setg(errp, "Cluster size must be between 512 and 64k");
139         ret = -EINVAL;
140         goto fail;
141     }
142 
143     /* l2_bits specifies number of entries; storing a uint64_t in each entry,
144      * so bytes = num_entries << 3. */
145     if (header.l2_bits < 9 - 3 || header.l2_bits > 16 - 3) {
146         error_setg(errp, "L2 table size must be between 512 and 64k");
147         ret = -EINVAL;
148         goto fail;
149     }
150 
151     if (header.crypt_method > QCOW_CRYPT_AES) {
152         error_setg(errp, "invalid encryption method in qcow header");
153         ret = -EINVAL;
154         goto fail;
155     }
156     if (!qcrypto_cipher_supports(QCRYPTO_CIPHER_ALG_AES_128)) {
157         error_setg(errp, "AES cipher not available");
158         ret = -EINVAL;
159         goto fail;
160     }
161     s->crypt_method_header = header.crypt_method;
162     if (s->crypt_method_header) {
163         if (bdrv_uses_whitelist() &&
164             s->crypt_method_header == QCOW_CRYPT_AES) {
165             error_setg(errp,
166                        "Use of AES-CBC encrypted qcow images is no longer "
167                        "supported in system emulators");
168             error_append_hint(errp,
169                               "You can use 'qemu-img convert' to convert your "
170                               "image to an alternative supported format, such "
171                               "as unencrypted qcow, or raw with the LUKS "
172                               "format instead.\n");
173             ret = -ENOSYS;
174             goto fail;
175         }
176 
177         bs->encrypted = 1;
178     }
179     s->cluster_bits = header.cluster_bits;
180     s->cluster_size = 1 << s->cluster_bits;
181     s->cluster_sectors = 1 << (s->cluster_bits - 9);
182     s->l2_bits = header.l2_bits;
183     s->l2_size = 1 << s->l2_bits;
184     bs->total_sectors = header.size / 512;
185     s->cluster_offset_mask = (1LL << (63 - s->cluster_bits)) - 1;
186 
187     /* read the level 1 table */
188     shift = s->cluster_bits + s->l2_bits;
189     if (header.size > UINT64_MAX - (1LL << shift)) {
190         error_setg(errp, "Image too large");
191         ret = -EINVAL;
192         goto fail;
193     } else {
194         uint64_t l1_size = (header.size + (1LL << shift) - 1) >> shift;
195         if (l1_size > INT_MAX / sizeof(uint64_t)) {
196             error_setg(errp, "Image too large");
197             ret = -EINVAL;
198             goto fail;
199         }
200         s->l1_size = l1_size;
201     }
202 
203     s->l1_table_offset = header.l1_table_offset;
204     s->l1_table = g_try_new(uint64_t, s->l1_size);
205     if (s->l1_table == NULL) {
206         error_setg(errp, "Could not allocate memory for L1 table");
207         ret = -ENOMEM;
208         goto fail;
209     }
210 
211     ret = bdrv_pread(bs->file->bs, s->l1_table_offset, s->l1_table,
212                s->l1_size * sizeof(uint64_t));
213     if (ret < 0) {
214         goto fail;
215     }
216 
217     for(i = 0;i < s->l1_size; i++) {
218         be64_to_cpus(&s->l1_table[i]);
219     }
220 
221     /* alloc L2 cache (max. 64k * 16 * 8 = 8 MB) */
222     s->l2_cache =
223         qemu_try_blockalign(bs->file->bs,
224                             s->l2_size * L2_CACHE_SIZE * sizeof(uint64_t));
225     if (s->l2_cache == NULL) {
226         error_setg(errp, "Could not allocate L2 table cache");
227         ret = -ENOMEM;
228         goto fail;
229     }
230     s->cluster_cache = g_malloc(s->cluster_size);
231     s->cluster_data = g_malloc(s->cluster_size);
232     s->cluster_cache_offset = -1;
233 
234     /* read the backing file name */
235     if (header.backing_file_offset != 0) {
236         len = header.backing_file_size;
237         if (len > 1023 || len >= sizeof(bs->backing_file)) {
238             error_setg(errp, "Backing file name too long");
239             ret = -EINVAL;
240             goto fail;
241         }
242         ret = bdrv_pread(bs->file->bs, header.backing_file_offset,
243                    bs->backing_file, len);
244         if (ret < 0) {
245             goto fail;
246         }
247         bs->backing_file[len] = '\0';
248     }
249 
250     /* Disable migration when qcow images are used */
251     error_setg(&s->migration_blocker, "The qcow format used by node '%s' "
252                "does not support live migration",
253                bdrv_get_device_or_node_name(bs));
254     migrate_add_blocker(s->migration_blocker);
255 
256     qemu_co_mutex_init(&s->lock);
257     return 0;
258 
259  fail:
260     g_free(s->l1_table);
261     qemu_vfree(s->l2_cache);
262     g_free(s->cluster_cache);
263     g_free(s->cluster_data);
264     return ret;
265 }
266 
267 
268 /* We have nothing to do for QCOW reopen, stubs just return
269  * success */
270 static int qcow_reopen_prepare(BDRVReopenState *state,
271                                BlockReopenQueue *queue, Error **errp)
272 {
273     return 0;
274 }
275 
276 static int qcow_set_key(BlockDriverState *bs, const char *key)
277 {
278     BDRVQcowState *s = bs->opaque;
279     uint8_t keybuf[16];
280     int len, i;
281     Error *err;
282 
283     memset(keybuf, 0, 16);
284     len = strlen(key);
285     if (len > 16)
286         len = 16;
287     /* XXX: we could compress the chars to 7 bits to increase
288        entropy */
289     for(i = 0;i < len;i++) {
290         keybuf[i] = key[i];
291     }
292     assert(bs->encrypted);
293 
294     qcrypto_cipher_free(s->cipher);
295     s->cipher = qcrypto_cipher_new(
296         QCRYPTO_CIPHER_ALG_AES_128,
297         QCRYPTO_CIPHER_MODE_CBC,
298         keybuf, G_N_ELEMENTS(keybuf),
299         &err);
300 
301     if (!s->cipher) {
302         /* XXX would be nice if errors in this method could
303          * be properly propagate to the caller. Would need
304          * the bdrv_set_key() API signature to be fixed. */
305         error_free(err);
306         return -1;
307     }
308     return 0;
309 }
310 
311 /* The crypt function is compatible with the linux cryptoloop
312    algorithm for < 4 GB images. NOTE: out_buf == in_buf is
313    supported */
314 static int encrypt_sectors(BDRVQcowState *s, int64_t sector_num,
315                            uint8_t *out_buf, const uint8_t *in_buf,
316                            int nb_sectors, bool enc, Error **errp)
317 {
318     union {
319         uint64_t ll[2];
320         uint8_t b[16];
321     } ivec;
322     int i;
323     int ret;
324 
325     for(i = 0; i < nb_sectors; i++) {
326         ivec.ll[0] = cpu_to_le64(sector_num);
327         ivec.ll[1] = 0;
328         if (qcrypto_cipher_setiv(s->cipher,
329                                  ivec.b, G_N_ELEMENTS(ivec.b),
330                                  errp) < 0) {
331             return -1;
332         }
333         if (enc) {
334             ret = qcrypto_cipher_encrypt(s->cipher,
335                                          in_buf,
336                                          out_buf,
337                                          512,
338                                          errp);
339         } else {
340             ret = qcrypto_cipher_decrypt(s->cipher,
341                                          in_buf,
342                                          out_buf,
343                                          512,
344                                          errp);
345         }
346         if (ret < 0) {
347             return -1;
348         }
349         sector_num++;
350         in_buf += 512;
351         out_buf += 512;
352     }
353     return 0;
354 }
355 
356 /* 'allocate' is:
357  *
358  * 0 to not allocate.
359  *
360  * 1 to allocate a normal cluster (for sector indexes 'n_start' to
361  * 'n_end')
362  *
363  * 2 to allocate a compressed cluster of size
364  * 'compressed_size'. 'compressed_size' must be > 0 and <
365  * cluster_size
366  *
367  * return 0 if not allocated.
368  */
369 static uint64_t get_cluster_offset(BlockDriverState *bs,
370                                    uint64_t offset, int allocate,
371                                    int compressed_size,
372                                    int n_start, int n_end)
373 {
374     BDRVQcowState *s = bs->opaque;
375     int min_index, i, j, l1_index, l2_index;
376     uint64_t l2_offset, *l2_table, cluster_offset, tmp;
377     uint32_t min_count;
378     int new_l2_table;
379 
380     l1_index = offset >> (s->l2_bits + s->cluster_bits);
381     l2_offset = s->l1_table[l1_index];
382     new_l2_table = 0;
383     if (!l2_offset) {
384         if (!allocate)
385             return 0;
386         /* allocate a new l2 entry */
387         l2_offset = bdrv_getlength(bs->file->bs);
388         /* round to cluster size */
389         l2_offset = (l2_offset + s->cluster_size - 1) & ~(s->cluster_size - 1);
390         /* update the L1 entry */
391         s->l1_table[l1_index] = l2_offset;
392         tmp = cpu_to_be64(l2_offset);
393         if (bdrv_pwrite_sync(bs->file->bs,
394                 s->l1_table_offset + l1_index * sizeof(tmp),
395                 &tmp, sizeof(tmp)) < 0)
396             return 0;
397         new_l2_table = 1;
398     }
399     for(i = 0; i < L2_CACHE_SIZE; i++) {
400         if (l2_offset == s->l2_cache_offsets[i]) {
401             /* increment the hit count */
402             if (++s->l2_cache_counts[i] == 0xffffffff) {
403                 for(j = 0; j < L2_CACHE_SIZE; j++) {
404                     s->l2_cache_counts[j] >>= 1;
405                 }
406             }
407             l2_table = s->l2_cache + (i << s->l2_bits);
408             goto found;
409         }
410     }
411     /* not found: load a new entry in the least used one */
412     min_index = 0;
413     min_count = 0xffffffff;
414     for(i = 0; i < L2_CACHE_SIZE; i++) {
415         if (s->l2_cache_counts[i] < min_count) {
416             min_count = s->l2_cache_counts[i];
417             min_index = i;
418         }
419     }
420     l2_table = s->l2_cache + (min_index << s->l2_bits);
421     if (new_l2_table) {
422         memset(l2_table, 0, s->l2_size * sizeof(uint64_t));
423         if (bdrv_pwrite_sync(bs->file->bs, l2_offset, l2_table,
424                 s->l2_size * sizeof(uint64_t)) < 0)
425             return 0;
426     } else {
427         if (bdrv_pread(bs->file->bs, l2_offset, l2_table,
428                        s->l2_size * sizeof(uint64_t)) !=
429             s->l2_size * sizeof(uint64_t))
430             return 0;
431     }
432     s->l2_cache_offsets[min_index] = l2_offset;
433     s->l2_cache_counts[min_index] = 1;
434  found:
435     l2_index = (offset >> s->cluster_bits) & (s->l2_size - 1);
436     cluster_offset = be64_to_cpu(l2_table[l2_index]);
437     if (!cluster_offset ||
438         ((cluster_offset & QCOW_OFLAG_COMPRESSED) && allocate == 1)) {
439         if (!allocate)
440             return 0;
441         /* allocate a new cluster */
442         if ((cluster_offset & QCOW_OFLAG_COMPRESSED) &&
443             (n_end - n_start) < s->cluster_sectors) {
444             /* if the cluster is already compressed, we must
445                decompress it in the case it is not completely
446                overwritten */
447             if (decompress_cluster(bs, cluster_offset) < 0)
448                 return 0;
449             cluster_offset = bdrv_getlength(bs->file->bs);
450             cluster_offset = (cluster_offset + s->cluster_size - 1) &
451                 ~(s->cluster_size - 1);
452             /* write the cluster content */
453             if (bdrv_pwrite(bs->file->bs, cluster_offset, s->cluster_cache,
454                             s->cluster_size) !=
455                 s->cluster_size)
456                 return -1;
457         } else {
458             cluster_offset = bdrv_getlength(bs->file->bs);
459             if (allocate == 1) {
460                 /* round to cluster size */
461                 cluster_offset = (cluster_offset + s->cluster_size - 1) &
462                     ~(s->cluster_size - 1);
463                 bdrv_truncate(bs->file->bs, cluster_offset + s->cluster_size);
464                 /* if encrypted, we must initialize the cluster
465                    content which won't be written */
466                 if (bs->encrypted &&
467                     (n_end - n_start) < s->cluster_sectors) {
468                     uint64_t start_sect;
469                     assert(s->cipher);
470                     start_sect = (offset & ~(s->cluster_size - 1)) >> 9;
471                     memset(s->cluster_data + 512, 0x00, 512);
472                     for(i = 0; i < s->cluster_sectors; i++) {
473                         if (i < n_start || i >= n_end) {
474                             Error *err = NULL;
475                             if (encrypt_sectors(s, start_sect + i,
476                                                 s->cluster_data,
477                                                 s->cluster_data + 512, 1,
478                                                 true, &err) < 0) {
479                                 error_free(err);
480                                 errno = EIO;
481                                 return -1;
482                             }
483                             if (bdrv_pwrite(bs->file->bs,
484                                             cluster_offset + i * 512,
485                                             s->cluster_data, 512) != 512)
486                                 return -1;
487                         }
488                     }
489                 }
490             } else if (allocate == 2) {
491                 cluster_offset |= QCOW_OFLAG_COMPRESSED |
492                     (uint64_t)compressed_size << (63 - s->cluster_bits);
493             }
494         }
495         /* update L2 table */
496         tmp = cpu_to_be64(cluster_offset);
497         l2_table[l2_index] = tmp;
498         if (bdrv_pwrite_sync(bs->file->bs, l2_offset + l2_index * sizeof(tmp),
499                 &tmp, sizeof(tmp)) < 0)
500             return 0;
501     }
502     return cluster_offset;
503 }
504 
505 static int64_t coroutine_fn qcow_co_get_block_status(BlockDriverState *bs,
506         int64_t sector_num, int nb_sectors, int *pnum, BlockDriverState **file)
507 {
508     BDRVQcowState *s = bs->opaque;
509     int index_in_cluster, n;
510     uint64_t cluster_offset;
511 
512     qemu_co_mutex_lock(&s->lock);
513     cluster_offset = get_cluster_offset(bs, sector_num << 9, 0, 0, 0, 0);
514     qemu_co_mutex_unlock(&s->lock);
515     index_in_cluster = sector_num & (s->cluster_sectors - 1);
516     n = s->cluster_sectors - index_in_cluster;
517     if (n > nb_sectors)
518         n = nb_sectors;
519     *pnum = n;
520     if (!cluster_offset) {
521         return 0;
522     }
523     if ((cluster_offset & QCOW_OFLAG_COMPRESSED) || s->cipher) {
524         return BDRV_BLOCK_DATA;
525     }
526     cluster_offset |= (index_in_cluster << BDRV_SECTOR_BITS);
527     *file = bs->file->bs;
528     return BDRV_BLOCK_DATA | BDRV_BLOCK_OFFSET_VALID | cluster_offset;
529 }
530 
531 static int decompress_buffer(uint8_t *out_buf, int out_buf_size,
532                              const uint8_t *buf, int buf_size)
533 {
534     z_stream strm1, *strm = &strm1;
535     int ret, out_len;
536 
537     memset(strm, 0, sizeof(*strm));
538 
539     strm->next_in = (uint8_t *)buf;
540     strm->avail_in = buf_size;
541     strm->next_out = out_buf;
542     strm->avail_out = out_buf_size;
543 
544     ret = inflateInit2(strm, -12);
545     if (ret != Z_OK)
546         return -1;
547     ret = inflate(strm, Z_FINISH);
548     out_len = strm->next_out - out_buf;
549     if ((ret != Z_STREAM_END && ret != Z_BUF_ERROR) ||
550         out_len != out_buf_size) {
551         inflateEnd(strm);
552         return -1;
553     }
554     inflateEnd(strm);
555     return 0;
556 }
557 
558 static int decompress_cluster(BlockDriverState *bs, uint64_t cluster_offset)
559 {
560     BDRVQcowState *s = bs->opaque;
561     int ret, csize;
562     uint64_t coffset;
563 
564     coffset = cluster_offset & s->cluster_offset_mask;
565     if (s->cluster_cache_offset != coffset) {
566         csize = cluster_offset >> (63 - s->cluster_bits);
567         csize &= (s->cluster_size - 1);
568         ret = bdrv_pread(bs->file->bs, coffset, s->cluster_data, csize);
569         if (ret != csize)
570             return -1;
571         if (decompress_buffer(s->cluster_cache, s->cluster_size,
572                               s->cluster_data, csize) < 0) {
573             return -1;
574         }
575         s->cluster_cache_offset = coffset;
576     }
577     return 0;
578 }
579 
580 static coroutine_fn int qcow_co_readv(BlockDriverState *bs, int64_t sector_num,
581                          int nb_sectors, QEMUIOVector *qiov)
582 {
583     BDRVQcowState *s = bs->opaque;
584     int index_in_cluster;
585     int ret = 0, n;
586     uint64_t cluster_offset;
587     struct iovec hd_iov;
588     QEMUIOVector hd_qiov;
589     uint8_t *buf;
590     void *orig_buf;
591     Error *err = NULL;
592 
593     if (qiov->niov > 1) {
594         buf = orig_buf = qemu_try_blockalign(bs, qiov->size);
595         if (buf == NULL) {
596             return -ENOMEM;
597         }
598     } else {
599         orig_buf = NULL;
600         buf = (uint8_t *)qiov->iov->iov_base;
601     }
602 
603     qemu_co_mutex_lock(&s->lock);
604 
605     while (nb_sectors != 0) {
606         /* prepare next request */
607         cluster_offset = get_cluster_offset(bs, sector_num << 9,
608                                                  0, 0, 0, 0);
609         index_in_cluster = sector_num & (s->cluster_sectors - 1);
610         n = s->cluster_sectors - index_in_cluster;
611         if (n > nb_sectors) {
612             n = nb_sectors;
613         }
614 
615         if (!cluster_offset) {
616             if (bs->backing) {
617                 /* read from the base image */
618                 hd_iov.iov_base = (void *)buf;
619                 hd_iov.iov_len = n * 512;
620                 qemu_iovec_init_external(&hd_qiov, &hd_iov, 1);
621                 qemu_co_mutex_unlock(&s->lock);
622                 ret = bdrv_co_readv(bs->backing->bs, sector_num,
623                                     n, &hd_qiov);
624                 qemu_co_mutex_lock(&s->lock);
625                 if (ret < 0) {
626                     goto fail;
627                 }
628             } else {
629                 /* Note: in this case, no need to wait */
630                 memset(buf, 0, 512 * n);
631             }
632         } else if (cluster_offset & QCOW_OFLAG_COMPRESSED) {
633             /* add AIO support for compressed blocks ? */
634             if (decompress_cluster(bs, cluster_offset) < 0) {
635                 goto fail;
636             }
637             memcpy(buf,
638                    s->cluster_cache + index_in_cluster * 512, 512 * n);
639         } else {
640             if ((cluster_offset & 511) != 0) {
641                 goto fail;
642             }
643             hd_iov.iov_base = (void *)buf;
644             hd_iov.iov_len = n * 512;
645             qemu_iovec_init_external(&hd_qiov, &hd_iov, 1);
646             qemu_co_mutex_unlock(&s->lock);
647             ret = bdrv_co_readv(bs->file->bs,
648                                 (cluster_offset >> 9) + index_in_cluster,
649                                 n, &hd_qiov);
650             qemu_co_mutex_lock(&s->lock);
651             if (ret < 0) {
652                 break;
653             }
654             if (bs->encrypted) {
655                 assert(s->cipher);
656                 if (encrypt_sectors(s, sector_num, buf, buf,
657                                     n, false, &err) < 0) {
658                     goto fail;
659                 }
660             }
661         }
662         ret = 0;
663 
664         nb_sectors -= n;
665         sector_num += n;
666         buf += n * 512;
667     }
668 
669 done:
670     qemu_co_mutex_unlock(&s->lock);
671 
672     if (qiov->niov > 1) {
673         qemu_iovec_from_buf(qiov, 0, orig_buf, qiov->size);
674         qemu_vfree(orig_buf);
675     }
676 
677     return ret;
678 
679 fail:
680     error_free(err);
681     ret = -EIO;
682     goto done;
683 }
684 
685 static coroutine_fn int qcow_co_writev(BlockDriverState *bs, int64_t sector_num,
686                           int nb_sectors, QEMUIOVector *qiov)
687 {
688     BDRVQcowState *s = bs->opaque;
689     int index_in_cluster;
690     uint64_t cluster_offset;
691     const uint8_t *src_buf;
692     int ret = 0, n;
693     uint8_t *cluster_data = NULL;
694     struct iovec hd_iov;
695     QEMUIOVector hd_qiov;
696     uint8_t *buf;
697     void *orig_buf;
698 
699     s->cluster_cache_offset = -1; /* disable compressed cache */
700 
701     if (qiov->niov > 1) {
702         buf = orig_buf = qemu_try_blockalign(bs, qiov->size);
703         if (buf == NULL) {
704             return -ENOMEM;
705         }
706         qemu_iovec_to_buf(qiov, 0, buf, qiov->size);
707     } else {
708         orig_buf = NULL;
709         buf = (uint8_t *)qiov->iov->iov_base;
710     }
711 
712     qemu_co_mutex_lock(&s->lock);
713 
714     while (nb_sectors != 0) {
715 
716         index_in_cluster = sector_num & (s->cluster_sectors - 1);
717         n = s->cluster_sectors - index_in_cluster;
718         if (n > nb_sectors) {
719             n = nb_sectors;
720         }
721         cluster_offset = get_cluster_offset(bs, sector_num << 9, 1, 0,
722                                             index_in_cluster,
723                                             index_in_cluster + n);
724         if (!cluster_offset || (cluster_offset & 511) != 0) {
725             ret = -EIO;
726             break;
727         }
728         if (bs->encrypted) {
729             Error *err = NULL;
730             assert(s->cipher);
731             if (!cluster_data) {
732                 cluster_data = g_malloc0(s->cluster_size);
733             }
734             if (encrypt_sectors(s, sector_num, cluster_data, buf,
735                                 n, true, &err) < 0) {
736                 error_free(err);
737                 ret = -EIO;
738                 break;
739             }
740             src_buf = cluster_data;
741         } else {
742             src_buf = buf;
743         }
744 
745         hd_iov.iov_base = (void *)src_buf;
746         hd_iov.iov_len = n * 512;
747         qemu_iovec_init_external(&hd_qiov, &hd_iov, 1);
748         qemu_co_mutex_unlock(&s->lock);
749         ret = bdrv_co_writev(bs->file->bs,
750                              (cluster_offset >> 9) + index_in_cluster,
751                              n, &hd_qiov);
752         qemu_co_mutex_lock(&s->lock);
753         if (ret < 0) {
754             break;
755         }
756         ret = 0;
757 
758         nb_sectors -= n;
759         sector_num += n;
760         buf += n * 512;
761     }
762     qemu_co_mutex_unlock(&s->lock);
763 
764     if (qiov->niov > 1) {
765         qemu_vfree(orig_buf);
766     }
767     g_free(cluster_data);
768 
769     return ret;
770 }
771 
772 static void qcow_close(BlockDriverState *bs)
773 {
774     BDRVQcowState *s = bs->opaque;
775 
776     qcrypto_cipher_free(s->cipher);
777     s->cipher = NULL;
778     g_free(s->l1_table);
779     qemu_vfree(s->l2_cache);
780     g_free(s->cluster_cache);
781     g_free(s->cluster_data);
782 
783     migrate_del_blocker(s->migration_blocker);
784     error_free(s->migration_blocker);
785 }
786 
787 static int qcow_create(const char *filename, QemuOpts *opts, Error **errp)
788 {
789     int header_size, backing_filename_len, l1_size, shift, i;
790     QCowHeader header;
791     uint8_t *tmp;
792     int64_t total_size = 0;
793     char *backing_file = NULL;
794     int flags = 0;
795     Error *local_err = NULL;
796     int ret;
797     BlockBackend *qcow_blk;
798 
799     /* Read out options */
800     total_size = ROUND_UP(qemu_opt_get_size_del(opts, BLOCK_OPT_SIZE, 0),
801                           BDRV_SECTOR_SIZE);
802     backing_file = qemu_opt_get_del(opts, BLOCK_OPT_BACKING_FILE);
803     if (qemu_opt_get_bool_del(opts, BLOCK_OPT_ENCRYPT, false)) {
804         flags |= BLOCK_FLAG_ENCRYPT;
805     }
806 
807     ret = bdrv_create_file(filename, opts, &local_err);
808     if (ret < 0) {
809         error_propagate(errp, local_err);
810         goto cleanup;
811     }
812 
813     qcow_blk = blk_new_open(filename, NULL, NULL,
814                             BDRV_O_RDWR | BDRV_O_PROTOCOL, &local_err);
815     if (qcow_blk == NULL) {
816         error_propagate(errp, local_err);
817         ret = -EIO;
818         goto cleanup;
819     }
820 
821     blk_set_allow_write_beyond_eof(qcow_blk, true);
822 
823     ret = blk_truncate(qcow_blk, 0);
824     if (ret < 0) {
825         goto exit;
826     }
827 
828     memset(&header, 0, sizeof(header));
829     header.magic = cpu_to_be32(QCOW_MAGIC);
830     header.version = cpu_to_be32(QCOW_VERSION);
831     header.size = cpu_to_be64(total_size);
832     header_size = sizeof(header);
833     backing_filename_len = 0;
834     if (backing_file) {
835         if (strcmp(backing_file, "fat:")) {
836             header.backing_file_offset = cpu_to_be64(header_size);
837             backing_filename_len = strlen(backing_file);
838             header.backing_file_size = cpu_to_be32(backing_filename_len);
839             header_size += backing_filename_len;
840         } else {
841             /* special backing file for vvfat */
842             backing_file = NULL;
843         }
844         header.cluster_bits = 9; /* 512 byte cluster to avoid copying
845                                     unmodified sectors */
846         header.l2_bits = 12; /* 32 KB L2 tables */
847     } else {
848         header.cluster_bits = 12; /* 4 KB clusters */
849         header.l2_bits = 9; /* 4 KB L2 tables */
850     }
851     header_size = (header_size + 7) & ~7;
852     shift = header.cluster_bits + header.l2_bits;
853     l1_size = (total_size + (1LL << shift) - 1) >> shift;
854 
855     header.l1_table_offset = cpu_to_be64(header_size);
856     if (flags & BLOCK_FLAG_ENCRYPT) {
857         header.crypt_method = cpu_to_be32(QCOW_CRYPT_AES);
858     } else {
859         header.crypt_method = cpu_to_be32(QCOW_CRYPT_NONE);
860     }
861 
862     /* write all the data */
863     ret = blk_pwrite(qcow_blk, 0, &header, sizeof(header), 0);
864     if (ret != sizeof(header)) {
865         goto exit;
866     }
867 
868     if (backing_file) {
869         ret = blk_pwrite(qcow_blk, sizeof(header),
870                          backing_file, backing_filename_len, 0);
871         if (ret != backing_filename_len) {
872             goto exit;
873         }
874     }
875 
876     tmp = g_malloc0(BDRV_SECTOR_SIZE);
877     for (i = 0; i < DIV_ROUND_UP(sizeof(uint64_t) * l1_size, BDRV_SECTOR_SIZE);
878          i++) {
879         ret = blk_pwrite(qcow_blk, header_size + BDRV_SECTOR_SIZE * i,
880                          tmp, BDRV_SECTOR_SIZE, 0);
881         if (ret != BDRV_SECTOR_SIZE) {
882             g_free(tmp);
883             goto exit;
884         }
885     }
886 
887     g_free(tmp);
888     ret = 0;
889 exit:
890     blk_unref(qcow_blk);
891 cleanup:
892     g_free(backing_file);
893     return ret;
894 }
895 
896 static int qcow_make_empty(BlockDriverState *bs)
897 {
898     BDRVQcowState *s = bs->opaque;
899     uint32_t l1_length = s->l1_size * sizeof(uint64_t);
900     int ret;
901 
902     memset(s->l1_table, 0, l1_length);
903     if (bdrv_pwrite_sync(bs->file->bs, s->l1_table_offset, s->l1_table,
904             l1_length) < 0)
905         return -1;
906     ret = bdrv_truncate(bs->file->bs, s->l1_table_offset + l1_length);
907     if (ret < 0)
908         return ret;
909 
910     memset(s->l2_cache, 0, s->l2_size * L2_CACHE_SIZE * sizeof(uint64_t));
911     memset(s->l2_cache_offsets, 0, L2_CACHE_SIZE * sizeof(uint64_t));
912     memset(s->l2_cache_counts, 0, L2_CACHE_SIZE * sizeof(uint32_t));
913 
914     return 0;
915 }
916 
917 /* XXX: put compressed sectors first, then all the cluster aligned
918    tables to avoid losing bytes in alignment */
919 static int qcow_write_compressed(BlockDriverState *bs, int64_t sector_num,
920                                  const uint8_t *buf, int nb_sectors)
921 {
922     BDRVQcowState *s = bs->opaque;
923     z_stream strm;
924     int ret, out_len;
925     uint8_t *out_buf;
926     uint64_t cluster_offset;
927 
928     if (nb_sectors != s->cluster_sectors) {
929         ret = -EINVAL;
930 
931         /* Zero-pad last write if image size is not cluster aligned */
932         if (sector_num + nb_sectors == bs->total_sectors &&
933             nb_sectors < s->cluster_sectors) {
934             uint8_t *pad_buf = qemu_blockalign(bs, s->cluster_size);
935             memset(pad_buf, 0, s->cluster_size);
936             memcpy(pad_buf, buf, nb_sectors * BDRV_SECTOR_SIZE);
937             ret = qcow_write_compressed(bs, sector_num,
938                                         pad_buf, s->cluster_sectors);
939             qemu_vfree(pad_buf);
940         }
941         return ret;
942     }
943 
944     out_buf = g_malloc(s->cluster_size + (s->cluster_size / 1000) + 128);
945 
946     /* best compression, small window, no zlib header */
947     memset(&strm, 0, sizeof(strm));
948     ret = deflateInit2(&strm, Z_DEFAULT_COMPRESSION,
949                        Z_DEFLATED, -12,
950                        9, Z_DEFAULT_STRATEGY);
951     if (ret != 0) {
952         ret = -EINVAL;
953         goto fail;
954     }
955 
956     strm.avail_in = s->cluster_size;
957     strm.next_in = (uint8_t *)buf;
958     strm.avail_out = s->cluster_size;
959     strm.next_out = out_buf;
960 
961     ret = deflate(&strm, Z_FINISH);
962     if (ret != Z_STREAM_END && ret != Z_OK) {
963         deflateEnd(&strm);
964         ret = -EINVAL;
965         goto fail;
966     }
967     out_len = strm.next_out - out_buf;
968 
969     deflateEnd(&strm);
970 
971     if (ret != Z_STREAM_END || out_len >= s->cluster_size) {
972         /* could not compress: write normal cluster */
973         ret = bdrv_write(bs, sector_num, buf, s->cluster_sectors);
974         if (ret < 0) {
975             goto fail;
976         }
977     } else {
978         cluster_offset = get_cluster_offset(bs, sector_num << 9, 2,
979                                             out_len, 0, 0);
980         if (cluster_offset == 0) {
981             ret = -EIO;
982             goto fail;
983         }
984 
985         cluster_offset &= s->cluster_offset_mask;
986         ret = bdrv_pwrite(bs->file->bs, cluster_offset, out_buf, out_len);
987         if (ret < 0) {
988             goto fail;
989         }
990     }
991 
992     ret = 0;
993 fail:
994     g_free(out_buf);
995     return ret;
996 }
997 
998 static int qcow_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
999 {
1000     BDRVQcowState *s = bs->opaque;
1001     bdi->cluster_size = s->cluster_size;
1002     return 0;
1003 }
1004 
1005 static QemuOptsList qcow_create_opts = {
1006     .name = "qcow-create-opts",
1007     .head = QTAILQ_HEAD_INITIALIZER(qcow_create_opts.head),
1008     .desc = {
1009         {
1010             .name = BLOCK_OPT_SIZE,
1011             .type = QEMU_OPT_SIZE,
1012             .help = "Virtual disk size"
1013         },
1014         {
1015             .name = BLOCK_OPT_BACKING_FILE,
1016             .type = QEMU_OPT_STRING,
1017             .help = "File name of a base image"
1018         },
1019         {
1020             .name = BLOCK_OPT_ENCRYPT,
1021             .type = QEMU_OPT_BOOL,
1022             .help = "Encrypt the image",
1023             .def_value_str = "off"
1024         },
1025         { /* end of list */ }
1026     }
1027 };
1028 
1029 static BlockDriver bdrv_qcow = {
1030     .format_name	= "qcow",
1031     .instance_size	= sizeof(BDRVQcowState),
1032     .bdrv_probe		= qcow_probe,
1033     .bdrv_open		= qcow_open,
1034     .bdrv_close		= qcow_close,
1035     .bdrv_reopen_prepare    = qcow_reopen_prepare,
1036     .bdrv_create            = qcow_create,
1037     .bdrv_has_zero_init     = bdrv_has_zero_init_1,
1038     .supports_backing       = true,
1039 
1040     .bdrv_co_readv          = qcow_co_readv,
1041     .bdrv_co_writev         = qcow_co_writev,
1042     .bdrv_co_get_block_status   = qcow_co_get_block_status,
1043 
1044     .bdrv_set_key           = qcow_set_key,
1045     .bdrv_make_empty        = qcow_make_empty,
1046     .bdrv_write_compressed  = qcow_write_compressed,
1047     .bdrv_get_info          = qcow_get_info,
1048 
1049     .create_opts            = &qcow_create_opts,
1050 };
1051 
1052 static void bdrv_qcow_init(void)
1053 {
1054     bdrv_register(&bdrv_qcow);
1055 }
1056 
1057 block_init(bdrv_qcow_init);
1058