xref: /qemu/include/block/block_int-common.h (revision 5e6f3db2)
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_INT_COMMON_H
25 #define BLOCK_INT_COMMON_H
26 
27 #include "block/aio.h"
28 #include "block/block-common.h"
29 #include "block/block-global-state.h"
30 #include "block/snapshot.h"
31 #include "qemu/iov.h"
32 #include "qemu/rcu.h"
33 #include "qemu/stats64.h"
34 
35 #define BLOCK_FLAG_LAZY_REFCOUNTS   8
36 
37 #define BLOCK_OPT_SIZE              "size"
38 #define BLOCK_OPT_ENCRYPT           "encryption"
39 #define BLOCK_OPT_ENCRYPT_FORMAT    "encrypt.format"
40 #define BLOCK_OPT_COMPAT6           "compat6"
41 #define BLOCK_OPT_HWVERSION         "hwversion"
42 #define BLOCK_OPT_BACKING_FILE      "backing_file"
43 #define BLOCK_OPT_BACKING_FMT       "backing_fmt"
44 #define BLOCK_OPT_CLUSTER_SIZE      "cluster_size"
45 #define BLOCK_OPT_TABLE_SIZE        "table_size"
46 #define BLOCK_OPT_PREALLOC          "preallocation"
47 #define BLOCK_OPT_SUBFMT            "subformat"
48 #define BLOCK_OPT_COMPAT_LEVEL      "compat"
49 #define BLOCK_OPT_LAZY_REFCOUNTS    "lazy_refcounts"
50 #define BLOCK_OPT_ADAPTER_TYPE      "adapter_type"
51 #define BLOCK_OPT_REDUNDANCY        "redundancy"
52 #define BLOCK_OPT_NOCOW             "nocow"
53 #define BLOCK_OPT_EXTENT_SIZE_HINT  "extent_size_hint"
54 #define BLOCK_OPT_OBJECT_SIZE       "object_size"
55 #define BLOCK_OPT_REFCOUNT_BITS     "refcount_bits"
56 #define BLOCK_OPT_DATA_FILE         "data_file"
57 #define BLOCK_OPT_DATA_FILE_RAW     "data_file_raw"
58 #define BLOCK_OPT_COMPRESSION_TYPE  "compression_type"
59 #define BLOCK_OPT_EXTL2             "extended_l2"
60 
61 #define BLOCK_PROBE_BUF_SIZE        512
62 
63 enum BdrvTrackedRequestType {
64     BDRV_TRACKED_READ,
65     BDRV_TRACKED_WRITE,
66     BDRV_TRACKED_DISCARD,
67     BDRV_TRACKED_TRUNCATE,
68 };
69 
70 /*
71  * That is not quite good that BdrvTrackedRequest structure is public,
72  * as block/io.c is very careful about incoming offset/bytes being
73  * correct. Be sure to assert bdrv_check_request() succeeded after any
74  * modification of BdrvTrackedRequest object out of block/io.c
75  */
76 typedef struct BdrvTrackedRequest {
77     BlockDriverState *bs;
78     int64_t offset;
79     int64_t bytes;
80     enum BdrvTrackedRequestType type;
81 
82     bool serialising;
83     int64_t overlap_offset;
84     int64_t overlap_bytes;
85 
86     QLIST_ENTRY(BdrvTrackedRequest) list;
87     Coroutine *co; /* owner, used for deadlock detection */
88     CoQueue wait_queue; /* coroutines blocked on this request */
89 
90     struct BdrvTrackedRequest *waiting_for;
91 } BdrvTrackedRequest;
92 
93 
94 struct BlockDriver {
95     /*
96      * These fields are initialized when this object is created,
97      * and are never changed afterwards.
98      */
99 
100     const char *format_name;
101     int instance_size;
102 
103     /*
104      * Set to true if the BlockDriver is a block filter. Block filters pass
105      * certain callbacks that refer to data (see block.c) to their bs->file
106      * or bs->backing (whichever one exists) if the driver doesn't implement
107      * them. Drivers that do not wish to forward must implement them and return
108      * -ENOTSUP.
109      * Note that filters are not allowed to modify data.
110      *
111      * Filters generally cannot have more than a single filtered child,
112      * because the data they present must at all times be the same as
113      * that on their filtered child.  That would be impossible to
114      * achieve for multiple filtered children.
115      * (And this filtered child must then be bs->file or bs->backing.)
116      */
117     bool is_filter;
118     /*
119      * Only make sense for filter drivers, for others must be false.
120      * If true, filtered child is bs->backing. Otherwise it's bs->file.
121      * Two internal filters use bs->backing as filtered child and has this
122      * field set to true: mirror_top and commit_top. There also two such test
123      * filters in tests/unit/test-bdrv-graph-mod.c.
124      *
125      * Never create any more such filters!
126      *
127      * TODO: imagine how to deprecate this behavior and make all filters work
128      * similarly using bs->file as filtered child.
129      */
130     bool filtered_child_is_backing;
131 
132     /*
133      * Set to true if the BlockDriver is a format driver.  Format nodes
134      * generally do not expect their children to be other format nodes
135      * (except for backing files), and so format probing is disabled
136      * on those children.
137      */
138     bool is_format;
139 
140     /*
141      * Set to true if the BlockDriver supports zoned children.
142      */
143     bool supports_zoned_children;
144 
145     /*
146      * Drivers not implementing bdrv_parse_filename nor bdrv_open should have
147      * this field set to true, except ones that are defined only by their
148      * child's bs.
149      * An example of the last type will be the quorum block driver.
150      */
151     bool bdrv_needs_filename;
152 
153     /*
154      * Set if a driver can support backing files. This also implies the
155      * following semantics:
156      *
157      *  - Return status 0 of .bdrv_co_block_status means that corresponding
158      *    blocks are not allocated in this layer of backing-chain
159      *  - For such (unallocated) blocks, read will:
160      *    - fill buffer with zeros if there is no backing file
161      *    - read from the backing file otherwise, where the block layer
162      *      takes care of reading zeros beyond EOF if backing file is short
163      */
164     bool supports_backing;
165 
166     /*
167      * Drivers setting this field must be able to work with just a plain
168      * filename with '<protocol_name>:' as a prefix, and no other options.
169      * Options may be extracted from the filename by implementing
170      * bdrv_parse_filename.
171      */
172     const char *protocol_name;
173 
174     /* List of options for creating images, terminated by name == NULL */
175     QemuOptsList *create_opts;
176 
177     /* List of options for image amend */
178     QemuOptsList *amend_opts;
179 
180     /*
181      * If this driver supports reopening images this contains a
182      * NULL-terminated list of the runtime options that can be
183      * modified. If an option in this list is unspecified during
184      * reopen then it _must_ be reset to its default value or return
185      * an error.
186      */
187     const char *const *mutable_opts;
188 
189     /*
190      * Pointer to a NULL-terminated array of names of strong options
191      * that can be specified for bdrv_open(). A strong option is one
192      * that changes the data of a BDS.
193      * If this pointer is NULL, the array is considered empty.
194      * "filename" and "driver" are always considered strong.
195      */
196     const char *const *strong_runtime_opts;
197 
198 
199     /*
200      * Global state (GS) API. These functions run under the BQL.
201      *
202      * See include/block/block-global-state.h for more information about
203      * the GS API.
204      */
205 
206     /*
207      * This function is invoked under BQL before .bdrv_co_amend()
208      * (which in contrast does not necessarily run under the BQL)
209      * to allow driver-specific initialization code that requires
210      * the BQL, like setting up specific permission flags.
211      */
212     int GRAPH_RDLOCK_PTR (*bdrv_amend_pre_run)(
213         BlockDriverState *bs, Error **errp);
214     /*
215      * This function is invoked under BQL after .bdrv_co_amend()
216      * to allow cleaning up what was done in .bdrv_amend_pre_run().
217      */
218     void GRAPH_RDLOCK_PTR (*bdrv_amend_clean)(BlockDriverState *bs);
219 
220     /*
221      * Return true if @to_replace can be replaced by a BDS with the
222      * same data as @bs without it affecting @bs's behavior (that is,
223      * without it being visible to @bs's parents).
224      */
225     bool GRAPH_RDLOCK_PTR (*bdrv_recurse_can_replace)(
226         BlockDriverState *bs, BlockDriverState *to_replace);
227 
228     int (*bdrv_probe_device)(const char *filename);
229 
230     /*
231      * Any driver implementing this callback is expected to be able to handle
232      * NULL file names in its .bdrv_open() implementation.
233      */
234     void (*bdrv_parse_filename)(const char *filename, QDict *options,
235                                 Error **errp);
236 
237     /* For handling image reopen for split or non-split files. */
238     int (*bdrv_reopen_prepare)(BDRVReopenState *reopen_state,
239                                BlockReopenQueue *queue, Error **errp);
240     void (*bdrv_reopen_commit)(BDRVReopenState *reopen_state);
241     void (*bdrv_reopen_commit_post)(BDRVReopenState *reopen_state);
242     void (*bdrv_reopen_abort)(BDRVReopenState *reopen_state);
243     void (*bdrv_join_options)(QDict *options, QDict *old_options);
244 
245     int GRAPH_UNLOCKED_PTR (*bdrv_open)(
246         BlockDriverState *bs, QDict *options, int flags, Error **errp);
247 
248     /* Protocol drivers should implement this instead of bdrv_open */
249     int GRAPH_UNLOCKED_PTR (*bdrv_file_open)(
250         BlockDriverState *bs, QDict *options, int flags, Error **errp);
251     void (*bdrv_close)(BlockDriverState *bs);
252 
253     int coroutine_fn GRAPH_UNLOCKED_PTR (*bdrv_co_create)(
254         BlockdevCreateOptions *opts, Error **errp);
255 
256     int coroutine_fn GRAPH_UNLOCKED_PTR (*bdrv_co_create_opts)(
257         BlockDriver *drv, const char *filename, QemuOpts *opts, Error **errp);
258 
259     int (*bdrv_amend_options)(BlockDriverState *bs,
260                               QemuOpts *opts,
261                               BlockDriverAmendStatusCB *status_cb,
262                               void *cb_opaque,
263                               bool force,
264                               Error **errp);
265 
266     int (*bdrv_make_empty)(BlockDriverState *bs);
267 
268     /*
269      * Refreshes the bs->exact_filename field. If that is impossible,
270      * bs->exact_filename has to be left empty.
271      */
272     void (*bdrv_refresh_filename)(BlockDriverState *bs);
273 
274     /*
275      * Gathers the open options for all children into @target.
276      * A simple format driver (without backing file support) might
277      * implement this function like this:
278      *
279      *     QINCREF(bs->file->bs->full_open_options);
280      *     qdict_put(target, "file", bs->file->bs->full_open_options);
281      *
282      * If not specified, the generic implementation will simply put
283      * all children's options under their respective name.
284      *
285      * @backing_overridden is true when bs->backing seems not to be
286      * the child that would result from opening bs->backing_file.
287      * Therefore, if it is true, the backing child's options should be
288      * gathered; otherwise, there is no need since the backing child
289      * is the one implied by the image header.
290      *
291      * Note that ideally this function would not be needed.  Every
292      * block driver which implements it is probably doing something
293      * shady regarding its runtime option structure.
294      */
295     void (*bdrv_gather_child_options)(BlockDriverState *bs, QDict *target,
296                                       bool backing_overridden);
297 
298     /*
299      * Returns an allocated string which is the directory name of this BDS: It
300      * will be used to make relative filenames absolute by prepending this
301      * function's return value to them.
302      */
303     char *(*bdrv_dirname)(BlockDriverState *bs, Error **errp);
304 
305     /*
306      * This informs the driver that we are no longer interested in the result
307      * of in-flight requests, so don't waste the time if possible.
308      *
309      * One example usage is to avoid waiting for an nbd target node reconnect
310      * timeout during job-cancel with force=true.
311      */
312     void (*bdrv_cancel_in_flight)(BlockDriverState *bs);
313 
314     int (*bdrv_inactivate)(BlockDriverState *bs);
315 
316     int (*bdrv_snapshot_create)(BlockDriverState *bs,
317                                 QEMUSnapshotInfo *sn_info);
318     int (*bdrv_snapshot_goto)(BlockDriverState *bs,
319                               const char *snapshot_id);
320     int (*bdrv_snapshot_delete)(BlockDriverState *bs,
321                                 const char *snapshot_id,
322                                 const char *name,
323                                 Error **errp);
324     int (*bdrv_snapshot_list)(BlockDriverState *bs,
325                               QEMUSnapshotInfo **psn_info);
326     int (*bdrv_snapshot_load_tmp)(BlockDriverState *bs,
327                                   const char *snapshot_id,
328                                   const char *name,
329                                   Error **errp);
330 
331     int (*bdrv_change_backing_file)(BlockDriverState *bs,
332         const char *backing_file, const char *backing_fmt);
333 
334     /* TODO Better pass a option string/QDict/QemuOpts to add any rule? */
335     int (*bdrv_debug_breakpoint)(BlockDriverState *bs, const char *event,
336         const char *tag);
337     int (*bdrv_debug_remove_breakpoint)(BlockDriverState *bs,
338         const char *tag);
339     int (*bdrv_debug_resume)(BlockDriverState *bs, const char *tag);
340     bool (*bdrv_debug_is_suspended)(BlockDriverState *bs, const char *tag);
341 
342     void GRAPH_RDLOCK_PTR (*bdrv_refresh_limits)(
343         BlockDriverState *bs, Error **errp);
344 
345     /*
346      * Returns 1 if newly created images are guaranteed to contain only
347      * zeros, 0 otherwise.
348      */
349     int (*bdrv_has_zero_init)(BlockDriverState *bs);
350 
351     /*
352      * Remove fd handlers, timers, and other event loop callbacks so the event
353      * loop is no longer in use.  Called with no in-flight requests and in
354      * depth-first traversal order with parents before child nodes.
355      */
356     void (*bdrv_detach_aio_context)(BlockDriverState *bs);
357 
358     /*
359      * Add fd handlers, timers, and other event loop callbacks so I/O requests
360      * can be processed again.  Called with no in-flight requests and in
361      * depth-first traversal order with child nodes before parent nodes.
362      */
363     void (*bdrv_attach_aio_context)(BlockDriverState *bs,
364                                     AioContext *new_context);
365 
366     /**
367      * bdrv_drain_begin is called if implemented in the beginning of a
368      * drain operation to drain and stop any internal sources of requests in
369      * the driver.
370      * bdrv_drain_end is called if implemented at the end of the drain.
371      *
372      * They should be used by the driver to e.g. manage scheduled I/O
373      * requests, or toggle an internal state. After the end of the drain new
374      * requests will continue normally.
375      *
376      * Implementations of both functions must not call aio_poll().
377      */
378     void (*bdrv_drain_begin)(BlockDriverState *bs);
379     void (*bdrv_drain_end)(BlockDriverState *bs);
380 
381     /**
382      * Try to get @bs's logical and physical block size.
383      * On success, store them in @bsz and return zero.
384      * On failure, return negative errno.
385      */
386     int (*bdrv_probe_blocksizes)(BlockDriverState *bs, BlockSizes *bsz);
387     /**
388      * Try to get @bs's geometry (cyls, heads, sectors)
389      * On success, store them in @geo and return 0.
390      * On failure return -errno.
391      * Only drivers that want to override guest geometry implement this
392      * callback; see hd_geometry_guess().
393      */
394     int (*bdrv_probe_geometry)(BlockDriverState *bs, HDGeometry *geo);
395 
396     void (*bdrv_add_child)(BlockDriverState *parent, BlockDriverState *child,
397                            Error **errp);
398     void (*bdrv_del_child)(BlockDriverState *parent, BdrvChild *child,
399                            Error **errp);
400 
401     /**
402      * Informs the block driver that a permission change is intended. The
403      * driver checks whether the change is permissible and may take other
404      * preparations for the change (e.g. get file system locks). This operation
405      * is always followed either by a call to either .bdrv_set_perm or
406      * .bdrv_abort_perm_update.
407      *
408      * Checks whether the requested set of cumulative permissions in @perm
409      * can be granted for accessing @bs and whether no other users are using
410      * permissions other than those given in @shared (both arguments take
411      * BLK_PERM_* bitmasks).
412      *
413      * If both conditions are met, 0 is returned. Otherwise, -errno is returned
414      * and errp is set to an error describing the conflict.
415      */
416     int (*bdrv_check_perm)(BlockDriverState *bs, uint64_t perm,
417                            uint64_t shared, Error **errp);
418 
419     /**
420      * Called to inform the driver that the set of cumulative set of used
421      * permissions for @bs has changed to @perm, and the set of shareable
422      * permission to @shared. The driver can use this to propagate changes to
423      * its children (i.e. request permissions only if a parent actually needs
424      * them).
425      *
426      * This function is only invoked after bdrv_check_perm(), so block drivers
427      * may rely on preparations made in their .bdrv_check_perm implementation.
428      */
429     void (*bdrv_set_perm)(BlockDriverState *bs, uint64_t perm, uint64_t shared);
430 
431     /*
432      * Called to inform the driver that after a previous bdrv_check_perm()
433      * call, the permission update is not performed and any preparations made
434      * for it (e.g. taken file locks) need to be undone.
435      *
436      * This function can be called even for nodes that never saw a
437      * bdrv_check_perm() call. It is a no-op then.
438      */
439     void (*bdrv_abort_perm_update)(BlockDriverState *bs);
440 
441     /**
442      * Returns in @nperm and @nshared the permissions that the driver for @bs
443      * needs on its child @c, based on the cumulative permissions requested by
444      * the parents in @parent_perm and @parent_shared.
445      *
446      * If @c is NULL, return the permissions for attaching a new child for the
447      * given @child_class and @role.
448      *
449      * If @reopen_queue is non-NULL, don't return the currently needed
450      * permissions, but those that will be needed after applying the
451      * @reopen_queue.
452      */
453      void (*bdrv_child_perm)(BlockDriverState *bs, BdrvChild *c,
454                              BdrvChildRole role,
455                              BlockReopenQueue *reopen_queue,
456                              uint64_t parent_perm, uint64_t parent_shared,
457                              uint64_t *nperm, uint64_t *nshared);
458 
459     /**
460      * Register/unregister a buffer for I/O. For example, when the driver is
461      * interested to know the memory areas that will later be used in iovs, so
462      * that it can do IOMMU mapping with VFIO etc., in order to get better
463      * performance. In the case of VFIO drivers, this callback is used to do
464      * DMA mapping for hot buffers.
465      *
466      * Returns: true on success, false on failure
467      */
468     bool GRAPH_RDLOCK_PTR (*bdrv_register_buf)(
469         BlockDriverState *bs, void *host, size_t size, Error **errp);
470     void GRAPH_RDLOCK_PTR (*bdrv_unregister_buf)(
471         BlockDriverState *bs, void *host, size_t size);
472 
473     /*
474      * This field is modified only under the BQL, and is part of
475      * the global state.
476      */
477     QLIST_ENTRY(BlockDriver) list;
478 
479     /*
480      * I/O API functions. These functions are thread-safe.
481      *
482      * See include/block/block-io.h for more information about
483      * the I/O API.
484      */
485 
486     int (*bdrv_probe)(const uint8_t *buf, int buf_size, const char *filename);
487 
488     int coroutine_fn GRAPH_RDLOCK_PTR (*bdrv_co_amend)(
489         BlockDriverState *bs, BlockdevAmendOptions *opts, bool force,
490         Error **errp);
491 
492     /* aio */
493     BlockAIOCB * GRAPH_RDLOCK_PTR (*bdrv_aio_preadv)(BlockDriverState *bs,
494         int64_t offset, int64_t bytes, QEMUIOVector *qiov,
495         BdrvRequestFlags flags, BlockCompletionFunc *cb, void *opaque);
496 
497     BlockAIOCB * GRAPH_RDLOCK_PTR (*bdrv_aio_pwritev)(BlockDriverState *bs,
498         int64_t offset, int64_t bytes, QEMUIOVector *qiov,
499         BdrvRequestFlags flags, BlockCompletionFunc *cb, void *opaque);
500 
501     BlockAIOCB * GRAPH_RDLOCK_PTR (*bdrv_aio_flush)(
502         BlockDriverState *bs, BlockCompletionFunc *cb, void *opaque);
503 
504     BlockAIOCB * GRAPH_RDLOCK_PTR (*bdrv_aio_pdiscard)(
505         BlockDriverState *bs, int64_t offset, int bytes,
506         BlockCompletionFunc *cb, void *opaque);
507 
508     int coroutine_fn GRAPH_RDLOCK_PTR (*bdrv_co_readv)(BlockDriverState *bs,
509         int64_t sector_num, int nb_sectors, QEMUIOVector *qiov);
510 
511     /**
512      * @offset: position in bytes to read at
513      * @bytes: number of bytes to read
514      * @qiov: the buffers to fill with read data
515      * @flags: currently unused, always 0
516      *
517      * @offset and @bytes will be a multiple of 'request_alignment',
518      * but the length of individual @qiov elements does not have to
519      * be a multiple.
520      *
521      * @bytes will always equal the total size of @qiov, and will be
522      * no larger than 'max_transfer'.
523      *
524      * The buffer in @qiov may point directly to guest memory.
525      */
526     int coroutine_fn GRAPH_RDLOCK_PTR (*bdrv_co_preadv)(BlockDriverState *bs,
527         int64_t offset, int64_t bytes, QEMUIOVector *qiov,
528         BdrvRequestFlags flags);
529 
530     int coroutine_fn GRAPH_RDLOCK_PTR (*bdrv_co_preadv_part)(
531         BlockDriverState *bs, int64_t offset, int64_t bytes,
532         QEMUIOVector *qiov, size_t qiov_offset,
533         BdrvRequestFlags flags);
534 
535     int coroutine_fn GRAPH_RDLOCK_PTR (*bdrv_co_writev)(BlockDriverState *bs,
536         int64_t sector_num, int nb_sectors, QEMUIOVector *qiov,
537         int flags);
538     /**
539      * @offset: position in bytes to write at
540      * @bytes: number of bytes to write
541      * @qiov: the buffers containing data to write
542      * @flags: zero or more bits allowed by 'supported_write_flags'
543      *
544      * @offset and @bytes will be a multiple of 'request_alignment',
545      * but the length of individual @qiov elements does not have to
546      * be a multiple.
547      *
548      * @bytes will always equal the total size of @qiov, and will be
549      * no larger than 'max_transfer'.
550      *
551      * The buffer in @qiov may point directly to guest memory.
552      */
553     int coroutine_fn GRAPH_RDLOCK_PTR (*bdrv_co_pwritev)(
554         BlockDriverState *bs, int64_t offset, int64_t bytes, QEMUIOVector *qiov,
555         BdrvRequestFlags flags);
556     int coroutine_fn GRAPH_RDLOCK_PTR (*bdrv_co_pwritev_part)(
557         BlockDriverState *bs, int64_t offset, int64_t bytes, QEMUIOVector *qiov,
558         size_t qiov_offset, BdrvRequestFlags flags);
559 
560     /*
561      * Efficiently zero a region of the disk image.  Typically an image format
562      * would use a compact metadata representation to implement this.  This
563      * function pointer may be NULL or return -ENOSUP and .bdrv_co_writev()
564      * will be called instead.
565      */
566     int coroutine_fn GRAPH_RDLOCK_PTR (*bdrv_co_pwrite_zeroes)(
567         BlockDriverState *bs, int64_t offset, int64_t bytes,
568         BdrvRequestFlags flags);
569 
570     int coroutine_fn GRAPH_RDLOCK_PTR (*bdrv_co_pdiscard)(
571         BlockDriverState *bs, int64_t offset, int64_t bytes);
572 
573     /*
574      * Map [offset, offset + nbytes) range onto a child of @bs to copy from,
575      * and invoke bdrv_co_copy_range_from(child, ...), or invoke
576      * bdrv_co_copy_range_to() if @bs is the leaf child to copy data from.
577      *
578      * See the comment of bdrv_co_copy_range for the parameter and return value
579      * semantics.
580      */
581     int coroutine_fn GRAPH_RDLOCK_PTR (*bdrv_co_copy_range_from)(
582         BlockDriverState *bs, BdrvChild *src, int64_t offset,
583         BdrvChild *dst, int64_t dst_offset, int64_t bytes,
584         BdrvRequestFlags read_flags, BdrvRequestFlags write_flags);
585 
586     /*
587      * Map [offset, offset + nbytes) range onto a child of bs to copy data to,
588      * and invoke bdrv_co_copy_range_to(child, src, ...), or perform the copy
589      * operation if @bs is the leaf and @src has the same BlockDriver.  Return
590      * -ENOTSUP if @bs is the leaf but @src has a different BlockDriver.
591      *
592      * See the comment of bdrv_co_copy_range for the parameter and return value
593      * semantics.
594      */
595     int coroutine_fn GRAPH_RDLOCK_PTR (*bdrv_co_copy_range_to)(
596         BlockDriverState *bs, BdrvChild *src, int64_t src_offset,
597         BdrvChild *dst, int64_t dst_offset, int64_t bytes,
598         BdrvRequestFlags read_flags, BdrvRequestFlags write_flags);
599 
600     /*
601      * Building block for bdrv_block_status[_above] and
602      * bdrv_is_allocated[_above].  The driver should answer only
603      * according to the current layer, and should only need to set
604      * BDRV_BLOCK_DATA, BDRV_BLOCK_ZERO, BDRV_BLOCK_OFFSET_VALID,
605      * and/or BDRV_BLOCK_RAW; if the current layer defers to a backing
606      * layer, the result should be 0 (and not BDRV_BLOCK_ZERO).  See
607      * block.h for the overall meaning of the bits.  As a hint, the
608      * flag want_zero is true if the caller cares more about precise
609      * mappings (favor accurate _OFFSET_VALID/_ZERO) or false for
610      * overall allocation (favor larger *pnum, perhaps by reporting
611      * _DATA instead of _ZERO).  The block layer guarantees input
612      * clamped to bdrv_getlength() and aligned to request_alignment,
613      * as well as non-NULL pnum, map, and file; in turn, the driver
614      * must return an error or set pnum to an aligned non-zero value.
615      *
616      * Note that @bytes is just a hint on how big of a region the
617      * caller wants to inspect.  It is not a limit on *pnum.
618      * Implementations are free to return larger values of *pnum if
619      * doing so does not incur a performance penalty.
620      *
621      * block/io.c's bdrv_co_block_status() will utilize an unclamped
622      * *pnum value for the block-status cache on protocol nodes, prior
623      * to clamping *pnum for return to its caller.
624      */
625     int coroutine_fn GRAPH_RDLOCK_PTR (*bdrv_co_block_status)(
626         BlockDriverState *bs,
627         bool want_zero, int64_t offset, int64_t bytes, int64_t *pnum,
628         int64_t *map, BlockDriverState **file);
629 
630     /*
631      * Snapshot-access API.
632      *
633      * Block-driver may provide snapshot-access API: special functions to access
634      * some internal "snapshot". The functions are similar with normal
635      * read/block_status/discard handler, but don't have any specific handling
636      * in generic block-layer: no serializing, no alignment, no tracked
637      * requests. So, block-driver that realizes these APIs is fully responsible
638      * for synchronization between snapshot-access API and normal IO requests.
639      *
640      * TODO: To be able to support qcow2's internal snapshots, this API will
641      * need to be extended to:
642      * - be able to select a specific snapshot
643      * - receive the snapshot's actual length (which may differ from bs's
644      *   length)
645      */
646     int coroutine_fn GRAPH_RDLOCK_PTR (*bdrv_co_preadv_snapshot)(
647         BlockDriverState *bs, int64_t offset, int64_t bytes,
648         QEMUIOVector *qiov, size_t qiov_offset);
649 
650     int coroutine_fn GRAPH_RDLOCK_PTR (*bdrv_co_snapshot_block_status)(
651         BlockDriverState *bs, bool want_zero, int64_t offset, int64_t bytes,
652         int64_t *pnum, int64_t *map, BlockDriverState **file);
653 
654     int coroutine_fn GRAPH_RDLOCK_PTR (*bdrv_co_pdiscard_snapshot)(
655         BlockDriverState *bs, int64_t offset, int64_t bytes);
656 
657     /*
658      * Invalidate any cached meta-data.
659      */
660     void coroutine_fn GRAPH_RDLOCK_PTR (*bdrv_co_invalidate_cache)(
661         BlockDriverState *bs, Error **errp);
662 
663     /*
664      * Flushes all data for all layers by calling bdrv_co_flush for underlying
665      * layers, if needed. This function is needed for deterministic
666      * synchronization of the flush finishing callback.
667      */
668     int coroutine_fn GRAPH_RDLOCK_PTR (*bdrv_co_flush)(BlockDriverState *bs);
669 
670     /* Delete a created file. */
671     int coroutine_fn GRAPH_RDLOCK_PTR (*bdrv_co_delete_file)(
672         BlockDriverState *bs, Error **errp);
673 
674     /*
675      * Flushes all data that was already written to the OS all the way down to
676      * the disk (for example file-posix.c calls fsync()).
677      */
678     int coroutine_fn GRAPH_RDLOCK_PTR (*bdrv_co_flush_to_disk)(
679         BlockDriverState *bs);
680 
681     /*
682      * Flushes all internal caches to the OS. The data may still sit in a
683      * writeback cache of the host OS, but it will survive a crash of the qemu
684      * process.
685      */
686     int coroutine_fn GRAPH_RDLOCK_PTR (*bdrv_co_flush_to_os)(
687         BlockDriverState *bs);
688 
689     /*
690      * Truncate @bs to @offset bytes using the given @prealloc mode
691      * when growing.  Modes other than PREALLOC_MODE_OFF should be
692      * rejected when shrinking @bs.
693      *
694      * If @exact is true, @bs must be resized to exactly @offset.
695      * Otherwise, it is sufficient for @bs (if it is a host block
696      * device and thus there is no way to resize it) to be at least
697      * @offset bytes in length.
698      *
699      * If @exact is true and this function fails but would succeed
700      * with @exact = false, it should return -ENOTSUP.
701      */
702     int coroutine_fn GRAPH_RDLOCK_PTR (*bdrv_co_truncate)(
703         BlockDriverState *bs, int64_t offset, bool exact,
704         PreallocMode prealloc, BdrvRequestFlags flags, Error **errp);
705 
706     int64_t coroutine_fn GRAPH_RDLOCK_PTR (*bdrv_co_getlength)(
707         BlockDriverState *bs);
708 
709     int64_t coroutine_fn GRAPH_RDLOCK_PTR (*bdrv_co_get_allocated_file_size)(
710         BlockDriverState *bs);
711 
712     BlockMeasureInfo *(*bdrv_measure)(QemuOpts *opts, BlockDriverState *in_bs,
713                                       Error **errp);
714 
715     int coroutine_fn GRAPH_RDLOCK_PTR (*bdrv_co_pwritev_compressed)(
716         BlockDriverState *bs, int64_t offset, int64_t bytes,
717         QEMUIOVector *qiov);
718 
719     int coroutine_fn GRAPH_RDLOCK_PTR (*bdrv_co_pwritev_compressed_part)(
720         BlockDriverState *bs, int64_t offset, int64_t bytes,
721         QEMUIOVector *qiov, size_t qiov_offset);
722 
723     int coroutine_fn GRAPH_RDLOCK_PTR (*bdrv_co_get_info)(
724         BlockDriverState *bs, BlockDriverInfo *bdi);
725 
726     ImageInfoSpecific *(*bdrv_get_specific_info)(BlockDriverState *bs,
727                                                  Error **errp);
728     BlockStatsSpecific *(*bdrv_get_specific_stats)(BlockDriverState *bs);
729 
730     int coroutine_fn GRAPH_RDLOCK_PTR (*bdrv_co_save_vmstate)(
731         BlockDriverState *bs, QEMUIOVector *qiov, int64_t pos);
732 
733     int coroutine_fn GRAPH_RDLOCK_PTR (*bdrv_co_load_vmstate)(
734         BlockDriverState *bs, QEMUIOVector *qiov, int64_t pos);
735 
736     int coroutine_fn (*bdrv_co_zone_report)(BlockDriverState *bs,
737             int64_t offset, unsigned int *nr_zones,
738             BlockZoneDescriptor *zones);
739     int coroutine_fn (*bdrv_co_zone_mgmt)(BlockDriverState *bs, BlockZoneOp op,
740             int64_t offset, int64_t len);
741     int coroutine_fn (*bdrv_co_zone_append)(BlockDriverState *bs,
742             int64_t *offset, QEMUIOVector *qiov,
743             BdrvRequestFlags flags);
744 
745     /* removable device specific */
746     bool coroutine_fn GRAPH_RDLOCK_PTR (*bdrv_co_is_inserted)(
747         BlockDriverState *bs);
748     void coroutine_fn GRAPH_RDLOCK_PTR (*bdrv_co_eject)(
749         BlockDriverState *bs, bool eject_flag);
750     void coroutine_fn GRAPH_RDLOCK_PTR (*bdrv_co_lock_medium)(
751         BlockDriverState *bs, bool locked);
752 
753     /* to control generic scsi devices */
754     BlockAIOCB *coroutine_fn GRAPH_RDLOCK_PTR (*bdrv_aio_ioctl)(
755         BlockDriverState *bs, unsigned long int req, void *buf,
756         BlockCompletionFunc *cb, void *opaque);
757 
758     int coroutine_fn GRAPH_RDLOCK_PTR (*bdrv_co_ioctl)(
759         BlockDriverState *bs, unsigned long int req, void *buf);
760 
761     /*
762      * Returns 0 for completed check, -errno for internal errors.
763      * The check results are stored in result.
764      */
765     int coroutine_fn GRAPH_RDLOCK_PTR (*bdrv_co_check)(
766         BlockDriverState *bs, BdrvCheckResult *result, BdrvCheckMode fix);
767 
768     void coroutine_fn GRAPH_RDLOCK_PTR (*bdrv_co_debug_event)(
769         BlockDriverState *bs, BlkdebugEvent event);
770 
771     bool (*bdrv_supports_persistent_dirty_bitmap)(BlockDriverState *bs);
772 
773     bool coroutine_fn GRAPH_RDLOCK_PTR (*bdrv_co_can_store_new_dirty_bitmap)(
774         BlockDriverState *bs, const char *name, uint32_t granularity,
775         Error **errp);
776 
777     int coroutine_fn GRAPH_RDLOCK_PTR (*bdrv_co_remove_persistent_dirty_bitmap)(
778         BlockDriverState *bs, const char *name, Error **errp);
779 };
780 
781 static inline bool TSA_NO_TSA block_driver_can_compress(BlockDriver *drv)
782 {
783     return drv->bdrv_co_pwritev_compressed ||
784            drv->bdrv_co_pwritev_compressed_part;
785 }
786 
787 typedef struct BlockLimits {
788     /*
789      * Alignment requirement, in bytes, for offset/length of I/O
790      * requests. Must be a power of 2 less than INT_MAX; defaults to
791      * 1 for drivers with modern byte interfaces, and to 512
792      * otherwise.
793      */
794     uint32_t request_alignment;
795 
796     /*
797      * Maximum number of bytes that can be discarded at once. Must be multiple
798      * of pdiscard_alignment, but need not be power of 2. May be 0 if no
799      * inherent 64-bit limit.
800      */
801     int64_t max_pdiscard;
802 
803     /*
804      * Optimal alignment for discard requests in bytes. A power of 2
805      * is best but not mandatory.  Must be a multiple of
806      * bl.request_alignment, and must be less than max_pdiscard if
807      * that is set. May be 0 if bl.request_alignment is good enough
808      */
809     uint32_t pdiscard_alignment;
810 
811     /*
812      * Maximum number of bytes that can zeroized at once. Must be multiple of
813      * pwrite_zeroes_alignment. 0 means no limit.
814      */
815     int64_t max_pwrite_zeroes;
816 
817     /*
818      * Optimal alignment for write zeroes requests in bytes. A power
819      * of 2 is best but not mandatory.  Must be a multiple of
820      * bl.request_alignment, and must be less than max_pwrite_zeroes
821      * if that is set. May be 0 if bl.request_alignment is good
822      * enough
823      */
824     uint32_t pwrite_zeroes_alignment;
825 
826     /*
827      * Optimal transfer length in bytes.  A power of 2 is best but not
828      * mandatory.  Must be a multiple of bl.request_alignment, or 0 if
829      * no preferred size
830      */
831     uint32_t opt_transfer;
832 
833     /*
834      * Maximal transfer length in bytes.  Need not be power of 2, but
835      * must be multiple of opt_transfer and bl.request_alignment, or 0
836      * for no 32-bit limit.  For now, anything larger than INT_MAX is
837      * clamped down.
838      */
839     uint32_t max_transfer;
840 
841     /*
842      * Maximal hardware transfer length in bytes.  Applies whenever
843      * transfers to the device bypass the kernel I/O scheduler, for
844      * example with SG_IO.  If larger than max_transfer or if zero,
845      * blk_get_max_hw_transfer will fall back to max_transfer.
846      */
847     uint64_t max_hw_transfer;
848 
849     /*
850      * Maximal number of scatter/gather elements allowed by the hardware.
851      * Applies whenever transfers to the device bypass the kernel I/O
852      * scheduler, for example with SG_IO.  If larger than max_iov
853      * or if zero, blk_get_max_hw_iov will fall back to max_iov.
854      */
855     int max_hw_iov;
856 
857 
858     /* memory alignment, in bytes so that no bounce buffer is needed */
859     size_t min_mem_alignment;
860 
861     /* memory alignment, in bytes, for bounce buffer */
862     size_t opt_mem_alignment;
863 
864     /* maximum number of iovec elements */
865     int max_iov;
866 
867     /*
868      * true if the length of the underlying file can change, and QEMU
869      * is expected to adjust automatically.  Mostly for CD-ROM drives,
870      * whose length is zero when the tray is empty (they don't need
871      * an explicit monitor command to load the disk inside the guest).
872      */
873     bool has_variable_length;
874 
875     /* device zone model */
876     BlockZoneModel zoned;
877 
878     /* zone size expressed in bytes */
879     uint32_t zone_size;
880 
881     /* total number of zones */
882     uint32_t nr_zones;
883 
884     /* maximum sectors of a zone append write operation */
885     uint32_t max_append_sectors;
886 
887     /* maximum number of open zones */
888     uint32_t max_open_zones;
889 
890     /* maximum number of active zones */
891     uint32_t max_active_zones;
892 
893     uint32_t write_granularity;
894 } BlockLimits;
895 
896 typedef struct BdrvOpBlocker BdrvOpBlocker;
897 
898 typedef struct BdrvAioNotifier {
899     void (*attached_aio_context)(AioContext *new_context, void *opaque);
900     void (*detach_aio_context)(void *opaque);
901 
902     void *opaque;
903     bool deleted;
904 
905     QLIST_ENTRY(BdrvAioNotifier) list;
906 } BdrvAioNotifier;
907 
908 struct BdrvChildClass {
909     /*
910      * If true, bdrv_replace_node() doesn't change the node this BdrvChild
911      * points to.
912      */
913     bool stay_at_node;
914 
915     /*
916      * If true, the parent is a BlockDriverState and bdrv_next_all_states()
917      * will return it. This information is used for drain_all, where every node
918      * will be drained separately, so the drain only needs to be propagated to
919      * non-BDS parents.
920      */
921     bool parent_is_bds;
922 
923     /*
924      * Global state (GS) API. These functions run under the BQL.
925      *
926      * See include/block/block-global-state.h for more information about
927      * the GS API.
928      */
929     void (*inherit_options)(BdrvChildRole role, bool parent_is_format,
930                             int *child_flags, QDict *child_options,
931                             int parent_flags, QDict *parent_options);
932     void (*change_media)(BdrvChild *child, bool load);
933 
934     /*
935      * Returns a malloced string that describes the parent of the child for a
936      * human reader. This could be a node-name, BlockBackend name, qdev ID or
937      * QOM path of the device owning the BlockBackend, job type and ID etc. The
938      * caller is responsible for freeing the memory.
939      */
940     char *(*get_parent_desc)(BdrvChild *child);
941 
942     /*
943      * Notifies the parent that the child has been activated/inactivated (e.g.
944      * when migration is completing) and it can start/stop requesting
945      * permissions and doing I/O on it.
946      */
947     void (*activate)(BdrvChild *child, Error **errp);
948     int (*inactivate)(BdrvChild *child);
949 
950     void GRAPH_WRLOCK_PTR (*attach)(BdrvChild *child);
951     void GRAPH_WRLOCK_PTR (*detach)(BdrvChild *child);
952 
953     /*
954      * If this pair of functions is implemented, the parent doesn't issue new
955      * requests after returning from .drained_begin() until .drained_end() is
956      * called.
957      *
958      * These functions must not change the graph (and therefore also must not
959      * call aio_poll(), which could change the graph indirectly).
960      *
961      * Note that this can be nested. If drained_begin() was called twice, new
962      * I/O is allowed only after drained_end() was called twice, too.
963      */
964     void (*drained_begin)(BdrvChild *child);
965     void (*drained_end)(BdrvChild *child);
966 
967     /*
968      * Returns whether the parent has pending requests for the child. This
969      * callback is polled after .drained_begin() has been called until all
970      * activity on the child has stopped.
971      */
972     bool (*drained_poll)(BdrvChild *child);
973 
974     /*
975      * Notifies the parent that the filename of its child has changed (e.g.
976      * because the direct child was removed from the backing chain), so that it
977      * can update its reference.
978      */
979     int (*update_filename)(BdrvChild *child, BlockDriverState *new_base,
980                            const char *filename, Error **errp);
981 
982     bool (*change_aio_ctx)(BdrvChild *child, AioContext *ctx,
983                            GHashTable *visited, Transaction *tran,
984                            Error **errp);
985 
986     /*
987      * I/O API functions. These functions are thread-safe.
988      *
989      * See include/block/block-io.h for more information about
990      * the I/O API.
991      */
992 
993     void (*resize)(BdrvChild *child);
994 
995     /*
996      * Returns a name that is supposedly more useful for human users than the
997      * node name for identifying the node in question (in particular, a BB
998      * name), or NULL if the parent can't provide a better name.
999      */
1000     const char *(*get_name)(BdrvChild *child);
1001 
1002     AioContext *(*get_parent_aio_context)(BdrvChild *child);
1003 };
1004 
1005 extern const BdrvChildClass child_of_bds;
1006 
1007 struct BdrvChild {
1008     BlockDriverState *bs;
1009     char *name;
1010     const BdrvChildClass *klass;
1011     BdrvChildRole role;
1012     void *opaque;
1013 
1014     /**
1015      * Granted permissions for operating on this BdrvChild (BLK_PERM_* bitmask)
1016      */
1017     uint64_t perm;
1018 
1019     /**
1020      * Permissions that can still be granted to other users of @bs while this
1021      * BdrvChild is still attached to it. (BLK_PERM_* bitmask)
1022      */
1023     uint64_t shared_perm;
1024 
1025     /*
1026      * This link is frozen: the child can neither be replaced nor
1027      * detached from the parent.
1028      */
1029     bool frozen;
1030 
1031     /*
1032      * True if the parent of this child has been drained by this BdrvChild
1033      * (through klass->drained_*).
1034      *
1035      * It is generally true if bs->quiesce_counter > 0. It may differ while the
1036      * child is entering or leaving a drained section.
1037      */
1038     bool quiesced_parent;
1039 
1040     QLIST_ENTRY(BdrvChild) next;
1041     QLIST_ENTRY(BdrvChild) next_parent;
1042 };
1043 
1044 /*
1045  * Allows bdrv_co_block_status() to cache one data region for a
1046  * protocol node.
1047  *
1048  * @valid: Whether the cache is valid (should be accessed with atomic
1049  *         functions so this can be reset by RCU readers)
1050  * @data_start: Offset where we know (or strongly assume) is data
1051  * @data_end: Offset where the data region ends (which is not necessarily
1052  *            the start of a zeroed region)
1053  */
1054 typedef struct BdrvBlockStatusCache {
1055     struct rcu_head rcu;
1056 
1057     bool valid;
1058     int64_t data_start;
1059     int64_t data_end;
1060 } BdrvBlockStatusCache;
1061 
1062 struct BlockDriverState {
1063     /*
1064      * Protected by big QEMU lock or read-only after opening.  No special
1065      * locking needed during I/O...
1066      */
1067     int open_flags; /* flags used to open the file, re-used for re-open */
1068     bool encrypted; /* if true, the media is encrypted */
1069     bool sg;        /* if true, the device is a /dev/sg* */
1070     bool probed;    /* if true, format was probed rather than specified */
1071     bool force_share; /* if true, always allow all shared permissions */
1072     bool implicit;  /* if true, this filter node was automatically inserted */
1073 
1074     BlockDriver *drv; /* NULL means no media */
1075     void *opaque;
1076 
1077     AioContext *aio_context; /* event loop used for fd handlers, timers, etc */
1078     /*
1079      * long-running tasks intended to always use the same AioContext as this
1080      * BDS may register themselves in this list to be notified of changes
1081      * regarding this BDS's context
1082      */
1083     QLIST_HEAD(, BdrvAioNotifier) aio_notifiers;
1084     bool walking_aio_notifiers; /* to make removal during iteration safe */
1085 
1086     char filename[PATH_MAX];
1087     /*
1088      * If not empty, this image is a diff in relation to backing_file.
1089      * Note that this is the name given in the image header and
1090      * therefore may or may not be equal to .backing->bs->filename.
1091      * If this field contains a relative path, it is to be resolved
1092      * relatively to the overlay's location.
1093      */
1094     char backing_file[PATH_MAX];
1095     /*
1096      * The backing filename indicated by the image header.  Contrary
1097      * to backing_file, if we ever open this file, auto_backing_file
1098      * is replaced by the resulting BDS's filename (i.e. after a
1099      * bdrv_refresh_filename() run).
1100      */
1101     char auto_backing_file[PATH_MAX];
1102     char backing_format[16]; /* if non-zero and backing_file exists */
1103 
1104     QDict *full_open_options;
1105     char exact_filename[PATH_MAX];
1106 
1107     /* I/O Limits */
1108     BlockLimits bl;
1109 
1110     /*
1111      * Flags honored during pread
1112      */
1113     BdrvRequestFlags supported_read_flags;
1114     /*
1115      * Flags honored during pwrite (so far: BDRV_REQ_FUA,
1116      * BDRV_REQ_WRITE_UNCHANGED).
1117      * If a driver does not support BDRV_REQ_WRITE_UNCHANGED, those
1118      * writes will be issued as normal writes without the flag set.
1119      * This is important to note for drivers that do not explicitly
1120      * request a WRITE permission for their children and instead take
1121      * the same permissions as their parent did (this is commonly what
1122      * block filters do).  Such drivers have to be aware that the
1123      * parent may have taken a WRITE_UNCHANGED permission only and is
1124      * issuing such requests.  Drivers either must make sure that
1125      * these requests do not result in plain WRITE accesses (usually
1126      * by supporting BDRV_REQ_WRITE_UNCHANGED, and then forwarding
1127      * every incoming write request as-is, including potentially that
1128      * flag), or they have to explicitly take the WRITE permission for
1129      * their children.
1130      */
1131     BdrvRequestFlags supported_write_flags;
1132     /*
1133      * Flags honored during pwrite_zeroes (so far: BDRV_REQ_FUA,
1134      * BDRV_REQ_MAY_UNMAP, BDRV_REQ_WRITE_UNCHANGED)
1135      */
1136     BdrvRequestFlags supported_zero_flags;
1137     /*
1138      * Flags honoured during truncate (so far: BDRV_REQ_ZERO_WRITE).
1139      *
1140      * If BDRV_REQ_ZERO_WRITE is given, the truncate operation must make sure
1141      * that any added space reads as all zeros. If this can't be guaranteed,
1142      * the operation must fail.
1143      */
1144     BdrvRequestFlags supported_truncate_flags;
1145 
1146     /* the following member gives a name to every node on the bs graph. */
1147     char node_name[32];
1148     /* element of the list of named nodes building the graph */
1149     QTAILQ_ENTRY(BlockDriverState) node_list;
1150     /* element of the list of all BlockDriverStates (all_bdrv_states) */
1151     QTAILQ_ENTRY(BlockDriverState) bs_list;
1152     /* element of the list of monitor-owned BDS */
1153     QTAILQ_ENTRY(BlockDriverState) monitor_list;
1154     int refcnt;
1155 
1156     /* operation blockers. Protected by BQL. */
1157     QLIST_HEAD(, BdrvOpBlocker) op_blockers[BLOCK_OP_TYPE_MAX];
1158 
1159     /*
1160      * The node that this node inherited default options from (and a reopen on
1161      * which can affect this node by changing these defaults). This is always a
1162      * parent node of this node.
1163      */
1164     BlockDriverState *inherits_from;
1165 
1166     /*
1167      * @backing and @file are some of @children or NULL. All these three fields
1168      * (@file, @backing and @children) are modified only in
1169      * bdrv_child_cb_attach() and bdrv_child_cb_detach().
1170      *
1171      * See also comment in include/block/block.h, to learn how backing and file
1172      * are connected with BdrvChildRole.
1173      */
1174     QLIST_HEAD(, BdrvChild) children;
1175     BdrvChild *backing;
1176     BdrvChild *file;
1177 
1178     QLIST_HEAD(, BdrvChild) parents;
1179 
1180     QDict *options;
1181     QDict *explicit_options;
1182     BlockdevDetectZeroesOptions detect_zeroes;
1183 
1184     /* The error object in use for blocking operations on backing_hd */
1185     Error *backing_blocker;
1186 
1187     /* Protected by AioContext lock */
1188 
1189     /*
1190      * If we are reading a disk image, give its size in sectors.
1191      * Generally read-only; it is written to by load_snapshot and
1192      * save_snaphost, but the block layer is quiescent during those.
1193      */
1194     int64_t total_sectors;
1195 
1196     /* threshold limit for writes, in bytes. "High water mark". */
1197     uint64_t write_threshold_offset;
1198 
1199     /*
1200      * Writing to the list requires the BQL _and_ the dirty_bitmap_mutex.
1201      * Reading from the list can be done with either the BQL or the
1202      * dirty_bitmap_mutex.  Modifying a bitmap only requires
1203      * dirty_bitmap_mutex.
1204      */
1205     QemuMutex dirty_bitmap_mutex;
1206     QLIST_HEAD(, BdrvDirtyBitmap) dirty_bitmaps;
1207 
1208     /* Offset after the highest byte written to */
1209     Stat64 wr_highest_offset;
1210 
1211     /*
1212      * If true, copy read backing sectors into image.  Can be >1 if more
1213      * than one client has requested copy-on-read.  Accessed with atomic
1214      * ops.
1215      */
1216     int copy_on_read;
1217 
1218     /*
1219      * number of in-flight requests; overall and serialising.
1220      * Accessed with atomic ops.
1221      */
1222     unsigned int in_flight;
1223     unsigned int serialising_in_flight;
1224 
1225     /* do we need to tell the quest if we have a volatile write cache? */
1226     int enable_write_cache;
1227 
1228     /* Accessed with atomic ops.  */
1229     int quiesce_counter;
1230 
1231     unsigned int write_gen;               /* Current data generation */
1232 
1233     /* Protected by reqs_lock.  */
1234     QemuMutex reqs_lock;
1235     QLIST_HEAD(, BdrvTrackedRequest) tracked_requests;
1236     CoQueue flush_queue;                  /* Serializing flush queue */
1237     bool active_flush_req;                /* Flush request in flight? */
1238 
1239     /* Only read/written by whoever has set active_flush_req to true.  */
1240     unsigned int flushed_gen;             /* Flushed write generation */
1241 
1242     /* BdrvChild links to this node may never be frozen */
1243     bool never_freeze;
1244 
1245     /* Lock for block-status cache RCU writers */
1246     CoMutex bsc_modify_lock;
1247     /* Always non-NULL, but must only be dereferenced under an RCU read guard */
1248     BdrvBlockStatusCache *block_status_cache;
1249 
1250     /* array of write pointers' location of each zone in the zoned device. */
1251     BlockZoneWps *wps;
1252 };
1253 
1254 struct BlockBackendRootState {
1255     int open_flags;
1256     BlockdevDetectZeroesOptions detect_zeroes;
1257 };
1258 
1259 typedef enum BlockMirrorBackingMode {
1260     /*
1261      * Reuse the existing backing chain from the source for the target.
1262      * - sync=full: Set backing BDS to NULL.
1263      * - sync=top:  Use source's backing BDS.
1264      * - sync=none: Use source as the backing BDS.
1265      */
1266     MIRROR_SOURCE_BACKING_CHAIN,
1267 
1268     /* Open the target's backing chain completely anew */
1269     MIRROR_OPEN_BACKING_CHAIN,
1270 
1271     /* Do not change the target's backing BDS after job completion */
1272     MIRROR_LEAVE_BACKING_CHAIN,
1273 } BlockMirrorBackingMode;
1274 
1275 
1276 /*
1277  * Essential block drivers which must always be statically linked into qemu, and
1278  * which therefore can be accessed without using bdrv_find_format()
1279  */
1280 extern BlockDriver bdrv_file;
1281 extern BlockDriver bdrv_raw;
1282 extern BlockDriver bdrv_qcow2;
1283 
1284 extern unsigned int bdrv_drain_all_count;
1285 extern QemuOptsList bdrv_create_opts_simple;
1286 
1287 /*
1288  * Common functions that are neither I/O nor Global State.
1289  *
1290  * See include/block/block-common.h for more information about
1291  * the Common API.
1292  */
1293 
1294 static inline BlockDriverState *child_bs(BdrvChild *child)
1295 {
1296     return child ? child->bs : NULL;
1297 }
1298 
1299 int bdrv_check_request(int64_t offset, int64_t bytes, Error **errp);
1300 char *create_tmp_file(Error **errp);
1301 void bdrv_parse_filename_strip_prefix(const char *filename, const char *prefix,
1302                                       QDict *options);
1303 
1304 
1305 int bdrv_check_qiov_request(int64_t offset, int64_t bytes,
1306                             QEMUIOVector *qiov, size_t qiov_offset,
1307                             Error **errp);
1308 
1309 #ifdef _WIN32
1310 int is_windows_drive(const char *filename);
1311 #endif
1312 
1313 #endif /* BLOCK_INT_COMMON_H */
1314