qcow: Switch to .bdrv_co_block_status()
[qemu.git] / block / qcow.c
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 "sysemu/block-backend.h"
30 #include "qemu/module.h"
31 #include "qemu/option.h"
32 #include "qemu/bswap.h"
33 #include <zlib.h>
34 #include "qapi/qmp/qdict.h"
35 #include "qapi/qmp/qstring.h"
36 #include "crypto/block.h"
37 #include "migration/blocker.h"
38 #include "block/crypto.h"
39
40 /**************************************************************/
41 /* QEMU COW block driver with compression and encryption support */
42
43 #define QCOW_MAGIC (('Q' << 24) | ('F' << 16) | ('I' << 8) | 0xfb)
44 #define QCOW_VERSION 1
45
46 #define QCOW_CRYPT_NONE 0
47 #define QCOW_CRYPT_AES  1
48
49 #define QCOW_OFLAG_COMPRESSED (1LL << 63)
50
51 typedef struct QCowHeader {
52     uint32_t magic;
53     uint32_t version;
54     uint64_t backing_file_offset;
55     uint32_t backing_file_size;
56     uint32_t mtime;
57     uint64_t size; /* in bytes */
58     uint8_t cluster_bits;
59     uint8_t l2_bits;
60     uint16_t padding;
61     uint32_t crypt_method;
62     uint64_t l1_table_offset;
63 } QEMU_PACKED QCowHeader;
64
65 #define L2_CACHE_SIZE 16
66
67 typedef struct BDRVQcowState {
68     int cluster_bits;
69     int cluster_size;
70     int cluster_sectors;
71     int l2_bits;
72     int l2_size;
73     unsigned int l1_size;
74     uint64_t cluster_offset_mask;
75     uint64_t l1_table_offset;
76     uint64_t *l1_table;
77     uint64_t *l2_cache;
78     uint64_t l2_cache_offsets[L2_CACHE_SIZE];
79     uint32_t l2_cache_counts[L2_CACHE_SIZE];
80     uint8_t *cluster_cache;
81     uint8_t *cluster_data;
82     uint64_t cluster_cache_offset;
83     QCryptoBlock *crypto; /* Disk encryption format driver */
84     uint32_t crypt_method_header;
85     CoMutex lock;
86     Error *migration_blocker;
87 } BDRVQcowState;
88
89 static int decompress_cluster(BlockDriverState *bs, uint64_t cluster_offset);
90
91 static int qcow_probe(const uint8_t *buf, int buf_size, const char *filename)
92 {
93     const QCowHeader *cow_header = (const void *)buf;
94
95     if (buf_size >= sizeof(QCowHeader) &&
96         be32_to_cpu(cow_header->magic) == QCOW_MAGIC &&
97         be32_to_cpu(cow_header->version) == QCOW_VERSION)
98         return 100;
99     else
100         return 0;
101 }
102
103 static QemuOptsList qcow_runtime_opts = {
104     .name = "qcow",
105     .head = QTAILQ_HEAD_INITIALIZER(qcow_runtime_opts.head),
106     .desc = {
107         BLOCK_CRYPTO_OPT_DEF_QCOW_KEY_SECRET("encrypt."),
108         { /* end of list */ }
109     },
110 };
111
112 static int qcow_open(BlockDriverState *bs, QDict *options, int flags,
113                      Error **errp)
114 {
115     BDRVQcowState *s = bs->opaque;
116     unsigned int len, i, shift;
117     int ret;
118     QCowHeader header;
119     Error *local_err = NULL;
120     QCryptoBlockOpenOptions *crypto_opts = NULL;
121     unsigned int cflags = 0;
122     QDict *encryptopts = NULL;
123     const char *encryptfmt;
124
125     qdict_extract_subqdict(options, &encryptopts, "encrypt.");
126     encryptfmt = qdict_get_try_str(encryptopts, "format");
127
128     bs->file = bdrv_open_child(NULL, options, "file", bs, &child_file,
129                                false, errp);
130     if (!bs->file) {
131         ret = -EINVAL;
132         goto fail;
133     }
134
135     ret = bdrv_pread(bs->file, 0, &header, sizeof(header));
136     if (ret < 0) {
137         goto fail;
138     }
139     be32_to_cpus(&header.magic);
140     be32_to_cpus(&header.version);
141     be64_to_cpus(&header.backing_file_offset);
142     be32_to_cpus(&header.backing_file_size);
143     be32_to_cpus(&header.mtime);
144     be64_to_cpus(&header.size);
145     be32_to_cpus(&header.crypt_method);
146     be64_to_cpus(&header.l1_table_offset);
147
148     if (header.magic != QCOW_MAGIC) {
149         error_setg(errp, "Image not in qcow format");
150         ret = -EINVAL;
151         goto fail;
152     }
153     if (header.version != QCOW_VERSION) {
154         error_setg(errp, "Unsupported qcow version %" PRIu32, header.version);
155         ret = -ENOTSUP;
156         goto fail;
157     }
158
159     if (header.size <= 1) {
160         error_setg(errp, "Image size is too small (must be at least 2 bytes)");
161         ret = -EINVAL;
162         goto fail;
163     }
164     if (header.cluster_bits < 9 || header.cluster_bits > 16) {
165         error_setg(errp, "Cluster size must be between 512 and 64k");
166         ret = -EINVAL;
167         goto fail;
168     }
169
170     /* l2_bits specifies number of entries; storing a uint64_t in each entry,
171      * so bytes = num_entries << 3. */
172     if (header.l2_bits < 9 - 3 || header.l2_bits > 16 - 3) {
173         error_setg(errp, "L2 table size must be between 512 and 64k");
174         ret = -EINVAL;
175         goto fail;
176     }
177
178     s->crypt_method_header = header.crypt_method;
179     if (s->crypt_method_header) {
180         if (bdrv_uses_whitelist() &&
181             s->crypt_method_header == QCOW_CRYPT_AES) {
182             error_setg(errp,
183                        "Use of AES-CBC encrypted qcow images is no longer "
184                        "supported in system emulators");
185             error_append_hint(errp,
186                               "You can use 'qemu-img convert' to convert your "
187                               "image to an alternative supported format, such "
188                               "as unencrypted qcow, or raw with the LUKS "
189                               "format instead.\n");
190             ret = -ENOSYS;
191             goto fail;
192         }
193         if (s->crypt_method_header == QCOW_CRYPT_AES) {
194             if (encryptfmt && !g_str_equal(encryptfmt, "aes")) {
195                 error_setg(errp,
196                            "Header reported 'aes' encryption format but "
197                            "options specify '%s'", encryptfmt);
198                 ret = -EINVAL;
199                 goto fail;
200             }
201             qdict_del(encryptopts, "format");
202             crypto_opts = block_crypto_open_opts_init(
203                 Q_CRYPTO_BLOCK_FORMAT_QCOW, 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, 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->cluster_sectors = 1 << (s->cluster_bits - 9);
235     s->l2_bits = header.l2_bits;
236     s->l2_size = 1 << s->l2_bits;
237     bs->total_sectors = header.size / 512;
238     s->cluster_offset_mask = (1LL << (63 - s->cluster_bits)) - 1;
239
240     /* read the level 1 table */
241     shift = s->cluster_bits + s->l2_bits;
242     if (header.size > UINT64_MAX - (1LL << shift)) {
243         error_setg(errp, "Image too large");
244         ret = -EINVAL;
245         goto fail;
246     } else {
247         uint64_t l1_size = (header.size + (1LL << shift) - 1) >> shift;
248         if (l1_size > INT_MAX / sizeof(uint64_t)) {
249             error_setg(errp, "Image too large");
250             ret = -EINVAL;
251             goto fail;
252         }
253         s->l1_size = l1_size;
254     }
255
256     s->l1_table_offset = header.l1_table_offset;
257     s->l1_table = g_try_new(uint64_t, s->l1_size);
258     if (s->l1_table == NULL) {
259         error_setg(errp, "Could not allocate memory for L1 table");
260         ret = -ENOMEM;
261         goto fail;
262     }
263
264     ret = bdrv_pread(bs->file, s->l1_table_offset, s->l1_table,
265                s->l1_size * sizeof(uint64_t));
266     if (ret < 0) {
267         goto fail;
268     }
269
270     for(i = 0;i < s->l1_size; i++) {
271         be64_to_cpus(&s->l1_table[i]);
272     }
273
274     /* alloc L2 cache (max. 64k * 16 * 8 = 8 MB) */
275     s->l2_cache =
276         qemu_try_blockalign(bs->file->bs,
277                             s->l2_size * L2_CACHE_SIZE * sizeof(uint64_t));
278     if (s->l2_cache == NULL) {
279         error_setg(errp, "Could not allocate L2 table cache");
280         ret = -ENOMEM;
281         goto fail;
282     }
283     s->cluster_cache = g_malloc(s->cluster_size);
284     s->cluster_data = g_malloc(s->cluster_size);
285     s->cluster_cache_offset = -1;
286
287     /* read the backing file name */
288     if (header.backing_file_offset != 0) {
289         len = header.backing_file_size;
290         if (len > 1023 || len >= sizeof(bs->backing_file)) {
291             error_setg(errp, "Backing file name too long");
292             ret = -EINVAL;
293             goto fail;
294         }
295         ret = bdrv_pread(bs->file, header.backing_file_offset,
296                    bs->backing_file, len);
297         if (ret < 0) {
298             goto fail;
299         }
300         bs->backing_file[len] = '\0';
301     }
302
303     /* Disable migration when qcow images are used */
304     error_setg(&s->migration_blocker, "The qcow format used by node '%s' "
305                "does not support live migration",
306                bdrv_get_device_or_node_name(bs));
307     ret = migrate_add_blocker(s->migration_blocker, &local_err);
308     if (local_err) {
309         error_propagate(errp, local_err);
310         error_free(s->migration_blocker);
311         goto fail;
312     }
313
314     QDECREF(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     QDECREF(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 indexes 'n_start' to
345  * 'n_end')
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                                &tmp, sizeof(tmp));
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, l2_table,
418                                s->l2_size * sizeof(uint64_t));
419         if (ret < 0) {
420             return ret;
421         }
422     } else {
423         ret = bdrv_pread(bs->file, l2_offset, l2_table,
424                          s->l2_size * sizeof(uint64_t));
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         /* allocate a new cluster */
440         if ((cluster_offset & QCOW_OFLAG_COMPRESSED) &&
441             (n_end - n_start) < s->cluster_sectors) {
442             /* if the cluster is already compressed, we must
443                decompress it in the case it is not completely
444                overwritten */
445             if (decompress_cluster(bs, cluster_offset) < 0) {
446                 return -EIO;
447             }
448             cluster_offset = bdrv_getlength(bs->file->bs);
449             if ((int64_t) cluster_offset < 0) {
450                 return cluster_offset;
451             }
452             cluster_offset = QEMU_ALIGN_UP(cluster_offset, s->cluster_size);
453             /* write the cluster content */
454             BLKDBG_EVENT(bs->file, BLKDBG_WRITE_AIO);
455             ret = bdrv_pwrite(bs->file, cluster_offset, s->cluster_cache,
456                               s->cluster_size);
457             if (ret < 0) {
458                 return ret;
459             }
460         } else {
461             cluster_offset = bdrv_getlength(bs->file->bs);
462             if ((int64_t) cluster_offset < 0) {
463                 return cluster_offset;
464             }
465             if (allocate == 1) {
466                 /* round to cluster size */
467                 cluster_offset = QEMU_ALIGN_UP(cluster_offset, s->cluster_size);
468                 if (cluster_offset + s->cluster_size > INT64_MAX) {
469                     return -E2BIG;
470                 }
471                 ret = bdrv_truncate(bs->file, cluster_offset + s->cluster_size,
472                                     PREALLOC_MODE_OFF, NULL);
473                 if (ret < 0) {
474                     return ret;
475                 }
476                 /* if encrypted, we must initialize the cluster
477                    content which won't be written */
478                 if (bs->encrypted &&
479                     (n_end - n_start) < s->cluster_sectors) {
480                     uint64_t start_sect;
481                     assert(s->crypto);
482                     start_sect = (offset & ~(s->cluster_size - 1)) >> 9;
483                     for(i = 0; i < s->cluster_sectors; i++) {
484                         if (i < n_start || i >= n_end) {
485                             memset(s->cluster_data, 0x00, 512);
486                             if (qcrypto_block_encrypt(s->crypto,
487                                                       (start_sect + i) *
488                                                       BDRV_SECTOR_SIZE,
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,
496                                               cluster_offset + i * 512,
497                                               s->cluster_data, 512);
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                                &tmp, sizeof(tmp));
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, s->cluster_data, csize);
600         if (ret != csize)
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 coroutine_fn int qcow_co_readv(BlockDriverState *bs, int64_t sector_num,
612                          int nb_sectors, QEMUIOVector *qiov)
613 {
614     BDRVQcowState *s = bs->opaque;
615     int index_in_cluster;
616     int ret = 0, n;
617     uint64_t cluster_offset;
618     struct iovec hd_iov;
619     QEMUIOVector hd_qiov;
620     uint8_t *buf;
621     void *orig_buf;
622
623     if (qiov->niov > 1) {
624         buf = orig_buf = qemu_try_blockalign(bs, qiov->size);
625         if (buf == NULL) {
626             return -ENOMEM;
627         }
628     } else {
629         orig_buf = NULL;
630         buf = (uint8_t *)qiov->iov->iov_base;
631     }
632
633     qemu_co_mutex_lock(&s->lock);
634
635     while (nb_sectors != 0) {
636         /* prepare next request */
637         ret = get_cluster_offset(bs, sector_num << 9,
638                                  0, 0, 0, 0, &cluster_offset);
639         if (ret < 0) {
640             break;
641         }
642         index_in_cluster = sector_num & (s->cluster_sectors - 1);
643         n = s->cluster_sectors - index_in_cluster;
644         if (n > nb_sectors) {
645             n = nb_sectors;
646         }
647
648         if (!cluster_offset) {
649             if (bs->backing) {
650                 /* read from the base image */
651                 hd_iov.iov_base = (void *)buf;
652                 hd_iov.iov_len = n * 512;
653                 qemu_iovec_init_external(&hd_qiov, &hd_iov, 1);
654                 qemu_co_mutex_unlock(&s->lock);
655                 /* qcow2 emits this on bs->file instead of bs->backing */
656                 BLKDBG_EVENT(bs->file, BLKDBG_READ_BACKING_AIO);
657                 ret = bdrv_co_readv(bs->backing, sector_num, n, &hd_qiov);
658                 qemu_co_mutex_lock(&s->lock);
659                 if (ret < 0) {
660                     break;
661                 }
662             } else {
663                 /* Note: in this case, no need to wait */
664                 memset(buf, 0, 512 * n);
665             }
666         } else if (cluster_offset & QCOW_OFLAG_COMPRESSED) {
667             /* add AIO support for compressed blocks ? */
668             if (decompress_cluster(bs, cluster_offset) < 0) {
669                 ret = -EIO;
670                 break;
671             }
672             memcpy(buf,
673                    s->cluster_cache + index_in_cluster * 512, 512 * n);
674         } else {
675             if ((cluster_offset & 511) != 0) {
676                 ret = -EIO;
677                 break;
678             }
679             hd_iov.iov_base = (void *)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             BLKDBG_EVENT(bs->file, BLKDBG_READ_AIO);
684             ret = bdrv_co_readv(bs->file,
685                                 (cluster_offset >> 9) + index_in_cluster,
686                                 n, &hd_qiov);
687             qemu_co_mutex_lock(&s->lock);
688             if (ret < 0) {
689                 break;
690             }
691             if (bs->encrypted) {
692                 assert(s->crypto);
693                 if (qcrypto_block_decrypt(s->crypto,
694                                           sector_num * BDRV_SECTOR_SIZE, buf,
695                                           n * BDRV_SECTOR_SIZE, NULL) < 0) {
696                     ret = -EIO;
697                     break;
698                 }
699             }
700         }
701         ret = 0;
702
703         nb_sectors -= n;
704         sector_num += n;
705         buf += n * 512;
706     }
707
708     qemu_co_mutex_unlock(&s->lock);
709
710     if (qiov->niov > 1) {
711         qemu_iovec_from_buf(qiov, 0, orig_buf, qiov->size);
712         qemu_vfree(orig_buf);
713     }
714
715     return ret;
716 }
717
718 static coroutine_fn int qcow_co_writev(BlockDriverState *bs, int64_t sector_num,
719                           int nb_sectors, QEMUIOVector *qiov)
720 {
721     BDRVQcowState *s = bs->opaque;
722     int index_in_cluster;
723     uint64_t cluster_offset;
724     int ret = 0, n;
725     struct iovec hd_iov;
726     QEMUIOVector hd_qiov;
727     uint8_t *buf;
728     void *orig_buf;
729
730     s->cluster_cache_offset = -1; /* disable compressed cache */
731
732     /* We must always copy the iov when encrypting, so we
733      * don't modify the original data buffer during encryption */
734     if (bs->encrypted || qiov->niov > 1) {
735         buf = orig_buf = qemu_try_blockalign(bs, qiov->size);
736         if (buf == NULL) {
737             return -ENOMEM;
738         }
739         qemu_iovec_to_buf(qiov, 0, buf, qiov->size);
740     } else {
741         orig_buf = NULL;
742         buf = (uint8_t *)qiov->iov->iov_base;
743     }
744
745     qemu_co_mutex_lock(&s->lock);
746
747     while (nb_sectors != 0) {
748
749         index_in_cluster = sector_num & (s->cluster_sectors - 1);
750         n = s->cluster_sectors - index_in_cluster;
751         if (n > nb_sectors) {
752             n = nb_sectors;
753         }
754         ret = get_cluster_offset(bs, sector_num << 9, 1, 0,
755                                  index_in_cluster,
756                                  index_in_cluster + n, &cluster_offset);
757         if (ret < 0) {
758             break;
759         }
760         if (!cluster_offset || (cluster_offset & 511) != 0) {
761             ret = -EIO;
762             break;
763         }
764         if (bs->encrypted) {
765             assert(s->crypto);
766             if (qcrypto_block_encrypt(s->crypto, sector_num * BDRV_SECTOR_SIZE,
767                                       buf, n * BDRV_SECTOR_SIZE, NULL) < 0) {
768                 ret = -EIO;
769                 break;
770             }
771         }
772
773         hd_iov.iov_base = (void *)buf;
774         hd_iov.iov_len = n * 512;
775         qemu_iovec_init_external(&hd_qiov, &hd_iov, 1);
776         qemu_co_mutex_unlock(&s->lock);
777         BLKDBG_EVENT(bs->file, BLKDBG_WRITE_AIO);
778         ret = bdrv_co_writev(bs->file,
779                              (cluster_offset >> 9) + index_in_cluster,
780                              n, &hd_qiov);
781         qemu_co_mutex_lock(&s->lock);
782         if (ret < 0) {
783             break;
784         }
785         ret = 0;
786
787         nb_sectors -= n;
788         sector_num += n;
789         buf += n * 512;
790     }
791     qemu_co_mutex_unlock(&s->lock);
792
793     qemu_vfree(orig_buf);
794
795     return ret;
796 }
797
798 static void qcow_close(BlockDriverState *bs)
799 {
800     BDRVQcowState *s = bs->opaque;
801
802     qcrypto_block_free(s->crypto);
803     s->crypto = NULL;
804     g_free(s->l1_table);
805     qemu_vfree(s->l2_cache);
806     g_free(s->cluster_cache);
807     g_free(s->cluster_data);
808
809     migrate_del_blocker(s->migration_blocker);
810     error_free(s->migration_blocker);
811 }
812
813 static int qcow_create(const char *filename, QemuOpts *opts, Error **errp)
814 {
815     int header_size, backing_filename_len, l1_size, shift, i;
816     QCowHeader header;
817     uint8_t *tmp;
818     int64_t total_size = 0;
819     char *backing_file = NULL;
820     Error *local_err = NULL;
821     int ret;
822     BlockBackend *qcow_blk;
823     char *encryptfmt = NULL;
824     QDict *options;
825     QDict *encryptopts = NULL;
826     QCryptoBlockCreateOptions *crypto_opts = NULL;
827     QCryptoBlock *crypto = NULL;
828
829     /* Read out options */
830     total_size = ROUND_UP(qemu_opt_get_size_del(opts, BLOCK_OPT_SIZE, 0),
831                           BDRV_SECTOR_SIZE);
832     if (total_size == 0) {
833         error_setg(errp, "Image size is too small, cannot be zero length");
834         ret = -EINVAL;
835         goto cleanup;
836     }
837
838     backing_file = qemu_opt_get_del(opts, BLOCK_OPT_BACKING_FILE);
839     encryptfmt = qemu_opt_get_del(opts, BLOCK_OPT_ENCRYPT_FORMAT);
840     if (encryptfmt) {
841         if (qemu_opt_get(opts, BLOCK_OPT_ENCRYPT)) {
842             error_setg(errp, "Options " BLOCK_OPT_ENCRYPT " and "
843                        BLOCK_OPT_ENCRYPT_FORMAT " are mutually exclusive");
844             ret = -EINVAL;
845             goto cleanup;
846         }
847     } else if (qemu_opt_get_bool_del(opts, BLOCK_OPT_ENCRYPT, false)) {
848         encryptfmt = g_strdup("aes");
849     }
850
851     ret = bdrv_create_file(filename, opts, &local_err);
852     if (ret < 0) {
853         error_propagate(errp, local_err);
854         goto cleanup;
855     }
856
857     qcow_blk = blk_new_open(filename, NULL, NULL,
858                             BDRV_O_RDWR | BDRV_O_RESIZE | BDRV_O_PROTOCOL,
859                             &local_err);
860     if (qcow_blk == NULL) {
861         error_propagate(errp, local_err);
862         ret = -EIO;
863         goto cleanup;
864     }
865
866     blk_set_allow_write_beyond_eof(qcow_blk, true);
867
868     ret = blk_truncate(qcow_blk, 0, PREALLOC_MODE_OFF, errp);
869     if (ret < 0) {
870         goto exit;
871     }
872
873     memset(&header, 0, sizeof(header));
874     header.magic = cpu_to_be32(QCOW_MAGIC);
875     header.version = cpu_to_be32(QCOW_VERSION);
876     header.size = cpu_to_be64(total_size);
877     header_size = sizeof(header);
878     backing_filename_len = 0;
879     if (backing_file) {
880         if (strcmp(backing_file, "fat:")) {
881             header.backing_file_offset = cpu_to_be64(header_size);
882             backing_filename_len = strlen(backing_file);
883             header.backing_file_size = cpu_to_be32(backing_filename_len);
884             header_size += backing_filename_len;
885         } else {
886             /* special backing file for vvfat */
887             g_free(backing_file);
888             backing_file = NULL;
889         }
890         header.cluster_bits = 9; /* 512 byte cluster to avoid copying
891                                     unmodified sectors */
892         header.l2_bits = 12; /* 32 KB L2 tables */
893     } else {
894         header.cluster_bits = 12; /* 4 KB clusters */
895         header.l2_bits = 9; /* 4 KB L2 tables */
896     }
897     header_size = (header_size + 7) & ~7;
898     shift = header.cluster_bits + header.l2_bits;
899     l1_size = (total_size + (1LL << shift) - 1) >> shift;
900
901     header.l1_table_offset = cpu_to_be64(header_size);
902
903     options = qemu_opts_to_qdict(opts, NULL);
904     qdict_extract_subqdict(options, &encryptopts, "encrypt.");
905     QDECREF(options);
906     if (encryptfmt) {
907         if (!g_str_equal(encryptfmt, "aes")) {
908             error_setg(errp, "Unknown encryption format '%s', expected 'aes'",
909                        encryptfmt);
910             ret = -EINVAL;
911             goto exit;
912         }
913         header.crypt_method = cpu_to_be32(QCOW_CRYPT_AES);
914
915         crypto_opts = block_crypto_create_opts_init(
916             Q_CRYPTO_BLOCK_FORMAT_QCOW, encryptopts, errp);
917         if (!crypto_opts) {
918             ret = -EINVAL;
919             goto exit;
920         }
921
922         crypto = qcrypto_block_create(crypto_opts, "encrypt.",
923                                       NULL, NULL, NULL, errp);
924         if (!crypto) {
925             ret = -EINVAL;
926             goto exit;
927         }
928     } else {
929         header.crypt_method = cpu_to_be32(QCOW_CRYPT_NONE);
930     }
931
932     /* write all the data */
933     ret = blk_pwrite(qcow_blk, 0, &header, sizeof(header), 0);
934     if (ret != sizeof(header)) {
935         goto exit;
936     }
937
938     if (backing_file) {
939         ret = blk_pwrite(qcow_blk, sizeof(header),
940                          backing_file, backing_filename_len, 0);
941         if (ret != backing_filename_len) {
942             goto exit;
943         }
944     }
945
946     tmp = g_malloc0(BDRV_SECTOR_SIZE);
947     for (i = 0; i < DIV_ROUND_UP(sizeof(uint64_t) * l1_size, BDRV_SECTOR_SIZE);
948          i++) {
949         ret = blk_pwrite(qcow_blk, header_size + BDRV_SECTOR_SIZE * i,
950                          tmp, BDRV_SECTOR_SIZE, 0);
951         if (ret != BDRV_SECTOR_SIZE) {
952             g_free(tmp);
953             goto exit;
954         }
955     }
956
957     g_free(tmp);
958     ret = 0;
959 exit:
960     blk_unref(qcow_blk);
961 cleanup:
962     QDECREF(encryptopts);
963     g_free(encryptfmt);
964     qcrypto_block_free(crypto);
965     qapi_free_QCryptoBlockCreateOptions(crypto_opts);
966     g_free(backing_file);
967     return ret;
968 }
969
970 static int qcow_make_empty(BlockDriverState *bs)
971 {
972     BDRVQcowState *s = bs->opaque;
973     uint32_t l1_length = s->l1_size * sizeof(uint64_t);
974     int ret;
975
976     memset(s->l1_table, 0, l1_length);
977     if (bdrv_pwrite_sync(bs->file, s->l1_table_offset, s->l1_table,
978             l1_length) < 0)
979         return -1;
980     ret = bdrv_truncate(bs->file, s->l1_table_offset + l1_length,
981                         PREALLOC_MODE_OFF, NULL);
982     if (ret < 0)
983         return ret;
984
985     memset(s->l2_cache, 0, s->l2_size * L2_CACHE_SIZE * sizeof(uint64_t));
986     memset(s->l2_cache_offsets, 0, L2_CACHE_SIZE * sizeof(uint64_t));
987     memset(s->l2_cache_counts, 0, L2_CACHE_SIZE * sizeof(uint32_t));
988
989     return 0;
990 }
991
992 /* XXX: put compressed sectors first, then all the cluster aligned
993    tables to avoid losing bytes in alignment */
994 static coroutine_fn int
995 qcow_co_pwritev_compressed(BlockDriverState *bs, uint64_t offset,
996                            uint64_t bytes, QEMUIOVector *qiov)
997 {
998     BDRVQcowState *s = bs->opaque;
999     QEMUIOVector hd_qiov;
1000     struct iovec iov;
1001     z_stream strm;
1002     int ret, out_len;
1003     uint8_t *buf, *out_buf;
1004     uint64_t cluster_offset;
1005
1006     buf = qemu_blockalign(bs, s->cluster_size);
1007     if (bytes != s->cluster_size) {
1008         if (bytes > s->cluster_size ||
1009             offset + bytes != bs->total_sectors << BDRV_SECTOR_BITS)
1010         {
1011             qemu_vfree(buf);
1012             return -EINVAL;
1013         }
1014         /* Zero-pad last write if image size is not cluster aligned */
1015         memset(buf + bytes, 0, s->cluster_size - bytes);
1016     }
1017     qemu_iovec_to_buf(qiov, 0, buf, qiov->size);
1018
1019     out_buf = g_malloc(s->cluster_size);
1020
1021     /* best compression, small window, no zlib header */
1022     memset(&strm, 0, sizeof(strm));
1023     ret = deflateInit2(&strm, Z_DEFAULT_COMPRESSION,
1024                        Z_DEFLATED, -12,
1025                        9, Z_DEFAULT_STRATEGY);
1026     if (ret != 0) {
1027         ret = -EINVAL;
1028         goto fail;
1029     }
1030
1031     strm.avail_in = s->cluster_size;
1032     strm.next_in = (uint8_t *)buf;
1033     strm.avail_out = s->cluster_size;
1034     strm.next_out = out_buf;
1035
1036     ret = deflate(&strm, Z_FINISH);
1037     if (ret != Z_STREAM_END && ret != Z_OK) {
1038         deflateEnd(&strm);
1039         ret = -EINVAL;
1040         goto fail;
1041     }
1042     out_len = strm.next_out - out_buf;
1043
1044     deflateEnd(&strm);
1045
1046     if (ret != Z_STREAM_END || out_len >= s->cluster_size) {
1047         /* could not compress: write normal cluster */
1048         ret = qcow_co_writev(bs, offset >> BDRV_SECTOR_BITS,
1049                              bytes >> BDRV_SECTOR_BITS, qiov);
1050         if (ret < 0) {
1051             goto fail;
1052         }
1053         goto success;
1054     }
1055     qemu_co_mutex_lock(&s->lock);
1056     ret = get_cluster_offset(bs, offset, 2, out_len, 0, 0, &cluster_offset);
1057     qemu_co_mutex_unlock(&s->lock);
1058     if (ret < 0) {
1059         goto fail;
1060     }
1061     if (cluster_offset == 0) {
1062         ret = -EIO;
1063         goto fail;
1064     }
1065     cluster_offset &= s->cluster_offset_mask;
1066
1067     iov = (struct iovec) {
1068         .iov_base   = out_buf,
1069         .iov_len    = out_len,
1070     };
1071     qemu_iovec_init_external(&hd_qiov, &iov, 1);
1072     BLKDBG_EVENT(bs->file, BLKDBG_WRITE_COMPRESSED);
1073     ret = bdrv_co_pwritev(bs->file, cluster_offset, out_len, &hd_qiov, 0);
1074     if (ret < 0) {
1075         goto fail;
1076     }
1077 success:
1078     ret = 0;
1079 fail:
1080     qemu_vfree(buf);
1081     g_free(out_buf);
1082     return ret;
1083 }
1084
1085 static int qcow_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
1086 {
1087     BDRVQcowState *s = bs->opaque;
1088     bdi->cluster_size = s->cluster_size;
1089     return 0;
1090 }
1091
1092 static QemuOptsList qcow_create_opts = {
1093     .name = "qcow-create-opts",
1094     .head = QTAILQ_HEAD_INITIALIZER(qcow_create_opts.head),
1095     .desc = {
1096         {
1097             .name = BLOCK_OPT_SIZE,
1098             .type = QEMU_OPT_SIZE,
1099             .help = "Virtual disk size"
1100         },
1101         {
1102             .name = BLOCK_OPT_BACKING_FILE,
1103             .type = QEMU_OPT_STRING,
1104             .help = "File name of a base image"
1105         },
1106         {
1107             .name = BLOCK_OPT_ENCRYPT,
1108             .type = QEMU_OPT_BOOL,
1109             .help = "Encrypt the image with format 'aes'. (Deprecated "
1110                     "in favor of " BLOCK_OPT_ENCRYPT_FORMAT "=aes)",
1111         },
1112         {
1113             .name = BLOCK_OPT_ENCRYPT_FORMAT,
1114             .type = QEMU_OPT_STRING,
1115             .help = "Encrypt the image, format choices: 'aes'",
1116         },
1117         BLOCK_CRYPTO_OPT_DEF_QCOW_KEY_SECRET("encrypt."),
1118         { /* end of list */ }
1119     }
1120 };
1121
1122 static BlockDriver bdrv_qcow = {
1123     .format_name        = "qcow",
1124     .instance_size      = sizeof(BDRVQcowState),
1125     .bdrv_probe         = qcow_probe,
1126     .bdrv_open          = qcow_open,
1127     .bdrv_close         = qcow_close,
1128     .bdrv_child_perm        = bdrv_format_default_perms,
1129     .bdrv_reopen_prepare    = qcow_reopen_prepare,
1130     .bdrv_create            = qcow_create,
1131     .bdrv_has_zero_init     = bdrv_has_zero_init_1,
1132     .supports_backing       = true,
1133
1134     .bdrv_co_readv          = qcow_co_readv,
1135     .bdrv_co_writev         = qcow_co_writev,
1136     .bdrv_co_block_status   = qcow_co_block_status,
1137
1138     .bdrv_make_empty        = qcow_make_empty,
1139     .bdrv_co_pwritev_compressed = qcow_co_pwritev_compressed,
1140     .bdrv_get_info          = qcow_get_info,
1141
1142     .create_opts            = &qcow_create_opts,
1143 };
1144
1145 static void bdrv_qcow_init(void)
1146 {
1147     bdrv_register(&bdrv_qcow);
1148 }
1149
1150 block_init(bdrv_qcow_init);
This page took 0.087908 seconds and 4 git commands to generate.