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