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