xref: /qemu/include/block/block-common.h (revision 84615a19)
1 /*
2  * QEMU System Emulator block driver
3  *
4  * Copyright (c) 2003 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 #ifndef BLOCK_COMMON_H
25 #define BLOCK_COMMON_H
26 
27 #include "qapi/qapi-types-block-core.h"
28 #include "qemu/queue.h"
29 
30 /*
31  * co_wrapper{*}: Function specifiers used by block-coroutine-wrapper.py
32  *
33  * Function specifiers, which do nothing but mark functions to be
34  * generated by scripts/block-coroutine-wrapper.py
35  *
36  * Usage: read docs/devel/block-coroutine-wrapper.rst
37  *
38  * There are 4 kind of specifiers:
39  * - co_wrapper functions can be called by only non-coroutine context, because
40  *   they always generate a new coroutine.
41  * - co_wrapper_mixed functions can be called by both coroutine and
42  *   non-coroutine context.
43  * - co_wrapper_bdrv_rdlock are co_wrapper functions but automatically take and
44  *   release the graph rdlock when creating a new coroutine
45  * - co_wrapper_mixed_bdrv_rdlock are co_wrapper_mixed functions but
46  *   automatically take and release the graph rdlock when creating a new
47  *   coroutine.
48  *
49  * These functions should not be called from a coroutine_fn; instead,
50  * call the wrapped function directly.
51  */
52 #define co_wrapper                     no_coroutine_fn
53 #define co_wrapper_mixed               no_coroutine_fn coroutine_mixed_fn
54 #define co_wrapper_bdrv_rdlock         no_coroutine_fn
55 #define co_wrapper_mixed_bdrv_rdlock   no_coroutine_fn coroutine_mixed_fn
56 
57 #include "block/blockjob.h"
58 
59 /* block.c */
60 typedef struct BlockDriver BlockDriver;
61 typedef struct BdrvChild BdrvChild;
62 typedef struct BdrvChildClass BdrvChildClass;
63 
64 typedef struct BlockDriverInfo {
65     /* in bytes, 0 if irrelevant */
66     int cluster_size;
67     /* offset at which the VM state can be saved (0 if not possible) */
68     int64_t vm_state_offset;
69     bool is_dirty;
70     /*
71      * True if this block driver only supports compressed writes
72      */
73     bool needs_compressed_writes;
74 } BlockDriverInfo;
75 
76 typedef struct BlockFragInfo {
77     uint64_t allocated_clusters;
78     uint64_t total_clusters;
79     uint64_t fragmented_clusters;
80     uint64_t compressed_clusters;
81 } BlockFragInfo;
82 
83 typedef enum {
84     BDRV_REQ_COPY_ON_READ       = 0x1,
85     BDRV_REQ_ZERO_WRITE         = 0x2,
86 
87     /*
88      * The BDRV_REQ_MAY_UNMAP flag is used in write_zeroes requests to indicate
89      * that the block driver should unmap (discard) blocks if it is guaranteed
90      * that the result will read back as zeroes. The flag is only passed to the
91      * driver if the block device is opened with BDRV_O_UNMAP.
92      */
93     BDRV_REQ_MAY_UNMAP          = 0x4,
94 
95     /*
96      * An optimization hint when all QEMUIOVector elements are within
97      * previously registered bdrv_register_buf() memory ranges.
98      *
99      * Code that replaces the user's QEMUIOVector elements with bounce buffers
100      * must take care to clear this flag.
101      */
102     BDRV_REQ_REGISTERED_BUF     = 0x8,
103 
104     BDRV_REQ_FUA                = 0x10,
105     BDRV_REQ_WRITE_COMPRESSED   = 0x20,
106 
107     /*
108      * Signifies that this write request will not change the visible disk
109      * content.
110      */
111     BDRV_REQ_WRITE_UNCHANGED    = 0x40,
112 
113     /*
114      * Forces request serialisation. Use only with write requests.
115      */
116     BDRV_REQ_SERIALISING        = 0x80,
117 
118     /*
119      * Execute the request only if the operation can be offloaded or otherwise
120      * be executed efficiently, but return an error instead of using a slow
121      * fallback.
122      */
123     BDRV_REQ_NO_FALLBACK        = 0x100,
124 
125     /*
126      * BDRV_REQ_PREFETCH makes sense only in the context of copy-on-read
127      * (i.e., together with the BDRV_REQ_COPY_ON_READ flag or when a COR
128      * filter is involved), in which case it signals that the COR operation
129      * need not read the data into memory (qiov) but only ensure they are
130      * copied to the top layer (i.e., that COR operation is done).
131      */
132     BDRV_REQ_PREFETCH  = 0x200,
133 
134     /*
135      * If we need to wait for other requests, just fail immediately. Used
136      * only together with BDRV_REQ_SERIALISING. Used only with requests aligned
137      * to request_alignment (corresponding assertions are in block/io.c).
138      */
139     BDRV_REQ_NO_WAIT = 0x400,
140 
141     /* Mask of valid flags */
142     BDRV_REQ_MASK               = 0x7ff,
143 } BdrvRequestFlags;
144 
145 #define BDRV_O_NO_SHARE    0x0001 /* don't share permissions */
146 #define BDRV_O_RDWR        0x0002
147 #define BDRV_O_RESIZE      0x0004 /* request permission for resizing the node */
148 #define BDRV_O_SNAPSHOT    0x0008 /* open the file read only and save
149                                      writes in a snapshot */
150 #define BDRV_O_TEMPORARY   0x0010 /* delete the file after use */
151 #define BDRV_O_NOCACHE     0x0020 /* do not use the host page cache */
152 #define BDRV_O_NATIVE_AIO  0x0080 /* use native AIO instead of the
153                                      thread pool */
154 #define BDRV_O_NO_BACKING  0x0100 /* don't open the backing file */
155 #define BDRV_O_NO_FLUSH    0x0200 /* disable flushing on this disk */
156 #define BDRV_O_COPY_ON_READ 0x0400 /* copy read backing sectors into image */
157 #define BDRV_O_INACTIVE    0x0800  /* consistency hint for migration handoff */
158 #define BDRV_O_CHECK       0x1000  /* open solely for consistency check */
159 #define BDRV_O_ALLOW_RDWR  0x2000  /* allow reopen to change from r/o to r/w */
160 #define BDRV_O_UNMAP       0x4000  /* execute guest UNMAP/TRIM operations */
161 #define BDRV_O_PROTOCOL    0x8000  /* if no block driver is explicitly given:
162                                       select an appropriate protocol driver,
163                                       ignoring the format layer */
164 #define BDRV_O_NO_IO       0x10000 /* don't initialize for I/O */
165 #define BDRV_O_AUTO_RDONLY 0x20000 /* degrade to read-only if opening
166                                       read-write fails */
167 #define BDRV_O_IO_URING    0x40000 /* use io_uring instead of the thread pool */
168 
169 #define BDRV_O_CACHE_MASK  (BDRV_O_NOCACHE | BDRV_O_NO_FLUSH)
170 
171 
172 /* Option names of options parsed by the block layer */
173 
174 #define BDRV_OPT_CACHE_WB       "cache.writeback"
175 #define BDRV_OPT_CACHE_DIRECT   "cache.direct"
176 #define BDRV_OPT_CACHE_NO_FLUSH "cache.no-flush"
177 #define BDRV_OPT_READ_ONLY      "read-only"
178 #define BDRV_OPT_AUTO_READ_ONLY "auto-read-only"
179 #define BDRV_OPT_DISCARD        "discard"
180 #define BDRV_OPT_FORCE_SHARE    "force-share"
181 
182 
183 #define BDRV_SECTOR_BITS   9
184 #define BDRV_SECTOR_SIZE   (1ULL << BDRV_SECTOR_BITS)
185 
186 #define BDRV_REQUEST_MAX_SECTORS MIN_CONST(SIZE_MAX >> BDRV_SECTOR_BITS, \
187                                            INT_MAX >> BDRV_SECTOR_BITS)
188 #define BDRV_REQUEST_MAX_BYTES (BDRV_REQUEST_MAX_SECTORS << BDRV_SECTOR_BITS)
189 
190 /*
191  * We want allow aligning requests and disk length up to any 32bit alignment
192  * and don't afraid of overflow.
193  * To achieve it, and in the same time use some pretty number as maximum disk
194  * size, let's define maximum "length" (a limit for any offset/bytes request and
195  * for disk size) to be the greatest power of 2 less than INT64_MAX.
196  */
197 #define BDRV_MAX_ALIGNMENT (1L << 30)
198 #define BDRV_MAX_LENGTH (QEMU_ALIGN_DOWN(INT64_MAX, BDRV_MAX_ALIGNMENT))
199 
200 /*
201  * Allocation status flags for bdrv_block_status() and friends.
202  *
203  * Public flags:
204  * BDRV_BLOCK_DATA: allocation for data at offset is tied to this layer
205  * BDRV_BLOCK_ZERO: offset reads as zero
206  * BDRV_BLOCK_OFFSET_VALID: an associated offset exists for accessing raw data
207  * BDRV_BLOCK_ALLOCATED: the content of the block is determined by this
208  *                       layer rather than any backing, set by block layer
209  * BDRV_BLOCK_EOF: the returned pnum covers through end of file for this
210  *                 layer, set by block layer
211  *
212  * Internal flags:
213  * BDRV_BLOCK_RAW: for use by passthrough drivers, such as raw, to request
214  *                 that the block layer recompute the answer from the returned
215  *                 BDS; must be accompanied by just BDRV_BLOCK_OFFSET_VALID.
216  * BDRV_BLOCK_RECURSE: request that the block layer will recursively search for
217  *                     zeroes in file child of current block node inside
218  *                     returned region. Only valid together with both
219  *                     BDRV_BLOCK_DATA and BDRV_BLOCK_OFFSET_VALID. Should not
220  *                     appear with BDRV_BLOCK_ZERO.
221  *
222  * If BDRV_BLOCK_OFFSET_VALID is set, the map parameter represents the
223  * host offset within the returned BDS that is allocated for the
224  * corresponding raw guest data.  However, whether that offset
225  * actually contains data also depends on BDRV_BLOCK_DATA, as follows:
226  *
227  * DATA ZERO OFFSET_VALID
228  *  t    t        t       sectors read as zero, returned file is zero at offset
229  *  t    f        t       sectors read as valid from file at offset
230  *  f    t        t       sectors preallocated, read as zero, returned file not
231  *                        necessarily zero at offset
232  *  f    f        t       sectors preallocated but read from backing_hd,
233  *                        returned file contains garbage at offset
234  *  t    t        f       sectors preallocated, read as zero, unknown offset
235  *  t    f        f       sectors read from unknown file or offset
236  *  f    t        f       not allocated or unknown offset, read as zero
237  *  f    f        f       not allocated or unknown offset, read from backing_hd
238  */
239 #define BDRV_BLOCK_DATA         0x01
240 #define BDRV_BLOCK_ZERO         0x02
241 #define BDRV_BLOCK_OFFSET_VALID 0x04
242 #define BDRV_BLOCK_RAW          0x08
243 #define BDRV_BLOCK_ALLOCATED    0x10
244 #define BDRV_BLOCK_EOF          0x20
245 #define BDRV_BLOCK_RECURSE      0x40
246 
247 typedef QTAILQ_HEAD(BlockReopenQueue, BlockReopenQueueEntry) BlockReopenQueue;
248 
249 typedef struct BDRVReopenState {
250     BlockDriverState *bs;
251     int flags;
252     BlockdevDetectZeroesOptions detect_zeroes;
253     bool backing_missing;
254     BlockDriverState *old_backing_bs; /* keep pointer for permissions update */
255     BlockDriverState *old_file_bs; /* keep pointer for permissions update */
256     QDict *options;
257     QDict *explicit_options;
258     void *opaque;
259 } BDRVReopenState;
260 
261 /*
262  * Block operation types
263  */
264 typedef enum BlockOpType {
265     BLOCK_OP_TYPE_BACKUP_SOURCE,
266     BLOCK_OP_TYPE_BACKUP_TARGET,
267     BLOCK_OP_TYPE_CHANGE,
268     BLOCK_OP_TYPE_COMMIT_SOURCE,
269     BLOCK_OP_TYPE_COMMIT_TARGET,
270     BLOCK_OP_TYPE_DATAPLANE,
271     BLOCK_OP_TYPE_DRIVE_DEL,
272     BLOCK_OP_TYPE_EJECT,
273     BLOCK_OP_TYPE_EXTERNAL_SNAPSHOT,
274     BLOCK_OP_TYPE_INTERNAL_SNAPSHOT,
275     BLOCK_OP_TYPE_INTERNAL_SNAPSHOT_DELETE,
276     BLOCK_OP_TYPE_MIRROR_SOURCE,
277     BLOCK_OP_TYPE_MIRROR_TARGET,
278     BLOCK_OP_TYPE_RESIZE,
279     BLOCK_OP_TYPE_STREAM,
280     BLOCK_OP_TYPE_REPLACE,
281     BLOCK_OP_TYPE_MAX,
282 } BlockOpType;
283 
284 /* Block node permission constants */
285 enum {
286     /**
287      * A user that has the "permission" of consistent reads is guaranteed that
288      * their view of the contents of the block device is complete and
289      * self-consistent, representing the contents of a disk at a specific
290      * point.
291      *
292      * For most block devices (including their backing files) this is true, but
293      * the property cannot be maintained in a few situations like for
294      * intermediate nodes of a commit block job.
295      */
296     BLK_PERM_CONSISTENT_READ    = 0x01,
297 
298     /** This permission is required to change the visible disk contents. */
299     BLK_PERM_WRITE              = 0x02,
300 
301     /**
302      * This permission (which is weaker than BLK_PERM_WRITE) is both enough and
303      * required for writes to the block node when the caller promises that
304      * the visible disk content doesn't change.
305      *
306      * As the BLK_PERM_WRITE permission is strictly stronger, either is
307      * sufficient to perform an unchanging write.
308      */
309     BLK_PERM_WRITE_UNCHANGED    = 0x04,
310 
311     /** This permission is required to change the size of a block node. */
312     BLK_PERM_RESIZE             = 0x08,
313 
314     /**
315      * There was a now-removed bit BLK_PERM_GRAPH_MOD, with value of 0x10. QEMU
316      * 6.1 and earlier may still lock the corresponding byte in block/file-posix
317      * locking.  So, implementing some new permission should be very careful to
318      * not interfere with this old unused thing.
319      */
320 
321     BLK_PERM_ALL                = 0x0f,
322 
323     DEFAULT_PERM_PASSTHROUGH    = BLK_PERM_CONSISTENT_READ
324                                  | BLK_PERM_WRITE
325                                  | BLK_PERM_WRITE_UNCHANGED
326                                  | BLK_PERM_RESIZE,
327 
328     DEFAULT_PERM_UNCHANGED      = BLK_PERM_ALL & ~DEFAULT_PERM_PASSTHROUGH,
329 };
330 
331 /*
332  * Flags that parent nodes assign to child nodes to specify what kind of
333  * role(s) they take.
334  *
335  * At least one of DATA, METADATA, FILTERED, or COW must be set for
336  * every child.
337  *
338  *
339  * = Connection with bs->children, bs->file and bs->backing fields =
340  *
341  * 1. Filters
342  *
343  * Filter drivers have drv->is_filter = true.
344  *
345  * Filter node has exactly one FILTERED|PRIMARY child, and may have other
346  * children which must not have these bits (one example is the
347  * copy-before-write filter, which also has its target DATA child).
348  *
349  * Filter nodes never have COW children.
350  *
351  * For most filters, the filtered child is linked in bs->file, bs->backing is
352  * NULL.  For some filters (as an exception), it is the other way around; those
353  * drivers will have drv->filtered_child_is_backing set to true (see that
354  * field’s documentation for what drivers this concerns)
355  *
356  * 2. "raw" driver (block/raw-format.c)
357  *
358  * Formally it's not a filter (drv->is_filter = false)
359  *
360  * bs->backing is always NULL
361  *
362  * Only has one child, linked in bs->file. Its role is either FILTERED|PRIMARY
363  * (like filter) or DATA|PRIMARY depending on options.
364  *
365  * 3. Other drivers
366  *
367  * Don't have any FILTERED children.
368  *
369  * May have at most one COW child. In this case it's linked in bs->backing.
370  * Otherwise bs->backing is NULL. COW child is never PRIMARY.
371  *
372  * May have at most one PRIMARY child. In this case it's linked in bs->file.
373  * Otherwise bs->file is NULL.
374  *
375  * May also have some other children that don't have the PRIMARY or COW bit set.
376  */
377 enum BdrvChildRoleBits {
378     /*
379      * This child stores data.
380      * Any node may have an arbitrary number of such children.
381      */
382     BDRV_CHILD_DATA         = (1 << 0),
383 
384     /*
385      * This child stores metadata.
386      * Any node may have an arbitrary number of metadata-storing
387      * children.
388      */
389     BDRV_CHILD_METADATA     = (1 << 1),
390 
391     /*
392      * A child that always presents exactly the same visible data as
393      * the parent, e.g. by virtue of the parent forwarding all reads
394      * and writes.
395      * This flag is mutually exclusive with DATA, METADATA, and COW.
396      * Any node may have at most one filtered child at a time.
397      */
398     BDRV_CHILD_FILTERED     = (1 << 2),
399 
400     /*
401      * Child from which to read all data that isn't allocated in the
402      * parent (i.e., the backing child); such data is copied to the
403      * parent through COW (and optionally COR).
404      * This field is mutually exclusive with DATA, METADATA, and
405      * FILTERED.
406      * Any node may have at most one such backing child at a time.
407      */
408     BDRV_CHILD_COW          = (1 << 3),
409 
410     /*
411      * The primary child.  For most drivers, this is the child whose
412      * filename applies best to the parent node.
413      * Any node may have at most one primary child at a time.
414      */
415     BDRV_CHILD_PRIMARY      = (1 << 4),
416 
417     /* Useful combination of flags */
418     BDRV_CHILD_IMAGE        = BDRV_CHILD_DATA
419                               | BDRV_CHILD_METADATA
420                               | BDRV_CHILD_PRIMARY,
421 };
422 
423 /* Mask of BdrvChildRoleBits values */
424 typedef unsigned int BdrvChildRole;
425 
426 typedef struct BdrvCheckResult {
427     int corruptions;
428     int leaks;
429     int check_errors;
430     int corruptions_fixed;
431     int leaks_fixed;
432     int64_t image_end_offset;
433     BlockFragInfo bfi;
434 } BdrvCheckResult;
435 
436 typedef enum {
437     BDRV_FIX_LEAKS    = 1,
438     BDRV_FIX_ERRORS   = 2,
439 } BdrvCheckMode;
440 
441 typedef struct BlockSizes {
442     uint32_t phys;
443     uint32_t log;
444 } BlockSizes;
445 
446 typedef struct HDGeometry {
447     uint32_t heads;
448     uint32_t sectors;
449     uint32_t cylinders;
450 } HDGeometry;
451 
452 /*
453  * Common functions that are neither I/O nor Global State.
454  *
455  * These functions must never call any function from other categories
456  * (I/O, "I/O or GS", Global State) except this one, but can be invoked by
457  * all of them.
458  */
459 
460 char *bdrv_perm_names(uint64_t perm);
461 uint64_t bdrv_qapi_perm_to_blk_perm(BlockPermission qapi_perm);
462 
463 void bdrv_init_with_whitelist(void);
464 bool bdrv_uses_whitelist(void);
465 int bdrv_is_whitelisted(BlockDriver *drv, bool read_only);
466 
467 int bdrv_parse_aio(const char *mode, int *flags);
468 int bdrv_parse_cache_mode(const char *mode, int *flags, bool *writethrough);
469 int bdrv_parse_discard_flags(const char *mode, int *flags);
470 
471 int path_has_protocol(const char *path);
472 int path_is_absolute(const char *path);
473 char *path_combine(const char *base_path, const char *filename);
474 
475 char *bdrv_get_full_backing_filename_from_filename(const char *backed,
476                                                    const char *backing,
477                                                    Error **errp);
478 
479 #endif /* BLOCK_COMMON_H */
480