Merge tag 'v2.12.0-rc1'
[qemu/ar7.git] / include / block / block_int.h
blob7f86da1796bff6c2b424744938b6fbb1926bff5a
1 /*
2 * QEMU System Emulator block driver
4 * Copyright (c) 2003 Fabrice Bellard
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:
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
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.
24 #ifndef BLOCK_INT_H
25 #define BLOCK_INT_H
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/main-loop.h"
37 #include "qemu/throttle.h"
39 #define BLOCK_FLAG_LAZY_REFCOUNTS 8
41 #define BLOCK_OPT_SIZE "size"
42 #define BLOCK_OPT_ENCRYPT "encryption"
43 #define BLOCK_OPT_ENCRYPT_FORMAT "encrypt.format"
44 #define BLOCK_OPT_COMPAT6 "compat6"
45 #define BLOCK_OPT_HWVERSION "hwversion"
46 #define BLOCK_OPT_BACKING_FILE "backing_file"
47 #define BLOCK_OPT_BACKING_FMT "backing_fmt"
48 #define BLOCK_OPT_CLUSTER_SIZE "cluster_size"
49 #define BLOCK_OPT_TABLE_SIZE "table_size"
50 #define BLOCK_OPT_PREALLOC "preallocation"
51 #define BLOCK_OPT_SUBFMT "subformat"
52 #define BLOCK_OPT_COMPAT_LEVEL "compat"
53 #define BLOCK_OPT_LAZY_REFCOUNTS "lazy_refcounts"
54 #define BLOCK_OPT_ADAPTER_TYPE "adapter_type"
55 #define BLOCK_OPT_REDUNDANCY "redundancy"
56 #define BLOCK_OPT_NOCOW "nocow"
57 #define BLOCK_OPT_OBJECT_SIZE "object_size"
58 #define BLOCK_OPT_REFCOUNT_BITS "refcount_bits"
60 #define BLOCK_PROBE_BUF_SIZE 512
62 enum BdrvTrackedRequestType {
63 BDRV_TRACKED_READ,
64 BDRV_TRACKED_WRITE,
65 BDRV_TRACKED_DISCARD,
68 typedef struct BdrvTrackedRequest {
69 BlockDriverState *bs;
70 int64_t offset;
71 unsigned int bytes;
72 enum BdrvTrackedRequestType type;
74 bool serialising;
75 int64_t overlap_offset;
76 unsigned int overlap_bytes;
78 QLIST_ENTRY(BdrvTrackedRequest) list;
79 Coroutine *co; /* owner, used for deadlock detection */
80 CoQueue wait_queue; /* coroutines blocked on this request */
82 struct BdrvTrackedRequest *waiting_for;
83 } BdrvTrackedRequest;
85 struct BlockDriver {
86 const char *format_name;
87 int instance_size;
89 /* set to true if the BlockDriver is a block filter. Block filters pass
90 * certain callbacks that refer to data (see block.c) to their bs->file if
91 * the driver doesn't implement them. Drivers that do not wish to forward
92 * must implement them and return -ENOTSUP.
94 bool is_filter;
95 /* for snapshots block filter like Quorum can implement the
96 * following recursive callback.
97 * It's purpose is to recurse on the filter children while calling
98 * bdrv_recurse_is_first_non_filter on them.
99 * For a sample implementation look in the future Quorum block filter.
101 bool (*bdrv_recurse_is_first_non_filter)(BlockDriverState *bs,
102 BlockDriverState *candidate);
104 int (*bdrv_probe)(const uint8_t *buf, int buf_size, const char *filename);
105 int (*bdrv_probe_device)(const char *filename);
107 /* Any driver implementing this callback is expected to be able to handle
108 * NULL file names in its .bdrv_open() implementation */
109 void (*bdrv_parse_filename)(const char *filename, QDict *options, Error **errp);
110 /* Drivers not implementing bdrv_parse_filename nor bdrv_open should have
111 * this field set to true, except ones that are defined only by their
112 * child's bs.
113 * An example of the last type will be the quorum block driver.
115 bool bdrv_needs_filename;
117 /* Set if a driver can support backing files */
118 bool supports_backing;
120 /* For handling image reopen for split or non-split files */
121 int (*bdrv_reopen_prepare)(BDRVReopenState *reopen_state,
122 BlockReopenQueue *queue, Error **errp);
123 void (*bdrv_reopen_commit)(BDRVReopenState *reopen_state);
124 void (*bdrv_reopen_abort)(BDRVReopenState *reopen_state);
125 void (*bdrv_join_options)(QDict *options, QDict *old_options);
127 int (*bdrv_open)(BlockDriverState *bs, QDict *options, int flags,
128 Error **errp);
130 /* Protocol drivers should implement this instead of bdrv_open */
131 int (*bdrv_file_open)(BlockDriverState *bs, QDict *options, int flags,
132 Error **errp);
133 void (*bdrv_close)(BlockDriverState *bs);
134 int coroutine_fn (*bdrv_co_create)(BlockdevCreateOptions *opts,
135 Error **errp);
136 int coroutine_fn (*bdrv_co_create_opts)(const char *filename,
137 QemuOpts *opts,
138 Error **errp);
139 int (*bdrv_make_empty)(BlockDriverState *bs);
141 void (*bdrv_refresh_filename)(BlockDriverState *bs, QDict *options);
143 /* aio */
144 BlockAIOCB *(*bdrv_aio_readv)(BlockDriverState *bs,
145 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
146 BlockCompletionFunc *cb, void *opaque);
147 BlockAIOCB *(*bdrv_aio_writev)(BlockDriverState *bs,
148 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
149 BlockCompletionFunc *cb, void *opaque);
150 BlockAIOCB *(*bdrv_aio_flush)(BlockDriverState *bs,
151 BlockCompletionFunc *cb, void *opaque);
152 BlockAIOCB *(*bdrv_aio_pdiscard)(BlockDriverState *bs,
153 int64_t offset, int bytes,
154 BlockCompletionFunc *cb, void *opaque);
156 int coroutine_fn (*bdrv_co_readv)(BlockDriverState *bs,
157 int64_t sector_num, int nb_sectors, QEMUIOVector *qiov);
160 * @offset: position in bytes to read at
161 * @bytes: number of bytes to read
162 * @qiov: the buffers to fill with read data
163 * @flags: currently unused, always 0
165 * @offset and @bytes will be a multiple of 'request_alignment',
166 * but the length of individual @qiov elements does not have to
167 * be a multiple.
169 * @bytes will always equal the total size of @qiov, and will be
170 * no larger than 'max_transfer'.
172 * The buffer in @qiov may point directly to guest memory.
174 int coroutine_fn (*bdrv_co_preadv)(BlockDriverState *bs,
175 uint64_t offset, uint64_t bytes, QEMUIOVector *qiov, int flags);
176 int coroutine_fn (*bdrv_co_writev)(BlockDriverState *bs,
177 int64_t sector_num, int nb_sectors, QEMUIOVector *qiov);
178 int coroutine_fn (*bdrv_co_writev_flags)(BlockDriverState *bs,
179 int64_t sector_num, int nb_sectors, QEMUIOVector *qiov, int flags);
181 * @offset: position in bytes to write at
182 * @bytes: number of bytes to write
183 * @qiov: the buffers containing data to write
184 * @flags: zero or more bits allowed by 'supported_write_flags'
186 * @offset and @bytes will be a multiple of 'request_alignment',
187 * but the length of individual @qiov elements does not have to
188 * be a multiple.
190 * @bytes will always equal the total size of @qiov, and will be
191 * no larger than 'max_transfer'.
193 * The buffer in @qiov may point directly to guest memory.
195 int coroutine_fn (*bdrv_co_pwritev)(BlockDriverState *bs,
196 uint64_t offset, uint64_t bytes, QEMUIOVector *qiov, int flags);
199 * Efficiently zero a region of the disk image. Typically an image format
200 * would use a compact metadata representation to implement this. This
201 * function pointer may be NULL or return -ENOSUP and .bdrv_co_writev()
202 * will be called instead.
204 int coroutine_fn (*bdrv_co_pwrite_zeroes)(BlockDriverState *bs,
205 int64_t offset, int bytes, BdrvRequestFlags flags);
206 int coroutine_fn (*bdrv_co_pdiscard)(BlockDriverState *bs,
207 int64_t offset, int bytes);
210 * Building block for bdrv_block_status[_above] and
211 * bdrv_is_allocated[_above]. The driver should answer only
212 * according to the current layer, and should only need to set
213 * BDRV_BLOCK_DATA, BDRV_BLOCK_ZERO, BDRV_BLOCK_OFFSET_VALID,
214 * and/or BDRV_BLOCK_RAW; if the current layer defers to a backing
215 * layer, the result should be 0 (and not BDRV_BLOCK_ZERO). See
216 * block.h for the overall meaning of the bits. As a hint, the
217 * flag want_zero is true if the caller cares more about precise
218 * mappings (favor accurate _OFFSET_VALID/_ZERO) or false for
219 * overall allocation (favor larger *pnum, perhaps by reporting
220 * _DATA instead of _ZERO). The block layer guarantees input
221 * clamped to bdrv_getlength() and aligned to request_alignment,
222 * as well as non-NULL pnum, map, and file; in turn, the driver
223 * must return an error or set pnum to an aligned non-zero value.
225 int coroutine_fn (*bdrv_co_block_status)(BlockDriverState *bs,
226 bool want_zero, int64_t offset, int64_t bytes, int64_t *pnum,
227 int64_t *map, BlockDriverState **file);
230 * Invalidate any cached meta-data.
232 void coroutine_fn (*bdrv_co_invalidate_cache)(BlockDriverState *bs,
233 Error **errp);
234 int (*bdrv_inactivate)(BlockDriverState *bs);
237 * Flushes all data for all layers by calling bdrv_co_flush for underlying
238 * layers, if needed. This function is needed for deterministic
239 * synchronization of the flush finishing callback.
241 int coroutine_fn (*bdrv_co_flush)(BlockDriverState *bs);
244 * Flushes all data that was already written to the OS all the way down to
245 * the disk (for example file-posix.c calls fsync()).
247 int coroutine_fn (*bdrv_co_flush_to_disk)(BlockDriverState *bs);
250 * Flushes all internal caches to the OS. The data may still sit in a
251 * writeback cache of the host OS, but it will survive a crash of the qemu
252 * process.
254 int coroutine_fn (*bdrv_co_flush_to_os)(BlockDriverState *bs);
257 * Drivers setting this field must be able to work with just a plain
258 * filename with '<protocol_name>:' as a prefix, and no other options.
259 * Options may be extracted from the filename by implementing
260 * bdrv_parse_filename.
262 const char *protocol_name;
263 int (*bdrv_truncate)(BlockDriverState *bs, int64_t offset,
264 PreallocMode prealloc, Error **errp);
266 int64_t (*bdrv_getlength)(BlockDriverState *bs);
267 bool has_variable_length;
268 int64_t (*bdrv_get_allocated_file_size)(BlockDriverState *bs);
269 BlockMeasureInfo *(*bdrv_measure)(QemuOpts *opts, BlockDriverState *in_bs,
270 Error **errp);
272 int coroutine_fn (*bdrv_co_pwritev_compressed)(BlockDriverState *bs,
273 uint64_t offset, uint64_t bytes, QEMUIOVector *qiov);
275 int (*bdrv_snapshot_create)(BlockDriverState *bs,
276 QEMUSnapshotInfo *sn_info);
277 int (*bdrv_snapshot_goto)(BlockDriverState *bs,
278 const char *snapshot_id);
279 int (*bdrv_snapshot_delete)(BlockDriverState *bs,
280 const char *snapshot_id,
281 const char *name,
282 Error **errp);
283 int (*bdrv_snapshot_list)(BlockDriverState *bs,
284 QEMUSnapshotInfo **psn_info);
285 int (*bdrv_snapshot_load_tmp)(BlockDriverState *bs,
286 const char *snapshot_id,
287 const char *name,
288 Error **errp);
289 int (*bdrv_get_info)(BlockDriverState *bs, BlockDriverInfo *bdi);
290 ImageInfoSpecific *(*bdrv_get_specific_info)(BlockDriverState *bs);
291 int (*bdrv_update)(BlockDriverState *bs, int argc, char **argv);
293 int coroutine_fn (*bdrv_save_vmstate)(BlockDriverState *bs,
294 QEMUIOVector *qiov,
295 int64_t pos);
296 int coroutine_fn (*bdrv_load_vmstate)(BlockDriverState *bs,
297 QEMUIOVector *qiov,
298 int64_t pos);
300 int (*bdrv_change_backing_file)(BlockDriverState *bs,
301 const char *backing_file, const char *backing_fmt);
303 /* removable device specific */
304 bool (*bdrv_is_inserted)(BlockDriverState *bs);
305 void (*bdrv_eject)(BlockDriverState *bs, bool eject_flag);
306 void (*bdrv_lock_medium)(BlockDriverState *bs, bool locked);
308 /* to control generic scsi devices */
309 BlockAIOCB *(*bdrv_aio_ioctl)(BlockDriverState *bs,
310 unsigned long int req, void *buf,
311 BlockCompletionFunc *cb, void *opaque);
312 int coroutine_fn (*bdrv_co_ioctl)(BlockDriverState *bs,
313 unsigned long int req, void *buf);
315 /* List of options for creating images, terminated by name == NULL */
316 QemuOptsList *create_opts;
319 * Returns 0 for completed check, -errno for internal errors.
320 * The check results are stored in result.
322 int coroutine_fn (*bdrv_co_check)(BlockDriverState *bs,
323 BdrvCheckResult *result,
324 BdrvCheckMode fix);
326 int (*bdrv_amend_options)(BlockDriverState *bs, QemuOpts *opts,
327 BlockDriverAmendStatusCB *status_cb,
328 void *cb_opaque);
330 void (*bdrv_debug_event)(BlockDriverState *bs, BlkdebugEvent event);
332 /* TODO Better pass a option string/QDict/QemuOpts to add any rule? */
333 int (*bdrv_debug_breakpoint)(BlockDriverState *bs, const char *event,
334 const char *tag);
335 int (*bdrv_debug_remove_breakpoint)(BlockDriverState *bs,
336 const char *tag);
337 int (*bdrv_debug_resume)(BlockDriverState *bs, const char *tag);
338 bool (*bdrv_debug_is_suspended)(BlockDriverState *bs, const char *tag);
340 void (*bdrv_refresh_limits)(BlockDriverState *bs, Error **errp);
343 * Returns 1 if newly created images are guaranteed to contain only
344 * zeros, 0 otherwise.
346 int (*bdrv_has_zero_init)(BlockDriverState *bs);
348 /* Remove fd handlers, timers, and other event loop callbacks so the event
349 * loop is no longer in use. Called with no in-flight requests and in
350 * depth-first traversal order with parents before child nodes.
352 void (*bdrv_detach_aio_context)(BlockDriverState *bs);
354 /* Add fd handlers, timers, and other event loop callbacks so I/O requests
355 * can be processed again. Called with no in-flight requests and in
356 * depth-first traversal order with child nodes before parent nodes.
358 void (*bdrv_attach_aio_context)(BlockDriverState *bs,
359 AioContext *new_context);
361 /* io queue for linux-aio */
362 void (*bdrv_io_plug)(BlockDriverState *bs);
363 void (*bdrv_io_unplug)(BlockDriverState *bs);
366 * Try to get @bs's logical and physical block size.
367 * On success, store them in @bsz and return zero.
368 * On failure, return negative errno.
370 int (*bdrv_probe_blocksizes)(BlockDriverState *bs, BlockSizes *bsz);
372 * Try to get @bs's geometry (cyls, heads, sectors)
373 * On success, store them in @geo and return 0.
374 * On failure return -errno.
375 * Only drivers that want to override guest geometry implement this
376 * callback; see hd_geometry_guess().
378 int (*bdrv_probe_geometry)(BlockDriverState *bs, HDGeometry *geo);
381 * bdrv_co_drain_begin is called if implemented in the beginning of a
382 * drain operation to drain and stop any internal sources of requests in
383 * the driver.
384 * bdrv_co_drain_end is called if implemented at the end of the drain.
386 * They should be used by the driver to e.g. manage scheduled I/O
387 * requests, or toggle an internal state. After the end of the drain new
388 * requests will continue normally.
390 void coroutine_fn (*bdrv_co_drain_begin)(BlockDriverState *bs);
391 void coroutine_fn (*bdrv_co_drain_end)(BlockDriverState *bs);
393 void (*bdrv_add_child)(BlockDriverState *parent, BlockDriverState *child,
394 Error **errp);
395 void (*bdrv_del_child)(BlockDriverState *parent, BdrvChild *child,
396 Error **errp);
399 * Informs the block driver that a permission change is intended. The
400 * driver checks whether the change is permissible and may take other
401 * preparations for the change (e.g. get file system locks). This operation
402 * is always followed either by a call to either .bdrv_set_perm or
403 * .bdrv_abort_perm_update.
405 * Checks whether the requested set of cumulative permissions in @perm
406 * can be granted for accessing @bs and whether no other users are using
407 * permissions other than those given in @shared (both arguments take
408 * BLK_PERM_* bitmasks).
410 * If both conditions are met, 0 is returned. Otherwise, -errno is returned
411 * and errp is set to an error describing the conflict.
413 int (*bdrv_check_perm)(BlockDriverState *bs, uint64_t perm,
414 uint64_t shared, Error **errp);
417 * Called to inform the driver that the set of cumulative set of used
418 * permissions for @bs has changed to @perm, and the set of sharable
419 * permission to @shared. The driver can use this to propagate changes to
420 * its children (i.e. request permissions only if a parent actually needs
421 * them).
423 * This function is only invoked after bdrv_check_perm(), so block drivers
424 * may rely on preparations made in their .bdrv_check_perm implementation.
426 void (*bdrv_set_perm)(BlockDriverState *bs, uint64_t perm, uint64_t shared);
429 * Called to inform the driver that after a previous bdrv_check_perm()
430 * call, the permission update is not performed and any preparations made
431 * for it (e.g. taken file locks) need to be undone.
433 * This function can be called even for nodes that never saw a
434 * bdrv_check_perm() call. It is a no-op then.
436 void (*bdrv_abort_perm_update)(BlockDriverState *bs);
439 * Returns in @nperm and @nshared the permissions that the driver for @bs
440 * needs on its child @c, based on the cumulative permissions requested by
441 * the parents in @parent_perm and @parent_shared.
443 * If @c is NULL, return the permissions for attaching a new child for the
444 * given @role.
446 * If @reopen_queue is non-NULL, don't return the currently needed
447 * permissions, but those that will be needed after applying the
448 * @reopen_queue.
450 void (*bdrv_child_perm)(BlockDriverState *bs, BdrvChild *c,
451 const BdrvChildRole *role,
452 BlockReopenQueue *reopen_queue,
453 uint64_t parent_perm, uint64_t parent_shared,
454 uint64_t *nperm, uint64_t *nshared);
457 * Bitmaps should be marked as 'IN_USE' in the image on reopening image
458 * as rw. This handler should realize it. It also should unset readonly
459 * field of BlockDirtyBitmap's in case of success.
461 int (*bdrv_reopen_bitmaps_rw)(BlockDriverState *bs, Error **errp);
462 bool (*bdrv_can_store_new_dirty_bitmap)(BlockDriverState *bs,
463 const char *name,
464 uint32_t granularity,
465 Error **errp);
466 void (*bdrv_remove_persistent_dirty_bitmap)(BlockDriverState *bs,
467 const char *name,
468 Error **errp);
471 * Register/unregister a buffer for I/O. For example, when the driver is
472 * interested to know the memory areas that will later be used in iovs, so
473 * that it can do IOMMU mapping with VFIO etc., in order to get better
474 * performance. In the case of VFIO drivers, this callback is used to do
475 * DMA mapping for hot buffers.
477 void (*bdrv_register_buf)(BlockDriverState *bs, void *host, size_t size);
478 void (*bdrv_unregister_buf)(BlockDriverState *bs, void *host);
479 QLIST_ENTRY(BlockDriver) list;
482 typedef struct BlockLimits {
483 /* Alignment requirement, in bytes, for offset/length of I/O
484 * requests. Must be a power of 2 less than INT_MAX; defaults to
485 * 1 for drivers with modern byte interfaces, and to 512
486 * otherwise. */
487 uint32_t request_alignment;
489 /* Maximum number of bytes that can be discarded at once (since it
490 * is signed, it must be < 2G, if set). Must be multiple of
491 * pdiscard_alignment, but need not be power of 2. May be 0 if no
492 * inherent 32-bit limit */
493 int32_t max_pdiscard;
495 /* Optimal alignment for discard requests in bytes. A power of 2
496 * is best but not mandatory. Must be a multiple of
497 * bl.request_alignment, and must be less than max_pdiscard if
498 * that is set. May be 0 if bl.request_alignment is good enough */
499 uint32_t pdiscard_alignment;
501 /* Maximum number of bytes that can zeroized at once (since it is
502 * signed, it must be < 2G, if set). Must be multiple of
503 * pwrite_zeroes_alignment. May be 0 if no inherent 32-bit limit */
504 int32_t max_pwrite_zeroes;
506 /* Optimal alignment for write zeroes requests in bytes. A power
507 * of 2 is best but not mandatory. Must be a multiple of
508 * bl.request_alignment, and must be less than max_pwrite_zeroes
509 * if that is set. May be 0 if bl.request_alignment is good
510 * enough */
511 uint32_t pwrite_zeroes_alignment;
513 /* Optimal transfer length in bytes. A power of 2 is best but not
514 * mandatory. Must be a multiple of bl.request_alignment, or 0 if
515 * no preferred size */
516 uint32_t opt_transfer;
518 /* Maximal transfer length in bytes. Need not be power of 2, but
519 * must be multiple of opt_transfer and bl.request_alignment, or 0
520 * for no 32-bit limit. For now, anything larger than INT_MAX is
521 * clamped down. */
522 uint32_t max_transfer;
524 /* memory alignment, in bytes so that no bounce buffer is needed */
525 size_t min_mem_alignment;
527 /* memory alignment, in bytes, for bounce buffer */
528 size_t opt_mem_alignment;
530 /* maximum number of iovec elements */
531 int max_iov;
532 } BlockLimits;
534 typedef struct BdrvOpBlocker BdrvOpBlocker;
536 typedef struct BdrvAioNotifier {
537 void (*attached_aio_context)(AioContext *new_context, void *opaque);
538 void (*detach_aio_context)(void *opaque);
540 void *opaque;
541 bool deleted;
543 QLIST_ENTRY(BdrvAioNotifier) list;
544 } BdrvAioNotifier;
546 struct BdrvChildRole {
547 /* If true, bdrv_replace_node() doesn't change the node this BdrvChild
548 * points to. */
549 bool stay_at_node;
551 void (*inherit_options)(int *child_flags, QDict *child_options,
552 int parent_flags, QDict *parent_options);
554 void (*change_media)(BdrvChild *child, bool load);
555 void (*resize)(BdrvChild *child);
557 /* Returns a name that is supposedly more useful for human users than the
558 * node name for identifying the node in question (in particular, a BB
559 * name), or NULL if the parent can't provide a better name. */
560 const char *(*get_name)(BdrvChild *child);
562 /* Returns a malloced string that describes the parent of the child for a
563 * human reader. This could be a node-name, BlockBackend name, qdev ID or
564 * QOM path of the device owning the BlockBackend, job type and ID etc. The
565 * caller is responsible for freeing the memory. */
566 char *(*get_parent_desc)(BdrvChild *child);
569 * If this pair of functions is implemented, the parent doesn't issue new
570 * requests after returning from .drained_begin() until .drained_end() is
571 * called.
573 * Note that this can be nested. If drained_begin() was called twice, new
574 * I/O is allowed only after drained_end() was called twice, too.
576 void (*drained_begin)(BdrvChild *child);
577 void (*drained_end)(BdrvChild *child);
579 /* Notifies the parent that the child has been activated/inactivated (e.g.
580 * when migration is completing) and it can start/stop requesting
581 * permissions and doing I/O on it. */
582 void (*activate)(BdrvChild *child, Error **errp);
583 int (*inactivate)(BdrvChild *child);
585 void (*attach)(BdrvChild *child);
586 void (*detach)(BdrvChild *child);
588 /* Notifies the parent that the filename of its child has changed (e.g.
589 * because the direct child was removed from the backing chain), so that it
590 * can update its reference. */
591 int (*update_filename)(BdrvChild *child, BlockDriverState *new_base,
592 const char *filename, Error **errp);
595 extern const BdrvChildRole child_file;
596 extern const BdrvChildRole child_format;
597 extern const BdrvChildRole child_backing;
599 struct BdrvChild {
600 BlockDriverState *bs;
601 char *name;
602 const BdrvChildRole *role;
603 void *opaque;
606 * Granted permissions for operating on this BdrvChild (BLK_PERM_* bitmask)
608 uint64_t perm;
611 * Permissions that can still be granted to other users of @bs while this
612 * BdrvChild is still attached to it. (BLK_PERM_* bitmask)
614 uint64_t shared_perm;
616 QLIST_ENTRY(BdrvChild) next;
617 QLIST_ENTRY(BdrvChild) next_parent;
621 * Note: the function bdrv_append() copies and swaps contents of
622 * BlockDriverStates, so if you add new fields to this struct, please
623 * inspect bdrv_append() to determine if the new fields need to be
624 * copied as well.
626 struct BlockDriverState {
627 /* Protected by big QEMU lock or read-only after opening. No special
628 * locking needed during I/O...
630 int open_flags; /* flags used to open the file, re-used for re-open */
631 bool read_only; /* if true, the media is read only */
632 bool encrypted; /* if true, the media is encrypted */
633 bool sg; /* if true, the device is a /dev/sg* */
634 bool probed; /* if true, format was probed rather than specified */
635 bool force_share; /* if true, always allow all shared permissions */
636 bool implicit; /* if true, this filter node was automatically inserted */
638 BlockDriver *drv; /* NULL means no media */
639 void *opaque;
641 AioContext *aio_context; /* event loop used for fd handlers, timers, etc */
642 /* long-running tasks intended to always use the same AioContext as this
643 * BDS may register themselves in this list to be notified of changes
644 * regarding this BDS's context */
645 QLIST_HEAD(, BdrvAioNotifier) aio_notifiers;
646 bool walking_aio_notifiers; /* to make removal during iteration safe */
648 char filename[PATH_MAX];
649 char backing_file[PATH_MAX]; /* if non zero, the image is a diff of
650 this file image */
651 char backing_format[16]; /* if non-zero and backing_file exists */
653 QDict *full_open_options;
654 char exact_filename[PATH_MAX];
656 BdrvChild *backing;
657 BdrvChild *file;
659 /* I/O Limits */
660 BlockLimits bl;
662 /* Flags honored during pwrite (so far: BDRV_REQ_FUA) */
663 unsigned int supported_write_flags;
664 /* Flags honored during pwrite_zeroes (so far: BDRV_REQ_FUA,
665 * BDRV_REQ_MAY_UNMAP) */
666 unsigned int supported_zero_flags;
668 /* the following member gives a name to every node on the bs graph. */
669 char node_name[32];
670 /* element of the list of named nodes building the graph */
671 QTAILQ_ENTRY(BlockDriverState) node_list;
672 /* element of the list of all BlockDriverStates (all_bdrv_states) */
673 QTAILQ_ENTRY(BlockDriverState) bs_list;
674 /* element of the list of monitor-owned BDS */
675 QTAILQ_ENTRY(BlockDriverState) monitor_list;
676 int refcnt;
678 /* operation blockers */
679 QLIST_HEAD(, BdrvOpBlocker) op_blockers[BLOCK_OP_TYPE_MAX];
681 /* long-running background operation */
682 BlockJob *job;
684 /* The node that this node inherited default options from (and a reopen on
685 * which can affect this node by changing these defaults). This is always a
686 * parent node of this node. */
687 BlockDriverState *inherits_from;
688 QLIST_HEAD(, BdrvChild) children;
689 QLIST_HEAD(, BdrvChild) parents;
691 QDict *options;
692 QDict *explicit_options;
693 BlockdevDetectZeroesOptions detect_zeroes;
695 /* The error object in use for blocking operations on backing_hd */
696 Error *backing_blocker;
698 /* Protected by AioContext lock */
700 /* If we are reading a disk image, give its size in sectors.
701 * Generally read-only; it is written to by load_snapshot and
702 * save_snaphost, but the block layer is quiescent during those.
704 int64_t total_sectors;
706 /* Callback before write request is processed */
707 NotifierWithReturnList before_write_notifiers;
709 /* threshold limit for writes, in bytes. "High water mark". */
710 uint64_t write_threshold_offset;
711 NotifierWithReturn write_threshold_notifier;
713 /* Writing to the list requires the BQL _and_ the dirty_bitmap_mutex.
714 * Reading from the list can be done with either the BQL or the
715 * dirty_bitmap_mutex. Modifying a bitmap only requires
716 * dirty_bitmap_mutex. */
717 QemuMutex dirty_bitmap_mutex;
718 QLIST_HEAD(, BdrvDirtyBitmap) dirty_bitmaps;
720 /* Offset after the highest byte written to */
721 Stat64 wr_highest_offset;
723 /* If true, copy read backing sectors into image. Can be >1 if more
724 * than one client has requested copy-on-read. Accessed with atomic
725 * ops.
727 int copy_on_read;
729 /* number of in-flight requests; overall and serialising.
730 * Accessed with atomic ops.
732 unsigned int in_flight;
733 unsigned int serialising_in_flight;
735 /* Kicked to signal main loop when a request completes. */
736 AioWait wait;
738 /* counter for nested bdrv_io_plug.
739 * Accessed with atomic ops.
741 unsigned io_plugged;
743 /* do we need to tell the quest if we have a volatile write cache? */
744 int enable_write_cache;
746 /* Accessed with atomic ops. */
747 int quiesce_counter;
748 int recursive_quiesce_counter;
750 unsigned int write_gen; /* Current data generation */
752 /* Protected by reqs_lock. */
753 CoMutex reqs_lock;
754 QLIST_HEAD(, BdrvTrackedRequest) tracked_requests;
755 CoQueue flush_queue; /* Serializing flush queue */
756 bool active_flush_req; /* Flush request in flight? */
758 /* Only read/written by whoever has set active_flush_req to true. */
759 unsigned int flushed_gen; /* Flushed write generation */
762 struct BlockBackendRootState {
763 int open_flags;
764 bool read_only;
765 BlockdevDetectZeroesOptions detect_zeroes;
768 typedef enum BlockMirrorBackingMode {
769 /* Reuse the existing backing chain from the source for the target.
770 * - sync=full: Set backing BDS to NULL.
771 * - sync=top: Use source's backing BDS.
772 * - sync=none: Use source as the backing BDS. */
773 MIRROR_SOURCE_BACKING_CHAIN,
775 /* Open the target's backing chain completely anew */
776 MIRROR_OPEN_BACKING_CHAIN,
778 /* Do not change the target's backing BDS after job completion */
779 MIRROR_LEAVE_BACKING_CHAIN,
780 } BlockMirrorBackingMode;
782 static inline BlockDriverState *backing_bs(BlockDriverState *bs)
784 return bs->backing ? bs->backing->bs : NULL;
788 /* Essential block drivers which must always be statically linked into qemu, and
789 * which therefore can be accessed without using bdrv_find_format() */
790 extern BlockDriver bdrv_file;
791 extern BlockDriver bdrv_raw;
792 extern BlockDriver bdrv_qcow2;
794 int coroutine_fn bdrv_co_preadv(BdrvChild *child,
795 int64_t offset, unsigned int bytes, QEMUIOVector *qiov,
796 BdrvRequestFlags flags);
797 int coroutine_fn bdrv_co_pwritev(BdrvChild *child,
798 int64_t offset, unsigned int bytes, QEMUIOVector *qiov,
799 BdrvRequestFlags flags);
801 void bdrv_apply_subtree_drain(BdrvChild *child, BlockDriverState *new_parent);
802 void bdrv_unapply_subtree_drain(BdrvChild *child, BlockDriverState *old_parent);
804 int get_tmp_filename(char *filename, int size);
805 BlockDriver *bdrv_probe_all(const uint8_t *buf, int buf_size,
806 const char *filename);
808 void bdrv_parse_filename_strip_prefix(const char *filename, const char *prefix,
809 QDict *options);
813 * bdrv_add_before_write_notifier:
815 * Register a callback that is invoked before write requests are processed but
816 * after any throttling or waiting for overlapping requests.
818 void bdrv_add_before_write_notifier(BlockDriverState *bs,
819 NotifierWithReturn *notifier);
822 * bdrv_detach_aio_context:
824 * May be called from .bdrv_detach_aio_context() to detach children from the
825 * current #AioContext. This is only needed by block drivers that manage their
826 * own children. Both ->file and ->backing are automatically handled and
827 * block drivers should not call this function on them explicitly.
829 void bdrv_detach_aio_context(BlockDriverState *bs);
832 * bdrv_attach_aio_context:
834 * May be called from .bdrv_attach_aio_context() to attach children to the new
835 * #AioContext. This is only needed by block drivers that manage their own
836 * children. Both ->file and ->backing are automatically handled and block
837 * drivers should not call this function on them explicitly.
839 void bdrv_attach_aio_context(BlockDriverState *bs,
840 AioContext *new_context);
843 * bdrv_add_aio_context_notifier:
845 * If a long-running job intends to be always run in the same AioContext as a
846 * certain BDS, it may use this function to be notified of changes regarding the
847 * association of the BDS to an AioContext.
849 * attached_aio_context() is called after the target BDS has been attached to a
850 * new AioContext; detach_aio_context() is called before the target BDS is being
851 * detached from its old AioContext.
853 void bdrv_add_aio_context_notifier(BlockDriverState *bs,
854 void (*attached_aio_context)(AioContext *new_context, void *opaque),
855 void (*detach_aio_context)(void *opaque), void *opaque);
858 * bdrv_remove_aio_context_notifier:
860 * Unsubscribe of change notifications regarding the BDS's AioContext. The
861 * parameters given here have to be the same as those given to
862 * bdrv_add_aio_context_notifier().
864 void bdrv_remove_aio_context_notifier(BlockDriverState *bs,
865 void (*aio_context_attached)(AioContext *,
866 void *),
867 void (*aio_context_detached)(void *),
868 void *opaque);
871 * bdrv_wakeup:
872 * @bs: The BlockDriverState for which an I/O operation has been completed.
874 * Wake up the main thread if it is waiting on BDRV_POLL_WHILE. During
875 * synchronous I/O on a BlockDriverState that is attached to another
876 * I/O thread, the main thread lets the I/O thread's event loop run,
877 * waiting for the I/O operation to complete. A bdrv_wakeup will wake
878 * up the main thread if necessary.
880 * Manual calls to bdrv_wakeup are rarely necessary, because
881 * bdrv_dec_in_flight already calls it.
883 void bdrv_wakeup(BlockDriverState *bs);
885 #ifdef _WIN32
886 int is_windows_drive(const char *filename);
887 #endif
890 * stream_start:
891 * @job_id: The id of the newly-created job, or %NULL to use the
892 * device name of @bs.
893 * @bs: Block device to operate on.
894 * @base: Block device that will become the new base, or %NULL to
895 * flatten the whole backing file chain onto @bs.
896 * @backing_file_str: The file name that will be written to @bs as the
897 * the new backing file if the job completes. Ignored if @base is %NULL.
898 * @speed: The maximum speed, in bytes per second, or 0 for unlimited.
899 * @on_error: The action to take upon error.
900 * @errp: Error object.
902 * Start a streaming operation on @bs. Clusters that are unallocated
903 * in @bs, but allocated in any image between @base and @bs (both
904 * exclusive) will be written to @bs. At the end of a successful
905 * streaming job, the backing file of @bs will be changed to
906 * @backing_file_str in the written image and to @base in the live
907 * BlockDriverState.
909 void stream_start(const char *job_id, BlockDriverState *bs,
910 BlockDriverState *base, const char *backing_file_str,
911 int64_t speed, BlockdevOnError on_error, Error **errp);
914 * commit_start:
915 * @job_id: The id of the newly-created job, or %NULL to use the
916 * device name of @bs.
917 * @bs: Active block device.
918 * @top: Top block device to be committed.
919 * @base: Block device that will be written into, and become the new top.
920 * @speed: The maximum speed, in bytes per second, or 0 for unlimited.
921 * @on_error: The action to take upon error.
922 * @backing_file_str: String to use as the backing file in @top's overlay
923 * @filter_node_name: The node name that should be assigned to the filter
924 * driver that the commit job inserts into the graph above @top. NULL means
925 * that a node name should be autogenerated.
926 * @errp: Error object.
929 void commit_start(const char *job_id, BlockDriverState *bs,
930 BlockDriverState *base, BlockDriverState *top, int64_t speed,
931 BlockdevOnError on_error, const char *backing_file_str,
932 const char *filter_node_name, Error **errp);
934 * commit_active_start:
935 * @job_id: The id of the newly-created job, or %NULL to use the
936 * device name of @bs.
937 * @bs: Active block device to be committed.
938 * @base: Block device that will be written into, and become the new top.
939 * @creation_flags: Flags that control the behavior of the Job lifetime.
940 * See @BlockJobCreateFlags
941 * @speed: The maximum speed, in bytes per second, or 0 for unlimited.
942 * @on_error: The action to take upon error.
943 * @filter_node_name: The node name that should be assigned to the filter
944 * driver that the commit job inserts into the graph above @bs. NULL means that
945 * a node name should be autogenerated.
946 * @cb: Completion function for the job.
947 * @opaque: Opaque pointer value passed to @cb.
948 * @auto_complete: Auto complete the job.
949 * @errp: Error object.
952 void commit_active_start(const char *job_id, BlockDriverState *bs,
953 BlockDriverState *base, int creation_flags,
954 int64_t speed, BlockdevOnError on_error,
955 const char *filter_node_name,
956 BlockCompletionFunc *cb, void *opaque,
957 bool auto_complete, Error **errp);
959 * mirror_start:
960 * @job_id: The id of the newly-created job, or %NULL to use the
961 * device name of @bs.
962 * @bs: Block device to operate on.
963 * @target: Block device to write to.
964 * @replaces: Block graph node name to replace once the mirror is done. Can
965 * only be used when full mirroring is selected.
966 * @speed: The maximum speed, in bytes per second, or 0 for unlimited.
967 * @granularity: The chosen granularity for the dirty bitmap.
968 * @buf_size: The amount of data that can be in flight at one time.
969 * @mode: Whether to collapse all images in the chain to the target.
970 * @backing_mode: How to establish the target's backing chain after completion.
971 * @on_source_error: The action to take upon error reading from the source.
972 * @on_target_error: The action to take upon error writing to the target.
973 * @unmap: Whether to unmap target where source sectors only contain zeroes.
974 * @filter_node_name: The node name that should be assigned to the filter
975 * driver that the mirror job inserts into the graph above @bs. NULL means that
976 * a node name should be autogenerated.
977 * @errp: Error object.
979 * Start a mirroring operation on @bs. Clusters that are allocated
980 * in @bs will be written to @target until the job is cancelled or
981 * manually completed. At the end of a successful mirroring job,
982 * @bs will be switched to read from @target.
984 void mirror_start(const char *job_id, BlockDriverState *bs,
985 BlockDriverState *target, const char *replaces,
986 int64_t speed, uint32_t granularity, int64_t buf_size,
987 MirrorSyncMode mode, BlockMirrorBackingMode backing_mode,
988 BlockdevOnError on_source_error,
989 BlockdevOnError on_target_error,
990 bool unmap, const char *filter_node_name, Error **errp);
993 * backup_job_create:
994 * @job_id: The id of the newly-created job, or %NULL to use the
995 * device name of @bs.
996 * @bs: Block device to operate on.
997 * @target: Block device to write to.
998 * @speed: The maximum speed, in bytes per second, or 0 for unlimited.
999 * @sync_mode: What parts of the disk image should be copied to the destination.
1000 * @sync_bitmap: The dirty bitmap if sync_mode is MIRROR_SYNC_MODE_INCREMENTAL.
1001 * @on_source_error: The action to take upon error reading from the source.
1002 * @on_target_error: The action to take upon error writing to the target.
1003 * @creation_flags: Flags that control the behavior of the Job lifetime.
1004 * See @BlockJobCreateFlags
1005 * @cb: Completion function for the job.
1006 * @opaque: Opaque pointer value passed to @cb.
1007 * @txn: Transaction that this job is part of (may be NULL).
1009 * Create a backup operation on @bs. Clusters in @bs are written to @target
1010 * until the job is cancelled or manually completed.
1012 BlockJob *backup_job_create(const char *job_id, BlockDriverState *bs,
1013 BlockDriverState *target, int64_t speed,
1014 MirrorSyncMode sync_mode,
1015 BdrvDirtyBitmap *sync_bitmap,
1016 bool compress,
1017 BlockdevOnError on_source_error,
1018 BlockdevOnError on_target_error,
1019 int creation_flags,
1020 BlockCompletionFunc *cb, void *opaque,
1021 BlockJobTxn *txn, Error **errp);
1023 void hmp_drive_add_node(Monitor *mon, const char *optstr);
1025 BdrvChild *bdrv_root_attach_child(BlockDriverState *child_bs,
1026 const char *child_name,
1027 const BdrvChildRole *child_role,
1028 uint64_t perm, uint64_t shared_perm,
1029 void *opaque, Error **errp);
1030 void bdrv_root_unref_child(BdrvChild *child);
1032 int bdrv_child_try_set_perm(BdrvChild *c, uint64_t perm, uint64_t shared,
1033 Error **errp);
1035 /* Default implementation for BlockDriver.bdrv_child_perm() that can be used by
1036 * block filters: Forward CONSISTENT_READ, WRITE, WRITE_UNCHANGED and RESIZE to
1037 * all children */
1038 void bdrv_filter_default_perms(BlockDriverState *bs, BdrvChild *c,
1039 const BdrvChildRole *role,
1040 BlockReopenQueue *reopen_queue,
1041 uint64_t perm, uint64_t shared,
1042 uint64_t *nperm, uint64_t *nshared);
1044 /* Default implementation for BlockDriver.bdrv_child_perm() that can be used by
1045 * (non-raw) image formats: Like above for bs->backing, but for bs->file it
1046 * requires WRITE | RESIZE for read-write images, always requires
1047 * CONSISTENT_READ and doesn't share WRITE. */
1048 void bdrv_format_default_perms(BlockDriverState *bs, BdrvChild *c,
1049 const BdrvChildRole *role,
1050 BlockReopenQueue *reopen_queue,
1051 uint64_t perm, uint64_t shared,
1052 uint64_t *nperm, uint64_t *nshared);
1055 * Default implementation for drivers to pass bdrv_co_block_status() to
1056 * their file.
1058 int coroutine_fn bdrv_co_block_status_from_file(BlockDriverState *bs,
1059 bool want_zero,
1060 int64_t offset,
1061 int64_t bytes,
1062 int64_t *pnum,
1063 int64_t *map,
1064 BlockDriverState **file);
1066 * Default implementation for drivers to pass bdrv_co_block_status() to
1067 * their backing file.
1069 int coroutine_fn bdrv_co_block_status_from_backing(BlockDriverState *bs,
1070 bool want_zero,
1071 int64_t offset,
1072 int64_t bytes,
1073 int64_t *pnum,
1074 int64_t *map,
1075 BlockDriverState **file);
1076 const char *bdrv_get_parent_name(const BlockDriverState *bs);
1077 void blk_dev_change_media_cb(BlockBackend *blk, bool load, Error **errp);
1078 bool blk_dev_has_removable_media(BlockBackend *blk);
1079 bool blk_dev_has_tray(BlockBackend *blk);
1080 void blk_dev_eject_request(BlockBackend *blk, bool force);
1081 bool blk_dev_is_tray_open(BlockBackend *blk);
1082 bool blk_dev_is_medium_locked(BlockBackend *blk);
1084 void bdrv_set_dirty(BlockDriverState *bs, int64_t offset, int64_t bytes);
1086 void bdrv_clear_dirty_bitmap(BdrvDirtyBitmap *bitmap, HBitmap **out);
1087 void bdrv_undo_clear_dirty_bitmap(BdrvDirtyBitmap *bitmap, HBitmap *in);
1089 void bdrv_inc_in_flight(BlockDriverState *bs);
1090 void bdrv_dec_in_flight(BlockDriverState *bs);
1092 void blockdev_close_all_bdrv_states(void);
1094 #endif /* BLOCK_INT_H */