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