xref: /openbmc/qemu/block/qcow2.h (revision c27c1cc3)
1 /*
2  * Block driver for the QCOW version 2 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 #ifndef BLOCK_QCOW2_H
26 #define BLOCK_QCOW2_H
27 
28 #include "crypto/block.h"
29 #include "qemu/coroutine.h"
30 #include "qemu/units.h"
31 #include "block/block_int.h"
32 
33 //#define DEBUG_ALLOC
34 //#define DEBUG_ALLOC2
35 //#define DEBUG_EXT
36 
37 #define QCOW_MAGIC (('Q' << 24) | ('F' << 16) | ('I' << 8) | 0xfb)
38 
39 #define QCOW_CRYPT_NONE 0
40 #define QCOW_CRYPT_AES  1
41 #define QCOW_CRYPT_LUKS 2
42 
43 #define QCOW_MAX_CRYPT_CLUSTERS 32
44 #define QCOW_MAX_SNAPSHOTS 65536
45 
46 /* Field widths in qcow2 mean normal cluster offsets cannot reach
47  * 64PB; depending on cluster size, compressed clusters can have a
48  * smaller limit (64PB for up to 16k clusters, then ramps down to
49  * 512TB for 2M clusters).  */
50 #define QCOW_MAX_CLUSTER_OFFSET ((1ULL << 56) - 1)
51 
52 /* 8 MB refcount table is enough for 2 PB images at 64k cluster size
53  * (128 GB for 512 byte clusters, 2 EB for 2 MB clusters) */
54 #define QCOW_MAX_REFTABLE_SIZE (8 * MiB)
55 
56 /* 32 MB L1 table is enough for 2 PB images at 64k cluster size
57  * (128 GB for 512 byte clusters, 2 EB for 2 MB clusters) */
58 #define QCOW_MAX_L1_SIZE (32 * MiB)
59 
60 /* Allow for an average of 1k per snapshot table entry, should be plenty of
61  * space for snapshot names and IDs */
62 #define QCOW_MAX_SNAPSHOTS_SIZE (1024 * QCOW_MAX_SNAPSHOTS)
63 
64 /* Maximum amount of extra data per snapshot table entry to accept */
65 #define QCOW_MAX_SNAPSHOT_EXTRA_DATA 1024
66 
67 /* Bitmap header extension constraints */
68 #define QCOW2_MAX_BITMAPS 65535
69 #define QCOW2_MAX_BITMAP_DIRECTORY_SIZE (1024 * QCOW2_MAX_BITMAPS)
70 
71 /* Maximum of parallel sub-request per guest request */
72 #define QCOW2_MAX_WORKERS 8
73 
74 /* indicate that the refcount of the referenced cluster is exactly one. */
75 #define QCOW_OFLAG_COPIED     (1ULL << 63)
76 /* indicate that the cluster is compressed (they never have the copied flag) */
77 #define QCOW_OFLAG_COMPRESSED (1ULL << 62)
78 /* The cluster reads as all zeros */
79 #define QCOW_OFLAG_ZERO (1ULL << 0)
80 
81 #define QCOW_EXTL2_SUBCLUSTERS_PER_CLUSTER 32
82 
83 /* The subcluster X [0..31] is allocated */
84 #define QCOW_OFLAG_SUB_ALLOC(X)   (1ULL << (X))
85 /* The subcluster X [0..31] reads as zeroes */
86 #define QCOW_OFLAG_SUB_ZERO(X)    (QCOW_OFLAG_SUB_ALLOC(X) << 32)
87 /* Subclusters [X, Y) (0 <= X <= Y <= 32) are allocated */
88 #define QCOW_OFLAG_SUB_ALLOC_RANGE(X, Y) \
89     (QCOW_OFLAG_SUB_ALLOC(Y) - QCOW_OFLAG_SUB_ALLOC(X))
90 /* Subclusters [X, Y) (0 <= X <= Y <= 32) read as zeroes */
91 #define QCOW_OFLAG_SUB_ZERO_RANGE(X, Y) \
92     (QCOW_OFLAG_SUB_ALLOC_RANGE(X, Y) << 32)
93 /* L2 entry bitmap with all allocation bits set */
94 #define QCOW_L2_BITMAP_ALL_ALLOC  (QCOW_OFLAG_SUB_ALLOC_RANGE(0, 32))
95 /* L2 entry bitmap with all "read as zeroes" bits set */
96 #define QCOW_L2_BITMAP_ALL_ZEROES (QCOW_OFLAG_SUB_ZERO_RANGE(0, 32))
97 
98 /* Size of normal and extended L2 entries */
99 #define L2E_SIZE_NORMAL   (sizeof(uint64_t))
100 #define L2E_SIZE_EXTENDED (sizeof(uint64_t) * 2)
101 
102 #define MIN_CLUSTER_BITS 9
103 #define MAX_CLUSTER_BITS 21
104 
105 /* Defined in the qcow2 spec (compressed cluster descriptor) */
106 #define QCOW2_COMPRESSED_SECTOR_SIZE 512U
107 #define QCOW2_COMPRESSED_SECTOR_MASK (~(QCOW2_COMPRESSED_SECTOR_SIZE - 1ULL))
108 
109 /* Must be at least 2 to cover COW */
110 #define MIN_L2_CACHE_SIZE 2 /* cache entries */
111 
112 /* Must be at least 4 to cover all cases of refcount table growth */
113 #define MIN_REFCOUNT_CACHE_SIZE 4 /* clusters */
114 
115 #ifdef CONFIG_LINUX
116 #define DEFAULT_L2_CACHE_MAX_SIZE (32 * MiB)
117 #define DEFAULT_CACHE_CLEAN_INTERVAL 600  /* seconds */
118 #else
119 #define DEFAULT_L2_CACHE_MAX_SIZE (8 * MiB)
120 /* Cache clean interval is currently available only on Linux, so must be 0 */
121 #define DEFAULT_CACHE_CLEAN_INTERVAL 0
122 #endif
123 
124 #define DEFAULT_CLUSTER_SIZE 65536
125 
126 #define QCOW2_OPT_DATA_FILE "data-file"
127 #define QCOW2_OPT_LAZY_REFCOUNTS "lazy-refcounts"
128 #define QCOW2_OPT_DISCARD_REQUEST "pass-discard-request"
129 #define QCOW2_OPT_DISCARD_SNAPSHOT "pass-discard-snapshot"
130 #define QCOW2_OPT_DISCARD_OTHER "pass-discard-other"
131 #define QCOW2_OPT_OVERLAP "overlap-check"
132 #define QCOW2_OPT_OVERLAP_TEMPLATE "overlap-check.template"
133 #define QCOW2_OPT_OVERLAP_MAIN_HEADER "overlap-check.main-header"
134 #define QCOW2_OPT_OVERLAP_ACTIVE_L1 "overlap-check.active-l1"
135 #define QCOW2_OPT_OVERLAP_ACTIVE_L2 "overlap-check.active-l2"
136 #define QCOW2_OPT_OVERLAP_REFCOUNT_TABLE "overlap-check.refcount-table"
137 #define QCOW2_OPT_OVERLAP_REFCOUNT_BLOCK "overlap-check.refcount-block"
138 #define QCOW2_OPT_OVERLAP_SNAPSHOT_TABLE "overlap-check.snapshot-table"
139 #define QCOW2_OPT_OVERLAP_INACTIVE_L1 "overlap-check.inactive-l1"
140 #define QCOW2_OPT_OVERLAP_INACTIVE_L2 "overlap-check.inactive-l2"
141 #define QCOW2_OPT_OVERLAP_BITMAP_DIRECTORY "overlap-check.bitmap-directory"
142 #define QCOW2_OPT_CACHE_SIZE "cache-size"
143 #define QCOW2_OPT_L2_CACHE_SIZE "l2-cache-size"
144 #define QCOW2_OPT_L2_CACHE_ENTRY_SIZE "l2-cache-entry-size"
145 #define QCOW2_OPT_REFCOUNT_CACHE_SIZE "refcount-cache-size"
146 #define QCOW2_OPT_CACHE_CLEAN_INTERVAL "cache-clean-interval"
147 
148 typedef struct QCowHeader {
149     uint32_t magic;
150     uint32_t version;
151     uint64_t backing_file_offset;
152     uint32_t backing_file_size;
153     uint32_t cluster_bits;
154     uint64_t size; /* in bytes */
155     uint32_t crypt_method;
156     uint32_t l1_size; /* XXX: save number of clusters instead ? */
157     uint64_t l1_table_offset;
158     uint64_t refcount_table_offset;
159     uint32_t refcount_table_clusters;
160     uint32_t nb_snapshots;
161     uint64_t snapshots_offset;
162 
163     /* The following fields are only valid for version >= 3 */
164     uint64_t incompatible_features;
165     uint64_t compatible_features;
166     uint64_t autoclear_features;
167 
168     uint32_t refcount_order;
169     uint32_t header_length;
170 
171     /* Additional fields */
172     uint8_t compression_type;
173 
174     /* header must be a multiple of 8 */
175     uint8_t padding[7];
176 } QEMU_PACKED QCowHeader;
177 
178 QEMU_BUILD_BUG_ON(!QEMU_IS_ALIGNED(sizeof(QCowHeader), 8));
179 
180 typedef struct QEMU_PACKED QCowSnapshotHeader {
181     /* header is 8 byte aligned */
182     uint64_t l1_table_offset;
183 
184     uint32_t l1_size;
185     uint16_t id_str_size;
186     uint16_t name_size;
187 
188     uint32_t date_sec;
189     uint32_t date_nsec;
190 
191     uint64_t vm_clock_nsec;
192 
193     uint32_t vm_state_size;
194     uint32_t extra_data_size; /* for extension */
195     /* extra data follows */
196     /* id_str follows */
197     /* name follows  */
198 } QCowSnapshotHeader;
199 
200 typedef struct QEMU_PACKED QCowSnapshotExtraData {
201     uint64_t vm_state_size_large;
202     uint64_t disk_size;
203 } QCowSnapshotExtraData;
204 
205 
206 typedef struct QCowSnapshot {
207     uint64_t l1_table_offset;
208     uint32_t l1_size;
209     char *id_str;
210     char *name;
211     uint64_t disk_size;
212     uint64_t vm_state_size;
213     uint32_t date_sec;
214     uint32_t date_nsec;
215     uint64_t vm_clock_nsec;
216     /* Size of all extra data, including QCowSnapshotExtraData if available */
217     uint32_t extra_data_size;
218     /* Data beyond QCowSnapshotExtraData, if any */
219     void *unknown_extra_data;
220 } QCowSnapshot;
221 
222 struct Qcow2Cache;
223 typedef struct Qcow2Cache Qcow2Cache;
224 
225 typedef struct Qcow2CryptoHeaderExtension {
226     uint64_t offset;
227     uint64_t length;
228 } QEMU_PACKED Qcow2CryptoHeaderExtension;
229 
230 typedef struct Qcow2UnknownHeaderExtension {
231     uint32_t magic;
232     uint32_t len;
233     QLIST_ENTRY(Qcow2UnknownHeaderExtension) next;
234     uint8_t data[];
235 } Qcow2UnknownHeaderExtension;
236 
237 enum {
238     QCOW2_FEAT_TYPE_INCOMPATIBLE    = 0,
239     QCOW2_FEAT_TYPE_COMPATIBLE      = 1,
240     QCOW2_FEAT_TYPE_AUTOCLEAR       = 2,
241 };
242 
243 /* Incompatible feature bits */
244 enum {
245     QCOW2_INCOMPAT_DIRTY_BITNR      = 0,
246     QCOW2_INCOMPAT_CORRUPT_BITNR    = 1,
247     QCOW2_INCOMPAT_DATA_FILE_BITNR  = 2,
248     QCOW2_INCOMPAT_COMPRESSION_BITNR = 3,
249     QCOW2_INCOMPAT_EXTL2_BITNR      = 4,
250     QCOW2_INCOMPAT_DIRTY            = 1 << QCOW2_INCOMPAT_DIRTY_BITNR,
251     QCOW2_INCOMPAT_CORRUPT          = 1 << QCOW2_INCOMPAT_CORRUPT_BITNR,
252     QCOW2_INCOMPAT_DATA_FILE        = 1 << QCOW2_INCOMPAT_DATA_FILE_BITNR,
253     QCOW2_INCOMPAT_COMPRESSION      = 1 << QCOW2_INCOMPAT_COMPRESSION_BITNR,
254     QCOW2_INCOMPAT_EXTL2            = 1 << QCOW2_INCOMPAT_EXTL2_BITNR,
255 
256     QCOW2_INCOMPAT_MASK             = QCOW2_INCOMPAT_DIRTY
257                                     | QCOW2_INCOMPAT_CORRUPT
258                                     | QCOW2_INCOMPAT_DATA_FILE
259                                     | QCOW2_INCOMPAT_COMPRESSION
260                                     | QCOW2_INCOMPAT_EXTL2,
261 };
262 
263 /* Compatible feature bits */
264 enum {
265     QCOW2_COMPAT_LAZY_REFCOUNTS_BITNR = 0,
266     QCOW2_COMPAT_LAZY_REFCOUNTS       = 1 << QCOW2_COMPAT_LAZY_REFCOUNTS_BITNR,
267 
268     QCOW2_COMPAT_FEAT_MASK            = QCOW2_COMPAT_LAZY_REFCOUNTS,
269 };
270 
271 /* Autoclear feature bits */
272 enum {
273     QCOW2_AUTOCLEAR_BITMAPS_BITNR       = 0,
274     QCOW2_AUTOCLEAR_DATA_FILE_RAW_BITNR = 1,
275     QCOW2_AUTOCLEAR_BITMAPS             = 1 << QCOW2_AUTOCLEAR_BITMAPS_BITNR,
276     QCOW2_AUTOCLEAR_DATA_FILE_RAW       = 1 << QCOW2_AUTOCLEAR_DATA_FILE_RAW_BITNR,
277 
278     QCOW2_AUTOCLEAR_MASK                = QCOW2_AUTOCLEAR_BITMAPS
279                                         | QCOW2_AUTOCLEAR_DATA_FILE_RAW,
280 };
281 
282 enum qcow2_discard_type {
283     QCOW2_DISCARD_NEVER = 0,
284     QCOW2_DISCARD_ALWAYS,
285     QCOW2_DISCARD_REQUEST,
286     QCOW2_DISCARD_SNAPSHOT,
287     QCOW2_DISCARD_OTHER,
288     QCOW2_DISCARD_MAX
289 };
290 
291 typedef struct Qcow2Feature {
292     uint8_t type;
293     uint8_t bit;
294     char    name[46];
295 } QEMU_PACKED Qcow2Feature;
296 
297 typedef struct Qcow2DiscardRegion {
298     BlockDriverState *bs;
299     uint64_t offset;
300     uint64_t bytes;
301     QTAILQ_ENTRY(Qcow2DiscardRegion) next;
302 } Qcow2DiscardRegion;
303 
304 typedef uint64_t Qcow2GetRefcountFunc(const void *refcount_array,
305                                       uint64_t index);
306 typedef void Qcow2SetRefcountFunc(void *refcount_array,
307                                   uint64_t index, uint64_t value);
308 
309 typedef struct Qcow2BitmapHeaderExt {
310     uint32_t nb_bitmaps;
311     uint32_t reserved32;
312     uint64_t bitmap_directory_size;
313     uint64_t bitmap_directory_offset;
314 } QEMU_PACKED Qcow2BitmapHeaderExt;
315 
316 #define QCOW2_MAX_THREADS 4
317 
318 typedef struct BDRVQcow2State {
319     int cluster_bits;
320     int cluster_size;
321     int l2_slice_size;
322     int subcluster_bits;
323     int subcluster_size;
324     int subclusters_per_cluster;
325     int l2_bits;
326     int l2_size;
327     int l1_size;
328     int l1_vm_state_index;
329     int refcount_block_bits;
330     int refcount_block_size;
331     int csize_shift;
332     int csize_mask;
333     uint64_t cluster_offset_mask;
334     uint64_t l1_table_offset;
335     uint64_t *l1_table;
336 
337     Qcow2Cache* l2_table_cache;
338     Qcow2Cache* refcount_block_cache;
339     QEMUTimer *cache_clean_timer;
340     unsigned cache_clean_interval;
341 
342     QLIST_HEAD(, QCowL2Meta) cluster_allocs;
343 
344     uint64_t *refcount_table;
345     uint64_t refcount_table_offset;
346     uint32_t refcount_table_size;
347     uint32_t max_refcount_table_index; /* Last used entry in refcount_table */
348     uint64_t free_cluster_index;
349     uint64_t free_byte_offset;
350 
351     CoMutex lock;
352 
353     Qcow2CryptoHeaderExtension crypto_header; /* QCow2 header extension */
354     QCryptoBlockOpenOptions *crypto_opts; /* Disk encryption runtime options */
355     QCryptoBlock *crypto; /* Disk encryption format driver */
356     bool crypt_physical_offset; /* Whether to use virtual or physical offset
357                                    for encryption initialization vector tweak */
358     uint32_t crypt_method_header;
359     uint64_t snapshots_offset;
360     int snapshots_size;
361     unsigned int nb_snapshots;
362     QCowSnapshot *snapshots;
363 
364     uint32_t nb_bitmaps;
365     uint64_t bitmap_directory_size;
366     uint64_t bitmap_directory_offset;
367 
368     int flags;
369     int qcow_version;
370     bool use_lazy_refcounts;
371     int refcount_order;
372     int refcount_bits;
373     uint64_t refcount_max;
374 
375     Qcow2GetRefcountFunc *get_refcount;
376     Qcow2SetRefcountFunc *set_refcount;
377 
378     bool discard_passthrough[QCOW2_DISCARD_MAX];
379 
380     int overlap_check; /* bitmask of Qcow2MetadataOverlap values */
381     bool signaled_corruption;
382 
383     uint64_t incompatible_features;
384     uint64_t compatible_features;
385     uint64_t autoclear_features;
386 
387     size_t unknown_header_fields_size;
388     void* unknown_header_fields;
389     QLIST_HEAD(, Qcow2UnknownHeaderExtension) unknown_header_ext;
390     QTAILQ_HEAD (, Qcow2DiscardRegion) discards;
391     bool cache_discards;
392 
393     /* Backing file path and format as stored in the image (this is not the
394      * effective path/format, which may be the result of a runtime option
395      * override) */
396     char *image_backing_file;
397     char *image_backing_format;
398     char *image_data_file;
399 
400     CoQueue thread_task_queue;
401     int nb_threads;
402 
403     BdrvChild *data_file;
404 
405     bool metadata_preallocation_checked;
406     bool metadata_preallocation;
407     /*
408      * Compression type used for the image. Default: 0 - ZLIB
409      * The image compression type is set on image creation.
410      * For now, the only way to change the compression type
411      * is to convert the image with the desired compression type set.
412      */
413     Qcow2CompressionType compression_type;
414 } BDRVQcow2State;
415 
416 typedef struct Qcow2COWRegion {
417     /**
418      * Offset of the COW region in bytes from the start of the first cluster
419      * touched by the request.
420      */
421     unsigned    offset;
422 
423     /** Number of bytes to copy */
424     unsigned    nb_bytes;
425 } Qcow2COWRegion;
426 
427 /**
428  * Describes an in-flight (part of a) write request that writes to clusters
429  * that are not referenced in their L2 table yet.
430  */
431 typedef struct QCowL2Meta
432 {
433     /** Guest offset of the first newly allocated cluster */
434     uint64_t offset;
435 
436     /** Host offset of the first newly allocated cluster */
437     uint64_t alloc_offset;
438 
439     /** Number of newly allocated clusters */
440     int nb_clusters;
441 
442     /** Do not free the old clusters */
443     bool keep_old_clusters;
444 
445     /**
446      * Requests that overlap with this allocation and wait to be restarted
447      * when the allocating request has completed.
448      */
449     CoQueue dependent_requests;
450 
451     /**
452      * The COW Region between the start of the first allocated cluster and the
453      * area the guest actually writes to.
454      */
455     Qcow2COWRegion cow_start;
456 
457     /**
458      * The COW Region between the area the guest actually writes to and the
459      * end of the last allocated cluster.
460      */
461     Qcow2COWRegion cow_end;
462 
463     /*
464      * Indicates that COW regions are already handled and do not require
465      * any more processing.
466      */
467     bool skip_cow;
468 
469     /**
470      * Indicates that this is not a normal write request but a preallocation.
471      * If the image has extended L2 entries this means that no new individual
472      * subclusters will be marked as allocated in the L2 bitmap (but any
473      * existing contents of that bitmap will be kept).
474      */
475     bool prealloc;
476 
477     /**
478      * The I/O vector with the data from the actual guest write request.
479      * If non-NULL, this is meant to be merged together with the data
480      * from @cow_start and @cow_end into one single write operation.
481      */
482     QEMUIOVector *data_qiov;
483     size_t data_qiov_offset;
484 
485     /** Pointer to next L2Meta of the same write request */
486     struct QCowL2Meta *next;
487 
488     QLIST_ENTRY(QCowL2Meta) next_in_flight;
489 } QCowL2Meta;
490 
491 /*
492  * In images with standard L2 entries all clusters are treated as if
493  * they had one subcluster so QCow2ClusterType and QCow2SubclusterType
494  * can be mapped to each other and have the exact same meaning
495  * (QCOW2_SUBCLUSTER_UNALLOCATED_ALLOC cannot happen in these images).
496  *
497  * In images with extended L2 entries QCow2ClusterType refers to the
498  * complete cluster and QCow2SubclusterType to each of the individual
499  * subclusters, so there are several possible combinations:
500  *
501  *     |--------------+---------------------------|
502  *     | Cluster type | Possible subcluster types |
503  *     |--------------+---------------------------|
504  *     | UNALLOCATED  |         UNALLOCATED_PLAIN |
505  *     |              |                ZERO_PLAIN |
506  *     |--------------+---------------------------|
507  *     | NORMAL       |         UNALLOCATED_ALLOC |
508  *     |              |                ZERO_ALLOC |
509  *     |              |                    NORMAL |
510  *     |--------------+---------------------------|
511  *     | COMPRESSED   |                COMPRESSED |
512  *     |--------------+---------------------------|
513  *
514  * QCOW2_SUBCLUSTER_INVALID means that the L2 entry is incorrect and
515  * the image should be marked corrupt.
516  */
517 
518 typedef enum QCow2ClusterType {
519     QCOW2_CLUSTER_UNALLOCATED,
520     QCOW2_CLUSTER_ZERO_PLAIN,
521     QCOW2_CLUSTER_ZERO_ALLOC,
522     QCOW2_CLUSTER_NORMAL,
523     QCOW2_CLUSTER_COMPRESSED,
524 } QCow2ClusterType;
525 
526 typedef enum QCow2SubclusterType {
527     QCOW2_SUBCLUSTER_UNALLOCATED_PLAIN,
528     QCOW2_SUBCLUSTER_UNALLOCATED_ALLOC,
529     QCOW2_SUBCLUSTER_ZERO_PLAIN,
530     QCOW2_SUBCLUSTER_ZERO_ALLOC,
531     QCOW2_SUBCLUSTER_NORMAL,
532     QCOW2_SUBCLUSTER_COMPRESSED,
533     QCOW2_SUBCLUSTER_INVALID,
534 } QCow2SubclusterType;
535 
536 typedef enum QCow2MetadataOverlap {
537     QCOW2_OL_MAIN_HEADER_BITNR      = 0,
538     QCOW2_OL_ACTIVE_L1_BITNR        = 1,
539     QCOW2_OL_ACTIVE_L2_BITNR        = 2,
540     QCOW2_OL_REFCOUNT_TABLE_BITNR   = 3,
541     QCOW2_OL_REFCOUNT_BLOCK_BITNR   = 4,
542     QCOW2_OL_SNAPSHOT_TABLE_BITNR   = 5,
543     QCOW2_OL_INACTIVE_L1_BITNR      = 6,
544     QCOW2_OL_INACTIVE_L2_BITNR      = 7,
545     QCOW2_OL_BITMAP_DIRECTORY_BITNR = 8,
546 
547     QCOW2_OL_MAX_BITNR              = 9,
548 
549     QCOW2_OL_NONE             = 0,
550     QCOW2_OL_MAIN_HEADER      = (1 << QCOW2_OL_MAIN_HEADER_BITNR),
551     QCOW2_OL_ACTIVE_L1        = (1 << QCOW2_OL_ACTIVE_L1_BITNR),
552     QCOW2_OL_ACTIVE_L2        = (1 << QCOW2_OL_ACTIVE_L2_BITNR),
553     QCOW2_OL_REFCOUNT_TABLE   = (1 << QCOW2_OL_REFCOUNT_TABLE_BITNR),
554     QCOW2_OL_REFCOUNT_BLOCK   = (1 << QCOW2_OL_REFCOUNT_BLOCK_BITNR),
555     QCOW2_OL_SNAPSHOT_TABLE   = (1 << QCOW2_OL_SNAPSHOT_TABLE_BITNR),
556     QCOW2_OL_INACTIVE_L1      = (1 << QCOW2_OL_INACTIVE_L1_BITNR),
557     /* NOTE: Checking overlaps with inactive L2 tables will result in bdrv
558      * reads. */
559     QCOW2_OL_INACTIVE_L2      = (1 << QCOW2_OL_INACTIVE_L2_BITNR),
560     QCOW2_OL_BITMAP_DIRECTORY = (1 << QCOW2_OL_BITMAP_DIRECTORY_BITNR),
561 } QCow2MetadataOverlap;
562 
563 /* Perform all overlap checks which can be done in constant time */
564 #define QCOW2_OL_CONSTANT \
565     (QCOW2_OL_MAIN_HEADER | QCOW2_OL_ACTIVE_L1 | QCOW2_OL_REFCOUNT_TABLE | \
566      QCOW2_OL_SNAPSHOT_TABLE | QCOW2_OL_BITMAP_DIRECTORY)
567 
568 /* Perform all overlap checks which don't require disk access */
569 #define QCOW2_OL_CACHED \
570     (QCOW2_OL_CONSTANT | QCOW2_OL_ACTIVE_L2 | QCOW2_OL_REFCOUNT_BLOCK | \
571      QCOW2_OL_INACTIVE_L1)
572 
573 /* Perform all overlap checks */
574 #define QCOW2_OL_ALL \
575     (QCOW2_OL_CACHED | QCOW2_OL_INACTIVE_L2)
576 
577 #define L1E_OFFSET_MASK 0x00fffffffffffe00ULL
578 #define L2E_OFFSET_MASK 0x00fffffffffffe00ULL
579 #define L2E_COMPRESSED_OFFSET_SIZE_MASK 0x3fffffffffffffffULL
580 
581 #define REFT_OFFSET_MASK 0xfffffffffffffe00ULL
582 
583 #define INV_OFFSET (-1ULL)
584 
585 static inline bool has_subclusters(BDRVQcow2State *s)
586 {
587     return s->incompatible_features & QCOW2_INCOMPAT_EXTL2;
588 }
589 
590 static inline size_t l2_entry_size(BDRVQcow2State *s)
591 {
592     return has_subclusters(s) ? L2E_SIZE_EXTENDED : L2E_SIZE_NORMAL;
593 }
594 
595 static inline uint64_t get_l2_entry(BDRVQcow2State *s, uint64_t *l2_slice,
596                                     int idx)
597 {
598     idx *= l2_entry_size(s) / sizeof(uint64_t);
599     return be64_to_cpu(l2_slice[idx]);
600 }
601 
602 static inline uint64_t get_l2_bitmap(BDRVQcow2State *s, uint64_t *l2_slice,
603                                      int idx)
604 {
605     if (has_subclusters(s)) {
606         idx *= l2_entry_size(s) / sizeof(uint64_t);
607         return be64_to_cpu(l2_slice[idx + 1]);
608     } else {
609         return 0; /* For convenience only; this value has no meaning. */
610     }
611 }
612 
613 static inline void set_l2_entry(BDRVQcow2State *s, uint64_t *l2_slice,
614                                 int idx, uint64_t entry)
615 {
616     idx *= l2_entry_size(s) / sizeof(uint64_t);
617     l2_slice[idx] = cpu_to_be64(entry);
618 }
619 
620 static inline void set_l2_bitmap(BDRVQcow2State *s, uint64_t *l2_slice,
621                                  int idx, uint64_t bitmap)
622 {
623     assert(has_subclusters(s));
624     idx *= l2_entry_size(s) / sizeof(uint64_t);
625     l2_slice[idx + 1] = cpu_to_be64(bitmap);
626 }
627 
628 static inline bool has_data_file(BlockDriverState *bs)
629 {
630     BDRVQcow2State *s = bs->opaque;
631     return (s->data_file != bs->file);
632 }
633 
634 static inline bool data_file_is_raw(BlockDriverState *bs)
635 {
636     BDRVQcow2State *s = bs->opaque;
637     return !!(s->autoclear_features & QCOW2_AUTOCLEAR_DATA_FILE_RAW);
638 }
639 
640 static inline int64_t start_of_cluster(BDRVQcow2State *s, int64_t offset)
641 {
642     return offset & ~(s->cluster_size - 1);
643 }
644 
645 static inline int64_t offset_into_cluster(BDRVQcow2State *s, int64_t offset)
646 {
647     return offset & (s->cluster_size - 1);
648 }
649 
650 static inline int64_t offset_into_subcluster(BDRVQcow2State *s, int64_t offset)
651 {
652     return offset & (s->subcluster_size - 1);
653 }
654 
655 static inline uint64_t size_to_clusters(BDRVQcow2State *s, uint64_t size)
656 {
657     return (size + (s->cluster_size - 1)) >> s->cluster_bits;
658 }
659 
660 static inline uint64_t size_to_subclusters(BDRVQcow2State *s, uint64_t size)
661 {
662     return (size + (s->subcluster_size - 1)) >> s->subcluster_bits;
663 }
664 
665 static inline int64_t size_to_l1(BDRVQcow2State *s, int64_t size)
666 {
667     int shift = s->cluster_bits + s->l2_bits;
668     return (size + (1ULL << shift) - 1) >> shift;
669 }
670 
671 static inline int offset_to_l1_index(BDRVQcow2State *s, uint64_t offset)
672 {
673     return offset >> (s->l2_bits + s->cluster_bits);
674 }
675 
676 static inline int offset_to_l2_index(BDRVQcow2State *s, int64_t offset)
677 {
678     return (offset >> s->cluster_bits) & (s->l2_size - 1);
679 }
680 
681 static inline int offset_to_l2_slice_index(BDRVQcow2State *s, int64_t offset)
682 {
683     return (offset >> s->cluster_bits) & (s->l2_slice_size - 1);
684 }
685 
686 static inline int offset_to_sc_index(BDRVQcow2State *s, int64_t offset)
687 {
688     return (offset >> s->subcluster_bits) & (s->subclusters_per_cluster - 1);
689 }
690 
691 static inline int64_t qcow2_vm_state_offset(BDRVQcow2State *s)
692 {
693     return (int64_t)s->l1_vm_state_index << (s->cluster_bits + s->l2_bits);
694 }
695 
696 static inline QCow2ClusterType qcow2_get_cluster_type(BlockDriverState *bs,
697                                                       uint64_t l2_entry)
698 {
699     BDRVQcow2State *s = bs->opaque;
700 
701     if (l2_entry & QCOW_OFLAG_COMPRESSED) {
702         return QCOW2_CLUSTER_COMPRESSED;
703     } else if ((l2_entry & QCOW_OFLAG_ZERO) && !has_subclusters(s)) {
704         if (l2_entry & L2E_OFFSET_MASK) {
705             return QCOW2_CLUSTER_ZERO_ALLOC;
706         }
707         return QCOW2_CLUSTER_ZERO_PLAIN;
708     } else if (!(l2_entry & L2E_OFFSET_MASK)) {
709         /* Offset 0 generally means unallocated, but it is ambiguous with
710          * external data files because 0 is a valid offset there. However, all
711          * clusters in external data files always have refcount 1, so we can
712          * rely on QCOW_OFLAG_COPIED to disambiguate. */
713         if (has_data_file(bs) && (l2_entry & QCOW_OFLAG_COPIED)) {
714             return QCOW2_CLUSTER_NORMAL;
715         } else {
716             return QCOW2_CLUSTER_UNALLOCATED;
717         }
718     } else {
719         return QCOW2_CLUSTER_NORMAL;
720     }
721 }
722 
723 /*
724  * In an image without subsclusters @l2_bitmap is ignored and
725  * @sc_index must be 0.
726  * Return QCOW2_SUBCLUSTER_INVALID if an invalid l2 entry is detected
727  * (this checks the whole entry and bitmap, not only the bits related
728  * to subcluster @sc_index).
729  */
730 static inline
731 QCow2SubclusterType qcow2_get_subcluster_type(BlockDriverState *bs,
732                                               uint64_t l2_entry,
733                                               uint64_t l2_bitmap,
734                                               unsigned sc_index)
735 {
736     BDRVQcow2State *s = bs->opaque;
737     QCow2ClusterType type = qcow2_get_cluster_type(bs, l2_entry);
738     assert(sc_index < s->subclusters_per_cluster);
739 
740     if (has_subclusters(s)) {
741         switch (type) {
742         case QCOW2_CLUSTER_COMPRESSED:
743             return QCOW2_SUBCLUSTER_COMPRESSED;
744         case QCOW2_CLUSTER_NORMAL:
745             if ((l2_bitmap >> 32) & l2_bitmap) {
746                 return QCOW2_SUBCLUSTER_INVALID;
747             } else if (l2_bitmap & QCOW_OFLAG_SUB_ZERO(sc_index)) {
748                 return QCOW2_SUBCLUSTER_ZERO_ALLOC;
749             } else if (l2_bitmap & QCOW_OFLAG_SUB_ALLOC(sc_index)) {
750                 return QCOW2_SUBCLUSTER_NORMAL;
751             } else {
752                 return QCOW2_SUBCLUSTER_UNALLOCATED_ALLOC;
753             }
754         case QCOW2_CLUSTER_UNALLOCATED:
755             if (l2_bitmap & QCOW_L2_BITMAP_ALL_ALLOC) {
756                 return QCOW2_SUBCLUSTER_INVALID;
757             } else if (l2_bitmap & QCOW_OFLAG_SUB_ZERO(sc_index)) {
758                 return QCOW2_SUBCLUSTER_ZERO_PLAIN;
759             } else {
760                 return QCOW2_SUBCLUSTER_UNALLOCATED_PLAIN;
761             }
762         default:
763             g_assert_not_reached();
764         }
765     } else {
766         switch (type) {
767         case QCOW2_CLUSTER_COMPRESSED:
768             return QCOW2_SUBCLUSTER_COMPRESSED;
769         case QCOW2_CLUSTER_ZERO_PLAIN:
770             return QCOW2_SUBCLUSTER_ZERO_PLAIN;
771         case QCOW2_CLUSTER_ZERO_ALLOC:
772             return QCOW2_SUBCLUSTER_ZERO_ALLOC;
773         case QCOW2_CLUSTER_NORMAL:
774             return QCOW2_SUBCLUSTER_NORMAL;
775         case QCOW2_CLUSTER_UNALLOCATED:
776             return QCOW2_SUBCLUSTER_UNALLOCATED_PLAIN;
777         default:
778             g_assert_not_reached();
779         }
780     }
781 }
782 
783 static inline bool qcow2_cluster_is_allocated(QCow2ClusterType type)
784 {
785     return (type == QCOW2_CLUSTER_COMPRESSED || type == QCOW2_CLUSTER_NORMAL ||
786             type == QCOW2_CLUSTER_ZERO_ALLOC);
787 }
788 
789 /* Check whether refcounts are eager or lazy */
790 static inline bool qcow2_need_accurate_refcounts(BDRVQcow2State *s)
791 {
792     return !(s->incompatible_features & QCOW2_INCOMPAT_DIRTY);
793 }
794 
795 static inline uint64_t l2meta_cow_start(QCowL2Meta *m)
796 {
797     return m->offset + m->cow_start.offset;
798 }
799 
800 static inline uint64_t l2meta_cow_end(QCowL2Meta *m)
801 {
802     return m->offset + m->cow_end.offset + m->cow_end.nb_bytes;
803 }
804 
805 static inline uint64_t refcount_diff(uint64_t r1, uint64_t r2)
806 {
807     return r1 > r2 ? r1 - r2 : r2 - r1;
808 }
809 
810 static inline
811 uint32_t offset_to_reftable_index(BDRVQcow2State *s, uint64_t offset)
812 {
813     return offset >> (s->refcount_block_bits + s->cluster_bits);
814 }
815 
816 /* qcow2.c functions */
817 int64_t qcow2_refcount_metadata_size(int64_t clusters, size_t cluster_size,
818                                      int refcount_order, bool generous_increase,
819                                      uint64_t *refblock_count);
820 
821 int qcow2_mark_dirty(BlockDriverState *bs);
822 int qcow2_mark_corrupt(BlockDriverState *bs);
823 int qcow2_mark_consistent(BlockDriverState *bs);
824 int qcow2_update_header(BlockDriverState *bs);
825 
826 void qcow2_signal_corruption(BlockDriverState *bs, bool fatal, int64_t offset,
827                              int64_t size, const char *message_format, ...)
828                              GCC_FMT_ATTR(5, 6);
829 
830 int qcow2_validate_table(BlockDriverState *bs, uint64_t offset,
831                          uint64_t entries, size_t entry_len,
832                          int64_t max_size_bytes, const char *table_name,
833                          Error **errp);
834 
835 /* qcow2-refcount.c functions */
836 int qcow2_refcount_init(BlockDriverState *bs);
837 void qcow2_refcount_close(BlockDriverState *bs);
838 
839 int qcow2_get_refcount(BlockDriverState *bs, int64_t cluster_index,
840                        uint64_t *refcount);
841 
842 int qcow2_update_cluster_refcount(BlockDriverState *bs, int64_t cluster_index,
843                                   uint64_t addend, bool decrease,
844                                   enum qcow2_discard_type type);
845 
846 int64_t qcow2_refcount_area(BlockDriverState *bs, uint64_t offset,
847                             uint64_t additional_clusters, bool exact_size,
848                             int new_refblock_index,
849                             uint64_t new_refblock_offset);
850 
851 int64_t qcow2_alloc_clusters(BlockDriverState *bs, uint64_t size);
852 int64_t qcow2_alloc_clusters_at(BlockDriverState *bs, uint64_t offset,
853                                 int64_t nb_clusters);
854 int64_t qcow2_alloc_bytes(BlockDriverState *bs, int size);
855 void qcow2_free_clusters(BlockDriverState *bs,
856                           int64_t offset, int64_t size,
857                           enum qcow2_discard_type type);
858 void qcow2_free_any_clusters(BlockDriverState *bs, uint64_t l2_entry,
859                              int nb_clusters, enum qcow2_discard_type type);
860 
861 int qcow2_update_snapshot_refcount(BlockDriverState *bs,
862     int64_t l1_table_offset, int l1_size, int addend);
863 
864 int coroutine_fn qcow2_flush_caches(BlockDriverState *bs);
865 int coroutine_fn qcow2_write_caches(BlockDriverState *bs);
866 int qcow2_check_refcounts(BlockDriverState *bs, BdrvCheckResult *res,
867                           BdrvCheckMode fix);
868 
869 void qcow2_process_discards(BlockDriverState *bs, int ret);
870 
871 int qcow2_check_metadata_overlap(BlockDriverState *bs, int ign, int64_t offset,
872                                  int64_t size);
873 int qcow2_pre_write_overlap_check(BlockDriverState *bs, int ign, int64_t offset,
874                                   int64_t size, bool data_file);
875 int qcow2_inc_refcounts_imrt(BlockDriverState *bs, BdrvCheckResult *res,
876                              void **refcount_table,
877                              int64_t *refcount_table_size,
878                              int64_t offset, int64_t size);
879 
880 int qcow2_change_refcount_order(BlockDriverState *bs, int refcount_order,
881                                 BlockDriverAmendStatusCB *status_cb,
882                                 void *cb_opaque, Error **errp);
883 int qcow2_shrink_reftable(BlockDriverState *bs);
884 int64_t qcow2_get_last_cluster(BlockDriverState *bs, int64_t size);
885 int qcow2_detect_metadata_preallocation(BlockDriverState *bs);
886 
887 /* qcow2-cluster.c functions */
888 int qcow2_grow_l1_table(BlockDriverState *bs, uint64_t min_size,
889                         bool exact_size);
890 int qcow2_shrink_l1_table(BlockDriverState *bs, uint64_t max_size);
891 int qcow2_write_l1_entry(BlockDriverState *bs, int l1_index);
892 int qcow2_encrypt_sectors(BDRVQcow2State *s, int64_t sector_num,
893                           uint8_t *buf, int nb_sectors, bool enc, Error **errp);
894 
895 int qcow2_get_host_offset(BlockDriverState *bs, uint64_t offset,
896                           unsigned int *bytes, uint64_t *host_offset,
897                           QCow2SubclusterType *subcluster_type);
898 int qcow2_alloc_cluster_offset(BlockDriverState *bs, uint64_t offset,
899                                unsigned int *bytes, uint64_t *host_offset,
900                                QCowL2Meta **m);
901 int qcow2_alloc_compressed_cluster_offset(BlockDriverState *bs,
902                                           uint64_t offset,
903                                           int compressed_size,
904                                           uint64_t *host_offset);
905 
906 int qcow2_alloc_cluster_link_l2(BlockDriverState *bs, QCowL2Meta *m);
907 void qcow2_alloc_cluster_abort(BlockDriverState *bs, QCowL2Meta *m);
908 int qcow2_cluster_discard(BlockDriverState *bs, uint64_t offset,
909                           uint64_t bytes, enum qcow2_discard_type type,
910                           bool full_discard);
911 int qcow2_subcluster_zeroize(BlockDriverState *bs, uint64_t offset,
912                              uint64_t bytes, int flags);
913 
914 int qcow2_expand_zero_clusters(BlockDriverState *bs,
915                                BlockDriverAmendStatusCB *status_cb,
916                                void *cb_opaque);
917 
918 /* qcow2-snapshot.c functions */
919 int qcow2_snapshot_create(BlockDriverState *bs, QEMUSnapshotInfo *sn_info);
920 int qcow2_snapshot_goto(BlockDriverState *bs, const char *snapshot_id);
921 int qcow2_snapshot_delete(BlockDriverState *bs,
922                           const char *snapshot_id,
923                           const char *name,
924                           Error **errp);
925 int qcow2_snapshot_list(BlockDriverState *bs, QEMUSnapshotInfo **psn_tab);
926 int qcow2_snapshot_load_tmp(BlockDriverState *bs,
927                             const char *snapshot_id,
928                             const char *name,
929                             Error **errp);
930 
931 void qcow2_free_snapshots(BlockDriverState *bs);
932 int qcow2_read_snapshots(BlockDriverState *bs, Error **errp);
933 int qcow2_write_snapshots(BlockDriverState *bs);
934 
935 int coroutine_fn qcow2_check_read_snapshot_table(BlockDriverState *bs,
936                                                  BdrvCheckResult *result,
937                                                  BdrvCheckMode fix);
938 int coroutine_fn qcow2_check_fix_snapshot_table(BlockDriverState *bs,
939                                                 BdrvCheckResult *result,
940                                                 BdrvCheckMode fix);
941 
942 /* qcow2-cache.c functions */
943 Qcow2Cache *qcow2_cache_create(BlockDriverState *bs, int num_tables,
944                                unsigned table_size);
945 int qcow2_cache_destroy(Qcow2Cache *c);
946 
947 void qcow2_cache_entry_mark_dirty(Qcow2Cache *c, void *table);
948 int qcow2_cache_flush(BlockDriverState *bs, Qcow2Cache *c);
949 int qcow2_cache_write(BlockDriverState *bs, Qcow2Cache *c);
950 int qcow2_cache_set_dependency(BlockDriverState *bs, Qcow2Cache *c,
951     Qcow2Cache *dependency);
952 void qcow2_cache_depends_on_flush(Qcow2Cache *c);
953 
954 void qcow2_cache_clean_unused(Qcow2Cache *c);
955 int qcow2_cache_empty(BlockDriverState *bs, Qcow2Cache *c);
956 
957 int qcow2_cache_get(BlockDriverState *bs, Qcow2Cache *c, uint64_t offset,
958     void **table);
959 int qcow2_cache_get_empty(BlockDriverState *bs, Qcow2Cache *c, uint64_t offset,
960     void **table);
961 void qcow2_cache_put(Qcow2Cache *c, void **table);
962 void *qcow2_cache_is_table_offset(Qcow2Cache *c, uint64_t offset);
963 void qcow2_cache_discard(Qcow2Cache *c, void *table);
964 
965 /* qcow2-bitmap.c functions */
966 int qcow2_check_bitmaps_refcounts(BlockDriverState *bs, BdrvCheckResult *res,
967                                   void **refcount_table,
968                                   int64_t *refcount_table_size);
969 bool qcow2_load_dirty_bitmaps(BlockDriverState *bs, Error **errp);
970 Qcow2BitmapInfoList *qcow2_get_bitmap_info_list(BlockDriverState *bs,
971                                                 Error **errp);
972 int qcow2_reopen_bitmaps_rw(BlockDriverState *bs, Error **errp);
973 int qcow2_truncate_bitmaps_check(BlockDriverState *bs, Error **errp);
974 void qcow2_store_persistent_dirty_bitmaps(BlockDriverState *bs,
975                                           bool release_stored, Error **errp);
976 int qcow2_reopen_bitmaps_ro(BlockDriverState *bs, Error **errp);
977 bool qcow2_co_can_store_new_dirty_bitmap(BlockDriverState *bs,
978                                          const char *name,
979                                          uint32_t granularity,
980                                          Error **errp);
981 int qcow2_co_remove_persistent_dirty_bitmap(BlockDriverState *bs,
982                                             const char *name,
983                                             Error **errp);
984 bool qcow2_supports_persistent_dirty_bitmap(BlockDriverState *bs);
985 uint64_t qcow2_get_persistent_dirty_bitmap_size(BlockDriverState *bs,
986                                                 uint32_t cluster_size);
987 
988 ssize_t coroutine_fn
989 qcow2_co_compress(BlockDriverState *bs, void *dest, size_t dest_size,
990                   const void *src, size_t src_size);
991 ssize_t coroutine_fn
992 qcow2_co_decompress(BlockDriverState *bs, void *dest, size_t dest_size,
993                     const void *src, size_t src_size);
994 int coroutine_fn
995 qcow2_co_encrypt(BlockDriverState *bs, uint64_t host_offset,
996                  uint64_t guest_offset, void *buf, size_t len);
997 int coroutine_fn
998 qcow2_co_decrypt(BlockDriverState *bs, uint64_t host_offset,
999                  uint64_t guest_offset, void *buf, size_t len);
1000 
1001 #endif
1002