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