Merge tag 'v2.10.0-rc0'
[qemu/ar7.git] / include / block / block_int.h
blobade1d1e3d4873afa0cf9f22f09bc901d0b243573
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 "qemu/option.h"
30 #include "qemu/queue.h"
31 #include "qemu/coroutine.h"
32 #include "qemu/stats64.h"
33 #include "qemu/timer.h"
34 #include "qapi-types.h"
35 #include "qemu/hbitmap.h"
36 #include "block/snapshot.h"
37 #include "qemu/main-loop.h"
38 #include "qemu/throttle.h"
40 #define BLOCK_FLAG_LAZY_REFCOUNTS 8
42 #define BLOCK_OPT_SIZE "size"
43 #define BLOCK_OPT_ENCRYPT "encryption"
44 #define BLOCK_OPT_ENCRYPT_FORMAT "encrypt.format"
45 #define BLOCK_OPT_COMPAT6 "compat6"
46 #define BLOCK_OPT_HWVERSION "hwversion"
47 #define BLOCK_OPT_BACKING_FILE "backing_file"
48 #define BLOCK_OPT_BACKING_FMT "backing_fmt"
49 #define BLOCK_OPT_CLUSTER_SIZE "cluster_size"
50 #define BLOCK_OPT_TABLE_SIZE "table_size"
51 #define BLOCK_OPT_PREALLOC "preallocation"
52 #define BLOCK_OPT_SUBFMT "subformat"
53 #define BLOCK_OPT_COMPAT_LEVEL "compat"
54 #define BLOCK_OPT_LAZY_REFCOUNTS "lazy_refcounts"
55 #define BLOCK_OPT_ADAPTER_TYPE "adapter_type"
56 #define BLOCK_OPT_REDUNDANCY "redundancy"
57 #define BLOCK_OPT_NOCOW "nocow"
58 #define BLOCK_OPT_OBJECT_SIZE "object_size"
59 #define BLOCK_OPT_REFCOUNT_BITS "refcount_bits"
61 #define BLOCK_PROBE_BUF_SIZE 512
63 enum BdrvTrackedRequestType {
64 BDRV_TRACKED_READ,
65 BDRV_TRACKED_WRITE,
66 BDRV_TRACKED_DISCARD,
69 typedef struct BdrvTrackedRequest {
70 BlockDriverState *bs;
71 int64_t offset;
72 unsigned int bytes;
73 enum BdrvTrackedRequestType type;
75 bool serialising;
76 int64_t overlap_offset;
77 unsigned int overlap_bytes;
79 QLIST_ENTRY(BdrvTrackedRequest) list;
80 Coroutine *co; /* owner, used for deadlock detection */
81 CoQueue wait_queue; /* coroutines blocked on this request */
83 struct BdrvTrackedRequest *waiting_for;
84 } BdrvTrackedRequest;
86 struct BlockDriver {
87 const char *format_name;
88 int instance_size;
90 /* set to true if the BlockDriver is a block filter */
91 bool is_filter;
92 /* for snapshots block filter like Quorum can implement the
93 * following recursive callback.
94 * It's purpose is to recurse on the filter children while calling
95 * bdrv_recurse_is_first_non_filter on them.
96 * For a sample implementation look in the future Quorum block filter.
98 bool (*bdrv_recurse_is_first_non_filter)(BlockDriverState *bs,
99 BlockDriverState *candidate);
101 int (*bdrv_probe)(const uint8_t *buf, int buf_size, const char *filename);
102 int (*bdrv_probe_device)(const char *filename);
104 /* Any driver implementing this callback is expected to be able to handle
105 * NULL file names in its .bdrv_open() implementation */
106 void (*bdrv_parse_filename)(const char *filename, QDict *options, Error **errp);
107 /* Drivers not implementing bdrv_parse_filename nor bdrv_open should have
108 * this field set to true, except ones that are defined only by their
109 * child's bs.
110 * An example of the last type will be the quorum block driver.
112 bool bdrv_needs_filename;
114 /* Set if a driver can support backing files */
115 bool supports_backing;
117 /* For handling image reopen for split or non-split files */
118 int (*bdrv_reopen_prepare)(BDRVReopenState *reopen_state,
119 BlockReopenQueue *queue, Error **errp);
120 void (*bdrv_reopen_commit)(BDRVReopenState *reopen_state);
121 void (*bdrv_reopen_abort)(BDRVReopenState *reopen_state);
122 void (*bdrv_join_options)(QDict *options, QDict *old_options);
124 int (*bdrv_open)(BlockDriverState *bs, QDict *options, int flags,
125 Error **errp);
126 int (*bdrv_file_open)(BlockDriverState *bs, QDict *options, int flags,
127 Error **errp);
128 void (*bdrv_close)(BlockDriverState *bs);
129 int (*bdrv_create)(const char *filename, QemuOpts *opts, Error **errp);
130 int (*bdrv_set_key)(BlockDriverState *bs, const char *key);
131 int (*bdrv_make_empty)(BlockDriverState *bs);
133 void (*bdrv_refresh_filename)(BlockDriverState *bs, QDict *options);
135 /* aio */
136 BlockAIOCB *(*bdrv_aio_readv)(BlockDriverState *bs,
137 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
138 BlockCompletionFunc *cb, void *opaque);
139 BlockAIOCB *(*bdrv_aio_writev)(BlockDriverState *bs,
140 int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
141 BlockCompletionFunc *cb, void *opaque);
142 BlockAIOCB *(*bdrv_aio_flush)(BlockDriverState *bs,
143 BlockCompletionFunc *cb, void *opaque);
144 BlockAIOCB *(*bdrv_aio_pdiscard)(BlockDriverState *bs,
145 int64_t offset, int bytes,
146 BlockCompletionFunc *cb, void *opaque);
148 int coroutine_fn (*bdrv_co_readv)(BlockDriverState *bs,
149 int64_t sector_num, int nb_sectors, QEMUIOVector *qiov);
150 int coroutine_fn (*bdrv_co_preadv)(BlockDriverState *bs,
151 uint64_t offset, uint64_t bytes, QEMUIOVector *qiov, int flags);
152 int coroutine_fn (*bdrv_co_writev)(BlockDriverState *bs,
153 int64_t sector_num, int nb_sectors, QEMUIOVector *qiov);
154 int coroutine_fn (*bdrv_co_writev_flags)(BlockDriverState *bs,
155 int64_t sector_num, int nb_sectors, QEMUIOVector *qiov, int flags);
156 int coroutine_fn (*bdrv_co_pwritev)(BlockDriverState *bs,
157 uint64_t offset, uint64_t bytes, QEMUIOVector *qiov, int flags);
160 * Efficiently zero a region of the disk image. Typically an image format
161 * would use a compact metadata representation to implement this. This
162 * function pointer may be NULL or return -ENOSUP and .bdrv_co_writev()
163 * will be called instead.
165 int coroutine_fn (*bdrv_co_pwrite_zeroes)(BlockDriverState *bs,
166 int64_t offset, int bytes, BdrvRequestFlags flags);
167 int coroutine_fn (*bdrv_co_pdiscard)(BlockDriverState *bs,
168 int64_t offset, int bytes);
171 * Building block for bdrv_block_status[_above]. The driver should
172 * answer only according to the current layer, and should not
173 * set BDRV_BLOCK_ALLOCATED, but may set BDRV_BLOCK_RAW. See block.h
174 * for the meaning of _DATA, _ZERO, and _OFFSET_VALID.
176 int64_t coroutine_fn (*bdrv_co_get_block_status)(BlockDriverState *bs,
177 int64_t sector_num, int nb_sectors, int *pnum,
178 BlockDriverState **file);
181 * Invalidate any cached meta-data.
183 void (*bdrv_invalidate_cache)(BlockDriverState *bs, Error **errp);
184 int (*bdrv_inactivate)(BlockDriverState *bs);
187 * Flushes all data for all layers by calling bdrv_co_flush for underlying
188 * layers, if needed. This function is needed for deterministic
189 * synchronization of the flush finishing callback.
191 int coroutine_fn (*bdrv_co_flush)(BlockDriverState *bs);
194 * Flushes all data that was already written to the OS all the way down to
195 * the disk (for example file-posix.c calls fsync()).
197 int coroutine_fn (*bdrv_co_flush_to_disk)(BlockDriverState *bs);
200 * Flushes all internal caches to the OS. The data may still sit in a
201 * writeback cache of the host OS, but it will survive a crash of the qemu
202 * process.
204 int coroutine_fn (*bdrv_co_flush_to_os)(BlockDriverState *bs);
206 const char *protocol_name;
207 int (*bdrv_truncate)(BlockDriverState *bs, int64_t offset,
208 PreallocMode prealloc, Error **errp);
210 int64_t (*bdrv_getlength)(BlockDriverState *bs);
211 bool has_variable_length;
212 int64_t (*bdrv_get_allocated_file_size)(BlockDriverState *bs);
213 BlockMeasureInfo *(*bdrv_measure)(QemuOpts *opts, BlockDriverState *in_bs,
214 Error **errp);
216 int coroutine_fn (*bdrv_co_pwritev_compressed)(BlockDriverState *bs,
217 uint64_t offset, uint64_t bytes, QEMUIOVector *qiov);
219 int (*bdrv_snapshot_create)(BlockDriverState *bs,
220 QEMUSnapshotInfo *sn_info);
221 int (*bdrv_snapshot_goto)(BlockDriverState *bs,
222 const char *snapshot_id);
223 int (*bdrv_snapshot_delete)(BlockDriverState *bs,
224 const char *snapshot_id,
225 const char *name,
226 Error **errp);
227 int (*bdrv_snapshot_list)(BlockDriverState *bs,
228 QEMUSnapshotInfo **psn_info);
229 int (*bdrv_snapshot_load_tmp)(BlockDriverState *bs,
230 const char *snapshot_id,
231 const char *name,
232 Error **errp);
233 int (*bdrv_get_info)(BlockDriverState *bs, BlockDriverInfo *bdi);
234 ImageInfoSpecific *(*bdrv_get_specific_info)(BlockDriverState *bs);
235 int (*bdrv_update)(BlockDriverState *bs, int argc, char **argv);
237 int coroutine_fn (*bdrv_save_vmstate)(BlockDriverState *bs,
238 QEMUIOVector *qiov,
239 int64_t pos);
240 int coroutine_fn (*bdrv_load_vmstate)(BlockDriverState *bs,
241 QEMUIOVector *qiov,
242 int64_t pos);
244 int (*bdrv_change_backing_file)(BlockDriverState *bs,
245 const char *backing_file, const char *backing_fmt);
247 /* removable device specific */
248 bool (*bdrv_is_inserted)(BlockDriverState *bs);
249 int (*bdrv_media_changed)(BlockDriverState *bs);
250 void (*bdrv_eject)(BlockDriverState *bs, bool eject_flag);
251 void (*bdrv_lock_medium)(BlockDriverState *bs, bool locked);
253 /* to control generic scsi devices */
254 BlockAIOCB *(*bdrv_aio_ioctl)(BlockDriverState *bs,
255 unsigned long int req, void *buf,
256 BlockCompletionFunc *cb, void *opaque);
257 int coroutine_fn (*bdrv_co_ioctl)(BlockDriverState *bs,
258 unsigned long int req, void *buf);
260 /* List of options for creating images, terminated by name == NULL */
261 QemuOptsList *create_opts;
264 * Returns 0 for completed check, -errno for internal errors.
265 * The check results are stored in result.
267 int (*bdrv_check)(BlockDriverState *bs, BdrvCheckResult *result,
268 BdrvCheckMode fix);
270 int (*bdrv_amend_options)(BlockDriverState *bs, QemuOpts *opts,
271 BlockDriverAmendStatusCB *status_cb,
272 void *cb_opaque);
274 void (*bdrv_debug_event)(BlockDriverState *bs, BlkdebugEvent event);
276 /* TODO Better pass a option string/QDict/QemuOpts to add any rule? */
277 int (*bdrv_debug_breakpoint)(BlockDriverState *bs, const char *event,
278 const char *tag);
279 int (*bdrv_debug_remove_breakpoint)(BlockDriverState *bs,
280 const char *tag);
281 int (*bdrv_debug_resume)(BlockDriverState *bs, const char *tag);
282 bool (*bdrv_debug_is_suspended)(BlockDriverState *bs, const char *tag);
284 void (*bdrv_refresh_limits)(BlockDriverState *bs, Error **errp);
287 * Returns 1 if newly created images are guaranteed to contain only
288 * zeros, 0 otherwise.
290 int (*bdrv_has_zero_init)(BlockDriverState *bs);
292 /* Remove fd handlers, timers, and other event loop callbacks so the event
293 * loop is no longer in use. Called with no in-flight requests and in
294 * depth-first traversal order with parents before child nodes.
296 void (*bdrv_detach_aio_context)(BlockDriverState *bs);
298 /* Add fd handlers, timers, and other event loop callbacks so I/O requests
299 * can be processed again. Called with no in-flight requests and in
300 * depth-first traversal order with child nodes before parent nodes.
302 void (*bdrv_attach_aio_context)(BlockDriverState *bs,
303 AioContext *new_context);
305 /* io queue for linux-aio */
306 void (*bdrv_io_plug)(BlockDriverState *bs);
307 void (*bdrv_io_unplug)(BlockDriverState *bs);
310 * Try to get @bs's logical and physical block size.
311 * On success, store them in @bsz and return zero.
312 * On failure, return negative errno.
314 int (*bdrv_probe_blocksizes)(BlockDriverState *bs, BlockSizes *bsz);
316 * Try to get @bs's geometry (cyls, heads, sectors)
317 * On success, store them in @geo and return 0.
318 * On failure return -errno.
319 * Only drivers that want to override guest geometry implement this
320 * callback; see hd_geometry_guess().
322 int (*bdrv_probe_geometry)(BlockDriverState *bs, HDGeometry *geo);
325 * Drain and stop any internal sources of requests in the driver, and
326 * remain so until next I/O callback (e.g. bdrv_co_writev) is called.
328 void coroutine_fn (*bdrv_co_drain)(BlockDriverState *bs);
330 void (*bdrv_add_child)(BlockDriverState *parent, BlockDriverState *child,
331 Error **errp);
332 void (*bdrv_del_child)(BlockDriverState *parent, BdrvChild *child,
333 Error **errp);
336 * Informs the block driver that a permission change is intended. The
337 * driver checks whether the change is permissible and may take other
338 * preparations for the change (e.g. get file system locks). This operation
339 * is always followed either by a call to either .bdrv_set_perm or
340 * .bdrv_abort_perm_update.
342 * Checks whether the requested set of cumulative permissions in @perm
343 * can be granted for accessing @bs and whether no other users are using
344 * permissions other than those given in @shared (both arguments take
345 * BLK_PERM_* bitmasks).
347 * If both conditions are met, 0 is returned. Otherwise, -errno is returned
348 * and errp is set to an error describing the conflict.
350 int (*bdrv_check_perm)(BlockDriverState *bs, uint64_t perm,
351 uint64_t shared, Error **errp);
354 * Called to inform the driver that the set of cumulative set of used
355 * permissions for @bs has changed to @perm, and the set of sharable
356 * permission to @shared. The driver can use this to propagate changes to
357 * its children (i.e. request permissions only if a parent actually needs
358 * them).
360 * This function is only invoked after bdrv_check_perm(), so block drivers
361 * may rely on preparations made in their .bdrv_check_perm implementation.
363 void (*bdrv_set_perm)(BlockDriverState *bs, uint64_t perm, uint64_t shared);
366 * Called to inform the driver that after a previous bdrv_check_perm()
367 * call, the permission update is not performed and any preparations made
368 * for it (e.g. taken file locks) need to be undone.
370 * This function can be called even for nodes that never saw a
371 * bdrv_check_perm() call. It is a no-op then.
373 void (*bdrv_abort_perm_update)(BlockDriverState *bs);
376 * Returns in @nperm and @nshared the permissions that the driver for @bs
377 * needs on its child @c, based on the cumulative permissions requested by
378 * the parents in @parent_perm and @parent_shared.
380 * If @c is NULL, return the permissions for attaching a new child for the
381 * given @role.
383 void (*bdrv_child_perm)(BlockDriverState *bs, BdrvChild *c,
384 const BdrvChildRole *role,
385 uint64_t parent_perm, uint64_t parent_shared,
386 uint64_t *nperm, uint64_t *nshared);
389 * Bitmaps should be marked as 'IN_USE' in the image on reopening image
390 * as rw. This handler should realize it. It also should unset readonly
391 * field of BlockDirtyBitmap's in case of success.
393 int (*bdrv_reopen_bitmaps_rw)(BlockDriverState *bs, Error **errp);
394 bool (*bdrv_can_store_new_dirty_bitmap)(BlockDriverState *bs,
395 const char *name,
396 uint32_t granularity,
397 Error **errp);
398 void (*bdrv_remove_persistent_dirty_bitmap)(BlockDriverState *bs,
399 const char *name,
400 Error **errp);
402 QLIST_ENTRY(BlockDriver) list;
405 typedef struct BlockLimits {
406 /* Alignment requirement, in bytes, for offset/length of I/O
407 * requests. Must be a power of 2 less than INT_MAX; defaults to
408 * 1 for drivers with modern byte interfaces, and to 512
409 * otherwise. */
410 uint32_t request_alignment;
412 /* Maximum number of bytes that can be discarded at once (since it
413 * is signed, it must be < 2G, if set). Must be multiple of
414 * pdiscard_alignment, but need not be power of 2. May be 0 if no
415 * inherent 32-bit limit */
416 int32_t max_pdiscard;
418 /* Optimal alignment for discard requests in bytes. A power of 2
419 * is best but not mandatory. Must be a multiple of
420 * bl.request_alignment, and must be less than max_pdiscard if
421 * that is set. May be 0 if bl.request_alignment is good enough */
422 uint32_t pdiscard_alignment;
424 /* Maximum number of bytes that can zeroized at once (since it is
425 * signed, it must be < 2G, if set). Must be multiple of
426 * pwrite_zeroes_alignment. May be 0 if no inherent 32-bit limit */
427 int32_t max_pwrite_zeroes;
429 /* Optimal alignment for write zeroes requests in bytes. A power
430 * of 2 is best but not mandatory. Must be a multiple of
431 * bl.request_alignment, and must be less than max_pwrite_zeroes
432 * if that is set. May be 0 if bl.request_alignment is good
433 * enough */
434 uint32_t pwrite_zeroes_alignment;
436 /* Optimal transfer length in bytes. A power of 2 is best but not
437 * mandatory. Must be a multiple of bl.request_alignment, or 0 if
438 * no preferred size */
439 uint32_t opt_transfer;
441 /* Maximal transfer length in bytes. Need not be power of 2, but
442 * must be multiple of opt_transfer and bl.request_alignment, or 0
443 * for no 32-bit limit. For now, anything larger than INT_MAX is
444 * clamped down. */
445 uint32_t max_transfer;
447 /* memory alignment, in bytes so that no bounce buffer is needed */
448 size_t min_mem_alignment;
450 /* memory alignment, in bytes, for bounce buffer */
451 size_t opt_mem_alignment;
453 /* maximum number of iovec elements */
454 int max_iov;
455 } BlockLimits;
457 typedef struct BdrvOpBlocker BdrvOpBlocker;
459 typedef struct BdrvAioNotifier {
460 void (*attached_aio_context)(AioContext *new_context, void *opaque);
461 void (*detach_aio_context)(void *opaque);
463 void *opaque;
464 bool deleted;
466 QLIST_ENTRY(BdrvAioNotifier) list;
467 } BdrvAioNotifier;
469 struct BdrvChildRole {
470 /* If true, bdrv_replace_node() doesn't change the node this BdrvChild
471 * points to. */
472 bool stay_at_node;
474 void (*inherit_options)(int *child_flags, QDict *child_options,
475 int parent_flags, QDict *parent_options);
477 void (*change_media)(BdrvChild *child, bool load);
478 void (*resize)(BdrvChild *child);
480 /* Returns a name that is supposedly more useful for human users than the
481 * node name for identifying the node in question (in particular, a BB
482 * name), or NULL if the parent can't provide a better name. */
483 const char *(*get_name)(BdrvChild *child);
485 /* Returns a malloced string that describes the parent of the child for a
486 * human reader. This could be a node-name, BlockBackend name, qdev ID or
487 * QOM path of the device owning the BlockBackend, job type and ID etc. The
488 * caller is responsible for freeing the memory. */
489 char *(*get_parent_desc)(BdrvChild *child);
492 * If this pair of functions is implemented, the parent doesn't issue new
493 * requests after returning from .drained_begin() until .drained_end() is
494 * called.
496 * Note that this can be nested. If drained_begin() was called twice, new
497 * I/O is allowed only after drained_end() was called twice, too.
499 void (*drained_begin)(BdrvChild *child);
500 void (*drained_end)(BdrvChild *child);
502 /* Notifies the parent that the child has been activated/inactivated (e.g.
503 * when migration is completing) and it can start/stop requesting
504 * permissions and doing I/O on it. */
505 void (*activate)(BdrvChild *child, Error **errp);
506 int (*inactivate)(BdrvChild *child);
508 void (*attach)(BdrvChild *child);
509 void (*detach)(BdrvChild *child);
512 extern const BdrvChildRole child_file;
513 extern const BdrvChildRole child_format;
514 extern const BdrvChildRole child_backing;
516 struct BdrvChild {
517 BlockDriverState *bs;
518 char *name;
519 const BdrvChildRole *role;
520 void *opaque;
523 * Granted permissions for operating on this BdrvChild (BLK_PERM_* bitmask)
525 uint64_t perm;
528 * Permissions that can still be granted to other users of @bs while this
529 * BdrvChild is still attached to it. (BLK_PERM_* bitmask)
531 uint64_t shared_perm;
533 QLIST_ENTRY(BdrvChild) next;
534 QLIST_ENTRY(BdrvChild) next_parent;
538 * Note: the function bdrv_append() copies and swaps contents of
539 * BlockDriverStates, so if you add new fields to this struct, please
540 * inspect bdrv_append() to determine if the new fields need to be
541 * copied as well.
543 struct BlockDriverState {
544 /* Protected by big QEMU lock or read-only after opening. No special
545 * locking needed during I/O...
547 int open_flags; /* flags used to open the file, re-used for re-open */
548 bool read_only; /* if true, the media is read only */
549 bool encrypted; /* if true, the media is encrypted */
550 bool sg; /* if true, the device is a /dev/sg* */
551 bool probed; /* if true, format was probed rather than specified */
552 bool force_share; /* if true, always allow all shared permissions */
553 bool implicit; /* if true, this filter node was automatically inserted */
555 BlockDriver *drv; /* NULL means no media */
556 void *opaque;
558 AioContext *aio_context; /* event loop used for fd handlers, timers, etc */
559 /* long-running tasks intended to always use the same AioContext as this
560 * BDS may register themselves in this list to be notified of changes
561 * regarding this BDS's context */
562 QLIST_HEAD(, BdrvAioNotifier) aio_notifiers;
563 bool walking_aio_notifiers; /* to make removal during iteration safe */
565 char filename[PATH_MAX];
566 char backing_file[PATH_MAX]; /* if non zero, the image is a diff of
567 this file image */
568 char backing_format[16]; /* if non-zero and backing_file exists */
570 QDict *full_open_options;
571 char exact_filename[PATH_MAX];
573 BdrvChild *backing;
574 BdrvChild *file;
576 /* I/O Limits */
577 BlockLimits bl;
579 /* Flags honored during pwrite (so far: BDRV_REQ_FUA) */
580 unsigned int supported_write_flags;
581 /* Flags honored during pwrite_zeroes (so far: BDRV_REQ_FUA,
582 * BDRV_REQ_MAY_UNMAP) */
583 unsigned int supported_zero_flags;
585 /* the following member gives a name to every node on the bs graph. */
586 char node_name[32];
587 /* element of the list of named nodes building the graph */
588 QTAILQ_ENTRY(BlockDriverState) node_list;
589 /* element of the list of all BlockDriverStates (all_bdrv_states) */
590 QTAILQ_ENTRY(BlockDriverState) bs_list;
591 /* element of the list of monitor-owned BDS */
592 QTAILQ_ENTRY(BlockDriverState) monitor_list;
593 int refcnt;
595 /* operation blockers */
596 QLIST_HEAD(, BdrvOpBlocker) op_blockers[BLOCK_OP_TYPE_MAX];
598 /* long-running background operation */
599 BlockJob *job;
601 /* The node that this node inherited default options from (and a reopen on
602 * which can affect this node by changing these defaults). This is always a
603 * parent node of this node. */
604 BlockDriverState *inherits_from;
605 QLIST_HEAD(, BdrvChild) children;
606 QLIST_HEAD(, BdrvChild) parents;
608 QDict *options;
609 QDict *explicit_options;
610 BlockdevDetectZeroesOptions detect_zeroes;
612 /* The error object in use for blocking operations on backing_hd */
613 Error *backing_blocker;
615 /* Protected by AioContext lock */
617 /* If we are reading a disk image, give its size in sectors.
618 * Generally read-only; it is written to by load_snapshot and
619 * save_snaphost, but the block layer is quiescent during those.
621 int64_t total_sectors;
623 /* Callback before write request is processed */
624 NotifierWithReturnList before_write_notifiers;
626 /* threshold limit for writes, in bytes. "High water mark". */
627 uint64_t write_threshold_offset;
628 NotifierWithReturn write_threshold_notifier;
630 /* Writing to the list requires the BQL _and_ the dirty_bitmap_mutex.
631 * Reading from the list can be done with either the BQL or the
632 * dirty_bitmap_mutex. Modifying a bitmap only requires
633 * dirty_bitmap_mutex. */
634 QemuMutex dirty_bitmap_mutex;
635 QLIST_HEAD(, BdrvDirtyBitmap) dirty_bitmaps;
637 /* Offset after the highest byte written to */
638 Stat64 wr_highest_offset;
640 /* If true, copy read backing sectors into image. Can be >1 if more
641 * than one client has requested copy-on-read. Accessed with atomic
642 * ops.
644 int copy_on_read;
646 /* number of in-flight requests; overall and serialising.
647 * Accessed with atomic ops.
649 unsigned int in_flight;
650 unsigned int serialising_in_flight;
652 /* Internal to BDRV_POLL_WHILE and bdrv_wakeup. Accessed with atomic
653 * ops.
655 bool wakeup;
657 /* counter for nested bdrv_io_plug.
658 * Accessed with atomic ops.
660 unsigned io_plugged;
662 /* do we need to tell the quest if we have a volatile write cache? */
663 int enable_write_cache;
665 /* Accessed with atomic ops. */
666 int quiesce_counter;
667 unsigned int write_gen; /* Current data generation */
669 /* Protected by reqs_lock. */
670 CoMutex reqs_lock;
671 QLIST_HEAD(, BdrvTrackedRequest) tracked_requests;
672 CoQueue flush_queue; /* Serializing flush queue */
673 bool active_flush_req; /* Flush request in flight? */
675 /* Only read/written by whoever has set active_flush_req to true. */
676 unsigned int flushed_gen; /* Flushed write generation */
679 struct BlockBackendRootState {
680 int open_flags;
681 bool read_only;
682 BlockdevDetectZeroesOptions detect_zeroes;
685 typedef enum BlockMirrorBackingMode {
686 /* Reuse the existing backing chain from the source for the target.
687 * - sync=full: Set backing BDS to NULL.
688 * - sync=top: Use source's backing BDS.
689 * - sync=none: Use source as the backing BDS. */
690 MIRROR_SOURCE_BACKING_CHAIN,
692 /* Open the target's backing chain completely anew */
693 MIRROR_OPEN_BACKING_CHAIN,
695 /* Do not change the target's backing BDS after job completion */
696 MIRROR_LEAVE_BACKING_CHAIN,
697 } BlockMirrorBackingMode;
699 static inline BlockDriverState *backing_bs(BlockDriverState *bs)
701 return bs->backing ? bs->backing->bs : NULL;
705 /* Essential block drivers which must always be statically linked into qemu, and
706 * which therefore can be accessed without using bdrv_find_format() */
707 extern BlockDriver bdrv_file;
708 extern BlockDriver bdrv_raw;
709 extern BlockDriver bdrv_qcow2;
711 int coroutine_fn bdrv_co_preadv(BdrvChild *child,
712 int64_t offset, unsigned int bytes, QEMUIOVector *qiov,
713 BdrvRequestFlags flags);
714 int coroutine_fn bdrv_co_pwritev(BdrvChild *child,
715 int64_t offset, unsigned int bytes, QEMUIOVector *qiov,
716 BdrvRequestFlags flags);
718 int get_tmp_filename(char *filename, int size);
719 BlockDriver *bdrv_probe_all(const uint8_t *buf, int buf_size,
720 const char *filename);
722 void bdrv_parse_filename_strip_prefix(const char *filename, const char *prefix,
723 QDict *options);
727 * bdrv_add_before_write_notifier:
729 * Register a callback that is invoked before write requests are processed but
730 * after any throttling or waiting for overlapping requests.
732 void bdrv_add_before_write_notifier(BlockDriverState *bs,
733 NotifierWithReturn *notifier);
736 * bdrv_detach_aio_context:
738 * May be called from .bdrv_detach_aio_context() to detach children from the
739 * current #AioContext. This is only needed by block drivers that manage their
740 * own children. Both ->file and ->backing are automatically handled and
741 * block drivers should not call this function on them explicitly.
743 void bdrv_detach_aio_context(BlockDriverState *bs);
746 * bdrv_attach_aio_context:
748 * May be called from .bdrv_attach_aio_context() to attach children to the new
749 * #AioContext. This is only needed by block drivers that manage their own
750 * children. Both ->file and ->backing are automatically handled and block
751 * drivers should not call this function on them explicitly.
753 void bdrv_attach_aio_context(BlockDriverState *bs,
754 AioContext *new_context);
757 * bdrv_add_aio_context_notifier:
759 * If a long-running job intends to be always run in the same AioContext as a
760 * certain BDS, it may use this function to be notified of changes regarding the
761 * association of the BDS to an AioContext.
763 * attached_aio_context() is called after the target BDS has been attached to a
764 * new AioContext; detach_aio_context() is called before the target BDS is being
765 * detached from its old AioContext.
767 void bdrv_add_aio_context_notifier(BlockDriverState *bs,
768 void (*attached_aio_context)(AioContext *new_context, void *opaque),
769 void (*detach_aio_context)(void *opaque), void *opaque);
772 * bdrv_remove_aio_context_notifier:
774 * Unsubscribe of change notifications regarding the BDS's AioContext. The
775 * parameters given here have to be the same as those given to
776 * bdrv_add_aio_context_notifier().
778 void bdrv_remove_aio_context_notifier(BlockDriverState *bs,
779 void (*aio_context_attached)(AioContext *,
780 void *),
781 void (*aio_context_detached)(void *),
782 void *opaque);
785 * bdrv_wakeup:
786 * @bs: The BlockDriverState for which an I/O operation has been completed.
788 * Wake up the main thread if it is waiting on BDRV_POLL_WHILE. During
789 * synchronous I/O on a BlockDriverState that is attached to another
790 * I/O thread, the main thread lets the I/O thread's event loop run,
791 * waiting for the I/O operation to complete. A bdrv_wakeup will wake
792 * up the main thread if necessary.
794 * Manual calls to bdrv_wakeup are rarely necessary, because
795 * bdrv_dec_in_flight already calls it.
797 void bdrv_wakeup(BlockDriverState *bs);
799 #ifdef _WIN32
800 int is_windows_drive(const char *filename);
801 #endif
804 * stream_start:
805 * @job_id: The id of the newly-created job, or %NULL to use the
806 * device name of @bs.
807 * @bs: Block device to operate on.
808 * @base: Block device that will become the new base, or %NULL to
809 * flatten the whole backing file chain onto @bs.
810 * @backing_file_str: The file name that will be written to @bs as the
811 * the new backing file if the job completes. Ignored if @base is %NULL.
812 * @speed: The maximum speed, in bytes per second, or 0 for unlimited.
813 * @on_error: The action to take upon error.
814 * @errp: Error object.
816 * Start a streaming operation on @bs. Clusters that are unallocated
817 * in @bs, but allocated in any image between @base and @bs (both
818 * exclusive) will be written to @bs. At the end of a successful
819 * streaming job, the backing file of @bs will be changed to
820 * @backing_file_str in the written image and to @base in the live
821 * BlockDriverState.
823 void stream_start(const char *job_id, BlockDriverState *bs,
824 BlockDriverState *base, const char *backing_file_str,
825 int64_t speed, BlockdevOnError on_error, Error **errp);
828 * commit_start:
829 * @job_id: The id of the newly-created job, or %NULL to use the
830 * device name of @bs.
831 * @bs: Active block device.
832 * @top: Top block device to be committed.
833 * @base: Block device that will be written into, and become the new top.
834 * @speed: The maximum speed, in bytes per second, or 0 for unlimited.
835 * @on_error: The action to take upon error.
836 * @backing_file_str: String to use as the backing file in @top's overlay
837 * @filter_node_name: The node name that should be assigned to the filter
838 * driver that the commit job inserts into the graph above @top. NULL means
839 * that a node name should be autogenerated.
840 * @errp: Error object.
843 void commit_start(const char *job_id, BlockDriverState *bs,
844 BlockDriverState *base, BlockDriverState *top, int64_t speed,
845 BlockdevOnError on_error, const char *backing_file_str,
846 const char *filter_node_name, Error **errp);
848 * commit_active_start:
849 * @job_id: The id of the newly-created job, or %NULL to use the
850 * device name of @bs.
851 * @bs: Active block device to be committed.
852 * @base: Block device that will be written into, and become the new top.
853 * @creation_flags: Flags that control the behavior of the Job lifetime.
854 * See @BlockJobCreateFlags
855 * @speed: The maximum speed, in bytes per second, or 0 for unlimited.
856 * @on_error: The action to take upon error.
857 * @filter_node_name: The node name that should be assigned to the filter
858 * driver that the commit job inserts into the graph above @bs. NULL means that
859 * a node name should be autogenerated.
860 * @cb: Completion function for the job.
861 * @opaque: Opaque pointer value passed to @cb.
862 * @auto_complete: Auto complete the job.
863 * @errp: Error object.
866 void commit_active_start(const char *job_id, BlockDriverState *bs,
867 BlockDriverState *base, int creation_flags,
868 int64_t speed, BlockdevOnError on_error,
869 const char *filter_node_name,
870 BlockCompletionFunc *cb, void *opaque,
871 bool auto_complete, Error **errp);
873 * mirror_start:
874 * @job_id: The id of the newly-created job, or %NULL to use the
875 * device name of @bs.
876 * @bs: Block device to operate on.
877 * @target: Block device to write to.
878 * @replaces: Block graph node name to replace once the mirror is done. Can
879 * only be used when full mirroring is selected.
880 * @speed: The maximum speed, in bytes per second, or 0 for unlimited.
881 * @granularity: The chosen granularity for the dirty bitmap.
882 * @buf_size: The amount of data that can be in flight at one time.
883 * @mode: Whether to collapse all images in the chain to the target.
884 * @backing_mode: How to establish the target's backing chain after completion.
885 * @on_source_error: The action to take upon error reading from the source.
886 * @on_target_error: The action to take upon error writing to the target.
887 * @unmap: Whether to unmap target where source sectors only contain zeroes.
888 * @filter_node_name: The node name that should be assigned to the filter
889 * driver that the mirror job inserts into the graph above @bs. NULL means that
890 * a node name should be autogenerated.
891 * @errp: Error object.
893 * Start a mirroring operation on @bs. Clusters that are allocated
894 * in @bs will be written to @target until the job is cancelled or
895 * manually completed. At the end of a successful mirroring job,
896 * @bs will be switched to read from @target.
898 void mirror_start(const char *job_id, BlockDriverState *bs,
899 BlockDriverState *target, const char *replaces,
900 int64_t speed, uint32_t granularity, int64_t buf_size,
901 MirrorSyncMode mode, BlockMirrorBackingMode backing_mode,
902 BlockdevOnError on_source_error,
903 BlockdevOnError on_target_error,
904 bool unmap, const char *filter_node_name, Error **errp);
907 * backup_job_create:
908 * @job_id: The id of the newly-created job, or %NULL to use the
909 * device name of @bs.
910 * @bs: Block device to operate on.
911 * @target: Block device to write to.
912 * @speed: The maximum speed, in bytes per second, or 0 for unlimited.
913 * @sync_mode: What parts of the disk image should be copied to the destination.
914 * @sync_bitmap: The dirty bitmap if sync_mode is MIRROR_SYNC_MODE_INCREMENTAL.
915 * @on_source_error: The action to take upon error reading from the source.
916 * @on_target_error: The action to take upon error writing to the target.
917 * @creation_flags: Flags that control the behavior of the Job lifetime.
918 * See @BlockJobCreateFlags
919 * @cb: Completion function for the job.
920 * @opaque: Opaque pointer value passed to @cb.
921 * @txn: Transaction that this job is part of (may be NULL).
923 * Create a backup operation on @bs. Clusters in @bs are written to @target
924 * until the job is cancelled or manually completed.
926 BlockJob *backup_job_create(const char *job_id, BlockDriverState *bs,
927 BlockDriverState *target, int64_t speed,
928 MirrorSyncMode sync_mode,
929 BdrvDirtyBitmap *sync_bitmap,
930 bool compress,
931 BlockdevOnError on_source_error,
932 BlockdevOnError on_target_error,
933 int creation_flags,
934 BlockCompletionFunc *cb, void *opaque,
935 BlockJobTxn *txn, Error **errp);
937 void hmp_drive_add_node(Monitor *mon, const char *optstr);
939 BdrvChild *bdrv_root_attach_child(BlockDriverState *child_bs,
940 const char *child_name,
941 const BdrvChildRole *child_role,
942 uint64_t perm, uint64_t shared_perm,
943 void *opaque, Error **errp);
944 void bdrv_root_unref_child(BdrvChild *child);
946 int bdrv_child_try_set_perm(BdrvChild *c, uint64_t perm, uint64_t shared,
947 Error **errp);
949 /* Default implementation for BlockDriver.bdrv_child_perm() that can be used by
950 * block filters: Forward CONSISTENT_READ, WRITE, WRITE_UNCHANGED and RESIZE to
951 * all children */
952 void bdrv_filter_default_perms(BlockDriverState *bs, BdrvChild *c,
953 const BdrvChildRole *role,
954 uint64_t perm, uint64_t shared,
955 uint64_t *nperm, uint64_t *nshared);
957 /* Default implementation for BlockDriver.bdrv_child_perm() that can be used by
958 * (non-raw) image formats: Like above for bs->backing, but for bs->file it
959 * requires WRITE | RESIZE for read-write images, always requires
960 * CONSISTENT_READ and doesn't share WRITE. */
961 void bdrv_format_default_perms(BlockDriverState *bs, BdrvChild *c,
962 const BdrvChildRole *role,
963 uint64_t perm, uint64_t shared,
964 uint64_t *nperm, uint64_t *nshared);
966 const char *bdrv_get_parent_name(const BlockDriverState *bs);
967 void blk_dev_change_media_cb(BlockBackend *blk, bool load, Error **errp);
968 bool blk_dev_has_removable_media(BlockBackend *blk);
969 bool blk_dev_has_tray(BlockBackend *blk);
970 void blk_dev_eject_request(BlockBackend *blk, bool force);
971 bool blk_dev_is_tray_open(BlockBackend *blk);
972 bool blk_dev_is_medium_locked(BlockBackend *blk);
974 void bdrv_set_dirty(BlockDriverState *bs, int64_t cur_sector, int64_t nr_sect);
975 bool bdrv_requests_pending(BlockDriverState *bs);
977 void bdrv_clear_dirty_bitmap(BdrvDirtyBitmap *bitmap, HBitmap **out);
978 void bdrv_undo_clear_dirty_bitmap(BdrvDirtyBitmap *bitmap, HBitmap *in);
980 void bdrv_inc_in_flight(BlockDriverState *bs);
981 void bdrv_dec_in_flight(BlockDriverState *bs);
983 void blockdev_close_all_bdrv_states(void);
985 #endif /* BLOCK_INT_H */