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