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