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