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