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