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