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