]> Git Repo - qemu.git/blame - block.c
block: Revert .bdrv_drained_begin/end to non-coroutine_fn
[qemu.git] / block.c
CommitLineData
fc01f7e7
FB
1/*
2 * QEMU System Emulator block driver
5fafdf24 3 *
fc01f7e7 4 * Copyright (c) 2003 Fabrice Bellard
c20555e1 5 * Copyright (c) 2020 Virtuozzo International GmbH.
5fafdf24 6 *
fc01f7e7
FB
7 * Permission is hereby granted, free of charge, to any person obtaining a copy
8 * of this software and associated documentation files (the "Software"), to deal
9 * in the Software without restriction, including without limitation the rights
10 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11 * copies of the Software, and to permit persons to whom the Software is
12 * furnished to do so, subject to the following conditions:
13 *
14 * The above copyright notice and this permission notice shall be included in
15 * all copies or substantial portions of the Software.
16 *
17 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
20 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
23 * THE SOFTWARE.
24 */
e688df6b 25
d38ea87a 26#include "qemu/osdep.h"
0ab8ed18 27#include "block/trace.h"
737e150e
PB
28#include "block/block_int.h"
29#include "block/blockjob.h"
0c9b70d5 30#include "block/fuse.h"
cd7fca95 31#include "block/nbd.h"
609f45ea 32#include "block/qdict.h"
d49b6836 33#include "qemu/error-report.h"
5e5733e5 34#include "block/module_block.h"
db725815 35#include "qemu/main-loop.h"
1de7afc9 36#include "qemu/module.h"
e688df6b 37#include "qapi/error.h"
452fcdbc 38#include "qapi/qmp/qdict.h"
7b1b5d19 39#include "qapi/qmp/qjson.h"
e59a0cf1 40#include "qapi/qmp/qnull.h"
fc81fa1e 41#include "qapi/qmp/qstring.h"
e1d74bc6
KW
42#include "qapi/qobject-output-visitor.h"
43#include "qapi/qapi-visit-block-core.h"
bfb197e0 44#include "sysemu/block-backend.h"
1de7afc9 45#include "qemu/notify.h"
922a01a0 46#include "qemu/option.h"
10817bf0 47#include "qemu/coroutine.h"
c13163fb 48#include "block/qapi.h"
1de7afc9 49#include "qemu/timer.h"
f348b6d1
VB
50#include "qemu/cutils.h"
51#include "qemu/id.h"
0bc329fb
HR
52#include "qemu/range.h"
53#include "qemu/rcu.h"
21c2283e 54#include "block/coroutines.h"
fc01f7e7 55
71e72a19 56#ifdef CONFIG_BSD
7674e7bf 57#include <sys/ioctl.h>
72cf2d4f 58#include <sys/queue.h>
feccdcee 59#if defined(HAVE_SYS_DISK_H)
7674e7bf
FB
60#include <sys/disk.h>
61#endif
c5e97233 62#endif
7674e7bf 63
49dc768d
AL
64#ifdef _WIN32
65#include <windows.h>
66#endif
67
1c9805a3
SH
68#define NOT_DONE 0x7fffffff /* used while emulated sync operation in progress */
69
3b491a90 70/* Protected by BQL */
dc364f4c
BC
71static QTAILQ_HEAD(, BlockDriverState) graph_bdrv_states =
72 QTAILQ_HEAD_INITIALIZER(graph_bdrv_states);
73
3b491a90 74/* Protected by BQL */
2c1d04e0
HR
75static QTAILQ_HEAD(, BlockDriverState) all_bdrv_states =
76 QTAILQ_HEAD_INITIALIZER(all_bdrv_states);
77
3b491a90 78/* Protected by BQL */
8a22f02a
SH
79static QLIST_HEAD(, BlockDriver) bdrv_drivers =
80 QLIST_HEAD_INITIALIZER(bdrv_drivers);
ea2384d3 81
5b363937
HR
82static BlockDriverState *bdrv_open_inherit(const char *filename,
83 const char *reference,
84 QDict *options, int flags,
85 BlockDriverState *parent,
bd86fb99 86 const BdrvChildClass *child_class,
272c02ea 87 BdrvChildRole child_role,
5b363937 88 Error **errp);
f3930ed0 89
bfb8aa6d
KW
90static bool bdrv_recurse_has_child(BlockDriverState *bs,
91 BlockDriverState *child);
92
544acc7d 93static void bdrv_replace_child_noperm(BdrvChild *child,
4eba825a 94 BlockDriverState *new_bs);
57f08941 95static void bdrv_remove_child(BdrvChild *child, Transaction *tran);
0978623e 96
72373e40
VSO
97static int bdrv_reopen_prepare(BDRVReopenState *reopen_state,
98 BlockReopenQueue *queue,
ecd30d2d 99 Transaction *change_child_tran, Error **errp);
53e96d1e
VSO
100static void bdrv_reopen_commit(BDRVReopenState *reopen_state);
101static void bdrv_reopen_abort(BDRVReopenState *reopen_state);
102
fa8fc1d0
EGE
103static bool bdrv_backing_overridden(BlockDriverState *bs);
104
7e8c182f 105static bool bdrv_change_aio_context(BlockDriverState *bs, AioContext *ctx,
e08cc001 106 GHashTable *visited, Transaction *tran,
7e8c182f
EGE
107 Error **errp);
108
eb852011
MA
109/* If non-zero, use only whitelisted block drivers */
110static int use_bdrv_whitelist;
111
9e0b22f4
SH
112#ifdef _WIN32
113static int is_windows_drive_prefix(const char *filename)
114{
115 return (((filename[0] >= 'a' && filename[0] <= 'z') ||
116 (filename[0] >= 'A' && filename[0] <= 'Z')) &&
117 filename[1] == ':');
118}
119
120int is_windows_drive(const char *filename)
121{
122 if (is_windows_drive_prefix(filename) &&
123 filename[2] == '\0')
124 return 1;
125 if (strstart(filename, "\\\\.\\", NULL) ||
126 strstart(filename, "//./", NULL))
127 return 1;
128 return 0;
129}
130#endif
131
339064d5
KW
132size_t bdrv_opt_mem_align(BlockDriverState *bs)
133{
134 if (!bs || !bs->drv) {
459b4e66 135 /* page size or 4k (hdd sector size) should be on the safe side */
8e3b0cbb 136 return MAX(4096, qemu_real_host_page_size());
339064d5 137 }
384a48fb 138 IO_CODE();
339064d5
KW
139
140 return bs->bl.opt_mem_alignment;
141}
142
4196d2f0
DL
143size_t bdrv_min_mem_align(BlockDriverState *bs)
144{
145 if (!bs || !bs->drv) {
459b4e66 146 /* page size or 4k (hdd sector size) should be on the safe side */
8e3b0cbb 147 return MAX(4096, qemu_real_host_page_size());
4196d2f0 148 }
384a48fb 149 IO_CODE();
4196d2f0
DL
150
151 return bs->bl.min_mem_alignment;
152}
153
9e0b22f4 154/* check if the path starts with "<protocol>:" */
5c98415b 155int path_has_protocol(const char *path)
9e0b22f4 156{
947995c0
PB
157 const char *p;
158
9e0b22f4
SH
159#ifdef _WIN32
160 if (is_windows_drive(path) ||
161 is_windows_drive_prefix(path)) {
162 return 0;
163 }
947995c0
PB
164 p = path + strcspn(path, ":/\\");
165#else
166 p = path + strcspn(path, ":/");
9e0b22f4
SH
167#endif
168
947995c0 169 return *p == ':';
9e0b22f4
SH
170}
171
83f64091 172int path_is_absolute(const char *path)
3b0d4f61 173{
21664424
FB
174#ifdef _WIN32
175 /* specific case for names like: "\\.\d:" */
f53f4da9 176 if (is_windows_drive(path) || is_windows_drive_prefix(path)) {
21664424 177 return 1;
f53f4da9
PB
178 }
179 return (*path == '/' || *path == '\\');
3b9f94e1 180#else
f53f4da9 181 return (*path == '/');
3b9f94e1 182#endif
3b0d4f61
FB
183}
184
009b03aa 185/* if filename is absolute, just return its duplicate. Otherwise, build a
83f64091
FB
186 path to it by considering it is relative to base_path. URL are
187 supported. */
009b03aa 188char *path_combine(const char *base_path, const char *filename)
3b0d4f61 189{
009b03aa 190 const char *protocol_stripped = NULL;
83f64091 191 const char *p, *p1;
009b03aa 192 char *result;
83f64091
FB
193 int len;
194
83f64091 195 if (path_is_absolute(filename)) {
009b03aa
HR
196 return g_strdup(filename);
197 }
0d54a6fe 198
009b03aa
HR
199 if (path_has_protocol(base_path)) {
200 protocol_stripped = strchr(base_path, ':');
201 if (protocol_stripped) {
202 protocol_stripped++;
0d54a6fe 203 }
009b03aa
HR
204 }
205 p = protocol_stripped ?: base_path;
0d54a6fe 206
009b03aa 207 p1 = strrchr(base_path, '/');
3b9f94e1 208#ifdef _WIN32
009b03aa
HR
209 {
210 const char *p2;
211 p2 = strrchr(base_path, '\\');
212 if (!p1 || p2 > p1) {
213 p1 = p2;
3b9f94e1 214 }
009b03aa 215 }
3b9f94e1 216#endif
009b03aa
HR
217 if (p1) {
218 p1++;
219 } else {
220 p1 = base_path;
221 }
222 if (p1 > p) {
223 p = p1;
3b0d4f61 224 }
009b03aa
HR
225 len = p - base_path;
226
227 result = g_malloc(len + strlen(filename) + 1);
228 memcpy(result, base_path, len);
229 strcpy(result + len, filename);
230
231 return result;
232}
233
03c320d8
HR
234/*
235 * Helper function for bdrv_parse_filename() implementations to remove optional
236 * protocol prefixes (especially "file:") from a filename and for putting the
237 * stripped filename into the options QDict if there is such a prefix.
238 */
239void bdrv_parse_filename_strip_prefix(const char *filename, const char *prefix,
240 QDict *options)
241{
242 if (strstart(filename, prefix, &filename)) {
243 /* Stripping the explicit protocol prefix may result in a protocol
244 * prefix being (wrongly) detected (if the filename contains a colon) */
245 if (path_has_protocol(filename)) {
18cf67c5 246 GString *fat_filename;
03c320d8
HR
247
248 /* This means there is some colon before the first slash; therefore,
249 * this cannot be an absolute path */
250 assert(!path_is_absolute(filename));
251
252 /* And we can thus fix the protocol detection issue by prefixing it
253 * by "./" */
18cf67c5
MA
254 fat_filename = g_string_new("./");
255 g_string_append(fat_filename, filename);
03c320d8 256
18cf67c5 257 assert(!path_has_protocol(fat_filename->str));
03c320d8 258
18cf67c5
MA
259 qdict_put(options, "filename",
260 qstring_from_gstring(fat_filename));
03c320d8
HR
261 } else {
262 /* If no protocol prefix was detected, we can use the shortened
263 * filename as-is */
264 qdict_put_str(options, "filename", filename);
265 }
266 }
267}
268
269
9c5e6594
KW
270/* Returns whether the image file is opened as read-only. Note that this can
271 * return false and writing to the image file is still not possible because the
272 * image is inactivated. */
93ed524e
JC
273bool bdrv_is_read_only(BlockDriverState *bs)
274{
384a48fb 275 IO_CODE();
975da073 276 return !(bs->open_flags & BDRV_O_RDWR);
93ed524e
JC
277}
278
54a32bfe
KW
279int bdrv_can_set_read_only(BlockDriverState *bs, bool read_only,
280 bool ignore_allow_rdw, Error **errp)
fe5241bf 281{
384a48fb
EGE
282 IO_CODE();
283
e2b8247a
JC
284 /* Do not set read_only if copy_on_read is enabled */
285 if (bs->copy_on_read && read_only) {
286 error_setg(errp, "Can't set node '%s' to r/o with copy-on-read enabled",
287 bdrv_get_device_or_node_name(bs));
288 return -EINVAL;
289 }
290
d6fcdf06 291 /* Do not clear read_only if it is prohibited */
54a32bfe
KW
292 if (!read_only && !(bs->open_flags & BDRV_O_ALLOW_RDWR) &&
293 !ignore_allow_rdw)
294 {
d6fcdf06
JC
295 error_setg(errp, "Node '%s' is read only",
296 bdrv_get_device_or_node_name(bs));
297 return -EPERM;
298 }
299
45803a03
JC
300 return 0;
301}
302
eaa2410f
KW
303/*
304 * Called by a driver that can only provide a read-only image.
305 *
306 * Returns 0 if the node is already read-only or it could switch the node to
307 * read-only because BDRV_O_AUTO_RDONLY is set.
308 *
309 * Returns -EACCES if the node is read-write and BDRV_O_AUTO_RDONLY is not set
310 * or bdrv_can_set_read_only() forbids making the node read-only. If @errmsg
311 * is not NULL, it is used as the error message for the Error object.
312 */
313int bdrv_apply_auto_read_only(BlockDriverState *bs, const char *errmsg,
314 Error **errp)
45803a03
JC
315{
316 int ret = 0;
384a48fb 317 IO_CODE();
45803a03 318
eaa2410f
KW
319 if (!(bs->open_flags & BDRV_O_RDWR)) {
320 return 0;
321 }
322 if (!(bs->open_flags & BDRV_O_AUTO_RDONLY)) {
323 goto fail;
45803a03
JC
324 }
325
eaa2410f
KW
326 ret = bdrv_can_set_read_only(bs, true, false, NULL);
327 if (ret < 0) {
328 goto fail;
eeae6a59
KW
329 }
330
eaa2410f
KW
331 bs->open_flags &= ~BDRV_O_RDWR;
332
e2b8247a 333 return 0;
eaa2410f
KW
334
335fail:
336 error_setg(errp, "%s", errmsg ?: "Image is read-only");
337 return -EACCES;
fe5241bf
JC
338}
339
645ae7d8
HR
340/*
341 * If @backing is empty, this function returns NULL without setting
342 * @errp. In all other cases, NULL will only be returned with @errp
343 * set.
344 *
345 * Therefore, a return value of NULL without @errp set means that
346 * there is no backing file; if @errp is set, there is one but its
347 * absolute filename cannot be generated.
348 */
349char *bdrv_get_full_backing_filename_from_filename(const char *backed,
350 const char *backing,
351 Error **errp)
dc5a1371 352{
645ae7d8
HR
353 if (backing[0] == '\0') {
354 return NULL;
355 } else if (path_has_protocol(backing) || path_is_absolute(backing)) {
356 return g_strdup(backing);
9f07429e
HR
357 } else if (backed[0] == '\0' || strstart(backed, "json:", NULL)) {
358 error_setg(errp, "Cannot use relative backing file names for '%s'",
359 backed);
645ae7d8 360 return NULL;
dc5a1371 361 } else {
645ae7d8 362 return path_combine(backed, backing);
dc5a1371
PB
363 }
364}
365
9f4793d8
HR
366/*
367 * If @filename is empty or NULL, this function returns NULL without
368 * setting @errp. In all other cases, NULL will only be returned with
369 * @errp set.
370 */
371static char *bdrv_make_absolute_filename(BlockDriverState *relative_to,
372 const char *filename, Error **errp)
0a82855a 373{
8df68616 374 char *dir, *full_name;
9f4793d8 375
8df68616
HR
376 if (!filename || filename[0] == '\0') {
377 return NULL;
378 } else if (path_has_protocol(filename) || path_is_absolute(filename)) {
379 return g_strdup(filename);
380 }
9f07429e 381
8df68616
HR
382 dir = bdrv_dirname(relative_to, errp);
383 if (!dir) {
384 return NULL;
385 }
f30c66ba 386
8df68616
HR
387 full_name = g_strconcat(dir, filename, NULL);
388 g_free(dir);
389 return full_name;
9f4793d8
HR
390}
391
392char *bdrv_get_full_backing_filename(BlockDriverState *bs, Error **errp)
393{
f791bf7f 394 GLOBAL_STATE_CODE();
9f4793d8 395 return bdrv_make_absolute_filename(bs, bs->backing_file, errp);
0a82855a
HR
396}
397
0eb7217e
SH
398void bdrv_register(BlockDriver *bdrv)
399{
a15f08dc 400 assert(bdrv->format_name);
f791bf7f 401 GLOBAL_STATE_CODE();
8a22f02a 402 QLIST_INSERT_HEAD(&bdrv_drivers, bdrv, list);
ea2384d3 403}
b338082b 404
e4e9986b
MA
405BlockDriverState *bdrv_new(void)
406{
407 BlockDriverState *bs;
408 int i;
409
f791bf7f
EGE
410 GLOBAL_STATE_CODE();
411
5839e53b 412 bs = g_new0(BlockDriverState, 1);
e4654d2d 413 QLIST_INIT(&bs->dirty_bitmaps);
fbe40ff7
FZ
414 for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
415 QLIST_INIT(&bs->op_blockers[i]);
416 }
3783fa3d 417 qemu_co_mutex_init(&bs->reqs_lock);
2119882c 418 qemu_mutex_init(&bs->dirty_bitmap_mutex);
9fcb0251 419 bs->refcnt = 1;
dcd04228 420 bs->aio_context = qemu_get_aio_context();
d7d512f6 421
3ff2f67a
EY
422 qemu_co_queue_init(&bs->flush_queue);
423
0bc329fb
HR
424 qemu_co_mutex_init(&bs->bsc_modify_lock);
425 bs->block_status_cache = g_new0(BdrvBlockStatusCache, 1);
426
0f12264e
KW
427 for (i = 0; i < bdrv_drain_all_count; i++) {
428 bdrv_drained_begin(bs);
429 }
430
2c1d04e0
HR
431 QTAILQ_INSERT_TAIL(&all_bdrv_states, bs, bs_list);
432
b338082b
FB
433 return bs;
434}
435
88d88798 436static BlockDriver *bdrv_do_find_format(const char *format_name)
ea2384d3
FB
437{
438 BlockDriver *drv1;
bdb73476 439 GLOBAL_STATE_CODE();
88d88798 440
8a22f02a
SH
441 QLIST_FOREACH(drv1, &bdrv_drivers, list) {
442 if (!strcmp(drv1->format_name, format_name)) {
ea2384d3 443 return drv1;
8a22f02a 444 }
ea2384d3 445 }
88d88798 446
ea2384d3
FB
447 return NULL;
448}
449
88d88798
MM
450BlockDriver *bdrv_find_format(const char *format_name)
451{
452 BlockDriver *drv1;
453 int i;
454
f791bf7f
EGE
455 GLOBAL_STATE_CODE();
456
88d88798
MM
457 drv1 = bdrv_do_find_format(format_name);
458 if (drv1) {
459 return drv1;
460 }
461
462 /* The driver isn't registered, maybe we need to load a module */
463 for (i = 0; i < (int)ARRAY_SIZE(block_driver_modules); ++i) {
464 if (!strcmp(block_driver_modules[i].format_name, format_name)) {
c551fb0b
CF
465 Error *local_err = NULL;
466 int rv = block_module_load(block_driver_modules[i].library_name,
467 &local_err);
468 if (rv > 0) {
469 return bdrv_do_find_format(format_name);
470 } else if (rv < 0) {
471 error_report_err(local_err);
472 }
88d88798
MM
473 break;
474 }
475 }
c551fb0b 476 return NULL;
88d88798
MM
477}
478
9ac404c5 479static int bdrv_format_is_whitelisted(const char *format_name, bool read_only)
eb852011 480{
b64ec4e4
FZ
481 static const char *whitelist_rw[] = {
482 CONFIG_BDRV_RW_WHITELIST
859aef02 483 NULL
b64ec4e4
FZ
484 };
485 static const char *whitelist_ro[] = {
486 CONFIG_BDRV_RO_WHITELIST
859aef02 487 NULL
eb852011
MA
488 };
489 const char **p;
490
b64ec4e4 491 if (!whitelist_rw[0] && !whitelist_ro[0]) {
eb852011 492 return 1; /* no whitelist, anything goes */
b64ec4e4 493 }
eb852011 494
b64ec4e4 495 for (p = whitelist_rw; *p; p++) {
9ac404c5 496 if (!strcmp(format_name, *p)) {
eb852011
MA
497 return 1;
498 }
499 }
b64ec4e4
FZ
500 if (read_only) {
501 for (p = whitelist_ro; *p; p++) {
9ac404c5 502 if (!strcmp(format_name, *p)) {
b64ec4e4
FZ
503 return 1;
504 }
505 }
506 }
eb852011
MA
507 return 0;
508}
509
9ac404c5
AS
510int bdrv_is_whitelisted(BlockDriver *drv, bool read_only)
511{
f791bf7f 512 GLOBAL_STATE_CODE();
9ac404c5
AS
513 return bdrv_format_is_whitelisted(drv->format_name, read_only);
514}
515
e6ff69bf
DB
516bool bdrv_uses_whitelist(void)
517{
518 return use_bdrv_whitelist;
519}
520
5b7e1542
ZYW
521typedef struct CreateCo {
522 BlockDriver *drv;
523 char *filename;
83d0521a 524 QemuOpts *opts;
5b7e1542 525 int ret;
cc84d90f 526 Error *err;
5b7e1542
ZYW
527} CreateCo;
528
529static void coroutine_fn bdrv_create_co_entry(void *opaque)
530{
cc84d90f
HR
531 Error *local_err = NULL;
532 int ret;
533
5b7e1542
ZYW
534 CreateCo *cco = opaque;
535 assert(cco->drv);
da359909 536 GLOBAL_STATE_CODE();
5b7e1542 537
b92902df
ML
538 ret = cco->drv->bdrv_co_create_opts(cco->drv,
539 cco->filename, cco->opts, &local_err);
621ff94d 540 error_propagate(&cco->err, local_err);
cc84d90f 541 cco->ret = ret;
5b7e1542
ZYW
542}
543
0e7e1989 544int bdrv_create(BlockDriver *drv, const char* filename,
83d0521a 545 QemuOpts *opts, Error **errp)
ea2384d3 546{
5b7e1542
ZYW
547 int ret;
548
f791bf7f
EGE
549 GLOBAL_STATE_CODE();
550
5b7e1542
ZYW
551 Coroutine *co;
552 CreateCo cco = {
553 .drv = drv,
554 .filename = g_strdup(filename),
83d0521a 555 .opts = opts,
5b7e1542 556 .ret = NOT_DONE,
cc84d90f 557 .err = NULL,
5b7e1542
ZYW
558 };
559
efc75e2a 560 if (!drv->bdrv_co_create_opts) {
cc84d90f 561 error_setg(errp, "Driver '%s' does not support image creation", drv->format_name);
80168bff
LC
562 ret = -ENOTSUP;
563 goto out;
5b7e1542
ZYW
564 }
565
566 if (qemu_in_coroutine()) {
567 /* Fast-path if already in coroutine context */
568 bdrv_create_co_entry(&cco);
569 } else {
0b8b8753
PB
570 co = qemu_coroutine_create(bdrv_create_co_entry, &cco);
571 qemu_coroutine_enter(co);
5b7e1542 572 while (cco.ret == NOT_DONE) {
b47ec2c4 573 aio_poll(qemu_get_aio_context(), true);
5b7e1542
ZYW
574 }
575 }
576
577 ret = cco.ret;
cc84d90f 578 if (ret < 0) {
84d18f06 579 if (cco.err) {
cc84d90f
HR
580 error_propagate(errp, cco.err);
581 } else {
582 error_setg_errno(errp, -ret, "Could not create image");
583 }
584 }
0e7e1989 585
80168bff
LC
586out:
587 g_free(cco.filename);
5b7e1542 588 return ret;
ea2384d3
FB
589}
590
fd17146c
HR
591/**
592 * Helper function for bdrv_create_file_fallback(): Resize @blk to at
593 * least the given @minimum_size.
594 *
595 * On success, return @blk's actual length.
596 * Otherwise, return -errno.
597 */
598static int64_t create_file_fallback_truncate(BlockBackend *blk,
599 int64_t minimum_size, Error **errp)
84a12e66 600{
cc84d90f 601 Error *local_err = NULL;
fd17146c 602 int64_t size;
cc84d90f 603 int ret;
84a12e66 604
bdb73476
EGE
605 GLOBAL_STATE_CODE();
606
8c6242b6
KW
607 ret = blk_truncate(blk, minimum_size, false, PREALLOC_MODE_OFF, 0,
608 &local_err);
fd17146c
HR
609 if (ret < 0 && ret != -ENOTSUP) {
610 error_propagate(errp, local_err);
611 return ret;
612 }
613
614 size = blk_getlength(blk);
615 if (size < 0) {
616 error_free(local_err);
617 error_setg_errno(errp, -size,
618 "Failed to inquire the new image file's length");
619 return size;
620 }
621
622 if (size < minimum_size) {
623 /* Need to grow the image, but we failed to do that */
624 error_propagate(errp, local_err);
625 return -ENOTSUP;
626 }
627
628 error_free(local_err);
629 local_err = NULL;
630
631 return size;
632}
633
634/**
635 * Helper function for bdrv_create_file_fallback(): Zero the first
636 * sector to remove any potentially pre-existing image header.
637 */
881a4c55
PB
638static int coroutine_fn
639create_file_fallback_zero_first_sector(BlockBackend *blk,
640 int64_t current_size,
641 Error **errp)
fd17146c
HR
642{
643 int64_t bytes_to_clear;
644 int ret;
645
bdb73476
EGE
646 GLOBAL_STATE_CODE();
647
fd17146c
HR
648 bytes_to_clear = MIN(current_size, BDRV_SECTOR_SIZE);
649 if (bytes_to_clear) {
ce47ff20 650 ret = blk_co_pwrite_zeroes(blk, 0, bytes_to_clear, BDRV_REQ_MAY_UNMAP);
fd17146c
HR
651 if (ret < 0) {
652 error_setg_errno(errp, -ret,
653 "Failed to clear the new image's first sector");
654 return ret;
655 }
656 }
657
658 return 0;
659}
660
5a5e7f8c
ML
661/**
662 * Simple implementation of bdrv_co_create_opts for protocol drivers
663 * which only support creation via opening a file
664 * (usually existing raw storage device)
665 */
666int coroutine_fn bdrv_co_create_opts_simple(BlockDriver *drv,
667 const char *filename,
668 QemuOpts *opts,
669 Error **errp)
fd17146c
HR
670{
671 BlockBackend *blk;
eeea1faa 672 QDict *options;
fd17146c
HR
673 int64_t size = 0;
674 char *buf = NULL;
675 PreallocMode prealloc;
676 Error *local_err = NULL;
677 int ret;
678
b4ad82aa
EGE
679 GLOBAL_STATE_CODE();
680
fd17146c
HR
681 size = qemu_opt_get_size_del(opts, BLOCK_OPT_SIZE, 0);
682 buf = qemu_opt_get_del(opts, BLOCK_OPT_PREALLOC);
683 prealloc = qapi_enum_parse(&PreallocMode_lookup, buf,
684 PREALLOC_MODE_OFF, &local_err);
685 g_free(buf);
686 if (local_err) {
687 error_propagate(errp, local_err);
688 return -EINVAL;
689 }
690
691 if (prealloc != PREALLOC_MODE_OFF) {
692 error_setg(errp, "Unsupported preallocation mode '%s'",
693 PreallocMode_str(prealloc));
694 return -ENOTSUP;
695 }
696
eeea1faa 697 options = qdict_new();
fd17146c
HR
698 qdict_put_str(options, "driver", drv->format_name);
699
700 blk = blk_new_open(filename, NULL, options,
701 BDRV_O_RDWR | BDRV_O_RESIZE, errp);
702 if (!blk) {
703 error_prepend(errp, "Protocol driver '%s' does not support image "
704 "creation, and opening the image failed: ",
705 drv->format_name);
706 return -EINVAL;
707 }
708
709 size = create_file_fallback_truncate(blk, size, errp);
710 if (size < 0) {
711 ret = size;
712 goto out;
713 }
714
715 ret = create_file_fallback_zero_first_sector(blk, size, errp);
716 if (ret < 0) {
717 goto out;
718 }
719
720 ret = 0;
721out:
722 blk_unref(blk);
723 return ret;
724}
725
726int bdrv_create_file(const char *filename, QemuOpts *opts, Error **errp)
727{
729222af 728 QemuOpts *protocol_opts;
fd17146c 729 BlockDriver *drv;
729222af
SG
730 QDict *qdict;
731 int ret;
fd17146c 732
f791bf7f
EGE
733 GLOBAL_STATE_CODE();
734
b65a5e12 735 drv = bdrv_find_protocol(filename, true, errp);
84a12e66 736 if (drv == NULL) {
16905d71 737 return -ENOENT;
84a12e66
CH
738 }
739
729222af
SG
740 if (!drv->create_opts) {
741 error_setg(errp, "Driver '%s' does not support image creation",
742 drv->format_name);
743 return -ENOTSUP;
744 }
745
746 /*
747 * 'opts' contains a QemuOptsList with a combination of format and protocol
748 * default values.
749 *
750 * The format properly removes its options, but the default values remain
751 * in 'opts->list'. So if the protocol has options with the same name
752 * (e.g. rbd has 'cluster_size' as qcow2), it will see the default values
753 * of the format, since for overlapping options, the format wins.
754 *
755 * To avoid this issue, lets convert QemuOpts to QDict, in this way we take
756 * only the set options, and then convert it back to QemuOpts, using the
757 * create_opts of the protocol. So the new QemuOpts, will contain only the
758 * protocol defaults.
759 */
760 qdict = qemu_opts_to_qdict(opts, NULL);
761 protocol_opts = qemu_opts_from_qdict(drv->create_opts, qdict, errp);
762 if (protocol_opts == NULL) {
763 ret = -EINVAL;
764 goto out;
765 }
766
767 ret = bdrv_create(drv, filename, protocol_opts, errp);
768out:
769 qemu_opts_del(protocol_opts);
770 qobject_unref(qdict);
771 return ret;
84a12e66
CH
772}
773
e1d7f8bb
DHB
774int coroutine_fn bdrv_co_delete_file(BlockDriverState *bs, Error **errp)
775{
776 Error *local_err = NULL;
777 int ret;
778
384a48fb 779 IO_CODE();
e1d7f8bb
DHB
780 assert(bs != NULL);
781
782 if (!bs->drv) {
783 error_setg(errp, "Block node '%s' is not opened", bs->filename);
784 return -ENOMEDIUM;
785 }
786
787 if (!bs->drv->bdrv_co_delete_file) {
788 error_setg(errp, "Driver '%s' does not support image deletion",
789 bs->drv->format_name);
790 return -ENOTSUP;
791 }
792
793 ret = bs->drv->bdrv_co_delete_file(bs, &local_err);
794 if (ret < 0) {
795 error_propagate(errp, local_err);
796 }
797
798 return ret;
799}
800
a890f08e
ML
801void coroutine_fn bdrv_co_delete_file_noerr(BlockDriverState *bs)
802{
803 Error *local_err = NULL;
804 int ret;
384a48fb 805 IO_CODE();
a890f08e
ML
806
807 if (!bs) {
808 return;
809 }
810
811 ret = bdrv_co_delete_file(bs, &local_err);
812 /*
813 * ENOTSUP will happen if the block driver doesn't support
814 * the 'bdrv_co_delete_file' interface. This is a predictable
815 * scenario and shouldn't be reported back to the user.
816 */
817 if (ret == -ENOTSUP) {
818 error_free(local_err);
819 } else if (ret < 0) {
820 error_report_err(local_err);
821 }
822}
823
892b7de8
ET
824/**
825 * Try to get @bs's logical and physical block size.
826 * On success, store them in @bsz struct and return 0.
827 * On failure return -errno.
828 * @bs must not be empty.
829 */
830int bdrv_probe_blocksizes(BlockDriverState *bs, BlockSizes *bsz)
831{
832 BlockDriver *drv = bs->drv;
93393e69 833 BlockDriverState *filtered = bdrv_filter_bs(bs);
f791bf7f 834 GLOBAL_STATE_CODE();
892b7de8
ET
835
836 if (drv && drv->bdrv_probe_blocksizes) {
837 return drv->bdrv_probe_blocksizes(bs, bsz);
93393e69
HR
838 } else if (filtered) {
839 return bdrv_probe_blocksizes(filtered, bsz);
892b7de8
ET
840 }
841
842 return -ENOTSUP;
843}
844
845/**
846 * Try to get @bs's geometry (cyls, heads, sectors).
847 * On success, store them in @geo struct and return 0.
848 * On failure return -errno.
849 * @bs must not be empty.
850 */
851int bdrv_probe_geometry(BlockDriverState *bs, HDGeometry *geo)
852{
853 BlockDriver *drv = bs->drv;
93393e69 854 BlockDriverState *filtered = bdrv_filter_bs(bs);
f791bf7f 855 GLOBAL_STATE_CODE();
892b7de8
ET
856
857 if (drv && drv->bdrv_probe_geometry) {
858 return drv->bdrv_probe_geometry(bs, geo);
93393e69
HR
859 } else if (filtered) {
860 return bdrv_probe_geometry(filtered, geo);
892b7de8
ET
861 }
862
863 return -ENOTSUP;
864}
865
eba25057
JM
866/*
867 * Create a uniquely-named empty temporary file.
69fbfff9
BM
868 * Return the actual file name used upon success, otherwise NULL.
869 * This string should be freed with g_free() when not needed any longer.
870 *
871 * Note: creating a temporary file for the caller to (re)open is
872 * inherently racy. Use g_file_open_tmp() instead whenever practical.
eba25057 873 */
69fbfff9 874char *create_tmp_file(Error **errp)
d5249393 875{
67b915a5 876 int fd;
7ccfb2eb 877 const char *tmpdir;
69fbfff9
BM
878 g_autofree char *filename = NULL;
879
880 tmpdir = g_get_tmp_dir();
881#ifndef _WIN32
882 /*
883 * See commit 69bef79 ("block: use /var/tmp instead of /tmp for -snapshot")
884 *
885 * This function is used to create temporary disk images (like -snapshot),
886 * so the files can become very large. /tmp is often a tmpfs where as
887 * /var/tmp is usually on a disk, so more appropriate for disk images.
888 */
889 if (!g_strcmp0(tmpdir, "/tmp")) {
69bef793
AS
890 tmpdir = "/var/tmp";
891 }
69fbfff9
BM
892#endif
893
894 filename = g_strdup_printf("%s/vl.XXXXXX", tmpdir);
895 fd = g_mkstemp(filename);
fe235a06 896 if (fd < 0) {
69fbfff9
BM
897 error_setg_errno(errp, errno, "Could not open temporary file '%s'",
898 filename);
899 return NULL;
eba25057 900 }
6b6471ee 901 close(fd);
69fbfff9
BM
902
903 return g_steal_pointer(&filename);
eba25057 904}
fc01f7e7 905
84a12e66
CH
906/*
907 * Detect host devices. By convention, /dev/cdrom[N] is always
908 * recognized as a host CDROM.
909 */
910static BlockDriver *find_hdev_driver(const char *filename)
911{
912 int score_max = 0, score;
913 BlockDriver *drv = NULL, *d;
bdb73476 914 GLOBAL_STATE_CODE();
84a12e66
CH
915
916 QLIST_FOREACH(d, &bdrv_drivers, list) {
917 if (d->bdrv_probe_device) {
918 score = d->bdrv_probe_device(filename);
919 if (score > score_max) {
920 score_max = score;
921 drv = d;
922 }
923 }
924 }
925
926 return drv;
927}
928
88d88798
MM
929static BlockDriver *bdrv_do_find_protocol(const char *protocol)
930{
931 BlockDriver *drv1;
bdb73476 932 GLOBAL_STATE_CODE();
88d88798
MM
933
934 QLIST_FOREACH(drv1, &bdrv_drivers, list) {
935 if (drv1->protocol_name && !strcmp(drv1->protocol_name, protocol)) {
936 return drv1;
937 }
938 }
939
940 return NULL;
941}
942
98289620 943BlockDriver *bdrv_find_protocol(const char *filename,
b65a5e12
HR
944 bool allow_protocol_prefix,
945 Error **errp)
83f64091
FB
946{
947 BlockDriver *drv1;
948 char protocol[128];
1cec71e3 949 int len;
83f64091 950 const char *p;
88d88798 951 int i;
19cb3738 952
f791bf7f 953 GLOBAL_STATE_CODE();
66f82cee
KW
954 /* TODO Drivers without bdrv_file_open must be specified explicitly */
955
39508e7a
CH
956 /*
957 * XXX(hch): we really should not let host device detection
958 * override an explicit protocol specification, but moving this
959 * later breaks access to device names with colons in them.
960 * Thanks to the brain-dead persistent naming schemes on udev-
961 * based Linux systems those actually are quite common.
962 */
963 drv1 = find_hdev_driver(filename);
964 if (drv1) {
965 return drv1;
966 }
967
98289620 968 if (!path_has_protocol(filename) || !allow_protocol_prefix) {
ef810437 969 return &bdrv_file;
84a12e66 970 }
98289620 971
9e0b22f4
SH
972 p = strchr(filename, ':');
973 assert(p != NULL);
1cec71e3
AL
974 len = p - filename;
975 if (len > sizeof(protocol) - 1)
976 len = sizeof(protocol) - 1;
977 memcpy(protocol, filename, len);
978 protocol[len] = '\0';
88d88798
MM
979
980 drv1 = bdrv_do_find_protocol(protocol);
981 if (drv1) {
982 return drv1;
983 }
984
985 for (i = 0; i < (int)ARRAY_SIZE(block_driver_modules); ++i) {
986 if (block_driver_modules[i].protocol_name &&
987 !strcmp(block_driver_modules[i].protocol_name, protocol)) {
c551fb0b
CF
988 int rv = block_module_load(block_driver_modules[i].library_name, errp);
989 if (rv > 0) {
990 drv1 = bdrv_do_find_protocol(protocol);
991 } else if (rv < 0) {
992 return NULL;
993 }
88d88798 994 break;
8a22f02a 995 }
83f64091 996 }
b65a5e12 997
88d88798
MM
998 if (!drv1) {
999 error_setg(errp, "Unknown protocol '%s'", protocol);
1000 }
1001 return drv1;
83f64091
FB
1002}
1003
c6684249
MA
1004/*
1005 * Guess image format by probing its contents.
1006 * This is not a good idea when your image is raw (CVE-2008-2004), but
1007 * we do it anyway for backward compatibility.
1008 *
1009 * @buf contains the image's first @buf_size bytes.
7cddd372
KW
1010 * @buf_size is the buffer size in bytes (generally BLOCK_PROBE_BUF_SIZE,
1011 * but can be smaller if the image file is smaller)
c6684249
MA
1012 * @filename is its filename.
1013 *
1014 * For all block drivers, call the bdrv_probe() method to get its
1015 * probing score.
1016 * Return the first block driver with the highest probing score.
1017 */
38f3ef57
KW
1018BlockDriver *bdrv_probe_all(const uint8_t *buf, int buf_size,
1019 const char *filename)
c6684249
MA
1020{
1021 int score_max = 0, score;
1022 BlockDriver *drv = NULL, *d;
967d7905 1023 IO_CODE();
c6684249
MA
1024
1025 QLIST_FOREACH(d, &bdrv_drivers, list) {
1026 if (d->bdrv_probe) {
1027 score = d->bdrv_probe(buf, buf_size, filename);
1028 if (score > score_max) {
1029 score_max = score;
1030 drv = d;
1031 }
1032 }
1033 }
1034
1035 return drv;
1036}
1037
5696c6e3 1038static int find_image_format(BlockBackend *file, const char *filename,
34b5d2c6 1039 BlockDriver **pdrv, Error **errp)
f3a5d3f8 1040{
c6684249 1041 BlockDriver *drv;
7cddd372 1042 uint8_t buf[BLOCK_PROBE_BUF_SIZE];
f500a6d3 1043 int ret = 0;
f8ea0b00 1044
bdb73476
EGE
1045 GLOBAL_STATE_CODE();
1046
08a00559 1047 /* Return the raw BlockDriver * to scsi-generic devices or empty drives */
5696c6e3 1048 if (blk_is_sg(file) || !blk_is_inserted(file) || blk_getlength(file) == 0) {
ef810437 1049 *pdrv = &bdrv_raw;
c98ac35d 1050 return ret;
1a396859 1051 }
f8ea0b00 1052
a9262f55 1053 ret = blk_pread(file, 0, sizeof(buf), buf, 0);
83f64091 1054 if (ret < 0) {
34b5d2c6
HR
1055 error_setg_errno(errp, -ret, "Could not read image for determining its "
1056 "format");
c98ac35d
SW
1057 *pdrv = NULL;
1058 return ret;
83f64091
FB
1059 }
1060
bf5b16fa 1061 drv = bdrv_probe_all(buf, sizeof(buf), filename);
c98ac35d 1062 if (!drv) {
34b5d2c6
HR
1063 error_setg(errp, "Could not determine image format: No compatible "
1064 "driver found");
bf5b16fa
AF
1065 *pdrv = NULL;
1066 return -ENOENT;
c98ac35d 1067 }
bf5b16fa 1068
c98ac35d 1069 *pdrv = drv;
bf5b16fa 1070 return 0;
ea2384d3
FB
1071}
1072
51762288
SH
1073/**
1074 * Set the current 'total_sectors' value
65a9bb25 1075 * Return 0 on success, -errno on error.
51762288 1076 */
3d9f2d2a 1077int refresh_total_sectors(BlockDriverState *bs, int64_t hint)
51762288
SH
1078{
1079 BlockDriver *drv = bs->drv;
967d7905 1080 IO_CODE();
51762288 1081
d470ad42
HR
1082 if (!drv) {
1083 return -ENOMEDIUM;
1084 }
1085
396759ad 1086 /* Do not attempt drv->bdrv_getlength() on scsi-generic devices */
b192af8a 1087 if (bdrv_is_sg(bs))
396759ad
NB
1088 return 0;
1089
51762288
SH
1090 /* query actual device if possible, otherwise just trust the hint */
1091 if (drv->bdrv_getlength) {
1092 int64_t length = drv->bdrv_getlength(bs);
1093 if (length < 0) {
1094 return length;
1095 }
7e382003 1096 hint = DIV_ROUND_UP(length, BDRV_SECTOR_SIZE);
51762288
SH
1097 }
1098
1099 bs->total_sectors = hint;
8b117001
VSO
1100
1101 if (bs->total_sectors * BDRV_SECTOR_SIZE > BDRV_MAX_LENGTH) {
1102 return -EFBIG;
1103 }
1104
51762288
SH
1105 return 0;
1106}
1107
cddff5ba
KW
1108/**
1109 * Combines a QDict of new block driver @options with any missing options taken
1110 * from @old_options, so that leaving out an option defaults to its old value.
1111 */
1112static void bdrv_join_options(BlockDriverState *bs, QDict *options,
1113 QDict *old_options)
1114{
da359909 1115 GLOBAL_STATE_CODE();
cddff5ba
KW
1116 if (bs->drv && bs->drv->bdrv_join_options) {
1117 bs->drv->bdrv_join_options(options, old_options);
1118 } else {
1119 qdict_join(options, old_options, false);
1120 }
1121}
1122
543770bd
AG
1123static BlockdevDetectZeroesOptions bdrv_parse_detect_zeroes(QemuOpts *opts,
1124 int open_flags,
1125 Error **errp)
1126{
1127 Error *local_err = NULL;
1128 char *value = qemu_opt_get_del(opts, "detect-zeroes");
1129 BlockdevDetectZeroesOptions detect_zeroes =
1130 qapi_enum_parse(&BlockdevDetectZeroesOptions_lookup, value,
1131 BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF, &local_err);
bdb73476 1132 GLOBAL_STATE_CODE();
543770bd
AG
1133 g_free(value);
1134 if (local_err) {
1135 error_propagate(errp, local_err);
1136 return detect_zeroes;
1137 }
1138
1139 if (detect_zeroes == BLOCKDEV_DETECT_ZEROES_OPTIONS_UNMAP &&
1140 !(open_flags & BDRV_O_UNMAP))
1141 {
1142 error_setg(errp, "setting detect-zeroes to unmap is not allowed "
1143 "without setting discard operation to unmap");
1144 }
1145
1146 return detect_zeroes;
1147}
1148
f80f2673
AM
1149/**
1150 * Set open flags for aio engine
1151 *
1152 * Return 0 on success, -1 if the engine specified is invalid
1153 */
1154int bdrv_parse_aio(const char *mode, int *flags)
1155{
1156 if (!strcmp(mode, "threads")) {
1157 /* do nothing, default */
1158 } else if (!strcmp(mode, "native")) {
1159 *flags |= BDRV_O_NATIVE_AIO;
1160#ifdef CONFIG_LINUX_IO_URING
1161 } else if (!strcmp(mode, "io_uring")) {
1162 *flags |= BDRV_O_IO_URING;
1163#endif
1164 } else {
1165 return -1;
1166 }
1167
1168 return 0;
1169}
1170
9e8f1835
PB
1171/**
1172 * Set open flags for a given discard mode
1173 *
1174 * Return 0 on success, -1 if the discard mode was invalid.
1175 */
1176int bdrv_parse_discard_flags(const char *mode, int *flags)
1177{
1178 *flags &= ~BDRV_O_UNMAP;
1179
1180 if (!strcmp(mode, "off") || !strcmp(mode, "ignore")) {
1181 /* do nothing */
1182 } else if (!strcmp(mode, "on") || !strcmp(mode, "unmap")) {
1183 *flags |= BDRV_O_UNMAP;
1184 } else {
1185 return -1;
1186 }
1187
1188 return 0;
1189}
1190
c3993cdc
SH
1191/**
1192 * Set open flags for a given cache mode
1193 *
1194 * Return 0 on success, -1 if the cache mode was invalid.
1195 */
53e8ae01 1196int bdrv_parse_cache_mode(const char *mode, int *flags, bool *writethrough)
c3993cdc
SH
1197{
1198 *flags &= ~BDRV_O_CACHE_MASK;
1199
1200 if (!strcmp(mode, "off") || !strcmp(mode, "none")) {
53e8ae01
KW
1201 *writethrough = false;
1202 *flags |= BDRV_O_NOCACHE;
92196b2f 1203 } else if (!strcmp(mode, "directsync")) {
53e8ae01 1204 *writethrough = true;
92196b2f 1205 *flags |= BDRV_O_NOCACHE;
c3993cdc 1206 } else if (!strcmp(mode, "writeback")) {
53e8ae01 1207 *writethrough = false;
c3993cdc 1208 } else if (!strcmp(mode, "unsafe")) {
53e8ae01 1209 *writethrough = false;
c3993cdc
SH
1210 *flags |= BDRV_O_NO_FLUSH;
1211 } else if (!strcmp(mode, "writethrough")) {
53e8ae01 1212 *writethrough = true;
c3993cdc
SH
1213 } else {
1214 return -1;
1215 }
1216
1217 return 0;
1218}
1219
b5411555
KW
1220static char *bdrv_child_get_parent_desc(BdrvChild *c)
1221{
1222 BlockDriverState *parent = c->opaque;
2c0a3acb 1223 return g_strdup_printf("node '%s'", bdrv_get_node_name(parent));
b5411555
KW
1224}
1225
20018e12
KW
1226static void bdrv_child_cb_drained_begin(BdrvChild *child)
1227{
1228 BlockDriverState *bs = child->opaque;
6cd5c9d7 1229 bdrv_do_drained_begin_quiesce(bs, NULL, false);
20018e12
KW
1230}
1231
89bd0305
KW
1232static bool bdrv_child_cb_drained_poll(BdrvChild *child)
1233{
1234 BlockDriverState *bs = child->opaque;
6cd5c9d7 1235 return bdrv_drain_poll(bs, false, NULL, false);
89bd0305
KW
1236}
1237
e037c09c
HR
1238static void bdrv_child_cb_drained_end(BdrvChild *child,
1239 int *drained_end_counter)
20018e12
KW
1240{
1241 BlockDriverState *bs = child->opaque;
e037c09c 1242 bdrv_drained_end_no_poll(bs, drained_end_counter);
20018e12
KW
1243}
1244
38701b6a
KW
1245static int bdrv_child_cb_inactivate(BdrvChild *child)
1246{
1247 BlockDriverState *bs = child->opaque;
bdb73476 1248 GLOBAL_STATE_CODE();
38701b6a
KW
1249 assert(bs->open_flags & BDRV_O_INACTIVE);
1250 return 0;
1251}
1252
27633e74
EGE
1253static bool bdrv_child_cb_change_aio_ctx(BdrvChild *child, AioContext *ctx,
1254 GHashTable *visited, Transaction *tran,
1255 Error **errp)
53a7d041
KW
1256{
1257 BlockDriverState *bs = child->opaque;
27633e74 1258 return bdrv_change_aio_context(bs, ctx, visited, tran, errp);
53a7d041
KW
1259}
1260
b1e6fc08 1261/*
73176bee
KW
1262 * Returns the options and flags that a temporary snapshot should get, based on
1263 * the originally requested flags (the originally requested image will have
1264 * flags like a backing file)
b1e6fc08 1265 */
73176bee
KW
1266static void bdrv_temp_snapshot_options(int *child_flags, QDict *child_options,
1267 int parent_flags, QDict *parent_options)
b1e6fc08 1268{
bdb73476 1269 GLOBAL_STATE_CODE();
73176bee
KW
1270 *child_flags = (parent_flags & ~BDRV_O_SNAPSHOT) | BDRV_O_TEMPORARY;
1271
1272 /* For temporary files, unconditional cache=unsafe is fine */
73176bee
KW
1273 qdict_set_default_str(child_options, BDRV_OPT_CACHE_DIRECT, "off");
1274 qdict_set_default_str(child_options, BDRV_OPT_CACHE_NO_FLUSH, "on");
41869044 1275
3f48686f 1276 /* Copy the read-only and discard options from the parent */
f87a0e29 1277 qdict_copy_default(child_options, parent_options, BDRV_OPT_READ_ONLY);
3f48686f 1278 qdict_copy_default(child_options, parent_options, BDRV_OPT_DISCARD);
f87a0e29 1279
41869044
KW
1280 /* aio=native doesn't work for cache.direct=off, so disable it for the
1281 * temporary snapshot */
1282 *child_flags &= ~BDRV_O_NATIVE_AIO;
b1e6fc08
KW
1283}
1284
db95dbba
KW
1285static void bdrv_backing_attach(BdrvChild *c)
1286{
1287 BlockDriverState *parent = c->opaque;
1288 BlockDriverState *backing_hd = c->bs;
1289
bdb73476 1290 GLOBAL_STATE_CODE();
db95dbba
KW
1291 assert(!parent->backing_blocker);
1292 error_setg(&parent->backing_blocker,
1293 "node is used as backing hd of '%s'",
1294 bdrv_get_device_or_node_name(parent));
1295
f30c66ba
HR
1296 bdrv_refresh_filename(backing_hd);
1297
db95dbba 1298 parent->open_flags &= ~BDRV_O_NO_BACKING;
db95dbba
KW
1299
1300 bdrv_op_block_all(backing_hd, parent->backing_blocker);
1301 /* Otherwise we won't be able to commit or stream */
1302 bdrv_op_unblock(backing_hd, BLOCK_OP_TYPE_COMMIT_TARGET,
1303 parent->backing_blocker);
1304 bdrv_op_unblock(backing_hd, BLOCK_OP_TYPE_STREAM,
1305 parent->backing_blocker);
1306 /*
1307 * We do backup in 3 ways:
1308 * 1. drive backup
1309 * The target bs is new opened, and the source is top BDS
1310 * 2. blockdev backup
1311 * Both the source and the target are top BDSes.
1312 * 3. internal backup(used for block replication)
1313 * Both the source and the target are backing file
1314 *
1315 * In case 1 and 2, neither the source nor the target is the backing file.
1316 * In case 3, we will block the top BDS, so there is only one block job
1317 * for the top BDS and its backing chain.
1318 */
1319 bdrv_op_unblock(backing_hd, BLOCK_OP_TYPE_BACKUP_SOURCE,
1320 parent->backing_blocker);
1321 bdrv_op_unblock(backing_hd, BLOCK_OP_TYPE_BACKUP_TARGET,
1322 parent->backing_blocker);
ca2f1234 1323}
d736f119 1324
db95dbba
KW
1325static void bdrv_backing_detach(BdrvChild *c)
1326{
1327 BlockDriverState *parent = c->opaque;
1328
bdb73476 1329 GLOBAL_STATE_CODE();
db95dbba
KW
1330 assert(parent->backing_blocker);
1331 bdrv_op_unblock_all(c->bs, parent->backing_blocker);
1332 error_free(parent->backing_blocker);
1333 parent->backing_blocker = NULL;
48e08288 1334}
d736f119 1335
6858eba0
KW
1336static int bdrv_backing_update_filename(BdrvChild *c, BlockDriverState *base,
1337 const char *filename, Error **errp)
1338{
1339 BlockDriverState *parent = c->opaque;
e94d3dba 1340 bool read_only = bdrv_is_read_only(parent);
6858eba0 1341 int ret;
bdb73476 1342 GLOBAL_STATE_CODE();
6858eba0 1343
e94d3dba
AG
1344 if (read_only) {
1345 ret = bdrv_reopen_set_read_only(parent, false, errp);
61f09cea
KW
1346 if (ret < 0) {
1347 return ret;
1348 }
1349 }
1350
6858eba0 1351 ret = bdrv_change_backing_file(parent, filename,
e54ee1b3
EB
1352 base->drv ? base->drv->format_name : "",
1353 false);
6858eba0 1354 if (ret < 0) {
64730694 1355 error_setg_errno(errp, -ret, "Could not update backing file link");
6858eba0
KW
1356 }
1357
e94d3dba
AG
1358 if (read_only) {
1359 bdrv_reopen_set_read_only(parent, true, NULL);
61f09cea
KW
1360 }
1361
6858eba0
KW
1362 return ret;
1363}
1364
fae8bd39
HR
1365/*
1366 * Returns the options and flags that a generic child of a BDS should
1367 * get, based on the given options and flags for the parent BDS.
1368 */
00ff7ffd
HR
1369static void bdrv_inherited_options(BdrvChildRole role, bool parent_is_format,
1370 int *child_flags, QDict *child_options,
1371 int parent_flags, QDict *parent_options)
fae8bd39
HR
1372{
1373 int flags = parent_flags;
bdb73476 1374 GLOBAL_STATE_CODE();
fae8bd39
HR
1375
1376 /*
1377 * First, decide whether to set, clear, or leave BDRV_O_PROTOCOL.
1378 * Generally, the question to answer is: Should this child be
1379 * format-probed by default?
1380 */
1381
1382 /*
1383 * Pure and non-filtered data children of non-format nodes should
1384 * be probed by default (even when the node itself has BDRV_O_PROTOCOL
1385 * set). This only affects a very limited set of drivers (namely
1386 * quorum and blkverify when this comment was written).
1387 * Force-clear BDRV_O_PROTOCOL then.
1388 */
1389 if (!parent_is_format &&
1390 (role & BDRV_CHILD_DATA) &&
1391 !(role & (BDRV_CHILD_METADATA | BDRV_CHILD_FILTERED)))
1392 {
1393 flags &= ~BDRV_O_PROTOCOL;
1394 }
1395
1396 /*
1397 * All children of format nodes (except for COW children) and all
1398 * metadata children in general should never be format-probed.
1399 * Force-set BDRV_O_PROTOCOL then.
1400 */
1401 if ((parent_is_format && !(role & BDRV_CHILD_COW)) ||
1402 (role & BDRV_CHILD_METADATA))
1403 {
1404 flags |= BDRV_O_PROTOCOL;
1405 }
1406
1407 /*
1408 * If the cache mode isn't explicitly set, inherit direct and no-flush from
1409 * the parent.
1410 */
1411 qdict_copy_default(child_options, parent_options, BDRV_OPT_CACHE_DIRECT);
1412 qdict_copy_default(child_options, parent_options, BDRV_OPT_CACHE_NO_FLUSH);
1413 qdict_copy_default(child_options, parent_options, BDRV_OPT_FORCE_SHARE);
1414
1415 if (role & BDRV_CHILD_COW) {
1416 /* backing files are opened read-only by default */
1417 qdict_set_default_str(child_options, BDRV_OPT_READ_ONLY, "on");
1418 qdict_set_default_str(child_options, BDRV_OPT_AUTO_READ_ONLY, "off");
1419 } else {
1420 /* Inherit the read-only option from the parent if it's not set */
1421 qdict_copy_default(child_options, parent_options, BDRV_OPT_READ_ONLY);
1422 qdict_copy_default(child_options, parent_options,
1423 BDRV_OPT_AUTO_READ_ONLY);
1424 }
1425
1426 /*
1427 * bdrv_co_pdiscard() respects unmap policy for the parent, so we
1428 * can default to enable it on lower layers regardless of the
1429 * parent option.
1430 */
1431 qdict_set_default_str(child_options, BDRV_OPT_DISCARD, "unmap");
1432
1433 /* Clear flags that only apply to the top layer */
1434 flags &= ~(BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING | BDRV_O_COPY_ON_READ);
1435
1436 if (role & BDRV_CHILD_METADATA) {
1437 flags &= ~BDRV_O_NO_IO;
1438 }
1439 if (role & BDRV_CHILD_COW) {
1440 flags &= ~BDRV_O_TEMPORARY;
1441 }
1442
1443 *child_flags = flags;
1444}
1445
ca2f1234
HR
1446static void bdrv_child_cb_attach(BdrvChild *child)
1447{
1448 BlockDriverState *bs = child->opaque;
1449
696bf4c7 1450 assert_bdrv_graph_writable(bs);
a225369b 1451 QLIST_INSERT_HEAD(&bs->children, child, next);
5bb04747
VSO
1452 if (bs->drv->is_filter || (child->role & BDRV_CHILD_FILTERED)) {
1453 /*
1454 * Here we handle filters and block/raw-format.c when it behave like
1455 * filter. They generally have a single PRIMARY child, which is also the
1456 * FILTERED child, and that they may have multiple more children, which
1457 * are neither PRIMARY nor FILTERED. And never we have a COW child here.
1458 * So bs->file will be the PRIMARY child, unless the PRIMARY child goes
1459 * into bs->backing on exceptional cases; and bs->backing will be
1460 * nothing else.
1461 */
1462 assert(!(child->role & BDRV_CHILD_COW));
1463 if (child->role & BDRV_CHILD_PRIMARY) {
1464 assert(child->role & BDRV_CHILD_FILTERED);
1465 assert(!bs->backing);
1466 assert(!bs->file);
1467
1468 if (bs->drv->filtered_child_is_backing) {
1469 bs->backing = child;
1470 } else {
1471 bs->file = child;
1472 }
1473 } else {
1474 assert(!(child->role & BDRV_CHILD_FILTERED));
1475 }
1476 } else if (child->role & BDRV_CHILD_COW) {
1477 assert(bs->drv->supports_backing);
1478 assert(!(child->role & BDRV_CHILD_PRIMARY));
1479 assert(!bs->backing);
1480 bs->backing = child;
ca2f1234 1481 bdrv_backing_attach(child);
5bb04747
VSO
1482 } else if (child->role & BDRV_CHILD_PRIMARY) {
1483 assert(!bs->file);
1484 bs->file = child;
ca2f1234
HR
1485 }
1486
1487 bdrv_apply_subtree_drain(child, bs);
1488}
1489
48e08288
HR
1490static void bdrv_child_cb_detach(BdrvChild *child)
1491{
1492 BlockDriverState *bs = child->opaque;
1493
1494 if (child->role & BDRV_CHILD_COW) {
1495 bdrv_backing_detach(child);
1496 }
1497
1498 bdrv_unapply_subtree_drain(child, bs);
a225369b 1499
696bf4c7 1500 assert_bdrv_graph_writable(bs);
a225369b 1501 QLIST_REMOVE(child, next);
5bb04747
VSO
1502 if (child == bs->backing) {
1503 assert(child != bs->file);
1504 bs->backing = NULL;
1505 } else if (child == bs->file) {
1506 bs->file = NULL;
1507 }
48e08288
HR
1508}
1509
43483550
HR
1510static int bdrv_child_cb_update_filename(BdrvChild *c, BlockDriverState *base,
1511 const char *filename, Error **errp)
1512{
1513 if (c->role & BDRV_CHILD_COW) {
1514 return bdrv_backing_update_filename(c, base, filename, errp);
1515 }
1516 return 0;
1517}
1518
fb62b588 1519AioContext *child_of_bds_get_parent_aio_context(BdrvChild *c)
3ca1f322
VSO
1520{
1521 BlockDriverState *bs = c->opaque;
384a48fb 1522 IO_CODE();
3ca1f322
VSO
1523
1524 return bdrv_get_aio_context(bs);
1525}
1526
43483550
HR
1527const BdrvChildClass child_of_bds = {
1528 .parent_is_bds = true,
1529 .get_parent_desc = bdrv_child_get_parent_desc,
1530 .inherit_options = bdrv_inherited_options,
1531 .drained_begin = bdrv_child_cb_drained_begin,
1532 .drained_poll = bdrv_child_cb_drained_poll,
1533 .drained_end = bdrv_child_cb_drained_end,
1534 .attach = bdrv_child_cb_attach,
1535 .detach = bdrv_child_cb_detach,
1536 .inactivate = bdrv_child_cb_inactivate,
27633e74 1537 .change_aio_ctx = bdrv_child_cb_change_aio_ctx,
43483550 1538 .update_filename = bdrv_child_cb_update_filename,
fb62b588 1539 .get_parent_aio_context = child_of_bds_get_parent_aio_context,
43483550
HR
1540};
1541
3ca1f322
VSO
1542AioContext *bdrv_child_get_parent_aio_context(BdrvChild *c)
1543{
d5f8d79c 1544 IO_CODE();
3ca1f322
VSO
1545 return c->klass->get_parent_aio_context(c);
1546}
1547
7b272452
KW
1548static int bdrv_open_flags(BlockDriverState *bs, int flags)
1549{
61de4c68 1550 int open_flags = flags;
bdb73476 1551 GLOBAL_STATE_CODE();
7b272452
KW
1552
1553 /*
1554 * Clear flags that are internal to the block layer before opening the
1555 * image.
1556 */
20cca275 1557 open_flags &= ~(BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING | BDRV_O_PROTOCOL);
7b272452 1558
7b272452
KW
1559 return open_flags;
1560}
1561
91a097e7
KW
1562static void update_flags_from_options(int *flags, QemuOpts *opts)
1563{
bdb73476
EGE
1564 GLOBAL_STATE_CODE();
1565
2a3d4331 1566 *flags &= ~(BDRV_O_CACHE_MASK | BDRV_O_RDWR | BDRV_O_AUTO_RDONLY);
91a097e7 1567
57f9db9a 1568 if (qemu_opt_get_bool_del(opts, BDRV_OPT_CACHE_NO_FLUSH, false)) {
91a097e7
KW
1569 *flags |= BDRV_O_NO_FLUSH;
1570 }
1571
57f9db9a 1572 if (qemu_opt_get_bool_del(opts, BDRV_OPT_CACHE_DIRECT, false)) {
91a097e7
KW
1573 *flags |= BDRV_O_NOCACHE;
1574 }
f87a0e29 1575
57f9db9a 1576 if (!qemu_opt_get_bool_del(opts, BDRV_OPT_READ_ONLY, false)) {
f87a0e29
AG
1577 *flags |= BDRV_O_RDWR;
1578 }
1579
e35bdc12
KW
1580 if (qemu_opt_get_bool_del(opts, BDRV_OPT_AUTO_READ_ONLY, false)) {
1581 *flags |= BDRV_O_AUTO_RDONLY;
1582 }
91a097e7
KW
1583}
1584
1585static void update_options_from_flags(QDict *options, int flags)
1586{
bdb73476 1587 GLOBAL_STATE_CODE();
91a097e7 1588 if (!qdict_haskey(options, BDRV_OPT_CACHE_DIRECT)) {
46f5ac20 1589 qdict_put_bool(options, BDRV_OPT_CACHE_DIRECT, flags & BDRV_O_NOCACHE);
91a097e7
KW
1590 }
1591 if (!qdict_haskey(options, BDRV_OPT_CACHE_NO_FLUSH)) {
46f5ac20
EB
1592 qdict_put_bool(options, BDRV_OPT_CACHE_NO_FLUSH,
1593 flags & BDRV_O_NO_FLUSH);
91a097e7 1594 }
f87a0e29 1595 if (!qdict_haskey(options, BDRV_OPT_READ_ONLY)) {
46f5ac20 1596 qdict_put_bool(options, BDRV_OPT_READ_ONLY, !(flags & BDRV_O_RDWR));
f87a0e29 1597 }
e35bdc12
KW
1598 if (!qdict_haskey(options, BDRV_OPT_AUTO_READ_ONLY)) {
1599 qdict_put_bool(options, BDRV_OPT_AUTO_READ_ONLY,
1600 flags & BDRV_O_AUTO_RDONLY);
1601 }
91a097e7
KW
1602}
1603
636ea370
KW
1604static void bdrv_assign_node_name(BlockDriverState *bs,
1605 const char *node_name,
1606 Error **errp)
6913c0c2 1607{
15489c76 1608 char *gen_node_name = NULL;
bdb73476 1609 GLOBAL_STATE_CODE();
6913c0c2 1610
15489c76
JC
1611 if (!node_name) {
1612 node_name = gen_node_name = id_generate(ID_BLOCK);
1613 } else if (!id_wellformed(node_name)) {
1614 /*
1615 * Check for empty string or invalid characters, but not if it is
1616 * generated (generated names use characters not available to the user)
1617 */
785ec4b1 1618 error_setg(errp, "Invalid node-name: '%s'", node_name);
636ea370 1619 return;
6913c0c2
BC
1620 }
1621
0c5e94ee 1622 /* takes care of avoiding namespaces collisions */
7f06d47e 1623 if (blk_by_name(node_name)) {
0c5e94ee
BC
1624 error_setg(errp, "node-name=%s is conflicting with a device id",
1625 node_name);
15489c76 1626 goto out;
0c5e94ee
BC
1627 }
1628
6913c0c2
BC
1629 /* takes care of avoiding duplicates node names */
1630 if (bdrv_find_node(node_name)) {
785ec4b1 1631 error_setg(errp, "Duplicate nodes with node-name='%s'", node_name);
15489c76 1632 goto out;
6913c0c2
BC
1633 }
1634
824808dd
KW
1635 /* Make sure that the node name isn't truncated */
1636 if (strlen(node_name) >= sizeof(bs->node_name)) {
1637 error_setg(errp, "Node name too long");
1638 goto out;
1639 }
1640
6913c0c2
BC
1641 /* copy node name into the bs and insert it into the graph list */
1642 pstrcpy(bs->node_name, sizeof(bs->node_name), node_name);
1643 QTAILQ_INSERT_TAIL(&graph_bdrv_states, bs, node_list);
15489c76
JC
1644out:
1645 g_free(gen_node_name);
6913c0c2
BC
1646}
1647
01a56501
KW
1648static int bdrv_open_driver(BlockDriverState *bs, BlockDriver *drv,
1649 const char *node_name, QDict *options,
1650 int open_flags, Error **errp)
1651{
1652 Error *local_err = NULL;
0f12264e 1653 int i, ret;
da359909 1654 GLOBAL_STATE_CODE();
01a56501
KW
1655
1656 bdrv_assign_node_name(bs, node_name, &local_err);
1657 if (local_err) {
1658 error_propagate(errp, local_err);
1659 return -EINVAL;
1660 }
1661
1662 bs->drv = drv;
1663 bs->opaque = g_malloc0(drv->instance_size);
1664
1665 if (drv->bdrv_file_open) {
1666 assert(!drv->bdrv_needs_filename || bs->filename[0]);
1667 ret = drv->bdrv_file_open(bs, options, open_flags, &local_err);
680c7f96 1668 } else if (drv->bdrv_open) {
01a56501 1669 ret = drv->bdrv_open(bs, options, open_flags, &local_err);
680c7f96
KW
1670 } else {
1671 ret = 0;
01a56501
KW
1672 }
1673
1674 if (ret < 0) {
1675 if (local_err) {
1676 error_propagate(errp, local_err);
1677 } else if (bs->filename[0]) {
1678 error_setg_errno(errp, -ret, "Could not open '%s'", bs->filename);
1679 } else {
1680 error_setg_errno(errp, -ret, "Could not open image");
1681 }
180ca19a 1682 goto open_failed;
01a56501
KW
1683 }
1684
e8b65355
SH
1685 assert(!(bs->supported_read_flags & ~BDRV_REQ_MASK));
1686 assert(!(bs->supported_write_flags & ~BDRV_REQ_MASK));
1687
1688 /*
1689 * Always allow the BDRV_REQ_REGISTERED_BUF optimization hint. This saves
1690 * drivers that pass read/write requests through to a child the trouble of
1691 * declaring support explicitly.
1692 *
1693 * Drivers must not propagate this flag accidentally when they initiate I/O
1694 * to a bounce buffer. That case should be rare though.
1695 */
1696 bs->supported_read_flags |= BDRV_REQ_REGISTERED_BUF;
1697 bs->supported_write_flags |= BDRV_REQ_REGISTERED_BUF;
1698
01a56501
KW
1699 ret = refresh_total_sectors(bs, bs->total_sectors);
1700 if (ret < 0) {
1701 error_setg_errno(errp, -ret, "Could not refresh total sector count");
180ca19a 1702 return ret;
01a56501
KW
1703 }
1704
1e4c797c 1705 bdrv_refresh_limits(bs, NULL, &local_err);
01a56501
KW
1706 if (local_err) {
1707 error_propagate(errp, local_err);
180ca19a 1708 return -EINVAL;
01a56501
KW
1709 }
1710
1711 assert(bdrv_opt_mem_align(bs) != 0);
1712 assert(bdrv_min_mem_align(bs) != 0);
1713 assert(is_power_of_2(bs->bl.request_alignment));
1714
0f12264e 1715 for (i = 0; i < bs->quiesce_counter; i++) {
5e8ac217
KW
1716 if (drv->bdrv_drain_begin) {
1717 drv->bdrv_drain_begin(bs);
0f12264e
KW
1718 }
1719 }
1720
01a56501 1721 return 0;
180ca19a
MP
1722open_failed:
1723 bs->drv = NULL;
1724 if (bs->file != NULL) {
1725 bdrv_unref_child(bs, bs->file);
5bb04747 1726 assert(!bs->file);
180ca19a 1727 }
01a56501
KW
1728 g_free(bs->opaque);
1729 bs->opaque = NULL;
01a56501
KW
1730 return ret;
1731}
1732
621d1737
VSO
1733/*
1734 * Create and open a block node.
1735 *
1736 * @options is a QDict of options to pass to the block drivers, or NULL for an
1737 * empty set of options. The reference to the QDict belongs to the block layer
1738 * after the call (even on failure), so if the caller intends to reuse the
1739 * dictionary, it needs to use qobject_ref() before calling bdrv_open.
1740 */
1741BlockDriverState *bdrv_new_open_driver_opts(BlockDriver *drv,
1742 const char *node_name,
1743 QDict *options, int flags,
1744 Error **errp)
680c7f96
KW
1745{
1746 BlockDriverState *bs;
1747 int ret;
1748
f791bf7f
EGE
1749 GLOBAL_STATE_CODE();
1750
680c7f96
KW
1751 bs = bdrv_new();
1752 bs->open_flags = flags;
621d1737
VSO
1753 bs->options = options ?: qdict_new();
1754 bs->explicit_options = qdict_clone_shallow(bs->options);
680c7f96
KW
1755 bs->opaque = NULL;
1756
1757 update_options_from_flags(bs->options, flags);
1758
1759 ret = bdrv_open_driver(bs, drv, node_name, bs->options, flags, errp);
1760 if (ret < 0) {
cb3e7f08 1761 qobject_unref(bs->explicit_options);
180ca19a 1762 bs->explicit_options = NULL;
cb3e7f08 1763 qobject_unref(bs->options);
180ca19a 1764 bs->options = NULL;
680c7f96
KW
1765 bdrv_unref(bs);
1766 return NULL;
1767 }
1768
1769 return bs;
1770}
1771
621d1737
VSO
1772/* Create and open a block node. */
1773BlockDriverState *bdrv_new_open_driver(BlockDriver *drv, const char *node_name,
1774 int flags, Error **errp)
1775{
f791bf7f 1776 GLOBAL_STATE_CODE();
621d1737
VSO
1777 return bdrv_new_open_driver_opts(drv, node_name, NULL, flags, errp);
1778}
1779
c5f3014b 1780QemuOptsList bdrv_runtime_opts = {
18edf289
KW
1781 .name = "bdrv_common",
1782 .head = QTAILQ_HEAD_INITIALIZER(bdrv_runtime_opts.head),
1783 .desc = {
1784 {
1785 .name = "node-name",
1786 .type = QEMU_OPT_STRING,
1787 .help = "Node name of the block device node",
1788 },
62392ebb
KW
1789 {
1790 .name = "driver",
1791 .type = QEMU_OPT_STRING,
1792 .help = "Block driver to use for the node",
1793 },
91a097e7
KW
1794 {
1795 .name = BDRV_OPT_CACHE_DIRECT,
1796 .type = QEMU_OPT_BOOL,
1797 .help = "Bypass software writeback cache on the host",
1798 },
1799 {
1800 .name = BDRV_OPT_CACHE_NO_FLUSH,
1801 .type = QEMU_OPT_BOOL,
1802 .help = "Ignore flush requests",
1803 },
f87a0e29
AG
1804 {
1805 .name = BDRV_OPT_READ_ONLY,
1806 .type = QEMU_OPT_BOOL,
1807 .help = "Node is opened in read-only mode",
1808 },
e35bdc12
KW
1809 {
1810 .name = BDRV_OPT_AUTO_READ_ONLY,
1811 .type = QEMU_OPT_BOOL,
1812 .help = "Node can become read-only if opening read-write fails",
1813 },
692e01a2
KW
1814 {
1815 .name = "detect-zeroes",
1816 .type = QEMU_OPT_STRING,
1817 .help = "try to optimize zero writes (off, on, unmap)",
1818 },
818584a4 1819 {
415bbca8 1820 .name = BDRV_OPT_DISCARD,
818584a4
KW
1821 .type = QEMU_OPT_STRING,
1822 .help = "discard operation (ignore/off, unmap/on)",
1823 },
5a9347c6
FZ
1824 {
1825 .name = BDRV_OPT_FORCE_SHARE,
1826 .type = QEMU_OPT_BOOL,
1827 .help = "always accept other writers (default: off)",
1828 },
18edf289
KW
1829 { /* end of list */ }
1830 },
1831};
1832
5a5e7f8c
ML
1833QemuOptsList bdrv_create_opts_simple = {
1834 .name = "simple-create-opts",
1835 .head = QTAILQ_HEAD_INITIALIZER(bdrv_create_opts_simple.head),
fd17146c
HR
1836 .desc = {
1837 {
1838 .name = BLOCK_OPT_SIZE,
1839 .type = QEMU_OPT_SIZE,
1840 .help = "Virtual disk size"
1841 },
1842 {
1843 .name = BLOCK_OPT_PREALLOC,
1844 .type = QEMU_OPT_STRING,
1845 .help = "Preallocation mode (allowed values: off)"
1846 },
1847 { /* end of list */ }
1848 }
1849};
1850
57915332
KW
1851/*
1852 * Common part for opening disk images and files
b6ad491a
KW
1853 *
1854 * Removes all processed options from *options.
57915332 1855 */
5696c6e3 1856static int bdrv_open_common(BlockDriverState *bs, BlockBackend *file,
82dc8b41 1857 QDict *options, Error **errp)
57915332
KW
1858{
1859 int ret, open_flags;
035fccdf 1860 const char *filename;
62392ebb 1861 const char *driver_name = NULL;
6913c0c2 1862 const char *node_name = NULL;
818584a4 1863 const char *discard;
18edf289 1864 QemuOpts *opts;
62392ebb 1865 BlockDriver *drv;
34b5d2c6 1866 Error *local_err = NULL;
307261b2 1867 bool ro;
57915332 1868
6405875c 1869 assert(bs->file == NULL);
707ff828 1870 assert(options != NULL && bs->options != options);
bdb73476 1871 GLOBAL_STATE_CODE();
57915332 1872
62392ebb 1873 opts = qemu_opts_create(&bdrv_runtime_opts, NULL, 0, &error_abort);
af175e85 1874 if (!qemu_opts_absorb_qdict(opts, options, errp)) {
62392ebb
KW
1875 ret = -EINVAL;
1876 goto fail_opts;
1877 }
1878
9b7e8691
AG
1879 update_flags_from_options(&bs->open_flags, opts);
1880
62392ebb
KW
1881 driver_name = qemu_opt_get(opts, "driver");
1882 drv = bdrv_find_format(driver_name);
1883 assert(drv != NULL);
1884
5a9347c6
FZ
1885 bs->force_share = qemu_opt_get_bool(opts, BDRV_OPT_FORCE_SHARE, false);
1886
1887 if (bs->force_share && (bs->open_flags & BDRV_O_RDWR)) {
1888 error_setg(errp,
1889 BDRV_OPT_FORCE_SHARE
1890 "=on can only be used with read-only images");
1891 ret = -EINVAL;
1892 goto fail_opts;
1893 }
1894
45673671 1895 if (file != NULL) {
f30c66ba 1896 bdrv_refresh_filename(blk_bs(file));
5696c6e3 1897 filename = blk_bs(file)->filename;
45673671 1898 } else {
129c7d1c
MA
1899 /*
1900 * Caution: while qdict_get_try_str() is fine, getting
1901 * non-string types would require more care. When @options
1902 * come from -blockdev or blockdev_add, its members are typed
1903 * according to the QAPI schema, but when they come from
1904 * -drive, they're all QString.
1905 */
45673671
KW
1906 filename = qdict_get_try_str(options, "filename");
1907 }
1908
4a008240 1909 if (drv->bdrv_needs_filename && (!filename || !filename[0])) {
765003db
KW
1910 error_setg(errp, "The '%s' block driver requires a file name",
1911 drv->format_name);
18edf289
KW
1912 ret = -EINVAL;
1913 goto fail_opts;
6913c0c2 1914 }
6913c0c2 1915
82dc8b41
KW
1916 trace_bdrv_open_common(bs, filename ?: "", bs->open_flags,
1917 drv->format_name);
62392ebb 1918
307261b2
VSO
1919 ro = bdrv_is_read_only(bs);
1920
1921 if (use_bdrv_whitelist && !bdrv_is_whitelisted(drv, ro)) {
1922 if (!ro && bdrv_is_whitelisted(drv, true)) {
8be25de6
KW
1923 ret = bdrv_apply_auto_read_only(bs, NULL, NULL);
1924 } else {
1925 ret = -ENOTSUP;
1926 }
1927 if (ret < 0) {
1928 error_setg(errp,
307261b2 1929 !ro && bdrv_is_whitelisted(drv, true)
8be25de6
KW
1930 ? "Driver '%s' can only be used for read-only devices"
1931 : "Driver '%s' is not whitelisted",
1932 drv->format_name);
1933 goto fail_opts;
1934 }
b64ec4e4 1935 }
57915332 1936
d3faa13e 1937 /* bdrv_new() and bdrv_close() make it so */
d73415a3 1938 assert(qatomic_read(&bs->copy_on_read) == 0);
d3faa13e 1939
82dc8b41 1940 if (bs->open_flags & BDRV_O_COPY_ON_READ) {
307261b2 1941 if (!ro) {
0ebd24e0
KW
1942 bdrv_enable_copy_on_read(bs);
1943 } else {
1944 error_setg(errp, "Can't use copy-on-read on read-only device");
18edf289
KW
1945 ret = -EINVAL;
1946 goto fail_opts;
0ebd24e0 1947 }
53fec9d3
SH
1948 }
1949
415bbca8 1950 discard = qemu_opt_get(opts, BDRV_OPT_DISCARD);
818584a4
KW
1951 if (discard != NULL) {
1952 if (bdrv_parse_discard_flags(discard, &bs->open_flags) != 0) {
1953 error_setg(errp, "Invalid discard option");
1954 ret = -EINVAL;
1955 goto fail_opts;
1956 }
1957 }
1958
543770bd
AG
1959 bs->detect_zeroes =
1960 bdrv_parse_detect_zeroes(opts, bs->open_flags, &local_err);
1961 if (local_err) {
1962 error_propagate(errp, local_err);
1963 ret = -EINVAL;
1964 goto fail_opts;
692e01a2
KW
1965 }
1966
c2ad1b0c
KW
1967 if (filename != NULL) {
1968 pstrcpy(bs->filename, sizeof(bs->filename), filename);
1969 } else {
1970 bs->filename[0] = '\0';
1971 }
91af7014 1972 pstrcpy(bs->exact_filename, sizeof(bs->exact_filename), bs->filename);
57915332 1973
66f82cee 1974 /* Open the image, either directly or using a protocol */
82dc8b41 1975 open_flags = bdrv_open_flags(bs, bs->open_flags);
01a56501 1976 node_name = qemu_opt_get(opts, "node-name");
57915332 1977
01a56501
KW
1978 assert(!drv->bdrv_file_open || file == NULL);
1979 ret = bdrv_open_driver(bs, drv, node_name, options, open_flags, errp);
51762288 1980 if (ret < 0) {
01a56501 1981 goto fail_opts;
3baca891
KW
1982 }
1983
18edf289 1984 qemu_opts_del(opts);
57915332
KW
1985 return 0;
1986
18edf289
KW
1987fail_opts:
1988 qemu_opts_del(opts);
57915332
KW
1989 return ret;
1990}
1991
5e5c4f63
KW
1992static QDict *parse_json_filename(const char *filename, Error **errp)
1993{
1994 QObject *options_obj;
1995 QDict *options;
1996 int ret;
bdb73476 1997 GLOBAL_STATE_CODE();
5e5c4f63
KW
1998
1999 ret = strstart(filename, "json:", &filename);
2000 assert(ret);
2001
5577fff7 2002 options_obj = qobject_from_json(filename, errp);
5e5c4f63 2003 if (!options_obj) {
5577fff7 2004 error_prepend(errp, "Could not parse the JSON options: ");
5e5c4f63
KW
2005 return NULL;
2006 }
2007
7dc847eb 2008 options = qobject_to(QDict, options_obj);
ca6b6e1e 2009 if (!options) {
cb3e7f08 2010 qobject_unref(options_obj);
5e5c4f63
KW
2011 error_setg(errp, "Invalid JSON object given");
2012 return NULL;
2013 }
2014
5e5c4f63
KW
2015 qdict_flatten(options);
2016
2017 return options;
2018}
2019
de3b53f0
KW
2020static void parse_json_protocol(QDict *options, const char **pfilename,
2021 Error **errp)
2022{
2023 QDict *json_options;
2024 Error *local_err = NULL;
bdb73476 2025 GLOBAL_STATE_CODE();
de3b53f0
KW
2026
2027 /* Parse json: pseudo-protocol */
2028 if (!*pfilename || !g_str_has_prefix(*pfilename, "json:")) {
2029 return;
2030 }
2031
2032 json_options = parse_json_filename(*pfilename, &local_err);
2033 if (local_err) {
2034 error_propagate(errp, local_err);
2035 return;
2036 }
2037
2038 /* Options given in the filename have lower priority than options
2039 * specified directly */
2040 qdict_join(options, json_options, false);
cb3e7f08 2041 qobject_unref(json_options);
de3b53f0
KW
2042 *pfilename = NULL;
2043}
2044
b6ce07aa 2045/*
f54120ff
KW
2046 * Fills in default options for opening images and converts the legacy
2047 * filename/flags pair to option QDict entries.
53a29513
HR
2048 * The BDRV_O_PROTOCOL flag in *flags will be set or cleared accordingly if a
2049 * block driver has been specified explicitly.
b6ce07aa 2050 */
de3b53f0 2051static int bdrv_fill_options(QDict **options, const char *filename,
053e1578 2052 int *flags, Error **errp)
ea2384d3 2053{
c2ad1b0c 2054 const char *drvname;
53a29513 2055 bool protocol = *flags & BDRV_O_PROTOCOL;
e3fa4bfa 2056 bool parse_filename = false;
053e1578 2057 BlockDriver *drv = NULL;
34b5d2c6 2058 Error *local_err = NULL;
83f64091 2059
da359909
EGE
2060 GLOBAL_STATE_CODE();
2061
129c7d1c
MA
2062 /*
2063 * Caution: while qdict_get_try_str() is fine, getting non-string
2064 * types would require more care. When @options come from
2065 * -blockdev or blockdev_add, its members are typed according to
2066 * the QAPI schema, but when they come from -drive, they're all
2067 * QString.
2068 */
53a29513 2069 drvname = qdict_get_try_str(*options, "driver");
053e1578
HR
2070 if (drvname) {
2071 drv = bdrv_find_format(drvname);
2072 if (!drv) {
2073 error_setg(errp, "Unknown driver '%s'", drvname);
2074 return -ENOENT;
2075 }
2076 /* If the user has explicitly specified the driver, this choice should
2077 * override the BDRV_O_PROTOCOL flag */
2078 protocol = drv->bdrv_file_open;
53a29513
HR
2079 }
2080
2081 if (protocol) {
2082 *flags |= BDRV_O_PROTOCOL;
2083 } else {
2084 *flags &= ~BDRV_O_PROTOCOL;
2085 }
2086
91a097e7
KW
2087 /* Translate cache options from flags into options */
2088 update_options_from_flags(*options, *flags);
2089
035fccdf 2090 /* Fetch the file name from the options QDict if necessary */
17b005f1 2091 if (protocol && filename) {
f54120ff 2092 if (!qdict_haskey(*options, "filename")) {
46f5ac20 2093 qdict_put_str(*options, "filename", filename);
f54120ff
KW
2094 parse_filename = true;
2095 } else {
2096 error_setg(errp, "Can't specify 'file' and 'filename' options at "
2097 "the same time");
2098 return -EINVAL;
2099 }
035fccdf
KW
2100 }
2101
c2ad1b0c 2102 /* Find the right block driver */
129c7d1c 2103 /* See cautionary note on accessing @options above */
f54120ff 2104 filename = qdict_get_try_str(*options, "filename");
f54120ff 2105
053e1578
HR
2106 if (!drvname && protocol) {
2107 if (filename) {
2108 drv = bdrv_find_protocol(filename, parse_filename, errp);
17b005f1 2109 if (!drv) {
053e1578 2110 return -EINVAL;
17b005f1 2111 }
053e1578
HR
2112
2113 drvname = drv->format_name;
46f5ac20 2114 qdict_put_str(*options, "driver", drvname);
053e1578
HR
2115 } else {
2116 error_setg(errp, "Must specify either driver or file");
2117 return -EINVAL;
98289620 2118 }
c2ad1b0c
KW
2119 }
2120
17b005f1 2121 assert(drv || !protocol);
c2ad1b0c 2122
f54120ff 2123 /* Driver-specific filename parsing */
17b005f1 2124 if (drv && drv->bdrv_parse_filename && parse_filename) {
5acd9d81 2125 drv->bdrv_parse_filename(filename, *options, &local_err);
84d18f06 2126 if (local_err) {
34b5d2c6 2127 error_propagate(errp, local_err);
f54120ff 2128 return -EINVAL;
6963a30d 2129 }
cd5d031e
HR
2130
2131 if (!drv->bdrv_needs_filename) {
2132 qdict_del(*options, "filename");
cd5d031e 2133 }
6963a30d
KW
2134 }
2135
f54120ff
KW
2136 return 0;
2137}
2138
148eb13c
KW
2139typedef struct BlockReopenQueueEntry {
2140 bool prepared;
69b736e7 2141 bool perms_checked;
148eb13c 2142 BDRVReopenState state;
859443b0 2143 QTAILQ_ENTRY(BlockReopenQueueEntry) entry;
148eb13c
KW
2144} BlockReopenQueueEntry;
2145
2146/*
2147 * Return the flags that @bs will have after the reopens in @q have
2148 * successfully completed. If @q is NULL (or @bs is not contained in @q),
2149 * return the current flags.
2150 */
2151static int bdrv_reopen_get_flags(BlockReopenQueue *q, BlockDriverState *bs)
2152{
2153 BlockReopenQueueEntry *entry;
2154
2155 if (q != NULL) {
859443b0 2156 QTAILQ_FOREACH(entry, q, entry) {
148eb13c
KW
2157 if (entry->state.bs == bs) {
2158 return entry->state.flags;
2159 }
2160 }
2161 }
2162
2163 return bs->open_flags;
2164}
2165
2166/* Returns whether the image file can be written to after the reopen queue @q
2167 * has been successfully applied, or right now if @q is NULL. */
cc022140
HR
2168static bool bdrv_is_writable_after_reopen(BlockDriverState *bs,
2169 BlockReopenQueue *q)
148eb13c
KW
2170{
2171 int flags = bdrv_reopen_get_flags(q, bs);
2172
2173 return (flags & (BDRV_O_RDWR | BDRV_O_INACTIVE)) == BDRV_O_RDWR;
2174}
2175
cc022140
HR
2176/*
2177 * Return whether the BDS can be written to. This is not necessarily
2178 * the same as !bdrv_is_read_only(bs), as inactivated images may not
2179 * be written to but do not count as read-only images.
2180 */
2181bool bdrv_is_writable(BlockDriverState *bs)
2182{
384a48fb 2183 IO_CODE();
cc022140
HR
2184 return bdrv_is_writable_after_reopen(bs, NULL);
2185}
2186
3bf416ba
VSO
2187static char *bdrv_child_user_desc(BdrvChild *c)
2188{
f0c28327 2189 GLOBAL_STATE_CODE();
da261b69 2190 return c->klass->get_parent_desc(c);
3bf416ba
VSO
2191}
2192
30ebb9aa
VSO
2193/*
2194 * Check that @a allows everything that @b needs. @a and @b must reference same
2195 * child node.
2196 */
3bf416ba
VSO
2197static bool bdrv_a_allow_b(BdrvChild *a, BdrvChild *b, Error **errp)
2198{
30ebb9aa
VSO
2199 const char *child_bs_name;
2200 g_autofree char *a_user = NULL;
2201 g_autofree char *b_user = NULL;
2202 g_autofree char *perms = NULL;
2203
2204 assert(a->bs);
2205 assert(a->bs == b->bs);
862fded9 2206 GLOBAL_STATE_CODE();
3bf416ba
VSO
2207
2208 if ((b->perm & a->shared_perm) == b->perm) {
2209 return true;
2210 }
2211
30ebb9aa
VSO
2212 child_bs_name = bdrv_get_node_name(b->bs);
2213 a_user = bdrv_child_user_desc(a);
2214 b_user = bdrv_child_user_desc(b);
2215 perms = bdrv_perm_names(b->perm & ~a->shared_perm);
2216
2217 error_setg(errp, "Permission conflict on node '%s': permissions '%s' are "
2218 "both required by %s (uses node '%s' as '%s' child) and "
2219 "unshared by %s (uses node '%s' as '%s' child).",
2220 child_bs_name, perms,
2221 b_user, child_bs_name, b->name,
2222 a_user, child_bs_name, a->name);
3bf416ba
VSO
2223
2224 return false;
2225}
2226
9397c14f 2227static bool bdrv_parent_perms_conflict(BlockDriverState *bs, Error **errp)
3bf416ba
VSO
2228{
2229 BdrvChild *a, *b;
862fded9 2230 GLOBAL_STATE_CODE();
3bf416ba
VSO
2231
2232 /*
2233 * During the loop we'll look at each pair twice. That's correct because
2234 * bdrv_a_allow_b() is asymmetric and we should check each pair in both
2235 * directions.
2236 */
2237 QLIST_FOREACH(a, &bs->parents, next_parent) {
2238 QLIST_FOREACH(b, &bs->parents, next_parent) {
9397c14f 2239 if (a == b) {
3bf416ba
VSO
2240 continue;
2241 }
2242
2243 if (!bdrv_a_allow_b(a, b, errp)) {
2244 return true;
2245 }
2246 }
2247 }
2248
2249 return false;
2250}
2251
ffd1a5a2 2252static void bdrv_child_perm(BlockDriverState *bs, BlockDriverState *child_bs,
e5d8a406
HR
2253 BdrvChild *c, BdrvChildRole role,
2254 BlockReopenQueue *reopen_queue,
ffd1a5a2
FZ
2255 uint64_t parent_perm, uint64_t parent_shared,
2256 uint64_t *nperm, uint64_t *nshared)
2257{
0b3ca76e 2258 assert(bs->drv && bs->drv->bdrv_child_perm);
da359909 2259 GLOBAL_STATE_CODE();
e5d8a406 2260 bs->drv->bdrv_child_perm(bs, c, role, reopen_queue,
0b3ca76e
AG
2261 parent_perm, parent_shared,
2262 nperm, nshared);
e0995dc3 2263 /* TODO Take force_share from reopen_queue */
ffd1a5a2
FZ
2264 if (child_bs && child_bs->force_share) {
2265 *nshared = BLK_PERM_ALL;
2266 }
2267}
2268
bd57f8f7
VSO
2269/*
2270 * Adds the whole subtree of @bs (including @bs itself) to the @list (except for
2271 * nodes that are already in the @list, of course) so that final list is
2272 * topologically sorted. Return the result (GSList @list object is updated, so
2273 * don't use old reference after function call).
2274 *
2275 * On function start @list must be already topologically sorted and for any node
2276 * in the @list the whole subtree of the node must be in the @list as well. The
2277 * simplest way to satisfy this criteria: use only result of
2278 * bdrv_topological_dfs() or NULL as @list parameter.
2279 */
2280static GSList *bdrv_topological_dfs(GSList *list, GHashTable *found,
2281 BlockDriverState *bs)
2282{
2283 BdrvChild *child;
2284 g_autoptr(GHashTable) local_found = NULL;
2285
bdb73476
EGE
2286 GLOBAL_STATE_CODE();
2287
bd57f8f7
VSO
2288 if (!found) {
2289 assert(!list);
2290 found = local_found = g_hash_table_new(NULL, NULL);
2291 }
2292
2293 if (g_hash_table_contains(found, bs)) {
2294 return list;
2295 }
2296 g_hash_table_add(found, bs);
2297
2298 QLIST_FOREACH(child, &bs->children, next) {
2299 list = bdrv_topological_dfs(list, found, child->bs);
2300 }
2301
2302 return g_slist_prepend(list, bs);
2303}
2304
ecb776bd
VSO
2305typedef struct BdrvChildSetPermState {
2306 BdrvChild *child;
2307 uint64_t old_perm;
2308 uint64_t old_shared_perm;
2309} BdrvChildSetPermState;
b0defa83
VSO
2310
2311static void bdrv_child_set_perm_abort(void *opaque)
2312{
ecb776bd
VSO
2313 BdrvChildSetPermState *s = opaque;
2314
862fded9
EGE
2315 GLOBAL_STATE_CODE();
2316
ecb776bd
VSO
2317 s->child->perm = s->old_perm;
2318 s->child->shared_perm = s->old_shared_perm;
b0defa83
VSO
2319}
2320
2321static TransactionActionDrv bdrv_child_set_pem_drv = {
2322 .abort = bdrv_child_set_perm_abort,
ecb776bd 2323 .clean = g_free,
b0defa83
VSO
2324};
2325
ecb776bd
VSO
2326static void bdrv_child_set_perm(BdrvChild *c, uint64_t perm,
2327 uint64_t shared, Transaction *tran)
b0defa83 2328{
ecb776bd 2329 BdrvChildSetPermState *s = g_new(BdrvChildSetPermState, 1);
862fded9 2330 GLOBAL_STATE_CODE();
ecb776bd
VSO
2331
2332 *s = (BdrvChildSetPermState) {
2333 .child = c,
2334 .old_perm = c->perm,
2335 .old_shared_perm = c->shared_perm,
2336 };
b0defa83
VSO
2337
2338 c->perm = perm;
2339 c->shared_perm = shared;
2340
ecb776bd 2341 tran_add(tran, &bdrv_child_set_pem_drv, s);
b0defa83
VSO
2342}
2343
2513ef59
VSO
2344static void bdrv_drv_set_perm_commit(void *opaque)
2345{
2346 BlockDriverState *bs = opaque;
2347 uint64_t cumulative_perms, cumulative_shared_perms;
da359909 2348 GLOBAL_STATE_CODE();
2513ef59
VSO
2349
2350 if (bs->drv->bdrv_set_perm) {
2351 bdrv_get_cumulative_perm(bs, &cumulative_perms,
2352 &cumulative_shared_perms);
2353 bs->drv->bdrv_set_perm(bs, cumulative_perms, cumulative_shared_perms);
2354 }
2355}
2356
2357static void bdrv_drv_set_perm_abort(void *opaque)
2358{
2359 BlockDriverState *bs = opaque;
da359909 2360 GLOBAL_STATE_CODE();
2513ef59
VSO
2361
2362 if (bs->drv->bdrv_abort_perm_update) {
2363 bs->drv->bdrv_abort_perm_update(bs);
2364 }
2365}
2366
2367TransactionActionDrv bdrv_drv_set_perm_drv = {
2368 .abort = bdrv_drv_set_perm_abort,
2369 .commit = bdrv_drv_set_perm_commit,
2370};
2371
2372static int bdrv_drv_set_perm(BlockDriverState *bs, uint64_t perm,
2373 uint64_t shared_perm, Transaction *tran,
2374 Error **errp)
2375{
da359909 2376 GLOBAL_STATE_CODE();
2513ef59
VSO
2377 if (!bs->drv) {
2378 return 0;
2379 }
2380
2381 if (bs->drv->bdrv_check_perm) {
2382 int ret = bs->drv->bdrv_check_perm(bs, perm, shared_perm, errp);
2383 if (ret < 0) {
2384 return ret;
2385 }
2386 }
2387
2388 if (tran) {
2389 tran_add(tran, &bdrv_drv_set_perm_drv, bs);
2390 }
2391
2392 return 0;
2393}
2394
0978623e
VSO
2395typedef struct BdrvReplaceChildState {
2396 BdrvChild *child;
2397 BlockDriverState *old_bs;
2398} BdrvReplaceChildState;
2399
2400static void bdrv_replace_child_commit(void *opaque)
2401{
2402 BdrvReplaceChildState *s = opaque;
bdb73476 2403 GLOBAL_STATE_CODE();
0978623e
VSO
2404
2405 bdrv_unref(s->old_bs);
2406}
2407
2408static void bdrv_replace_child_abort(void *opaque)
2409{
2410 BdrvReplaceChildState *s = opaque;
2411 BlockDriverState *new_bs = s->child->bs;
2412
bdb73476 2413 GLOBAL_STATE_CODE();
0f0b1e29 2414 /* old_bs reference is transparently moved from @s to @s->child */
544acc7d 2415 bdrv_replace_child_noperm(s->child, s->old_bs);
0978623e
VSO
2416 bdrv_unref(new_bs);
2417}
2418
2419static TransactionActionDrv bdrv_replace_child_drv = {
2420 .commit = bdrv_replace_child_commit,
2421 .abort = bdrv_replace_child_abort,
2422 .clean = g_free,
2423};
2424
2425/*
4bf021db 2426 * bdrv_replace_child_tran
0978623e
VSO
2427 *
2428 * Note: real unref of old_bs is done only on commit.
4bf021db
VSO
2429 *
2430 * The function doesn't update permissions, caller is responsible for this.
0978623e 2431 */
0f0b1e29 2432static void bdrv_replace_child_tran(BdrvChild *child, BlockDriverState *new_bs,
4eba825a 2433 Transaction *tran)
0978623e
VSO
2434{
2435 BdrvReplaceChildState *s = g_new(BdrvReplaceChildState, 1);
2436 *s = (BdrvReplaceChildState) {
0f0b1e29
VSO
2437 .child = child,
2438 .old_bs = child->bs,
0978623e
VSO
2439 };
2440 tran_add(tran, &bdrv_replace_child_drv, s);
2441
2442 if (new_bs) {
2443 bdrv_ref(new_bs);
2444 }
544acc7d 2445 bdrv_replace_child_noperm(child, new_bs);
0f0b1e29 2446 /* old_bs reference is transparently moved from @child to @s */
0978623e
VSO
2447}
2448
33a610c3 2449/*
c20555e1
VSO
2450 * Refresh permissions in @bs subtree. The function is intended to be called
2451 * after some graph modification that was done without permission update.
33a610c3 2452 */
c20555e1
VSO
2453static int bdrv_node_refresh_perm(BlockDriverState *bs, BlockReopenQueue *q,
2454 Transaction *tran, Error **errp)
33a610c3
KW
2455{
2456 BlockDriver *drv = bs->drv;
2457 BdrvChild *c;
2458 int ret;
c20555e1 2459 uint64_t cumulative_perms, cumulative_shared_perms;
862fded9 2460 GLOBAL_STATE_CODE();
c20555e1
VSO
2461
2462 bdrv_get_cumulative_perm(bs, &cumulative_perms, &cumulative_shared_perms);
33a610c3
KW
2463
2464 /* Write permissions never work with read-only images */
2465 if ((cumulative_perms & (BLK_PERM_WRITE | BLK_PERM_WRITE_UNCHANGED)) &&
cc022140 2466 !bdrv_is_writable_after_reopen(bs, q))
33a610c3 2467 {
481e0eee
HR
2468 if (!bdrv_is_writable_after_reopen(bs, NULL)) {
2469 error_setg(errp, "Block node is read-only");
2470 } else {
c20555e1
VSO
2471 error_setg(errp, "Read-only block node '%s' cannot support "
2472 "read-write users", bdrv_get_node_name(bs));
481e0eee
HR
2473 }
2474
33a610c3
KW
2475 return -EPERM;
2476 }
2477
9c60a5d1
KW
2478 /*
2479 * Unaligned requests will automatically be aligned to bl.request_alignment
2480 * and without RESIZE we can't extend requests to write to space beyond the
2481 * end of the image, so it's required that the image size is aligned.
2482 */
2483 if ((cumulative_perms & (BLK_PERM_WRITE | BLK_PERM_WRITE_UNCHANGED)) &&
2484 !(cumulative_perms & BLK_PERM_RESIZE))
2485 {
2486 if ((bs->total_sectors * BDRV_SECTOR_SIZE) % bs->bl.request_alignment) {
2487 error_setg(errp, "Cannot get 'write' permission without 'resize': "
2488 "Image size is not a multiple of request "
2489 "alignment");
2490 return -EPERM;
2491 }
2492 }
2493
33a610c3
KW
2494 /* Check this node */
2495 if (!drv) {
2496 return 0;
2497 }
2498
b1d2bbeb 2499 ret = bdrv_drv_set_perm(bs, cumulative_perms, cumulative_shared_perms, tran,
2513ef59
VSO
2500 errp);
2501 if (ret < 0) {
2502 return ret;
33a610c3
KW
2503 }
2504
78e421c9 2505 /* Drivers that never have children can omit .bdrv_child_perm() */
33a610c3 2506 if (!drv->bdrv_child_perm) {
78e421c9 2507 assert(QLIST_EMPTY(&bs->children));
33a610c3
KW
2508 return 0;
2509 }
2510
2511 /* Check all children */
2512 QLIST_FOREACH(c, &bs->children, next) {
2513 uint64_t cur_perm, cur_shared;
9eab1544 2514
e5d8a406 2515 bdrv_child_perm(bs, c->bs, c, c->role, q,
ffd1a5a2
FZ
2516 cumulative_perms, cumulative_shared_perms,
2517 &cur_perm, &cur_shared);
ecb776bd 2518 bdrv_child_set_perm(c, cur_perm, cur_shared, tran);
bd57f8f7
VSO
2519 }
2520
2521 return 0;
2522}
3ef45e02 2523
fb0ff4d1
VSO
2524/*
2525 * @list is a product of bdrv_topological_dfs() (may be called several times) -
2526 * a topologically sorted subgraph.
2527 */
2528static int bdrv_do_refresh_perms(GSList *list, BlockReopenQueue *q,
2529 Transaction *tran, Error **errp)
bd57f8f7
VSO
2530{
2531 int ret;
b1d2bbeb 2532 BlockDriverState *bs;
862fded9 2533 GLOBAL_STATE_CODE();
bd57f8f7 2534
b1d2bbeb
VSO
2535 for ( ; list; list = list->next) {
2536 bs = list->data;
2537
9397c14f 2538 if (bdrv_parent_perms_conflict(bs, errp)) {
b1d2bbeb 2539 return -EINVAL;
bd57f8f7
VSO
2540 }
2541
c20555e1 2542 ret = bdrv_node_refresh_perm(bs, q, tran, errp);
33a610c3
KW
2543 if (ret < 0) {
2544 return ret;
2545 }
2546 }
2547
2548 return 0;
2549}
2550
fb0ff4d1
VSO
2551/*
2552 * @list is any list of nodes. List is completed by all subtrees and
2553 * topologically sorted. It's not a problem if some node occurs in the @list
2554 * several times.
2555 */
2556static int bdrv_list_refresh_perms(GSList *list, BlockReopenQueue *q,
2557 Transaction *tran, Error **errp)
2558{
2559 g_autoptr(GHashTable) found = g_hash_table_new(NULL, NULL);
2560 g_autoptr(GSList) refresh_list = NULL;
2561
2562 for ( ; list; list = list->next) {
2563 refresh_list = bdrv_topological_dfs(refresh_list, found, list->data);
2564 }
2565
2566 return bdrv_do_refresh_perms(refresh_list, q, tran, errp);
2567}
2568
c7a0f2be
KW
2569void bdrv_get_cumulative_perm(BlockDriverState *bs, uint64_t *perm,
2570 uint64_t *shared_perm)
33a610c3
KW
2571{
2572 BdrvChild *c;
2573 uint64_t cumulative_perms = 0;
2574 uint64_t cumulative_shared_perms = BLK_PERM_ALL;
2575
b4ad82aa
EGE
2576 GLOBAL_STATE_CODE();
2577
33a610c3
KW
2578 QLIST_FOREACH(c, &bs->parents, next_parent) {
2579 cumulative_perms |= c->perm;
2580 cumulative_shared_perms &= c->shared_perm;
2581 }
2582
2583 *perm = cumulative_perms;
2584 *shared_perm = cumulative_shared_perms;
2585}
2586
5176196c 2587char *bdrv_perm_names(uint64_t perm)
d083319f
KW
2588{
2589 struct perm_name {
2590 uint64_t perm;
2591 const char *name;
2592 } permissions[] = {
2593 { BLK_PERM_CONSISTENT_READ, "consistent read" },
2594 { BLK_PERM_WRITE, "write" },
2595 { BLK_PERM_WRITE_UNCHANGED, "write unchanged" },
2596 { BLK_PERM_RESIZE, "resize" },
d083319f
KW
2597 { 0, NULL }
2598 };
2599
e2a7423a 2600 GString *result = g_string_sized_new(30);
d083319f
KW
2601 struct perm_name *p;
2602
2603 for (p = permissions; p->name; p++) {
2604 if (perm & p->perm) {
e2a7423a
AG
2605 if (result->len > 0) {
2606 g_string_append(result, ", ");
2607 }
2608 g_string_append(result, p->name);
d083319f
KW
2609 }
2610 }
2611
e2a7423a 2612 return g_string_free(result, FALSE);
d083319f
KW
2613}
2614
33a610c3 2615
f1316edb
VSO
2616/* @tran is allowed to be NULL. In this case no rollback is possible */
2617static int bdrv_refresh_perms(BlockDriverState *bs, Transaction *tran,
2618 Error **errp)
bb87e4d1
VSO
2619{
2620 int ret;
f1316edb 2621 Transaction *local_tran = NULL;
b1d2bbeb 2622 g_autoptr(GSList) list = bdrv_topological_dfs(NULL, NULL, bs);
862fded9 2623 GLOBAL_STATE_CODE();
bb87e4d1 2624
f1316edb
VSO
2625 if (!tran) {
2626 tran = local_tran = tran_new();
2627 }
2628
fb0ff4d1 2629 ret = bdrv_do_refresh_perms(list, NULL, tran, errp);
f1316edb
VSO
2630
2631 if (local_tran) {
2632 tran_finalize(local_tran, ret);
2633 }
bb87e4d1 2634
b1d2bbeb 2635 return ret;
bb87e4d1
VSO
2636}
2637
33a610c3
KW
2638int bdrv_child_try_set_perm(BdrvChild *c, uint64_t perm, uint64_t shared,
2639 Error **errp)
2640{
1046779e 2641 Error *local_err = NULL;
83928dc4 2642 Transaction *tran = tran_new();
33a610c3
KW
2643 int ret;
2644
b4ad82aa
EGE
2645 GLOBAL_STATE_CODE();
2646
ecb776bd 2647 bdrv_child_set_perm(c, perm, shared, tran);
83928dc4 2648
f1316edb 2649 ret = bdrv_refresh_perms(c->bs, tran, &local_err);
83928dc4
VSO
2650
2651 tran_finalize(tran, ret);
2652
33a610c3 2653 if (ret < 0) {
071b474f
VSO
2654 if ((perm & ~c->perm) || (c->shared_perm & ~shared)) {
2655 /* tighten permissions */
1046779e
HR
2656 error_propagate(errp, local_err);
2657 } else {
2658 /*
2659 * Our caller may intend to only loosen restrictions and
2660 * does not expect this function to fail. Errors are not
2661 * fatal in such a case, so we can just hide them from our
2662 * caller.
2663 */
2664 error_free(local_err);
2665 ret = 0;
2666 }
33a610c3
KW
2667 }
2668
83928dc4 2669 return ret;
d5e6f437
KW
2670}
2671
c1087f12
HR
2672int bdrv_child_refresh_perms(BlockDriverState *bs, BdrvChild *c, Error **errp)
2673{
2674 uint64_t parent_perms, parent_shared;
2675 uint64_t perms, shared;
2676
b4ad82aa
EGE
2677 GLOBAL_STATE_CODE();
2678
c1087f12 2679 bdrv_get_cumulative_perm(bs, &parent_perms, &parent_shared);
e5d8a406 2680 bdrv_child_perm(bs, c->bs, c, c->role, NULL,
bf8e925e 2681 parent_perms, parent_shared, &perms, &shared);
c1087f12
HR
2682
2683 return bdrv_child_try_set_perm(c, perms, shared, errp);
2684}
2685
87278af1
HR
2686/*
2687 * Default implementation for .bdrv_child_perm() for block filters:
2688 * Forward CONSISTENT_READ, WRITE, WRITE_UNCHANGED, and RESIZE to the
2689 * filtered child.
2690 */
2691static void bdrv_filter_default_perms(BlockDriverState *bs, BdrvChild *c,
87278af1
HR
2692 BdrvChildRole role,
2693 BlockReopenQueue *reopen_queue,
2694 uint64_t perm, uint64_t shared,
2695 uint64_t *nperm, uint64_t *nshared)
6a1b9ee1 2696{
862fded9 2697 GLOBAL_STATE_CODE();
e444fa83
KW
2698 *nperm = perm & DEFAULT_PERM_PASSTHROUGH;
2699 *nshared = (shared & DEFAULT_PERM_PASSTHROUGH) | DEFAULT_PERM_UNCHANGED;
6a1b9ee1
KW
2700}
2701
70082db4 2702static void bdrv_default_perms_for_cow(BlockDriverState *bs, BdrvChild *c,
70082db4
HR
2703 BdrvChildRole role,
2704 BlockReopenQueue *reopen_queue,
2705 uint64_t perm, uint64_t shared,
2706 uint64_t *nperm, uint64_t *nshared)
2707{
e5d8a406 2708 assert(role & BDRV_CHILD_COW);
862fded9 2709 GLOBAL_STATE_CODE();
70082db4
HR
2710
2711 /*
2712 * We want consistent read from backing files if the parent needs it.
2713 * No other operations are performed on backing files.
2714 */
2715 perm &= BLK_PERM_CONSISTENT_READ;
2716
2717 /*
2718 * If the parent can deal with changing data, we're okay with a
2719 * writable and resizable backing file.
2720 * TODO Require !(perm & BLK_PERM_CONSISTENT_READ), too?
2721 */
2722 if (shared & BLK_PERM_WRITE) {
2723 shared = BLK_PERM_WRITE | BLK_PERM_RESIZE;
2724 } else {
2725 shared = 0;
2726 }
2727
64631f36 2728 shared |= BLK_PERM_CONSISTENT_READ | BLK_PERM_WRITE_UNCHANGED;
70082db4
HR
2729
2730 if (bs->open_flags & BDRV_O_INACTIVE) {
2731 shared |= BLK_PERM_WRITE | BLK_PERM_RESIZE;
2732 }
2733
2734 *nperm = perm;
2735 *nshared = shared;
2736}
2737
6f838a4b 2738static void bdrv_default_perms_for_storage(BlockDriverState *bs, BdrvChild *c,
6f838a4b
HR
2739 BdrvChildRole role,
2740 BlockReopenQueue *reopen_queue,
2741 uint64_t perm, uint64_t shared,
2742 uint64_t *nperm, uint64_t *nshared)
2743{
2744 int flags;
2745
862fded9 2746 GLOBAL_STATE_CODE();
e5d8a406 2747 assert(role & (BDRV_CHILD_METADATA | BDRV_CHILD_DATA));
6f838a4b
HR
2748
2749 flags = bdrv_reopen_get_flags(reopen_queue, bs);
2750
2751 /*
2752 * Apart from the modifications below, the same permissions are
2753 * forwarded and left alone as for filters
2754 */
e5d8a406 2755 bdrv_filter_default_perms(bs, c, role, reopen_queue,
6f838a4b
HR
2756 perm, shared, &perm, &shared);
2757
f889054f
HR
2758 if (role & BDRV_CHILD_METADATA) {
2759 /* Format drivers may touch metadata even if the guest doesn't write */
2760 if (bdrv_is_writable_after_reopen(bs, reopen_queue)) {
2761 perm |= BLK_PERM_WRITE | BLK_PERM_RESIZE;
2762 }
2763
2764 /*
2765 * bs->file always needs to be consistent because of the
2766 * metadata. We can never allow other users to resize or write
2767 * to it.
2768 */
2769 if (!(flags & BDRV_O_NO_IO)) {
2770 perm |= BLK_PERM_CONSISTENT_READ;
2771 }
2772 shared &= ~(BLK_PERM_WRITE | BLK_PERM_RESIZE);
6f838a4b
HR
2773 }
2774
f889054f
HR
2775 if (role & BDRV_CHILD_DATA) {
2776 /*
2777 * Technically, everything in this block is a subset of the
2778 * BDRV_CHILD_METADATA path taken above, and so this could
2779 * be an "else if" branch. However, that is not obvious, and
2780 * this function is not performance critical, therefore we let
2781 * this be an independent "if".
2782 */
2783
2784 /*
2785 * We cannot allow other users to resize the file because the
2786 * format driver might have some assumptions about the size
2787 * (e.g. because it is stored in metadata, or because the file
2788 * is split into fixed-size data files).
2789 */
2790 shared &= ~BLK_PERM_RESIZE;
2791
2792 /*
2793 * WRITE_UNCHANGED often cannot be performed as such on the
2794 * data file. For example, the qcow2 driver may still need to
2795 * write copied clusters on copy-on-read.
2796 */
2797 if (perm & BLK_PERM_WRITE_UNCHANGED) {
2798 perm |= BLK_PERM_WRITE;
2799 }
2800
2801 /*
2802 * If the data file is written to, the format driver may
2803 * expect to be able to resize it by writing beyond the EOF.
2804 */
2805 if (perm & BLK_PERM_WRITE) {
2806 perm |= BLK_PERM_RESIZE;
2807 }
6f838a4b 2808 }
6f838a4b
HR
2809
2810 if (bs->open_flags & BDRV_O_INACTIVE) {
2811 shared |= BLK_PERM_WRITE | BLK_PERM_RESIZE;
2812 }
2813
2814 *nperm = perm;
2815 *nshared = shared;
2816}
2817
2519f549 2818void bdrv_default_perms(BlockDriverState *bs, BdrvChild *c,
e5d8a406 2819 BdrvChildRole role, BlockReopenQueue *reopen_queue,
2519f549
HR
2820 uint64_t perm, uint64_t shared,
2821 uint64_t *nperm, uint64_t *nshared)
2822{
b4ad82aa 2823 GLOBAL_STATE_CODE();
2519f549
HR
2824 if (role & BDRV_CHILD_FILTERED) {
2825 assert(!(role & (BDRV_CHILD_DATA | BDRV_CHILD_METADATA |
2826 BDRV_CHILD_COW)));
e5d8a406 2827 bdrv_filter_default_perms(bs, c, role, reopen_queue,
2519f549
HR
2828 perm, shared, nperm, nshared);
2829 } else if (role & BDRV_CHILD_COW) {
2830 assert(!(role & (BDRV_CHILD_DATA | BDRV_CHILD_METADATA)));
e5d8a406 2831 bdrv_default_perms_for_cow(bs, c, role, reopen_queue,
2519f549
HR
2832 perm, shared, nperm, nshared);
2833 } else if (role & (BDRV_CHILD_METADATA | BDRV_CHILD_DATA)) {
e5d8a406 2834 bdrv_default_perms_for_storage(bs, c, role, reopen_queue,
2519f549
HR
2835 perm, shared, nperm, nshared);
2836 } else {
2837 g_assert_not_reached();
2838 }
2839}
2840
7b1d9c4d
HR
2841uint64_t bdrv_qapi_perm_to_blk_perm(BlockPermission qapi_perm)
2842{
2843 static const uint64_t permissions[] = {
2844 [BLOCK_PERMISSION_CONSISTENT_READ] = BLK_PERM_CONSISTENT_READ,
2845 [BLOCK_PERMISSION_WRITE] = BLK_PERM_WRITE,
2846 [BLOCK_PERMISSION_WRITE_UNCHANGED] = BLK_PERM_WRITE_UNCHANGED,
2847 [BLOCK_PERMISSION_RESIZE] = BLK_PERM_RESIZE,
7b1d9c4d
HR
2848 };
2849
2850 QEMU_BUILD_BUG_ON(ARRAY_SIZE(permissions) != BLOCK_PERMISSION__MAX);
2851 QEMU_BUILD_BUG_ON(1UL << ARRAY_SIZE(permissions) != BLK_PERM_ALL + 1);
2852
2853 assert(qapi_perm < BLOCK_PERMISSION__MAX);
2854
2855 return permissions[qapi_perm];
2856}
2857
544acc7d 2858static void bdrv_replace_child_noperm(BdrvChild *child,
4eba825a 2859 BlockDriverState *new_bs)
e9740bc6
KW
2860{
2861 BlockDriverState *old_bs = child->bs;
debc2927
HR
2862 int new_bs_quiesce_counter;
2863 int drain_saldo;
e9740bc6 2864
2cad1ebe 2865 assert(!child->frozen);
bfb8aa6d 2866 assert(old_bs != new_bs);
f0c28327 2867 GLOBAL_STATE_CODE();
2cad1ebe 2868
bb2614e9
FZ
2869 if (old_bs && new_bs) {
2870 assert(bdrv_get_aio_context(old_bs) == bdrv_get_aio_context(new_bs));
2871 }
debc2927
HR
2872
2873 new_bs_quiesce_counter = (new_bs ? new_bs->quiesce_counter : 0);
2874 drain_saldo = new_bs_quiesce_counter - child->parent_quiesce_counter;
2875
2876 /*
2877 * If the new child node is drained but the old one was not, flush
2878 * all outstanding requests to the old child node.
2879 */
bd86fb99 2880 while (drain_saldo > 0 && child->klass->drained_begin) {
debc2927
HR
2881 bdrv_parent_drained_begin_single(child, true);
2882 drain_saldo--;
2883 }
2884
e9740bc6 2885 if (old_bs) {
d736f119
KW
2886 /* Detach first so that the recursive drain sections coming from @child
2887 * are already gone and we only end the drain sections that came from
2888 * elsewhere. */
bd86fb99
HR
2889 if (child->klass->detach) {
2890 child->klass->detach(child);
d736f119 2891 }
696bf4c7 2892 assert_bdrv_graph_writable(old_bs);
e9740bc6
KW
2893 QLIST_REMOVE(child, next_parent);
2894 }
36fe1331
KW
2895
2896 child->bs = new_bs;
2897
e9740bc6 2898 if (new_bs) {
696bf4c7 2899 assert_bdrv_graph_writable(new_bs);
e9740bc6 2900 QLIST_INSERT_HEAD(&new_bs->parents, child, next_parent);
debc2927
HR
2901
2902 /*
2903 * Detaching the old node may have led to the new node's
2904 * quiesce_counter having been decreased. Not a problem, we
2905 * just need to recognize this here and then invoke
2906 * drained_end appropriately more often.
2907 */
2908 assert(new_bs->quiesce_counter <= new_bs_quiesce_counter);
2909 drain_saldo += new_bs->quiesce_counter - new_bs_quiesce_counter;
33a610c3 2910
d736f119
KW
2911 /* Attach only after starting new drained sections, so that recursive
2912 * drain sections coming from @child don't get an extra .drained_begin
2913 * callback. */
bd86fb99
HR
2914 if (child->klass->attach) {
2915 child->klass->attach(child);
8ee03995
KW
2916 }
2917 }
debc2927
HR
2918
2919 /*
2920 * If the old child node was drained but the new one is not, allow
2921 * requests to come in only after the new node has been attached.
2922 */
bd86fb99 2923 while (drain_saldo < 0 && child->klass->drained_end) {
debc2927
HR
2924 bdrv_parent_drained_end_single(child);
2925 drain_saldo++;
2926 }
8ee03995 2927}
33a610c3 2928
04c9c3a5
HR
2929/**
2930 * Free the given @child.
2931 *
2932 * The child must be empty (i.e. `child->bs == NULL`) and it must be
2933 * unused (i.e. not in a children list).
2934 */
2935static void bdrv_child_free(BdrvChild *child)
df581792 2936{
548a74c0 2937 assert(!child->bs);
bdb73476 2938 GLOBAL_STATE_CODE();
a225369b 2939 assert(!child->next.le_prev); /* not in children list */
04c9c3a5
HR
2940
2941 g_free(child->name);
2942 g_free(child);
548a74c0 2943}
d5e6f437 2944
548a74c0 2945typedef struct BdrvAttachChildCommonState {
5bb04747 2946 BdrvChild *child;
548a74c0
VSO
2947 AioContext *old_parent_ctx;
2948 AioContext *old_child_ctx;
2949} BdrvAttachChildCommonState;
2950
2951static void bdrv_attach_child_common_abort(void *opaque)
2952{
2953 BdrvAttachChildCommonState *s = opaque;
5bb04747 2954 BlockDriverState *bs = s->child->bs;
548a74c0 2955
f0c28327 2956 GLOBAL_STATE_CODE();
5bb04747 2957 bdrv_replace_child_noperm(s->child, NULL);
548a74c0
VSO
2958
2959 if (bdrv_get_aio_context(bs) != s->old_child_ctx) {
142e6907 2960 bdrv_try_change_aio_context(bs, s->old_child_ctx, NULL, &error_abort);
548a74c0
VSO
2961 }
2962
5bb04747 2963 if (bdrv_child_get_parent_aio_context(s->child) != s->old_parent_ctx) {
f8be48ad
EGE
2964 Transaction *tran;
2965 GHashTable *visited;
2966 bool ret;
548a74c0 2967
f8be48ad 2968 tran = tran_new();
548a74c0 2969
f8be48ad
EGE
2970 /* No need to visit `child`, because it has been detached already */
2971 visited = g_hash_table_new(NULL, NULL);
2972 ret = s->child->klass->change_aio_ctx(s->child, s->old_parent_ctx,
2973 visited, tran, &error_abort);
2974 g_hash_table_destroy(visited);
2975
2976 /* transaction is supposed to always succeed */
2977 assert(ret == true);
2978 tran_commit(tran);
d5e6f437
KW
2979 }
2980
548a74c0 2981 bdrv_unref(bs);
5bb04747 2982 bdrv_child_free(s->child);
548a74c0
VSO
2983}
2984
2985static TransactionActionDrv bdrv_attach_child_common_drv = {
2986 .abort = bdrv_attach_child_common_abort,
2987 .clean = g_free,
2988};
2989
2990/*
2991 * Common part of attaching bdrv child to bs or to blk or to job
f8d2ad78 2992 *
7ec390d5 2993 * Function doesn't update permissions, caller is responsible for this.
5bb04747
VSO
2994 *
2995 * Returns new created child.
548a74c0 2996 */
5bb04747
VSO
2997static BdrvChild *bdrv_attach_child_common(BlockDriverState *child_bs,
2998 const char *child_name,
2999 const BdrvChildClass *child_class,
3000 BdrvChildRole child_role,
3001 uint64_t perm, uint64_t shared_perm,
3002 void *opaque,
3003 Transaction *tran, Error **errp)
548a74c0
VSO
3004{
3005 BdrvChild *new_child;
3006 AioContext *parent_ctx;
3007 AioContext *child_ctx = bdrv_get_aio_context(child_bs);
3008
da261b69 3009 assert(child_class->get_parent_desc);
bdb73476 3010 GLOBAL_STATE_CODE();
548a74c0
VSO
3011
3012 new_child = g_new(BdrvChild, 1);
3013 *new_child = (BdrvChild) {
d5e6f437
KW
3014 .bs = NULL,
3015 .name = g_strdup(child_name),
bd86fb99 3016 .klass = child_class,
258b7765 3017 .role = child_role,
d5e6f437
KW
3018 .perm = perm,
3019 .shared_perm = shared_perm,
3020 .opaque = opaque,
df581792
KW
3021 };
3022
548a74c0
VSO
3023 /*
3024 * If the AioContexts don't match, first try to move the subtree of
132ada80 3025 * child_bs into the AioContext of the new parent. If this doesn't work,
548a74c0
VSO
3026 * try moving the parent into the AioContext of child_bs instead.
3027 */
3028 parent_ctx = bdrv_child_get_parent_aio_context(new_child);
3029 if (child_ctx != parent_ctx) {
3030 Error *local_err = NULL;
142e6907
EGE
3031 int ret = bdrv_try_change_aio_context(child_bs, parent_ctx, NULL,
3032 &local_err);
548a74c0 3033
f8be48ad
EGE
3034 if (ret < 0 && child_class->change_aio_ctx) {
3035 Transaction *tran = tran_new();
3036 GHashTable *visited = g_hash_table_new(NULL, NULL);
3037 bool ret_child;
3038
3039 g_hash_table_add(visited, new_child);
3040 ret_child = child_class->change_aio_ctx(new_child, child_ctx,
3041 visited, tran, NULL);
3042 if (ret_child == true) {
132ada80
KW
3043 error_free(local_err);
3044 ret = 0;
132ada80 3045 }
f8be48ad
EGE
3046 tran_finalize(tran, ret_child == true ? 0 : -1);
3047 g_hash_table_destroy(visited);
132ada80 3048 }
548a74c0 3049
132ada80
KW
3050 if (ret < 0) {
3051 error_propagate(errp, local_err);
04c9c3a5 3052 bdrv_child_free(new_child);
5bb04747 3053 return NULL;
132ada80
KW
3054 }
3055 }
3056
548a74c0 3057 bdrv_ref(child_bs);
544acc7d 3058 bdrv_replace_child_noperm(new_child, child_bs);
b4b059f6 3059
548a74c0
VSO
3060 BdrvAttachChildCommonState *s = g_new(BdrvAttachChildCommonState, 1);
3061 *s = (BdrvAttachChildCommonState) {
5bb04747 3062 .child = new_child,
548a74c0
VSO
3063 .old_parent_ctx = parent_ctx,
3064 .old_child_ctx = child_ctx,
3065 };
3066 tran_add(tran, &bdrv_attach_child_common_drv, s);
3067
5bb04747 3068 return new_child;
548a74c0
VSO
3069}
3070
f8d2ad78 3071/*
7ec390d5 3072 * Function doesn't update permissions, caller is responsible for this.
f8d2ad78 3073 */
5bb04747
VSO
3074static BdrvChild *bdrv_attach_child_noperm(BlockDriverState *parent_bs,
3075 BlockDriverState *child_bs,
3076 const char *child_name,
3077 const BdrvChildClass *child_class,
3078 BdrvChildRole child_role,
3079 Transaction *tran,
3080 Error **errp)
aa5a04c7 3081{
aa5a04c7
VSO
3082 uint64_t perm, shared_perm;
3083
3084 assert(parent_bs->drv);
bdb73476 3085 GLOBAL_STATE_CODE();
aa5a04c7 3086
bfb8aa6d
KW
3087 if (bdrv_recurse_has_child(child_bs, parent_bs)) {
3088 error_setg(errp, "Making '%s' a %s child of '%s' would create a cycle",
3089 child_bs->node_name, child_name, parent_bs->node_name);
5bb04747 3090 return NULL;
bfb8aa6d
KW
3091 }
3092
aa5a04c7
VSO
3093 bdrv_get_cumulative_perm(parent_bs, &perm, &shared_perm);
3094 bdrv_child_perm(parent_bs, child_bs, NULL, child_role, NULL,
3095 perm, shared_perm, &perm, &shared_perm);
3096
5bb04747
VSO
3097 return bdrv_attach_child_common(child_bs, child_name, child_class,
3098 child_role, perm, shared_perm, parent_bs,
3099 tran, errp);
aa5a04c7
VSO
3100}
3101
548a74c0
VSO
3102/*
3103 * This function steals the reference to child_bs from the caller.
3104 * That reference is later dropped by bdrv_root_unref_child().
3105 *
3106 * On failure NULL is returned, errp is set and the reference to
3107 * child_bs is also dropped.
3108 *
3109 * The caller must hold the AioContext lock @child_bs, but not that of @ctx
3110 * (unless @child_bs is already in @ctx).
3111 */
3112BdrvChild *bdrv_root_attach_child(BlockDriverState *child_bs,
3113 const char *child_name,
3114 const BdrvChildClass *child_class,
3115 BdrvChildRole child_role,
3116 uint64_t perm, uint64_t shared_perm,
3117 void *opaque, Error **errp)
3118{
3119 int ret;
5bb04747 3120 BdrvChild *child;
548a74c0
VSO
3121 Transaction *tran = tran_new();
3122
b4ad82aa
EGE
3123 GLOBAL_STATE_CODE();
3124
5bb04747 3125 child = bdrv_attach_child_common(child_bs, child_name, child_class,
548a74c0 3126 child_role, perm, shared_perm, opaque,
5bb04747
VSO
3127 tran, errp);
3128 if (!child) {
3129 ret = -EINVAL;
e878bb12 3130 goto out;
548a74c0
VSO
3131 }
3132
f1316edb 3133 ret = bdrv_refresh_perms(child_bs, tran, errp);
548a74c0 3134
e878bb12
KW
3135out:
3136 tran_finalize(tran, ret);
f8d2ad78 3137
548a74c0 3138 bdrv_unref(child_bs);
5bb04747
VSO
3139
3140 return ret < 0 ? NULL : child;
df581792
KW
3141}
3142
b441dc71
AG
3143/*
3144 * This function transfers the reference to child_bs from the caller
3145 * to parent_bs. That reference is later dropped by parent_bs on
3146 * bdrv_close() or if someone calls bdrv_unref_child().
3147 *
3148 * On failure NULL is returned, errp is set and the reference to
3149 * child_bs is also dropped.
132ada80
KW
3150 *
3151 * If @parent_bs and @child_bs are in different AioContexts, the caller must
3152 * hold the AioContext lock for @child_bs, but not for @parent_bs.
b441dc71 3153 */
98292c61
WC
3154BdrvChild *bdrv_attach_child(BlockDriverState *parent_bs,
3155 BlockDriverState *child_bs,
3156 const char *child_name,
bd86fb99 3157 const BdrvChildClass *child_class,
258b7765 3158 BdrvChildRole child_role,
8b2ff529 3159 Error **errp)
f21d96d0 3160{
aa5a04c7 3161 int ret;
5bb04747 3162 BdrvChild *child;
aa5a04c7 3163 Transaction *tran = tran_new();
f68c598b 3164
f791bf7f
EGE
3165 GLOBAL_STATE_CODE();
3166
5bb04747
VSO
3167 child = bdrv_attach_child_noperm(parent_bs, child_bs, child_name,
3168 child_class, child_role, tran, errp);
3169 if (!child) {
3170 ret = -EINVAL;
aa5a04c7
VSO
3171 goto out;
3172 }
d5e6f437 3173
f1316edb 3174 ret = bdrv_refresh_perms(parent_bs, tran, errp);
aa5a04c7
VSO
3175 if (ret < 0) {
3176 goto out;
d5e6f437
KW
3177 }
3178
aa5a04c7
VSO
3179out:
3180 tran_finalize(tran, ret);
3181
3182 bdrv_unref(child_bs);
3183
5bb04747 3184 return ret < 0 ? NULL : child;
f21d96d0
KW
3185}
3186
7b99a266 3187/* Callers must ensure that child->frozen is false. */
f21d96d0 3188void bdrv_root_unref_child(BdrvChild *child)
33a60407 3189{
00eb93b5 3190 BlockDriverState *child_bs = child->bs;
779020cb 3191
f791bf7f 3192 GLOBAL_STATE_CODE();
00eb93b5
VSO
3193 bdrv_replace_child_noperm(child, NULL);
3194 bdrv_child_free(child);
3195
3196 if (child_bs) {
3197 /*
3198 * Update permissions for old node. We're just taking a parent away, so
3199 * we're loosening restrictions. Errors of permission update are not
3200 * fatal in this case, ignore them.
3201 */
f1316edb 3202 bdrv_refresh_perms(child_bs, NULL, NULL);
00eb93b5
VSO
3203
3204 /*
3205 * When the parent requiring a non-default AioContext is removed, the
3206 * node moves back to the main AioContext
3207 */
3208 bdrv_try_change_aio_context(child_bs, qemu_get_aio_context(), NULL,
3209 NULL);
3210 }
f791bf7f 3211
f21d96d0
KW
3212 bdrv_unref(child_bs);
3213}
3214
332b3a17
VSO
3215typedef struct BdrvSetInheritsFrom {
3216 BlockDriverState *bs;
3217 BlockDriverState *old_inherits_from;
3218} BdrvSetInheritsFrom;
3219
3220static void bdrv_set_inherits_from_abort(void *opaque)
3221{
3222 BdrvSetInheritsFrom *s = opaque;
3223
3224 s->bs->inherits_from = s->old_inherits_from;
3225}
3226
3227static TransactionActionDrv bdrv_set_inherits_from_drv = {
3228 .abort = bdrv_set_inherits_from_abort,
3229 .clean = g_free,
3230};
3231
3232/* @tran is allowed to be NULL. In this case no rollback is possible */
3233static void bdrv_set_inherits_from(BlockDriverState *bs,
3234 BlockDriverState *new_inherits_from,
3235 Transaction *tran)
3236{
3237 if (tran) {
3238 BdrvSetInheritsFrom *s = g_new(BdrvSetInheritsFrom, 1);
3239
3240 *s = (BdrvSetInheritsFrom) {
3241 .bs = bs,
3242 .old_inherits_from = bs->inherits_from,
3243 };
3244
3245 tran_add(tran, &bdrv_set_inherits_from_drv, s);
3246 }
3247
3248 bs->inherits_from = new_inherits_from;
3249}
3250
3cf746b3
HR
3251/**
3252 * Clear all inherits_from pointers from children and grandchildren of
3253 * @root that point to @root, where necessary.
332b3a17 3254 * @tran is allowed to be NULL. In this case no rollback is possible
3cf746b3 3255 */
332b3a17
VSO
3256static void bdrv_unset_inherits_from(BlockDriverState *root, BdrvChild *child,
3257 Transaction *tran)
f21d96d0 3258{
3cf746b3 3259 BdrvChild *c;
4e4bf5c4 3260
3cf746b3
HR
3261 if (child->bs->inherits_from == root) {
3262 /*
3263 * Remove inherits_from only when the last reference between root and
3264 * child->bs goes away.
3265 */
3266 QLIST_FOREACH(c, &root->children, next) {
4e4bf5c4
KW
3267 if (c != child && c->bs == child->bs) {
3268 break;
3269 }
3270 }
3271 if (c == NULL) {
332b3a17 3272 bdrv_set_inherits_from(child->bs, NULL, tran);
4e4bf5c4 3273 }
33a60407
KW
3274 }
3275
3cf746b3 3276 QLIST_FOREACH(c, &child->bs->children, next) {
332b3a17 3277 bdrv_unset_inherits_from(root, c, tran);
3cf746b3
HR
3278 }
3279}
3280
7b99a266 3281/* Callers must ensure that child->frozen is false. */
3cf746b3
HR
3282void bdrv_unref_child(BlockDriverState *parent, BdrvChild *child)
3283{
f791bf7f 3284 GLOBAL_STATE_CODE();
3cf746b3
HR
3285 if (child == NULL) {
3286 return;
3287 }
3288
332b3a17 3289 bdrv_unset_inherits_from(parent, child, NULL);
f21d96d0 3290 bdrv_root_unref_child(child);
33a60407
KW
3291}
3292
5c8cab48
KW
3293
3294static void bdrv_parent_cb_change_media(BlockDriverState *bs, bool load)
3295{
3296 BdrvChild *c;
f0c28327 3297 GLOBAL_STATE_CODE();
5c8cab48 3298 QLIST_FOREACH(c, &bs->parents, next_parent) {
bd86fb99
HR
3299 if (c->klass->change_media) {
3300 c->klass->change_media(c, load);
5c8cab48
KW
3301 }
3302 }
3303}
3304
0065c455
AG
3305/* Return true if you can reach parent going through child->inherits_from
3306 * recursively. If parent or child are NULL, return false */
3307static bool bdrv_inherits_from_recursive(BlockDriverState *child,
3308 BlockDriverState *parent)
3309{
3310 while (child && child != parent) {
3311 child = child->inherits_from;
3312 }
3313
3314 return child != NULL;
3315}
3316
25191e5f
HR
3317/*
3318 * Return the BdrvChildRole for @bs's backing child. bs->backing is
3319 * mostly used for COW backing children (role = COW), but also for
3320 * filtered children (role = FILTERED | PRIMARY).
3321 */
3322static BdrvChildRole bdrv_backing_role(BlockDriverState *bs)
3323{
3324 if (bs->drv && bs->drv->is_filter) {
3325 return BDRV_CHILD_FILTERED | BDRV_CHILD_PRIMARY;
3326 } else {
3327 return BDRV_CHILD_COW;
3328 }
3329}
3330
5db15a57 3331/*
e9238278
VSO
3332 * Sets the bs->backing or bs->file link of a BDS. A new reference is created;
3333 * callers which don't need their own reference any more must call bdrv_unref().
7ec390d5
VSO
3334 *
3335 * Function doesn't update permissions, caller is responsible for this.
5db15a57 3336 */
e9238278
VSO
3337static int bdrv_set_file_or_backing_noperm(BlockDriverState *parent_bs,
3338 BlockDriverState *child_bs,
3339 bool is_backing,
3340 Transaction *tran, Error **errp)
8d24cce1 3341{
e9238278
VSO
3342 bool update_inherits_from =
3343 bdrv_inherits_from_recursive(child_bs, parent_bs);
3344 BdrvChild *child = is_backing ? parent_bs->backing : parent_bs->file;
3345 BdrvChildRole role;
0065c455 3346
bdb73476
EGE
3347 GLOBAL_STATE_CODE();
3348
e9238278
VSO
3349 if (!parent_bs->drv) {
3350 /*
3351 * Node without drv is an object without a class :/. TODO: finally fix
3352 * qcow2 driver to never clear bs->drv and implement format corruption
3353 * handling in other way.
3354 */
3355 error_setg(errp, "Node corrupted");
3356 return -EINVAL;
3357 }
3358
3359 if (child && child->frozen) {
3360 error_setg(errp, "Cannot change frozen '%s' link from '%s' to '%s'",
3361 child->name, parent_bs->node_name, child->bs->node_name);
a1e708fc 3362 return -EPERM;
2cad1ebe
AG
3363 }
3364
25f78d9e
VSO
3365 if (is_backing && !parent_bs->drv->is_filter &&
3366 !parent_bs->drv->supports_backing)
3367 {
3368 error_setg(errp, "Driver '%s' of node '%s' does not support backing "
3369 "files", parent_bs->drv->format_name, parent_bs->node_name);
3370 return -EINVAL;
3371 }
3372
e9238278
VSO
3373 if (parent_bs->drv->is_filter) {
3374 role = BDRV_CHILD_FILTERED | BDRV_CHILD_PRIMARY;
3375 } else if (is_backing) {
3376 role = BDRV_CHILD_COW;
3377 } else {
3378 /*
3379 * We only can use same role as it is in existing child. We don't have
3380 * infrastructure to determine role of file child in generic way
3381 */
3382 if (!child) {
3383 error_setg(errp, "Cannot set file child to format node without "
3384 "file child");
3385 return -EINVAL;
3386 }
3387 role = child->role;
826b6ca0
FZ
3388 }
3389
e9238278
VSO
3390 if (child) {
3391 bdrv_unset_inherits_from(parent_bs, child, tran);
57f08941 3392 bdrv_remove_child(child, tran);
e9238278
VSO
3393 }
3394
3395 if (!child_bs) {
8d24cce1
FZ
3396 goto out;
3397 }
12fa4af6 3398
5bb04747
VSO
3399 child = bdrv_attach_child_noperm(parent_bs, child_bs,
3400 is_backing ? "backing" : "file",
3401 &child_of_bds, role,
3402 tran, errp);
3403 if (!child) {
3404 return -EINVAL;
a1e708fc
VSO
3405 }
3406
160333e1
VSO
3407
3408 /*
e9238278 3409 * If inherits_from pointed recursively to bs then let's update it to
160333e1
VSO
3410 * point directly to bs (else it will become NULL).
3411 */
a1e708fc 3412 if (update_inherits_from) {
e9238278 3413 bdrv_set_inherits_from(child_bs, parent_bs, tran);
0065c455 3414 }
826b6ca0 3415
8d24cce1 3416out:
e9238278 3417 bdrv_refresh_limits(parent_bs, tran, NULL);
160333e1
VSO
3418
3419 return 0;
3420}
3421
e9238278
VSO
3422static int bdrv_set_backing_noperm(BlockDriverState *bs,
3423 BlockDriverState *backing_hd,
3424 Transaction *tran, Error **errp)
3425{
bdb73476 3426 GLOBAL_STATE_CODE();
e9238278
VSO
3427 return bdrv_set_file_or_backing_noperm(bs, backing_hd, true, tran, errp);
3428}
3429
160333e1
VSO
3430int bdrv_set_backing_hd(BlockDriverState *bs, BlockDriverState *backing_hd,
3431 Error **errp)
3432{
3433 int ret;
3434 Transaction *tran = tran_new();
3435
f791bf7f 3436 GLOBAL_STATE_CODE();
c0829cb1
VSO
3437 bdrv_drained_begin(bs);
3438
160333e1
VSO
3439 ret = bdrv_set_backing_noperm(bs, backing_hd, tran, errp);
3440 if (ret < 0) {
3441 goto out;
3442 }
3443
f1316edb 3444 ret = bdrv_refresh_perms(bs, tran, errp);
160333e1
VSO
3445out:
3446 tran_finalize(tran, ret);
a1e708fc 3447
c0829cb1
VSO
3448 bdrv_drained_end(bs);
3449
a1e708fc 3450 return ret;
8d24cce1
FZ
3451}
3452
31ca6d07
KW
3453/*
3454 * Opens the backing file for a BlockDriverState if not yet open
3455 *
d9b7b057
KW
3456 * bdref_key specifies the key for the image's BlockdevRef in the options QDict.
3457 * That QDict has to be flattened; therefore, if the BlockdevRef is a QDict
3458 * itself, all options starting with "${bdref_key}." are considered part of the
3459 * BlockdevRef.
3460 *
3461 * TODO Can this be unified with bdrv_open_image()?
31ca6d07 3462 */
d9b7b057
KW
3463int bdrv_open_backing_file(BlockDriverState *bs, QDict *parent_options,
3464 const char *bdref_key, Error **errp)
9156df12 3465{
6b6833c1 3466 char *backing_filename = NULL;
d9b7b057
KW
3467 char *bdref_key_dot;
3468 const char *reference = NULL;
317fc44e 3469 int ret = 0;
998c2019 3470 bool implicit_backing = false;
8d24cce1 3471 BlockDriverState *backing_hd;
d9b7b057
KW
3472 QDict *options;
3473 QDict *tmp_parent_options = NULL;
34b5d2c6 3474 Error *local_err = NULL;
9156df12 3475
f791bf7f
EGE
3476 GLOBAL_STATE_CODE();
3477
760e0063 3478 if (bs->backing != NULL) {
1ba4b6a5 3479 goto free_exit;
9156df12
PB
3480 }
3481
31ca6d07 3482 /* NULL means an empty set of options */
d9b7b057
KW
3483 if (parent_options == NULL) {
3484 tmp_parent_options = qdict_new();
3485 parent_options = tmp_parent_options;
31ca6d07
KW
3486 }
3487
9156df12 3488 bs->open_flags &= ~BDRV_O_NO_BACKING;
d9b7b057
KW
3489
3490 bdref_key_dot = g_strdup_printf("%s.", bdref_key);
3491 qdict_extract_subqdict(parent_options, &options, bdref_key_dot);
3492 g_free(bdref_key_dot);
3493
129c7d1c
MA
3494 /*
3495 * Caution: while qdict_get_try_str() is fine, getting non-string
3496 * types would require more care. When @parent_options come from
3497 * -blockdev or blockdev_add, its members are typed according to
3498 * the QAPI schema, but when they come from -drive, they're all
3499 * QString.
3500 */
d9b7b057
KW
3501 reference = qdict_get_try_str(parent_options, bdref_key);
3502 if (reference || qdict_haskey(options, "file.filename")) {
6b6833c1 3503 /* keep backing_filename NULL */
1cb6f506 3504 } else if (bs->backing_file[0] == '\0' && qdict_size(options) == 0) {
cb3e7f08 3505 qobject_unref(options);
1ba4b6a5 3506 goto free_exit;
dbecebdd 3507 } else {
998c2019
HR
3508 if (qdict_size(options) == 0) {
3509 /* If the user specifies options that do not modify the
3510 * backing file's behavior, we might still consider it the
3511 * implicit backing file. But it's easier this way, and
3512 * just specifying some of the backing BDS's options is
3513 * only possible with -drive anyway (otherwise the QAPI
3514 * schema forces the user to specify everything). */
3515 implicit_backing = !strcmp(bs->auto_backing_file, bs->backing_file);
3516 }
3517
6b6833c1 3518 backing_filename = bdrv_get_full_backing_filename(bs, &local_err);
9f07429e
HR
3519 if (local_err) {
3520 ret = -EINVAL;
3521 error_propagate(errp, local_err);
cb3e7f08 3522 qobject_unref(options);
9f07429e
HR
3523 goto free_exit;
3524 }
9156df12
PB
3525 }
3526
8ee79e70
KW
3527 if (!bs->drv || !bs->drv->supports_backing) {
3528 ret = -EINVAL;
3529 error_setg(errp, "Driver doesn't support backing files");
cb3e7f08 3530 qobject_unref(options);
8ee79e70
KW
3531 goto free_exit;
3532 }
3533
6bff597b
PK
3534 if (!reference &&
3535 bs->backing_format[0] != '\0' && !qdict_haskey(options, "driver")) {
46f5ac20 3536 qdict_put_str(options, "driver", bs->backing_format);
9156df12
PB
3537 }
3538
6b6833c1 3539 backing_hd = bdrv_open_inherit(backing_filename, reference, options, 0, bs,
25191e5f 3540 &child_of_bds, bdrv_backing_role(bs), errp);
5b363937 3541 if (!backing_hd) {
9156df12 3542 bs->open_flags |= BDRV_O_NO_BACKING;
e43bfd9c 3543 error_prepend(errp, "Could not open backing file: ");
5b363937 3544 ret = -EINVAL;
1ba4b6a5 3545 goto free_exit;
9156df12 3546 }
df581792 3547
998c2019
HR
3548 if (implicit_backing) {
3549 bdrv_refresh_filename(backing_hd);
3550 pstrcpy(bs->auto_backing_file, sizeof(bs->auto_backing_file),
3551 backing_hd->filename);
3552 }
3553
5db15a57
KW
3554 /* Hook up the backing file link; drop our reference, bs owns the
3555 * backing_hd reference now */
dc9c10a1 3556 ret = bdrv_set_backing_hd(bs, backing_hd, errp);
5db15a57 3557 bdrv_unref(backing_hd);
dc9c10a1 3558 if (ret < 0) {
12fa4af6
KW
3559 goto free_exit;
3560 }
d80ac658 3561
d9b7b057
KW
3562 qdict_del(parent_options, bdref_key);
3563
1ba4b6a5
BC
3564free_exit:
3565 g_free(backing_filename);
cb3e7f08 3566 qobject_unref(tmp_parent_options);
1ba4b6a5 3567 return ret;
9156df12
PB
3568}
3569
2d6b86af
KW
3570static BlockDriverState *
3571bdrv_open_child_bs(const char *filename, QDict *options, const char *bdref_key,
bd86fb99 3572 BlockDriverState *parent, const BdrvChildClass *child_class,
272c02ea 3573 BdrvChildRole child_role, bool allow_none, Error **errp)
da557aac 3574{
2d6b86af 3575 BlockDriverState *bs = NULL;
da557aac 3576 QDict *image_options;
da557aac
HR
3577 char *bdref_key_dot;
3578 const char *reference;
3579
bd86fb99 3580 assert(child_class != NULL);
f67503e5 3581
da557aac
HR
3582 bdref_key_dot = g_strdup_printf("%s.", bdref_key);
3583 qdict_extract_subqdict(options, &image_options, bdref_key_dot);
3584 g_free(bdref_key_dot);
3585
129c7d1c
MA
3586 /*
3587 * Caution: while qdict_get_try_str() is fine, getting non-string
3588 * types would require more care. When @options come from
3589 * -blockdev or blockdev_add, its members are typed according to
3590 * the QAPI schema, but when they come from -drive, they're all
3591 * QString.
3592 */
da557aac
HR
3593 reference = qdict_get_try_str(options, bdref_key);
3594 if (!filename && !reference && !qdict_size(image_options)) {
b4b059f6 3595 if (!allow_none) {
da557aac
HR
3596 error_setg(errp, "A block device must be specified for \"%s\"",
3597 bdref_key);
da557aac 3598 }
cb3e7f08 3599 qobject_unref(image_options);
da557aac
HR
3600 goto done;
3601 }
3602
5b363937 3603 bs = bdrv_open_inherit(filename, reference, image_options, 0,
272c02ea 3604 parent, child_class, child_role, errp);
5b363937 3605 if (!bs) {
df581792
KW
3606 goto done;
3607 }
3608
da557aac
HR
3609done:
3610 qdict_del(options, bdref_key);
2d6b86af
KW
3611 return bs;
3612}
3613
3614/*
3615 * Opens a disk image whose options are given as BlockdevRef in another block
3616 * device's options.
3617 *
3618 * If allow_none is true, no image will be opened if filename is false and no
3619 * BlockdevRef is given. NULL will be returned, but errp remains unset.
3620 *
3621 * bdrev_key specifies the key for the image's BlockdevRef in the options QDict.
3622 * That QDict has to be flattened; therefore, if the BlockdevRef is a QDict
3623 * itself, all options starting with "${bdref_key}." are considered part of the
3624 * BlockdevRef.
3625 *
3626 * The BlockdevRef will be removed from the options QDict.
3627 */
3628BdrvChild *bdrv_open_child(const char *filename,
3629 QDict *options, const char *bdref_key,
3630 BlockDriverState *parent,
bd86fb99 3631 const BdrvChildClass *child_class,
258b7765 3632 BdrvChildRole child_role,
2d6b86af
KW
3633 bool allow_none, Error **errp)
3634{
3635 BlockDriverState *bs;
3636
f791bf7f
EGE
3637 GLOBAL_STATE_CODE();
3638
bd86fb99 3639 bs = bdrv_open_child_bs(filename, options, bdref_key, parent, child_class,
272c02ea 3640 child_role, allow_none, errp);
2d6b86af
KW
3641 if (bs == NULL) {
3642 return NULL;
3643 }
3644
258b7765
HR
3645 return bdrv_attach_child(parent, bs, bdref_key, child_class, child_role,
3646 errp);
b4b059f6
KW
3647}
3648
83930780
VSO
3649/*
3650 * Wrapper on bdrv_open_child() for most popular case: open primary child of bs.
3651 */
3652int bdrv_open_file_child(const char *filename,
3653 QDict *options, const char *bdref_key,
3654 BlockDriverState *parent, Error **errp)
3655{
3656 BdrvChildRole role;
3657
3658 /* commit_top and mirror_top don't use this function */
3659 assert(!parent->drv->filtered_child_is_backing);
83930780
VSO
3660 role = parent->drv->is_filter ?
3661 (BDRV_CHILD_FILTERED | BDRV_CHILD_PRIMARY) : BDRV_CHILD_IMAGE;
3662
5bb04747
VSO
3663 if (!bdrv_open_child(filename, options, bdref_key, parent,
3664 &child_of_bds, role, false, errp))
3665 {
3666 return -EINVAL;
3667 }
83930780 3668
5bb04747 3669 return 0;
83930780
VSO
3670}
3671
bd86fb99
HR
3672/*
3673 * TODO Future callers may need to specify parent/child_class in order for
3674 * option inheritance to work. Existing callers use it for the root node.
3675 */
e1d74bc6
KW
3676BlockDriverState *bdrv_open_blockdev_ref(BlockdevRef *ref, Error **errp)
3677{
3678 BlockDriverState *bs = NULL;
e1d74bc6
KW
3679 QObject *obj = NULL;
3680 QDict *qdict = NULL;
3681 const char *reference = NULL;
3682 Visitor *v = NULL;
3683
f791bf7f
EGE
3684 GLOBAL_STATE_CODE();
3685
e1d74bc6
KW
3686 if (ref->type == QTYPE_QSTRING) {
3687 reference = ref->u.reference;
3688 } else {
3689 BlockdevOptions *options = &ref->u.definition;
3690 assert(ref->type == QTYPE_QDICT);
3691
3692 v = qobject_output_visitor_new(&obj);
1f584248 3693 visit_type_BlockdevOptions(v, NULL, &options, &error_abort);
e1d74bc6
KW
3694 visit_complete(v, &obj);
3695
7dc847eb 3696 qdict = qobject_to(QDict, obj);
e1d74bc6
KW
3697 qdict_flatten(qdict);
3698
3699 /* bdrv_open_inherit() defaults to the values in bdrv_flags (for
3700 * compatibility with other callers) rather than what we want as the
3701 * real defaults. Apply the defaults here instead. */
3702 qdict_set_default_str(qdict, BDRV_OPT_CACHE_DIRECT, "off");
3703 qdict_set_default_str(qdict, BDRV_OPT_CACHE_NO_FLUSH, "off");
3704 qdict_set_default_str(qdict, BDRV_OPT_READ_ONLY, "off");
e35bdc12
KW
3705 qdict_set_default_str(qdict, BDRV_OPT_AUTO_READ_ONLY, "off");
3706
e1d74bc6
KW
3707 }
3708
272c02ea 3709 bs = bdrv_open_inherit(NULL, reference, qdict, 0, NULL, NULL, 0, errp);
e1d74bc6 3710 obj = NULL;
cb3e7f08 3711 qobject_unref(obj);
e1d74bc6
KW
3712 visit_free(v);
3713 return bs;
3714}
3715
66836189
HR
3716static BlockDriverState *bdrv_append_temp_snapshot(BlockDriverState *bs,
3717 int flags,
3718 QDict *snapshot_options,
3719 Error **errp)
b998875d 3720{
69fbfff9 3721 g_autofree char *tmp_filename = NULL;
b998875d 3722 int64_t total_size;
83d0521a 3723 QemuOpts *opts = NULL;
ff6ed714 3724 BlockDriverState *bs_snapshot = NULL;
b998875d
KW
3725 int ret;
3726
bdb73476
EGE
3727 GLOBAL_STATE_CODE();
3728
b998875d
KW
3729 /* if snapshot, we create a temporary backing file and open it
3730 instead of opening 'filename' directly */
3731
3732 /* Get the required size from the image */
f187743a
KW
3733 total_size = bdrv_getlength(bs);
3734 if (total_size < 0) {
3735 error_setg_errno(errp, -total_size, "Could not get image size");
1ba4b6a5 3736 goto out;
f187743a 3737 }
b998875d
KW
3738
3739 /* Create the temporary image */
69fbfff9
BM
3740 tmp_filename = create_tmp_file(errp);
3741 if (!tmp_filename) {
1ba4b6a5 3742 goto out;
b998875d
KW
3743 }
3744
ef810437 3745 opts = qemu_opts_create(bdrv_qcow2.create_opts, NULL, 0,
c282e1fd 3746 &error_abort);
39101f25 3747 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, total_size, &error_abort);
e43bfd9c 3748 ret = bdrv_create(&bdrv_qcow2, tmp_filename, opts, errp);
83d0521a 3749 qemu_opts_del(opts);
b998875d 3750 if (ret < 0) {
e43bfd9c
MA
3751 error_prepend(errp, "Could not create temporary overlay '%s': ",
3752 tmp_filename);
1ba4b6a5 3753 goto out;
b998875d
KW
3754 }
3755
73176bee 3756 /* Prepare options QDict for the temporary file */
46f5ac20
EB
3757 qdict_put_str(snapshot_options, "file.driver", "file");
3758 qdict_put_str(snapshot_options, "file.filename", tmp_filename);
3759 qdict_put_str(snapshot_options, "driver", "qcow2");
b998875d 3760
5b363937 3761 bs_snapshot = bdrv_open(NULL, NULL, snapshot_options, flags, errp);
73176bee 3762 snapshot_options = NULL;
5b363937 3763 if (!bs_snapshot) {
1ba4b6a5 3764 goto out;
b998875d
KW
3765 }
3766
934aee14
VSO
3767 ret = bdrv_append(bs_snapshot, bs, errp);
3768 if (ret < 0) {
ff6ed714 3769 bs_snapshot = NULL;
b2c2832c
KW
3770 goto out;
3771 }
1ba4b6a5
BC
3772
3773out:
cb3e7f08 3774 qobject_unref(snapshot_options);
ff6ed714 3775 return bs_snapshot;
b998875d
KW
3776}
3777
b6ce07aa
KW
3778/*
3779 * Opens a disk image (raw, qcow2, vmdk, ...)
de9c0cec
KW
3780 *
3781 * options is a QDict of options to pass to the block drivers, or NULL for an
3782 * empty set of options. The reference to the QDict belongs to the block layer
3783 * after the call (even on failure), so if the caller intends to reuse the
cb3e7f08 3784 * dictionary, it needs to use qobject_ref() before calling bdrv_open.
f67503e5
HR
3785 *
3786 * If *pbs is NULL, a new BDS will be created with a pointer to it stored there.
3787 * If it is not NULL, the referenced BDS will be reused.
ddf5636d
HR
3788 *
3789 * The reference parameter may be used to specify an existing block device which
3790 * should be opened. If specified, neither options nor a filename may be given,
3791 * nor can an existing BDS be reused (that is, *pbs has to be NULL).
b6ce07aa 3792 */
5b363937
HR
3793static BlockDriverState *bdrv_open_inherit(const char *filename,
3794 const char *reference,
3795 QDict *options, int flags,
3796 BlockDriverState *parent,
bd86fb99 3797 const BdrvChildClass *child_class,
272c02ea 3798 BdrvChildRole child_role,
5b363937 3799 Error **errp)
ea2384d3 3800{
b6ce07aa 3801 int ret;
5696c6e3 3802 BlockBackend *file = NULL;
9a4f4c31 3803 BlockDriverState *bs;
ce343771 3804 BlockDriver *drv = NULL;
2f624b80 3805 BdrvChild *child;
74fe54f2 3806 const char *drvname;
3e8c2e57 3807 const char *backing;
34b5d2c6 3808 Error *local_err = NULL;
73176bee 3809 QDict *snapshot_options = NULL;
b1e6fc08 3810 int snapshot_flags = 0;
712e7874 3811
bd86fb99
HR
3812 assert(!child_class || !flags);
3813 assert(!child_class == !parent);
f0c28327 3814 GLOBAL_STATE_CODE();
f67503e5 3815
ddf5636d
HR
3816 if (reference) {
3817 bool options_non_empty = options ? qdict_size(options) : false;
cb3e7f08 3818 qobject_unref(options);
ddf5636d 3819
ddf5636d
HR
3820 if (filename || options_non_empty) {
3821 error_setg(errp, "Cannot reference an existing block device with "
3822 "additional options or a new filename");
5b363937 3823 return NULL;
ddf5636d
HR
3824 }
3825
3826 bs = bdrv_lookup_bs(reference, reference, errp);
3827 if (!bs) {
5b363937 3828 return NULL;
ddf5636d 3829 }
76b22320 3830
ddf5636d 3831 bdrv_ref(bs);
5b363937 3832 return bs;
ddf5636d
HR
3833 }
3834
5b363937 3835 bs = bdrv_new();
f67503e5 3836
de9c0cec
KW
3837 /* NULL means an empty set of options */
3838 if (options == NULL) {
3839 options = qdict_new();
3840 }
3841
145f598e 3842 /* json: syntax counts as explicit options, as if in the QDict */
de3b53f0
KW
3843 parse_json_protocol(options, &filename, &local_err);
3844 if (local_err) {
de3b53f0
KW
3845 goto fail;
3846 }
3847
145f598e
KW
3848 bs->explicit_options = qdict_clone_shallow(options);
3849
bd86fb99 3850 if (child_class) {
3cdc69d3
HR
3851 bool parent_is_format;
3852
3853 if (parent->drv) {
3854 parent_is_format = parent->drv->is_format;
3855 } else {
3856 /*
3857 * parent->drv is not set yet because this node is opened for
3858 * (potential) format probing. That means that @parent is going
3859 * to be a format node.
3860 */
3861 parent_is_format = true;
3862 }
3863
bddcec37 3864 bs->inherits_from = parent;
3cdc69d3
HR
3865 child_class->inherit_options(child_role, parent_is_format,
3866 &flags, options,
bd86fb99 3867 parent->open_flags, parent->options);
f3930ed0
KW
3868 }
3869
de3b53f0 3870 ret = bdrv_fill_options(&options, filename, &flags, &local_err);
dfde483e 3871 if (ret < 0) {
462f5bcf
KW
3872 goto fail;
3873 }
3874
129c7d1c
MA
3875 /*
3876 * Set the BDRV_O_RDWR and BDRV_O_ALLOW_RDWR flags.
3877 * Caution: getting a boolean member of @options requires care.
3878 * When @options come from -blockdev or blockdev_add, members are
3879 * typed according to the QAPI schema, but when they come from
3880 * -drive, they're all QString.
3881 */
f87a0e29
AG
3882 if (g_strcmp0(qdict_get_try_str(options, BDRV_OPT_READ_ONLY), "on") &&
3883 !qdict_get_try_bool(options, BDRV_OPT_READ_ONLY, false)) {
3884 flags |= (BDRV_O_RDWR | BDRV_O_ALLOW_RDWR);
3885 } else {
3886 flags &= ~BDRV_O_RDWR;
14499ea5
AG
3887 }
3888
3889 if (flags & BDRV_O_SNAPSHOT) {
3890 snapshot_options = qdict_new();
3891 bdrv_temp_snapshot_options(&snapshot_flags, snapshot_options,
3892 flags, options);
f87a0e29
AG
3893 /* Let bdrv_backing_options() override "read-only" */
3894 qdict_del(options, BDRV_OPT_READ_ONLY);
00ff7ffd
HR
3895 bdrv_inherited_options(BDRV_CHILD_COW, true,
3896 &flags, options, flags, options);
14499ea5
AG
3897 }
3898
62392ebb
KW
3899 bs->open_flags = flags;
3900 bs->options = options;
3901 options = qdict_clone_shallow(options);
3902
76c591b0 3903 /* Find the right image format driver */
129c7d1c 3904 /* See cautionary note on accessing @options above */
76c591b0
KW
3905 drvname = qdict_get_try_str(options, "driver");
3906 if (drvname) {
3907 drv = bdrv_find_format(drvname);
76c591b0
KW
3908 if (!drv) {
3909 error_setg(errp, "Unknown driver: '%s'", drvname);
76c591b0
KW
3910 goto fail;
3911 }
3912 }
3913
3914 assert(drvname || !(flags & BDRV_O_PROTOCOL));
76c591b0 3915
129c7d1c 3916 /* See cautionary note on accessing @options above */
3e8c2e57 3917 backing = qdict_get_try_str(options, "backing");
e59a0cf1
HR
3918 if (qobject_to(QNull, qdict_get(options, "backing")) != NULL ||
3919 (backing && *backing == '\0'))
3920 {
4f7be280
HR
3921 if (backing) {
3922 warn_report("Use of \"backing\": \"\" is deprecated; "
3923 "use \"backing\": null instead");
3924 }
3e8c2e57 3925 flags |= BDRV_O_NO_BACKING;
ae0f57f0
KW
3926 qdict_del(bs->explicit_options, "backing");
3927 qdict_del(bs->options, "backing");
3e8c2e57
AG
3928 qdict_del(options, "backing");
3929 }
3930
5696c6e3 3931 /* Open image file without format layer. This BlockBackend is only used for
4e4bf5c4
KW
3932 * probing, the block drivers will do their own bdrv_open_child() for the
3933 * same BDS, which is why we put the node name back into options. */
f4788adc 3934 if ((flags & BDRV_O_PROTOCOL) == 0) {
5696c6e3
KW
3935 BlockDriverState *file_bs;
3936
3937 file_bs = bdrv_open_child_bs(filename, options, "file", bs,
58944401
HR
3938 &child_of_bds, BDRV_CHILD_IMAGE,
3939 true, &local_err);
1fdd6933 3940 if (local_err) {
f4788adc
KW
3941 goto fail;
3942 }
5696c6e3 3943 if (file_bs != NULL) {
dacaa162
KW
3944 /* Not requesting BLK_PERM_CONSISTENT_READ because we're only
3945 * looking at the header to guess the image format. This works even
3946 * in cases where a guest would not see a consistent state. */
d861ab3a 3947 file = blk_new(bdrv_get_aio_context(file_bs), 0, BLK_PERM_ALL);
d7086422 3948 blk_insert_bs(file, file_bs, &local_err);
5696c6e3 3949 bdrv_unref(file_bs);
d7086422
KW
3950 if (local_err) {
3951 goto fail;
3952 }
5696c6e3 3953
46f5ac20 3954 qdict_put_str(options, "file", bdrv_get_node_name(file_bs));
4e4bf5c4 3955 }
f500a6d3
KW
3956 }
3957
76c591b0 3958 /* Image format probing */
38f3ef57 3959 bs->probed = !drv;
76c591b0 3960 if (!drv && file) {
cf2ab8fc 3961 ret = find_image_format(file, filename, &drv, &local_err);
17b005f1 3962 if (ret < 0) {
8bfea15d 3963 goto fail;
2a05cbe4 3964 }
62392ebb
KW
3965 /*
3966 * This option update would logically belong in bdrv_fill_options(),
3967 * but we first need to open bs->file for the probing to work, while
3968 * opening bs->file already requires the (mostly) final set of options
3969 * so that cache mode etc. can be inherited.
3970 *
3971 * Adding the driver later is somewhat ugly, but it's not an option
3972 * that would ever be inherited, so it's correct. We just need to make
3973 * sure to update both bs->options (which has the full effective
3974 * options for bs) and options (which has file.* already removed).
3975 */
46f5ac20
EB
3976 qdict_put_str(bs->options, "driver", drv->format_name);
3977 qdict_put_str(options, "driver", drv->format_name);
76c591b0 3978 } else if (!drv) {
17b005f1 3979 error_setg(errp, "Must specify either driver or file");
8bfea15d 3980 goto fail;
ea2384d3 3981 }
b6ce07aa 3982
53a29513
HR
3983 /* BDRV_O_PROTOCOL must be set iff a protocol BDS is about to be created */
3984 assert(!!(flags & BDRV_O_PROTOCOL) == !!drv->bdrv_file_open);
3985 /* file must be NULL if a protocol BDS is about to be created
3986 * (the inverse results in an error message from bdrv_open_common()) */
3987 assert(!(flags & BDRV_O_PROTOCOL) || !file);
3988
b6ce07aa 3989 /* Open the image */
82dc8b41 3990 ret = bdrv_open_common(bs, file, options, &local_err);
b6ce07aa 3991 if (ret < 0) {
8bfea15d 3992 goto fail;
6987307c
CH
3993 }
3994
4e4bf5c4 3995 if (file) {
5696c6e3 3996 blk_unref(file);
f500a6d3
KW
3997 file = NULL;
3998 }
3999
b6ce07aa 4000 /* If there is a backing file, use it */
9156df12 4001 if ((flags & BDRV_O_NO_BACKING) == 0) {
d9b7b057 4002 ret = bdrv_open_backing_file(bs, options, "backing", &local_err);
b6ce07aa 4003 if (ret < 0) {
b6ad491a 4004 goto close_and_fail;
b6ce07aa 4005 }
b6ce07aa
KW
4006 }
4007
50196d7a
AG
4008 /* Remove all children options and references
4009 * from bs->options and bs->explicit_options */
2f624b80
AG
4010 QLIST_FOREACH(child, &bs->children, next) {
4011 char *child_key_dot;
4012 child_key_dot = g_strdup_printf("%s.", child->name);
4013 qdict_extract_subqdict(bs->explicit_options, NULL, child_key_dot);
4014 qdict_extract_subqdict(bs->options, NULL, child_key_dot);
50196d7a
AG
4015 qdict_del(bs->explicit_options, child->name);
4016 qdict_del(bs->options, child->name);
2f624b80
AG
4017 g_free(child_key_dot);
4018 }
4019
b6ad491a 4020 /* Check if any unknown options were used */
7ad2757f 4021 if (qdict_size(options) != 0) {
b6ad491a 4022 const QDictEntry *entry = qdict_first(options);
5acd9d81
HR
4023 if (flags & BDRV_O_PROTOCOL) {
4024 error_setg(errp, "Block protocol '%s' doesn't support the option "
4025 "'%s'", drv->format_name, entry->key);
4026 } else {
d0e46a55
HR
4027 error_setg(errp,
4028 "Block format '%s' does not support the option '%s'",
4029 drv->format_name, entry->key);
5acd9d81 4030 }
b6ad491a 4031
b6ad491a
KW
4032 goto close_and_fail;
4033 }
b6ad491a 4034
c01c214b 4035 bdrv_parent_cb_change_media(bs, true);
b6ce07aa 4036
cb3e7f08 4037 qobject_unref(options);
8961be33 4038 options = NULL;
dd62f1ca
KW
4039
4040 /* For snapshot=on, create a temporary qcow2 overlay. bs points to the
4041 * temporary snapshot afterwards. */
4042 if (snapshot_flags) {
66836189
HR
4043 BlockDriverState *snapshot_bs;
4044 snapshot_bs = bdrv_append_temp_snapshot(bs, snapshot_flags,
4045 snapshot_options, &local_err);
73176bee 4046 snapshot_options = NULL;
dd62f1ca
KW
4047 if (local_err) {
4048 goto close_and_fail;
4049 }
5b363937
HR
4050 /* We are not going to return bs but the overlay on top of it
4051 * (snapshot_bs); thus, we have to drop the strong reference to bs
4052 * (which we obtained by calling bdrv_new()). bs will not be deleted,
4053 * though, because the overlay still has a reference to it. */
4054 bdrv_unref(bs);
4055 bs = snapshot_bs;
dd62f1ca
KW
4056 }
4057
5b363937 4058 return bs;
b6ce07aa 4059
8bfea15d 4060fail:
5696c6e3 4061 blk_unref(file);
cb3e7f08
MAL
4062 qobject_unref(snapshot_options);
4063 qobject_unref(bs->explicit_options);
4064 qobject_unref(bs->options);
4065 qobject_unref(options);
de9c0cec 4066 bs->options = NULL;
998cbd6a 4067 bs->explicit_options = NULL;
5b363937 4068 bdrv_unref(bs);
621ff94d 4069 error_propagate(errp, local_err);
5b363937 4070 return NULL;
de9c0cec 4071
b6ad491a 4072close_and_fail:
5b363937 4073 bdrv_unref(bs);
cb3e7f08
MAL
4074 qobject_unref(snapshot_options);
4075 qobject_unref(options);
621ff94d 4076 error_propagate(errp, local_err);
5b363937 4077 return NULL;
b6ce07aa
KW
4078}
4079
5b363937
HR
4080BlockDriverState *bdrv_open(const char *filename, const char *reference,
4081 QDict *options, int flags, Error **errp)
f3930ed0 4082{
f791bf7f
EGE
4083 GLOBAL_STATE_CODE();
4084
5b363937 4085 return bdrv_open_inherit(filename, reference, options, flags, NULL,
272c02ea 4086 NULL, 0, errp);
f3930ed0
KW
4087}
4088
faf116b4
AG
4089/* Return true if the NULL-terminated @list contains @str */
4090static bool is_str_in_list(const char *str, const char *const *list)
4091{
4092 if (str && list) {
4093 int i;
4094 for (i = 0; list[i] != NULL; i++) {
4095 if (!strcmp(str, list[i])) {
4096 return true;
4097 }
4098 }
4099 }
4100 return false;
4101}
4102
4103/*
4104 * Check that every option set in @bs->options is also set in
4105 * @new_opts.
4106 *
4107 * Options listed in the common_options list and in
4108 * @bs->drv->mutable_opts are skipped.
4109 *
4110 * Return 0 on success, otherwise return -EINVAL and set @errp.
4111 */
4112static int bdrv_reset_options_allowed(BlockDriverState *bs,
4113 const QDict *new_opts, Error **errp)
4114{
4115 const QDictEntry *e;
4116 /* These options are common to all block drivers and are handled
4117 * in bdrv_reopen_prepare() so they can be left out of @new_opts */
4118 const char *const common_options[] = {
4119 "node-name", "discard", "cache.direct", "cache.no-flush",
4120 "read-only", "auto-read-only", "detect-zeroes", NULL
4121 };
4122
4123 for (e = qdict_first(bs->options); e; e = qdict_next(bs->options, e)) {
4124 if (!qdict_haskey(new_opts, e->key) &&
4125 !is_str_in_list(e->key, common_options) &&
4126 !is_str_in_list(e->key, bs->drv->mutable_opts)) {
4127 error_setg(errp, "Option '%s' cannot be reset "
4128 "to its default value", e->key);
4129 return -EINVAL;
4130 }
4131 }
4132
4133 return 0;
4134}
4135
cb828c31
AG
4136/*
4137 * Returns true if @child can be reached recursively from @bs
4138 */
4139static bool bdrv_recurse_has_child(BlockDriverState *bs,
4140 BlockDriverState *child)
4141{
4142 BdrvChild *c;
4143
4144 if (bs == child) {
4145 return true;
4146 }
4147
4148 QLIST_FOREACH(c, &bs->children, next) {
4149 if (bdrv_recurse_has_child(c->bs, child)) {
4150 return true;
4151 }
4152 }
4153
4154 return false;
4155}
4156
e971aa12
JC
4157/*
4158 * Adds a BlockDriverState to a simple queue for an atomic, transactional
4159 * reopen of multiple devices.
4160 *
859443b0 4161 * bs_queue can either be an existing BlockReopenQueue that has had QTAILQ_INIT
e971aa12
JC
4162 * already performed, or alternatively may be NULL a new BlockReopenQueue will
4163 * be created and initialized. This newly created BlockReopenQueue should be
4164 * passed back in for subsequent calls that are intended to be of the same
4165 * atomic 'set'.
4166 *
4167 * bs is the BlockDriverState to add to the reopen queue.
4168 *
4d2cb092
KW
4169 * options contains the changed options for the associated bs
4170 * (the BlockReopenQueue takes ownership)
4171 *
e971aa12
JC
4172 * flags contains the open flags for the associated bs
4173 *
4174 * returns a pointer to bs_queue, which is either the newly allocated
4175 * bs_queue, or the existing bs_queue being used.
4176 *
1a63a907 4177 * bs must be drained between bdrv_reopen_queue() and bdrv_reopen_multiple().
e971aa12 4178 */
28518102
KW
4179static BlockReopenQueue *bdrv_reopen_queue_child(BlockReopenQueue *bs_queue,
4180 BlockDriverState *bs,
4181 QDict *options,
bd86fb99 4182 const BdrvChildClass *klass,
272c02ea 4183 BdrvChildRole role,
3cdc69d3 4184 bool parent_is_format,
28518102 4185 QDict *parent_options,
077e8e20
AG
4186 int parent_flags,
4187 bool keep_old_opts)
e971aa12
JC
4188{
4189 assert(bs != NULL);
4190
4191 BlockReopenQueueEntry *bs_entry;
67251a31 4192 BdrvChild *child;
9aa09ddd
AG
4193 QDict *old_options, *explicit_options, *options_copy;
4194 int flags;
4195 QemuOpts *opts;
67251a31 4196
1a63a907
KW
4197 /* Make sure that the caller remembered to use a drained section. This is
4198 * important to avoid graph changes between the recursive queuing here and
4199 * bdrv_reopen_multiple(). */
4200 assert(bs->quiesce_counter > 0);
f0c28327 4201 GLOBAL_STATE_CODE();
1a63a907 4202
e971aa12
JC
4203 if (bs_queue == NULL) {
4204 bs_queue = g_new0(BlockReopenQueue, 1);
859443b0 4205 QTAILQ_INIT(bs_queue);
e971aa12
JC
4206 }
4207
4d2cb092
KW
4208 if (!options) {
4209 options = qdict_new();
4210 }
4211
5b7ba05f 4212 /* Check if this BlockDriverState is already in the queue */
859443b0 4213 QTAILQ_FOREACH(bs_entry, bs_queue, entry) {
5b7ba05f
AG
4214 if (bs == bs_entry->state.bs) {
4215 break;
4216 }
4217 }
4218
28518102
KW
4219 /*
4220 * Precedence of options:
4221 * 1. Explicitly passed in options (highest)
9aa09ddd
AG
4222 * 2. Retained from explicitly set options of bs
4223 * 3. Inherited from parent node
4224 * 4. Retained from effective options of bs
28518102
KW
4225 */
4226
145f598e 4227 /* Old explicitly set values (don't overwrite by inherited value) */
077e8e20
AG
4228 if (bs_entry || keep_old_opts) {
4229 old_options = qdict_clone_shallow(bs_entry ?
4230 bs_entry->state.explicit_options :
4231 bs->explicit_options);
4232 bdrv_join_options(bs, options, old_options);
4233 qobject_unref(old_options);
5b7ba05f 4234 }
145f598e
KW
4235
4236 explicit_options = qdict_clone_shallow(options);
4237
28518102
KW
4238 /* Inherit from parent node */
4239 if (parent_options) {
9aa09ddd 4240 flags = 0;
3cdc69d3 4241 klass->inherit_options(role, parent_is_format, &flags, options,
272c02ea 4242 parent_flags, parent_options);
9aa09ddd
AG
4243 } else {
4244 flags = bdrv_get_flags(bs);
28518102
KW
4245 }
4246
077e8e20
AG
4247 if (keep_old_opts) {
4248 /* Old values are used for options that aren't set yet */
4249 old_options = qdict_clone_shallow(bs->options);
4250 bdrv_join_options(bs, options, old_options);
4251 qobject_unref(old_options);
4252 }
4d2cb092 4253
9aa09ddd
AG
4254 /* We have the final set of options so let's update the flags */
4255 options_copy = qdict_clone_shallow(options);
4256 opts = qemu_opts_create(&bdrv_runtime_opts, NULL, 0, &error_abort);
4257 qemu_opts_absorb_qdict(opts, options_copy, NULL);
4258 update_flags_from_options(&flags, opts);
4259 qemu_opts_del(opts);
4260 qobject_unref(options_copy);
4261
fd452021 4262 /* bdrv_open_inherit() sets and clears some additional flags internally */
f1f25a2e 4263 flags &= ~BDRV_O_PROTOCOL;
fd452021
KW
4264 if (flags & BDRV_O_RDWR) {
4265 flags |= BDRV_O_ALLOW_RDWR;
4266 }
f1f25a2e 4267
1857c97b
KW
4268 if (!bs_entry) {
4269 bs_entry = g_new0(BlockReopenQueueEntry, 1);
859443b0 4270 QTAILQ_INSERT_TAIL(bs_queue, bs_entry, entry);
1857c97b 4271 } else {
cb3e7f08
MAL
4272 qobject_unref(bs_entry->state.options);
4273 qobject_unref(bs_entry->state.explicit_options);
1857c97b
KW
4274 }
4275
4276 bs_entry->state.bs = bs;
4277 bs_entry->state.options = options;
4278 bs_entry->state.explicit_options = explicit_options;
4279 bs_entry->state.flags = flags;
4280
8546632e
AG
4281 /*
4282 * If keep_old_opts is false then it means that unspecified
4283 * options must be reset to their original value. We don't allow
4284 * resetting 'backing' but we need to know if the option is
4285 * missing in order to decide if we have to return an error.
4286 */
4287 if (!keep_old_opts) {
4288 bs_entry->state.backing_missing =
4289 !qdict_haskey(options, "backing") &&
4290 !qdict_haskey(options, "backing.driver");
4291 }
4292
67251a31 4293 QLIST_FOREACH(child, &bs->children, next) {
8546632e
AG
4294 QDict *new_child_options = NULL;
4295 bool child_keep_old = keep_old_opts;
67251a31 4296
4c9dfe5d
KW
4297 /* reopen can only change the options of block devices that were
4298 * implicitly created and inherited options. For other (referenced)
4299 * block devices, a syntax like "backing.foo" results in an error. */
67251a31
KW
4300 if (child->bs->inherits_from != bs) {
4301 continue;
4302 }
4303
8546632e
AG
4304 /* Check if the options contain a child reference */
4305 if (qdict_haskey(options, child->name)) {
4306 const char *childref = qdict_get_try_str(options, child->name);
4307 /*
4308 * The current child must not be reopened if the child
4309 * reference is null or points to a different node.
4310 */
4311 if (g_strcmp0(childref, child->bs->node_name)) {
4312 continue;
4313 }
4314 /*
4315 * If the child reference points to the current child then
4316 * reopen it with its existing set of options (note that
4317 * it can still inherit new options from the parent).
4318 */
4319 child_keep_old = true;
4320 } else {
4321 /* Extract child options ("child-name.*") */
4322 char *child_key_dot = g_strdup_printf("%s.", child->name);
4323 qdict_extract_subqdict(explicit_options, NULL, child_key_dot);
4324 qdict_extract_subqdict(options, &new_child_options, child_key_dot);
4325 g_free(child_key_dot);
4326 }
4c9dfe5d 4327
9aa09ddd 4328 bdrv_reopen_queue_child(bs_queue, child->bs, new_child_options,
3cdc69d3
HR
4329 child->klass, child->role, bs->drv->is_format,
4330 options, flags, child_keep_old);
e971aa12
JC
4331 }
4332
e971aa12
JC
4333 return bs_queue;
4334}
4335
28518102
KW
4336BlockReopenQueue *bdrv_reopen_queue(BlockReopenQueue *bs_queue,
4337 BlockDriverState *bs,
077e8e20 4338 QDict *options, bool keep_old_opts)
28518102 4339{
f791bf7f
EGE
4340 GLOBAL_STATE_CODE();
4341
3cdc69d3
HR
4342 return bdrv_reopen_queue_child(bs_queue, bs, options, NULL, 0, false,
4343 NULL, 0, keep_old_opts);
28518102
KW
4344}
4345
ab5b5228
AG
4346void bdrv_reopen_queue_free(BlockReopenQueue *bs_queue)
4347{
f791bf7f 4348 GLOBAL_STATE_CODE();
ab5b5228
AG
4349 if (bs_queue) {
4350 BlockReopenQueueEntry *bs_entry, *next;
4351 QTAILQ_FOREACH_SAFE(bs_entry, bs_queue, entry, next) {
4352 qobject_unref(bs_entry->state.explicit_options);
4353 qobject_unref(bs_entry->state.options);
4354 g_free(bs_entry);
4355 }
4356 g_free(bs_queue);
4357 }
4358}
4359
e971aa12
JC
4360/*
4361 * Reopen multiple BlockDriverStates atomically & transactionally.
4362 *
4363 * The queue passed in (bs_queue) must have been built up previous
4364 * via bdrv_reopen_queue().
4365 *
4366 * Reopens all BDS specified in the queue, with the appropriate
4367 * flags. All devices are prepared for reopen, and failure of any
50d6a8a3 4368 * device will cause all device changes to be abandoned, and intermediate
e971aa12
JC
4369 * data cleaned up.
4370 *
4371 * If all devices prepare successfully, then the changes are committed
4372 * to all devices.
4373 *
1a63a907
KW
4374 * All affected nodes must be drained between bdrv_reopen_queue() and
4375 * bdrv_reopen_multiple().
6cf42ca2
KW
4376 *
4377 * To be called from the main thread, with all other AioContexts unlocked.
e971aa12 4378 */
5019aece 4379int bdrv_reopen_multiple(BlockReopenQueue *bs_queue, Error **errp)
e971aa12
JC
4380{
4381 int ret = -1;
4382 BlockReopenQueueEntry *bs_entry, *next;
6cf42ca2 4383 AioContext *ctx;
72373e40 4384 Transaction *tran = tran_new();
72373e40 4385 g_autoptr(GSList) refresh_list = NULL;
e971aa12 4386
6cf42ca2 4387 assert(qemu_get_current_aio_context() == qemu_get_aio_context());
e971aa12 4388 assert(bs_queue != NULL);
da359909 4389 GLOBAL_STATE_CODE();
e971aa12 4390
a2aabf88 4391 QTAILQ_FOREACH(bs_entry, bs_queue, entry) {
6cf42ca2
KW
4392 ctx = bdrv_get_aio_context(bs_entry->state.bs);
4393 aio_context_acquire(ctx);
a2aabf88 4394 ret = bdrv_flush(bs_entry->state.bs);
6cf42ca2 4395 aio_context_release(ctx);
a2aabf88
VSO
4396 if (ret < 0) {
4397 error_setg_errno(errp, -ret, "Error flushing drive");
e3fc91aa 4398 goto abort;
a2aabf88
VSO
4399 }
4400 }
4401
859443b0 4402 QTAILQ_FOREACH(bs_entry, bs_queue, entry) {
1a63a907 4403 assert(bs_entry->state.bs->quiesce_counter > 0);
6cf42ca2
KW
4404 ctx = bdrv_get_aio_context(bs_entry->state.bs);
4405 aio_context_acquire(ctx);
72373e40 4406 ret = bdrv_reopen_prepare(&bs_entry->state, bs_queue, tran, errp);
6cf42ca2 4407 aio_context_release(ctx);
72373e40
VSO
4408 if (ret < 0) {
4409 goto abort;
e971aa12
JC
4410 }
4411 bs_entry->prepared = true;
4412 }
4413
859443b0 4414 QTAILQ_FOREACH(bs_entry, bs_queue, entry) {
69b736e7 4415 BDRVReopenState *state = &bs_entry->state;
72373e40 4416
fb0ff4d1 4417 refresh_list = g_slist_prepend(refresh_list, state->bs);
72373e40 4418 if (state->old_backing_bs) {
fb0ff4d1 4419 refresh_list = g_slist_prepend(refresh_list, state->old_backing_bs);
cb828c31 4420 }
ecd30d2d 4421 if (state->old_file_bs) {
fb0ff4d1 4422 refresh_list = g_slist_prepend(refresh_list, state->old_file_bs);
ecd30d2d 4423 }
72373e40
VSO
4424 }
4425
4426 /*
4427 * Note that file-posix driver rely on permission update done during reopen
4428 * (even if no permission changed), because it wants "new" permissions for
4429 * reconfiguring the fd and that's why it does it in raw_check_perm(), not
4430 * in raw_reopen_prepare() which is called with "old" permissions.
4431 */
4432 ret = bdrv_list_refresh_perms(refresh_list, bs_queue, tran, errp);
4433 if (ret < 0) {
4434 goto abort;
69b736e7
KW
4435 }
4436
fcd6a4f4
VSO
4437 /*
4438 * If we reach this point, we have success and just need to apply the
4439 * changes.
4440 *
4441 * Reverse order is used to comfort qcow2 driver: on commit it need to write
4442 * IN_USE flag to the image, to mark bitmaps in the image as invalid. But
4443 * children are usually goes after parents in reopen-queue, so go from last
4444 * to first element.
e971aa12 4445 */
fcd6a4f4 4446 QTAILQ_FOREACH_REVERSE(bs_entry, bs_queue, entry) {
6cf42ca2
KW
4447 ctx = bdrv_get_aio_context(bs_entry->state.bs);
4448 aio_context_acquire(ctx);
e971aa12 4449 bdrv_reopen_commit(&bs_entry->state);
6cf42ca2 4450 aio_context_release(ctx);
e971aa12
JC
4451 }
4452
72373e40 4453 tran_commit(tran);
69b736e7 4454
72373e40
VSO
4455 QTAILQ_FOREACH_REVERSE(bs_entry, bs_queue, entry) {
4456 BlockDriverState *bs = bs_entry->state.bs;
74ad9a3b 4457
72373e40 4458 if (bs->drv->bdrv_reopen_commit_post) {
6cf42ca2
KW
4459 ctx = bdrv_get_aio_context(bs);
4460 aio_context_acquire(ctx);
72373e40 4461 bs->drv->bdrv_reopen_commit_post(&bs_entry->state);
6cf42ca2 4462 aio_context_release(ctx);
69b736e7
KW
4463 }
4464 }
17e1e2be 4465
72373e40
VSO
4466 ret = 0;
4467 goto cleanup;
17e1e2be 4468
72373e40
VSO
4469abort:
4470 tran_abort(tran);
4471 QTAILQ_FOREACH_SAFE(bs_entry, bs_queue, entry, next) {
4472 if (bs_entry->prepared) {
6cf42ca2
KW
4473 ctx = bdrv_get_aio_context(bs_entry->state.bs);
4474 aio_context_acquire(ctx);
72373e40 4475 bdrv_reopen_abort(&bs_entry->state);
6cf42ca2 4476 aio_context_release(ctx);
17e1e2be
PK
4477 }
4478 }
72373e40 4479
e971aa12 4480cleanup:
ab5b5228 4481 bdrv_reopen_queue_free(bs_queue);
40840e41 4482
e971aa12
JC
4483 return ret;
4484}
4485
6cf42ca2
KW
4486int bdrv_reopen(BlockDriverState *bs, QDict *opts, bool keep_old_opts,
4487 Error **errp)
6e1000a8 4488{
6cf42ca2 4489 AioContext *ctx = bdrv_get_aio_context(bs);
6e1000a8 4490 BlockReopenQueue *queue;
6cf42ca2 4491 int ret;
6e1000a8 4492
f791bf7f
EGE
4493 GLOBAL_STATE_CODE();
4494
6e1000a8 4495 bdrv_subtree_drained_begin(bs);
6cf42ca2
KW
4496 if (ctx != qemu_get_aio_context()) {
4497 aio_context_release(ctx);
4498 }
4499
4500 queue = bdrv_reopen_queue(NULL, bs, opts, keep_old_opts);
5019aece 4501 ret = bdrv_reopen_multiple(queue, errp);
6cf42ca2
KW
4502
4503 if (ctx != qemu_get_aio_context()) {
4504 aio_context_acquire(ctx);
4505 }
6e1000a8
AG
4506 bdrv_subtree_drained_end(bs);
4507
4508 return ret;
4509}
4510
6cf42ca2
KW
4511int bdrv_reopen_set_read_only(BlockDriverState *bs, bool read_only,
4512 Error **errp)
4513{
4514 QDict *opts = qdict_new();
4515
f791bf7f
EGE
4516 GLOBAL_STATE_CODE();
4517
6cf42ca2
KW
4518 qdict_put_bool(opts, BDRV_OPT_READ_ONLY, read_only);
4519
4520 return bdrv_reopen(bs, opts, true, errp);
4521}
4522
cb828c31
AG
4523/*
4524 * Take a BDRVReopenState and check if the value of 'backing' in the
4525 * reopen_state->options QDict is valid or not.
4526 *
4527 * If 'backing' is missing from the QDict then return 0.
4528 *
4529 * If 'backing' contains the node name of the backing file of
4530 * reopen_state->bs then return 0.
4531 *
4532 * If 'backing' contains a different node name (or is null) then check
4533 * whether the current backing file can be replaced with the new one.
4534 * If that's the case then reopen_state->replace_backing_bs is set to
4535 * true and reopen_state->new_backing_bs contains a pointer to the new
4536 * backing BlockDriverState (or NULL).
4537 *
4538 * Return 0 on success, otherwise return < 0 and set @errp.
4539 */
ecd30d2d
AG
4540static int bdrv_reopen_parse_file_or_backing(BDRVReopenState *reopen_state,
4541 bool is_backing, Transaction *tran,
4542 Error **errp)
cb828c31
AG
4543{
4544 BlockDriverState *bs = reopen_state->bs;
ecd30d2d
AG
4545 BlockDriverState *new_child_bs;
4546 BlockDriverState *old_child_bs = is_backing ? child_bs(bs->backing) :
4547 child_bs(bs->file);
4548 const char *child_name = is_backing ? "backing" : "file";
cb828c31
AG
4549 QObject *value;
4550 const char *str;
4551
bdb73476
EGE
4552 GLOBAL_STATE_CODE();
4553
ecd30d2d 4554 value = qdict_get(reopen_state->options, child_name);
cb828c31
AG
4555 if (value == NULL) {
4556 return 0;
4557 }
4558
4559 switch (qobject_type(value)) {
4560 case QTYPE_QNULL:
ecd30d2d
AG
4561 assert(is_backing); /* The 'file' option does not allow a null value */
4562 new_child_bs = NULL;
cb828c31
AG
4563 break;
4564 case QTYPE_QSTRING:
410f44f5 4565 str = qstring_get_str(qobject_to(QString, value));
ecd30d2d
AG
4566 new_child_bs = bdrv_lookup_bs(NULL, str, errp);
4567 if (new_child_bs == NULL) {
cb828c31 4568 return -EINVAL;
ecd30d2d
AG
4569 } else if (bdrv_recurse_has_child(new_child_bs, bs)) {
4570 error_setg(errp, "Making '%s' a %s child of '%s' would create a "
4571 "cycle", str, child_name, bs->node_name);
cb828c31
AG
4572 return -EINVAL;
4573 }
4574 break;
4575 default:
ecd30d2d
AG
4576 /*
4577 * The options QDict has been flattened, so 'backing' and 'file'
4578 * do not allow any other data type here.
4579 */
cb828c31
AG
4580 g_assert_not_reached();
4581 }
4582
ecd30d2d
AG
4583 if (old_child_bs == new_child_bs) {
4584 return 0;
4585 }
4586
4587 if (old_child_bs) {
4588 if (bdrv_skip_implicit_filters(old_child_bs) == new_child_bs) {
cbfdb98c
VSO
4589 return 0;
4590 }
4591
ecd30d2d
AG
4592 if (old_child_bs->implicit) {
4593 error_setg(errp, "Cannot replace implicit %s child of %s",
4594 child_name, bs->node_name);
cbfdb98c
VSO
4595 return -EPERM;
4596 }
4597 }
4598
ecd30d2d 4599 if (bs->drv->is_filter && !old_child_bs) {
25f78d9e
VSO
4600 /*
4601 * Filters always have a file or a backing child, so we are trying to
4602 * change wrong child
4603 */
4604 error_setg(errp, "'%s' is a %s filter node that does not support a "
ecd30d2d 4605 "%s child", bs->node_name, bs->drv->format_name, child_name);
1d42f48c
HR
4606 return -EINVAL;
4607 }
4608
ecd30d2d
AG
4609 if (is_backing) {
4610 reopen_state->old_backing_bs = old_child_bs;
4611 } else {
4612 reopen_state->old_file_bs = old_child_bs;
4613 }
4614
4615 return bdrv_set_file_or_backing_noperm(bs, new_child_bs, is_backing,
4616 tran, errp);
cb828c31
AG
4617}
4618
e971aa12
JC
4619/*
4620 * Prepares a BlockDriverState for reopen. All changes are staged in the
4621 * 'opaque' field of the BDRVReopenState, which is used and allocated by
4622 * the block driver layer .bdrv_reopen_prepare()
4623 *
4624 * bs is the BlockDriverState to reopen
4625 * flags are the new open flags
4626 * queue is the reopen queue
4627 *
4628 * Returns 0 on success, non-zero on error. On error errp will be set
4629 * as well.
4630 *
4631 * On failure, bdrv_reopen_abort() will be called to clean up any data.
4632 * It is the responsibility of the caller to then call the abort() or
4633 * commit() for any other BDS that have been left in a prepare() state
4634 *
4635 */
53e96d1e 4636static int bdrv_reopen_prepare(BDRVReopenState *reopen_state,
72373e40 4637 BlockReopenQueue *queue,
ecd30d2d 4638 Transaction *change_child_tran, Error **errp)
e971aa12
JC
4639{
4640 int ret = -1;
e6d79c41 4641 int old_flags;
e971aa12
JC
4642 Error *local_err = NULL;
4643 BlockDriver *drv;
ccf9dc07 4644 QemuOpts *opts;
4c8350fe 4645 QDict *orig_reopen_opts;
593b3071 4646 char *discard = NULL;
3d8ce171 4647 bool read_only;
9ad08c44 4648 bool drv_prepared = false;
e971aa12
JC
4649
4650 assert(reopen_state != NULL);
4651 assert(reopen_state->bs->drv != NULL);
da359909 4652 GLOBAL_STATE_CODE();
e971aa12
JC
4653 drv = reopen_state->bs->drv;
4654
4c8350fe
AG
4655 /* This function and each driver's bdrv_reopen_prepare() remove
4656 * entries from reopen_state->options as they are processed, so
4657 * we need to make a copy of the original QDict. */
4658 orig_reopen_opts = qdict_clone_shallow(reopen_state->options);
4659
ccf9dc07
KW
4660 /* Process generic block layer options */
4661 opts = qemu_opts_create(&bdrv_runtime_opts, NULL, 0, &error_abort);
af175e85 4662 if (!qemu_opts_absorb_qdict(opts, reopen_state->options, errp)) {
ccf9dc07
KW
4663 ret = -EINVAL;
4664 goto error;
4665 }
4666
e6d79c41
AG
4667 /* This was already called in bdrv_reopen_queue_child() so the flags
4668 * are up-to-date. This time we simply want to remove the options from
4669 * QemuOpts in order to indicate that they have been processed. */
4670 old_flags = reopen_state->flags;
91a097e7 4671 update_flags_from_options(&reopen_state->flags, opts);
e6d79c41 4672 assert(old_flags == reopen_state->flags);
91a097e7 4673
415bbca8 4674 discard = qemu_opt_get_del(opts, BDRV_OPT_DISCARD);
593b3071
AG
4675 if (discard != NULL) {
4676 if (bdrv_parse_discard_flags(discard, &reopen_state->flags) != 0) {
4677 error_setg(errp, "Invalid discard option");
4678 ret = -EINVAL;
4679 goto error;
4680 }
4681 }
4682
543770bd
AG
4683 reopen_state->detect_zeroes =
4684 bdrv_parse_detect_zeroes(opts, reopen_state->flags, &local_err);
4685 if (local_err) {
4686 error_propagate(errp, local_err);
4687 ret = -EINVAL;
4688 goto error;
4689 }
4690
57f9db9a
AG
4691 /* All other options (including node-name and driver) must be unchanged.
4692 * Put them back into the QDict, so that they are checked at the end
4693 * of this function. */
4694 qemu_opts_to_qdict(opts, reopen_state->options);
ccf9dc07 4695
3d8ce171
JC
4696 /* If we are to stay read-only, do not allow permission change
4697 * to r/w. Attempting to set to r/w may fail if either BDRV_O_ALLOW_RDWR is
4698 * not set, or if the BDS still has copy_on_read enabled */
4699 read_only = !(reopen_state->flags & BDRV_O_RDWR);
54a32bfe 4700 ret = bdrv_can_set_read_only(reopen_state->bs, read_only, true, &local_err);
3d8ce171
JC
4701 if (local_err) {
4702 error_propagate(errp, local_err);
e971aa12
JC
4703 goto error;
4704 }
4705
e971aa12 4706 if (drv->bdrv_reopen_prepare) {
faf116b4
AG
4707 /*
4708 * If a driver-specific option is missing, it means that we
4709 * should reset it to its default value.
4710 * But not all options allow that, so we need to check it first.
4711 */
4712 ret = bdrv_reset_options_allowed(reopen_state->bs,
4713 reopen_state->options, errp);
4714 if (ret) {
4715 goto error;
4716 }
4717
e971aa12
JC
4718 ret = drv->bdrv_reopen_prepare(reopen_state, queue, &local_err);
4719 if (ret) {
4720 if (local_err != NULL) {
4721 error_propagate(errp, local_err);
4722 } else {
f30c66ba 4723 bdrv_refresh_filename(reopen_state->bs);
d8b6895f
LC
4724 error_setg(errp, "failed while preparing to reopen image '%s'",
4725 reopen_state->bs->filename);
e971aa12
JC
4726 }
4727 goto error;
4728 }
4729 } else {
4730 /* It is currently mandatory to have a bdrv_reopen_prepare()
4731 * handler for each supported drv. */
81e5f78a
AG
4732 error_setg(errp, "Block format '%s' used by node '%s' "
4733 "does not support reopening files", drv->format_name,
4734 bdrv_get_device_or_node_name(reopen_state->bs));
e971aa12
JC
4735 ret = -1;
4736 goto error;
4737 }
4738
9ad08c44
HR
4739 drv_prepared = true;
4740
bacd9b87
AG
4741 /*
4742 * We must provide the 'backing' option if the BDS has a backing
4743 * file or if the image file has a backing file name as part of
4744 * its metadata. Otherwise the 'backing' option can be omitted.
4745 */
4746 if (drv->supports_backing && reopen_state->backing_missing &&
1d42f48c 4747 (reopen_state->bs->backing || reopen_state->bs->backing_file[0])) {
8546632e
AG
4748 error_setg(errp, "backing is missing for '%s'",
4749 reopen_state->bs->node_name);
4750 ret = -EINVAL;
4751 goto error;
4752 }
4753
cb828c31
AG
4754 /*
4755 * Allow changing the 'backing' option. The new value can be
4756 * either a reference to an existing node (using its node name)
4757 * or NULL to simply detach the current backing file.
4758 */
ecd30d2d
AG
4759 ret = bdrv_reopen_parse_file_or_backing(reopen_state, true,
4760 change_child_tran, errp);
cb828c31
AG
4761 if (ret < 0) {
4762 goto error;
4763 }
4764 qdict_del(reopen_state->options, "backing");
4765
ecd30d2d
AG
4766 /* Allow changing the 'file' option. In this case NULL is not allowed */
4767 ret = bdrv_reopen_parse_file_or_backing(reopen_state, false,
4768 change_child_tran, errp);
4769 if (ret < 0) {
4770 goto error;
4771 }
4772 qdict_del(reopen_state->options, "file");
4773
4d2cb092
KW
4774 /* Options that are not handled are only okay if they are unchanged
4775 * compared to the old state. It is expected that some options are only
4776 * used for the initial open, but not reopen (e.g. filename) */
4777 if (qdict_size(reopen_state->options)) {
4778 const QDictEntry *entry = qdict_first(reopen_state->options);
4779
4780 do {
54fd1b0d
HR
4781 QObject *new = entry->value;
4782 QObject *old = qdict_get(reopen_state->bs->options, entry->key);
4783
db905283
AG
4784 /* Allow child references (child_name=node_name) as long as they
4785 * point to the current child (i.e. everything stays the same). */
4786 if (qobject_type(new) == QTYPE_QSTRING) {
4787 BdrvChild *child;
4788 QLIST_FOREACH(child, &reopen_state->bs->children, next) {
4789 if (!strcmp(child->name, entry->key)) {
4790 break;
4791 }
4792 }
4793
4794 if (child) {
410f44f5
MA
4795 if (!strcmp(child->bs->node_name,
4796 qstring_get_str(qobject_to(QString, new)))) {
db905283
AG
4797 continue; /* Found child with this name, skip option */
4798 }
4799 }
4800 }
4801
129c7d1c 4802 /*
54fd1b0d
HR
4803 * TODO: When using -drive to specify blockdev options, all values
4804 * will be strings; however, when using -blockdev, blockdev-add or
4805 * filenames using the json:{} pseudo-protocol, they will be
4806 * correctly typed.
4807 * In contrast, reopening options are (currently) always strings
4808 * (because you can only specify them through qemu-io; all other
4809 * callers do not specify any options).
4810 * Therefore, when using anything other than -drive to create a BDS,
4811 * this cannot detect non-string options as unchanged, because
4812 * qobject_is_equal() always returns false for objects of different
4813 * type. In the future, this should be remedied by correctly typing
4814 * all options. For now, this is not too big of an issue because
4815 * the user can simply omit options which cannot be changed anyway,
4816 * so they will stay unchanged.
129c7d1c 4817 */
54fd1b0d 4818 if (!qobject_is_equal(new, old)) {
4d2cb092
KW
4819 error_setg(errp, "Cannot change the option '%s'", entry->key);
4820 ret = -EINVAL;
4821 goto error;
4822 }
4823 } while ((entry = qdict_next(reopen_state->options, entry)));
4824 }
4825
e971aa12
JC
4826 ret = 0;
4827
4c8350fe
AG
4828 /* Restore the original reopen_state->options QDict */
4829 qobject_unref(reopen_state->options);
4830 reopen_state->options = qobject_ref(orig_reopen_opts);
4831
e971aa12 4832error:
9ad08c44
HR
4833 if (ret < 0 && drv_prepared) {
4834 /* drv->bdrv_reopen_prepare() has succeeded, so we need to
4835 * call drv->bdrv_reopen_abort() before signaling an error
4836 * (bdrv_reopen_multiple() will not call bdrv_reopen_abort()
4837 * when the respective bdrv_reopen_prepare() has failed) */
4838 if (drv->bdrv_reopen_abort) {
4839 drv->bdrv_reopen_abort(reopen_state);
4840 }
4841 }
ccf9dc07 4842 qemu_opts_del(opts);
4c8350fe 4843 qobject_unref(orig_reopen_opts);
593b3071 4844 g_free(discard);
e971aa12
JC
4845 return ret;
4846}
4847
4848/*
4849 * Takes the staged changes for the reopen from bdrv_reopen_prepare(), and
4850 * makes them final by swapping the staging BlockDriverState contents into
4851 * the active BlockDriverState contents.
4852 */
53e96d1e 4853static void bdrv_reopen_commit(BDRVReopenState *reopen_state)
e971aa12
JC
4854{
4855 BlockDriver *drv;
50bf65ba 4856 BlockDriverState *bs;
50196d7a 4857 BdrvChild *child;
e971aa12
JC
4858
4859 assert(reopen_state != NULL);
50bf65ba
VSO
4860 bs = reopen_state->bs;
4861 drv = bs->drv;
e971aa12 4862 assert(drv != NULL);
da359909 4863 GLOBAL_STATE_CODE();
e971aa12
JC
4864
4865 /* If there are any driver level actions to take */
4866 if (drv->bdrv_reopen_commit) {
4867 drv->bdrv_reopen_commit(reopen_state);
4868 }
4869
4870 /* set BDS specific flags now */
cb3e7f08 4871 qobject_unref(bs->explicit_options);
4c8350fe 4872 qobject_unref(bs->options);
ab5b5228
AG
4873 qobject_ref(reopen_state->explicit_options);
4874 qobject_ref(reopen_state->options);
145f598e 4875
50bf65ba 4876 bs->explicit_options = reopen_state->explicit_options;
4c8350fe 4877 bs->options = reopen_state->options;
50bf65ba 4878 bs->open_flags = reopen_state->flags;
543770bd 4879 bs->detect_zeroes = reopen_state->detect_zeroes;
355ef4ac 4880
50196d7a
AG
4881 /* Remove child references from bs->options and bs->explicit_options.
4882 * Child options were already removed in bdrv_reopen_queue_child() */
4883 QLIST_FOREACH(child, &bs->children, next) {
4884 qdict_del(bs->explicit_options, child->name);
4885 qdict_del(bs->options, child->name);
4886 }
3d0e8743
VSO
4887 /* backing is probably removed, so it's not handled by previous loop */
4888 qdict_del(bs->explicit_options, "backing");
4889 qdict_del(bs->options, "backing");
4890
1e4c797c 4891 bdrv_refresh_limits(bs, NULL, NULL);
e971aa12
JC
4892}
4893
4894/*
4895 * Abort the reopen, and delete and free the staged changes in
4896 * reopen_state
4897 */
53e96d1e 4898static void bdrv_reopen_abort(BDRVReopenState *reopen_state)
e971aa12
JC
4899{
4900 BlockDriver *drv;
4901
4902 assert(reopen_state != NULL);
4903 drv = reopen_state->bs->drv;
4904 assert(drv != NULL);
da359909 4905 GLOBAL_STATE_CODE();
e971aa12
JC
4906
4907 if (drv->bdrv_reopen_abort) {
4908 drv->bdrv_reopen_abort(reopen_state);
4909 }
4910}
4911
4912
64dff520 4913static void bdrv_close(BlockDriverState *bs)
fc01f7e7 4914{
33384421 4915 BdrvAioNotifier *ban, *ban_next;
50a3efb0 4916 BdrvChild *child, *next;
33384421 4917
f791bf7f 4918 GLOBAL_STATE_CODE();
30f55fb8 4919 assert(!bs->refcnt);
99b7e775 4920
fc27291d 4921 bdrv_drained_begin(bs); /* complete I/O */
58fda173 4922 bdrv_flush(bs);
53ec73e2 4923 bdrv_drain(bs); /* in case flush left pending I/O */
fc27291d 4924
3cbc002c 4925 if (bs->drv) {
3c005293 4926 if (bs->drv->bdrv_close) {
7b99a266 4927 /* Must unfreeze all children, so bdrv_unref_child() works */
3c005293
VSO
4928 bs->drv->bdrv_close(bs);
4929 }
9a4f4c31 4930 bs->drv = NULL;
50a3efb0 4931 }
9a7dedbc 4932
50a3efb0 4933 QLIST_FOREACH_SAFE(child, &bs->children, next, next) {
dd4118c7 4934 bdrv_unref_child(bs, child);
b338082b 4935 }
98f90dba 4936
5bb04747
VSO
4937 assert(!bs->backing);
4938 assert(!bs->file);
50a3efb0
AG
4939 g_free(bs->opaque);
4940 bs->opaque = NULL;
d73415a3 4941 qatomic_set(&bs->copy_on_read, 0);
50a3efb0
AG
4942 bs->backing_file[0] = '\0';
4943 bs->backing_format[0] = '\0';
4944 bs->total_sectors = 0;
4945 bs->encrypted = false;
4946 bs->sg = false;
cb3e7f08
MAL
4947 qobject_unref(bs->options);
4948 qobject_unref(bs->explicit_options);
50a3efb0
AG
4949 bs->options = NULL;
4950 bs->explicit_options = NULL;
cb3e7f08 4951 qobject_unref(bs->full_open_options);
50a3efb0 4952 bs->full_open_options = NULL;
0bc329fb
HR
4953 g_free(bs->block_status_cache);
4954 bs->block_status_cache = NULL;
50a3efb0 4955
cca43ae1
VSO
4956 bdrv_release_named_dirty_bitmaps(bs);
4957 assert(QLIST_EMPTY(&bs->dirty_bitmaps));
4958
33384421
HR
4959 QLIST_FOREACH_SAFE(ban, &bs->aio_notifiers, list, ban_next) {
4960 g_free(ban);
4961 }
4962 QLIST_INIT(&bs->aio_notifiers);
fc27291d 4963 bdrv_drained_end(bs);
1a6d3bd2
GK
4964
4965 /*
4966 * If we're still inside some bdrv_drain_all_begin()/end() sections, end
4967 * them now since this BDS won't exist anymore when bdrv_drain_all_end()
4968 * gets called.
4969 */
4970 if (bs->quiesce_counter) {
4971 bdrv_drain_all_end_quiesce(bs);
4972 }
b338082b
FB
4973}
4974
2bc93fed
MK
4975void bdrv_close_all(void)
4976{
f791bf7f 4977 GLOBAL_STATE_CODE();
880eeec6 4978 assert(job_next(NULL) == NULL);
ca9bd24c
HR
4979
4980 /* Drop references from requests still in flight, such as canceled block
4981 * jobs whose AIO context has not been polled yet */
4982 bdrv_drain_all();
2bc93fed 4983
ca9bd24c
HR
4984 blk_remove_all_bs();
4985 blockdev_close_all_bdrv_states();
ed78cda3 4986
a1a2af07 4987 assert(QTAILQ_EMPTY(&all_bdrv_states));
2bc93fed
MK
4988}
4989
d0ac0380
KW
4990static bool should_update_child(BdrvChild *c, BlockDriverState *to)
4991{
2f30b7c3
VSO
4992 GQueue *queue;
4993 GHashTable *found;
4994 bool ret;
d0ac0380 4995
bd86fb99 4996 if (c->klass->stay_at_node) {
d0ac0380
KW
4997 return false;
4998 }
4999
ec9f10fe
HR
5000 /* If the child @c belongs to the BDS @to, replacing the current
5001 * c->bs by @to would mean to create a loop.
5002 *
5003 * Such a case occurs when appending a BDS to a backing chain.
5004 * For instance, imagine the following chain:
5005 *
5006 * guest device -> node A -> further backing chain...
5007 *
5008 * Now we create a new BDS B which we want to put on top of this
5009 * chain, so we first attach A as its backing node:
5010 *
5011 * node B
5012 * |
5013 * v
5014 * guest device -> node A -> further backing chain...
5015 *
5016 * Finally we want to replace A by B. When doing that, we want to
5017 * replace all pointers to A by pointers to B -- except for the
5018 * pointer from B because (1) that would create a loop, and (2)
5019 * that pointer should simply stay intact:
5020 *
5021 * guest device -> node B
5022 * |
5023 * v
5024 * node A -> further backing chain...
5025 *
5026 * In general, when replacing a node A (c->bs) by a node B (@to),
5027 * if A is a child of B, that means we cannot replace A by B there
5028 * because that would create a loop. Silently detaching A from B
5029 * is also not really an option. So overall just leaving A in
2f30b7c3
VSO
5030 * place there is the most sensible choice.
5031 *
5032 * We would also create a loop in any cases where @c is only
5033 * indirectly referenced by @to. Prevent this by returning false
5034 * if @c is found (by breadth-first search) anywhere in the whole
5035 * subtree of @to.
5036 */
5037
5038 ret = true;
5039 found = g_hash_table_new(NULL, NULL);
5040 g_hash_table_add(found, to);
5041 queue = g_queue_new();
5042 g_queue_push_tail(queue, to);
5043
5044 while (!g_queue_is_empty(queue)) {
5045 BlockDriverState *v = g_queue_pop_head(queue);
5046 BdrvChild *c2;
5047
5048 QLIST_FOREACH(c2, &v->children, next) {
5049 if (c2 == c) {
5050 ret = false;
5051 break;
5052 }
5053
5054 if (g_hash_table_contains(found, c2->bs)) {
5055 continue;
5056 }
5057
5058 g_queue_push_tail(queue, c2->bs);
5059 g_hash_table_add(found, c2->bs);
d0ac0380
KW
5060 }
5061 }
5062
2f30b7c3
VSO
5063 g_queue_free(queue);
5064 g_hash_table_destroy(found);
5065
5066 return ret;
d0ac0380
KW
5067}
5068
57f08941 5069static void bdrv_remove_child_commit(void *opaque)
46541ee5 5070{
bdb73476 5071 GLOBAL_STATE_CODE();
5bb04747 5072 bdrv_child_free(opaque);
82b54cf5
HR
5073}
5074
57f08941
VSO
5075static TransactionActionDrv bdrv_remove_child_drv = {
5076 .commit = bdrv_remove_child_commit,
46541ee5
VSO
5077};
5078
57f08941
VSO
5079/* Function doesn't update permissions, caller is responsible for this. */
5080static void bdrv_remove_child(BdrvChild *child, Transaction *tran)
46541ee5 5081{
46541ee5
VSO
5082 if (!child) {
5083 return;
5084 }
5085
5086 if (child->bs) {
a2c37a30 5087 bdrv_replace_child_tran(child, NULL, tran);
46541ee5
VSO
5088 }
5089
57f08941 5090 tran_add(tran, &bdrv_remove_child_drv, child);
46541ee5
VSO
5091}
5092
117caba9
VSO
5093static int bdrv_replace_node_noperm(BlockDriverState *from,
5094 BlockDriverState *to,
5095 bool auto_skip, Transaction *tran,
5096 Error **errp)
5097{
5098 BdrvChild *c, *next;
5099
bdb73476 5100 GLOBAL_STATE_CODE();
82b54cf5 5101
117caba9
VSO
5102 QLIST_FOREACH_SAFE(c, &from->parents, next_parent, next) {
5103 assert(c->bs == from);
5104 if (!should_update_child(c, to)) {
5105 if (auto_skip) {
5106 continue;
5107 }
5108 error_setg(errp, "Should not change '%s' link to '%s'",
5109 c->name, from->node_name);
5110 return -EINVAL;
5111 }
5112 if (c->frozen) {
5113 error_setg(errp, "Cannot change '%s' link to '%s'",
5114 c->name, from->node_name);
5115 return -EPERM;
5116 }
0f0b1e29 5117 bdrv_replace_child_tran(c, to, tran);
117caba9
VSO
5118 }
5119
5120 return 0;
5121}
5122
313274bb
VSO
5123/*
5124 * With auto_skip=true bdrv_replace_node_common skips updating from parents
5125 * if it creates a parent-child relation loop or if parent is block-job.
5126 *
5127 * With auto_skip=false the error is returned if from has a parent which should
5128 * not be updated.
3108a15c
VSO
5129 *
5130 * With @detach_subchain=true @to must be in a backing chain of @from. In this
5131 * case backing link of the cow-parent of @to is removed.
313274bb 5132 */
a1e708fc
VSO
5133static int bdrv_replace_node_common(BlockDriverState *from,
5134 BlockDriverState *to,
3108a15c
VSO
5135 bool auto_skip, bool detach_subchain,
5136 Error **errp)
dd62f1ca 5137{
3bb0e298 5138 Transaction *tran = tran_new();
3bb0e298 5139 g_autoptr(GSList) refresh_list = NULL;
2d369d6e 5140 BlockDriverState *to_cow_parent = NULL;
234ac1a9
KW
5141 int ret;
5142
bdb73476 5143 GLOBAL_STATE_CODE();
82b54cf5 5144
3108a15c
VSO
5145 if (detach_subchain) {
5146 assert(bdrv_chain_contains(from, to));
5147 assert(from != to);
5148 for (to_cow_parent = from;
5149 bdrv_filter_or_cow_bs(to_cow_parent) != to;
5150 to_cow_parent = bdrv_filter_or_cow_bs(to_cow_parent))
5151 {
5152 ;
5153 }
5154 }
5155
234ac1a9
KW
5156 /* Make sure that @from doesn't go away until we have successfully attached
5157 * all of its parents to @to. */
5158 bdrv_ref(from);
dd62f1ca 5159
f871abd6 5160 assert(qemu_get_current_aio_context() == qemu_get_aio_context());
30dd65f3 5161 assert(bdrv_get_aio_context(from) == bdrv_get_aio_context(to));
f871abd6
KW
5162 bdrv_drained_begin(from);
5163
3bb0e298
VSO
5164 /*
5165 * Do the replacement without permission update.
5166 * Replacement may influence the permissions, we should calculate new
5167 * permissions based on new graph. If we fail, we'll roll-back the
5168 * replacement.
5169 */
117caba9
VSO
5170 ret = bdrv_replace_node_noperm(from, to, auto_skip, tran, errp);
5171 if (ret < 0) {
5172 goto out;
234ac1a9
KW
5173 }
5174
3108a15c 5175 if (detach_subchain) {
f38eaec4 5176 bdrv_remove_child(bdrv_filter_or_cow_child(to_cow_parent), tran);
3108a15c
VSO
5177 }
5178
fb0ff4d1
VSO
5179 refresh_list = g_slist_prepend(refresh_list, to);
5180 refresh_list = g_slist_prepend(refresh_list, from);
9bd910e2 5181
3bb0e298
VSO
5182 ret = bdrv_list_refresh_perms(refresh_list, NULL, tran, errp);
5183 if (ret < 0) {
5184 goto out;
dd62f1ca 5185 }
234ac1a9 5186
a1e708fc
VSO
5187 ret = 0;
5188
234ac1a9 5189out:
3bb0e298
VSO
5190 tran_finalize(tran, ret);
5191
f871abd6 5192 bdrv_drained_end(from);
234ac1a9 5193 bdrv_unref(from);
a1e708fc
VSO
5194
5195 return ret;
dd62f1ca
KW
5196}
5197
a1e708fc
VSO
5198int bdrv_replace_node(BlockDriverState *from, BlockDriverState *to,
5199 Error **errp)
313274bb 5200{
f791bf7f
EGE
5201 GLOBAL_STATE_CODE();
5202
3108a15c
VSO
5203 return bdrv_replace_node_common(from, to, true, false, errp);
5204}
5205
5206int bdrv_drop_filter(BlockDriverState *bs, Error **errp)
5207{
f791bf7f
EGE
5208 GLOBAL_STATE_CODE();
5209
3108a15c
VSO
5210 return bdrv_replace_node_common(bs, bdrv_filter_or_cow_bs(bs), true, true,
5211 errp);
313274bb
VSO
5212}
5213
4ddc07ca
PB
5214/*
5215 * Add new bs contents at the top of an image chain while the chain is
5216 * live, while keeping required fields on the top layer.
5217 *
5218 * This will modify the BlockDriverState fields, and swap contents
5219 * between bs_new and bs_top. Both bs_new and bs_top are modified.
5220 *
2272edcf
VSO
5221 * bs_new must not be attached to a BlockBackend and must not have backing
5222 * child.
4ddc07ca
PB
5223 *
5224 * This function does not create any image files.
5225 */
a1e708fc
VSO
5226int bdrv_append(BlockDriverState *bs_new, BlockDriverState *bs_top,
5227 Error **errp)
4ddc07ca 5228{
2272edcf 5229 int ret;
5bb04747 5230 BdrvChild *child;
2272edcf
VSO
5231 Transaction *tran = tran_new();
5232
f791bf7f
EGE
5233 GLOBAL_STATE_CODE();
5234
2272edcf
VSO
5235 assert(!bs_new->backing);
5236
5bb04747
VSO
5237 child = bdrv_attach_child_noperm(bs_new, bs_top, "backing",
5238 &child_of_bds, bdrv_backing_role(bs_new),
5239 tran, errp);
5240 if (!child) {
5241 ret = -EINVAL;
2272edcf 5242 goto out;
b2c2832c 5243 }
dd62f1ca 5244
2272edcf 5245 ret = bdrv_replace_node_noperm(bs_top, bs_new, true, tran, errp);
a1e708fc 5246 if (ret < 0) {
2272edcf 5247 goto out;
234ac1a9 5248 }
4ddc07ca 5249
f1316edb 5250 ret = bdrv_refresh_perms(bs_new, tran, errp);
2272edcf
VSO
5251out:
5252 tran_finalize(tran, ret);
5253
1e4c797c 5254 bdrv_refresh_limits(bs_top, NULL, NULL);
2272edcf
VSO
5255
5256 return ret;
8802d1fd
JC
5257}
5258
bd8f4c42
VSO
5259/* Not for empty child */
5260int bdrv_replace_child_bs(BdrvChild *child, BlockDriverState *new_bs,
5261 Error **errp)
5262{
5263 int ret;
5264 Transaction *tran = tran_new();
bd8f4c42
VSO
5265 g_autoptr(GSList) refresh_list = NULL;
5266 BlockDriverState *old_bs = child->bs;
5267
f791bf7f
EGE
5268 GLOBAL_STATE_CODE();
5269
bd8f4c42
VSO
5270 bdrv_ref(old_bs);
5271 bdrv_drained_begin(old_bs);
5272 bdrv_drained_begin(new_bs);
5273
0f0b1e29 5274 bdrv_replace_child_tran(child, new_bs, tran);
bd8f4c42 5275
fb0ff4d1
VSO
5276 refresh_list = g_slist_prepend(refresh_list, old_bs);
5277 refresh_list = g_slist_prepend(refresh_list, new_bs);
bd8f4c42
VSO
5278
5279 ret = bdrv_list_refresh_perms(refresh_list, NULL, tran, errp);
5280
5281 tran_finalize(tran, ret);
5282
5283 bdrv_drained_end(old_bs);
5284 bdrv_drained_end(new_bs);
5285 bdrv_unref(old_bs);
5286
5287 return ret;
5288}
5289
4f6fd349 5290static void bdrv_delete(BlockDriverState *bs)
b338082b 5291{
3718d8ab 5292 assert(bdrv_op_blocker_is_empty(bs));
4f6fd349 5293 assert(!bs->refcnt);
f791bf7f 5294 GLOBAL_STATE_CODE();
18846dee 5295
1b7bdbc1 5296 /* remove from list, if necessary */
63eaaae0
KW
5297 if (bs->node_name[0] != '\0') {
5298 QTAILQ_REMOVE(&graph_bdrv_states, bs, node_list);
5299 }
2c1d04e0
HR
5300 QTAILQ_REMOVE(&all_bdrv_states, bs, bs_list);
5301
30c321f9
AK
5302 bdrv_close(bs);
5303
7267c094 5304 g_free(bs);
fc01f7e7
FB
5305}
5306
96796fae
VSO
5307
5308/*
5309 * Replace @bs by newly created block node.
5310 *
5311 * @options is a QDict of options to pass to the block drivers, or NULL for an
5312 * empty set of options. The reference to the QDict belongs to the block layer
5313 * after the call (even on failure), so if the caller intends to reuse the
5314 * dictionary, it needs to use qobject_ref() before calling bdrv_open.
5315 */
5316BlockDriverState *bdrv_insert_node(BlockDriverState *bs, QDict *options,
8872ef78
AS
5317 int flags, Error **errp)
5318{
f053b7e8
VSO
5319 ERRP_GUARD();
5320 int ret;
b11c8739
VSO
5321 BlockDriverState *new_node_bs = NULL;
5322 const char *drvname, *node_name;
5323 BlockDriver *drv;
5324
5325 drvname = qdict_get_try_str(options, "driver");
5326 if (!drvname) {
5327 error_setg(errp, "driver is not specified");
5328 goto fail;
5329 }
5330
5331 drv = bdrv_find_format(drvname);
5332 if (!drv) {
5333 error_setg(errp, "Unknown driver: '%s'", drvname);
5334 goto fail;
5335 }
8872ef78 5336
b11c8739
VSO
5337 node_name = qdict_get_try_str(options, "node-name");
5338
f791bf7f
EGE
5339 GLOBAL_STATE_CODE();
5340
b11c8739
VSO
5341 new_node_bs = bdrv_new_open_driver_opts(drv, node_name, options, flags,
5342 errp);
5343 options = NULL; /* bdrv_new_open_driver() eats options */
5344 if (!new_node_bs) {
8872ef78 5345 error_prepend(errp, "Could not create node: ");
b11c8739 5346 goto fail;
8872ef78
AS
5347 }
5348
5349 bdrv_drained_begin(bs);
f053b7e8 5350 ret = bdrv_replace_node(bs, new_node_bs, errp);
8872ef78
AS
5351 bdrv_drained_end(bs);
5352
f053b7e8
VSO
5353 if (ret < 0) {
5354 error_prepend(errp, "Could not replace node: ");
b11c8739 5355 goto fail;
8872ef78
AS
5356 }
5357
5358 return new_node_bs;
b11c8739
VSO
5359
5360fail:
5361 qobject_unref(options);
5362 bdrv_unref(new_node_bs);
5363 return NULL;
8872ef78
AS
5364}
5365
e97fc193
AL
5366/*
5367 * Run consistency checks on an image
5368 *
e076f338 5369 * Returns 0 if the check could be completed (it doesn't mean that the image is
a1c7273b 5370 * free of errors) or -errno when an internal error occurred. The results of the
e076f338 5371 * check are stored in res.
e97fc193 5372 */
21c2283e
VSO
5373int coroutine_fn bdrv_co_check(BlockDriverState *bs,
5374 BdrvCheckResult *res, BdrvCheckMode fix)
e97fc193 5375{
1581a70d 5376 IO_CODE();
908bcd54
HR
5377 if (bs->drv == NULL) {
5378 return -ENOMEDIUM;
5379 }
2fd61638 5380 if (bs->drv->bdrv_co_check == NULL) {
e97fc193
AL
5381 return -ENOTSUP;
5382 }
5383
e076f338 5384 memset(res, 0, sizeof(*res));
2fd61638
PB
5385 return bs->drv->bdrv_co_check(bs, res, fix);
5386}
5387
756e6736
KW
5388/*
5389 * Return values:
5390 * 0 - success
5391 * -EINVAL - backing format specified, but no file
5392 * -ENOSPC - can't update the backing file because no space is left in the
5393 * image file header
5394 * -ENOTSUP - format driver doesn't support changing the backing file
5395 */
e54ee1b3 5396int bdrv_change_backing_file(BlockDriverState *bs, const char *backing_file,
497a30db 5397 const char *backing_fmt, bool require)
756e6736
KW
5398{
5399 BlockDriver *drv = bs->drv;
469ef350 5400 int ret;
756e6736 5401
f791bf7f
EGE
5402 GLOBAL_STATE_CODE();
5403
d470ad42
HR
5404 if (!drv) {
5405 return -ENOMEDIUM;
5406 }
5407
5f377794
PB
5408 /* Backing file format doesn't make sense without a backing file */
5409 if (backing_fmt && !backing_file) {
5410 return -EINVAL;
5411 }
5412
497a30db
EB
5413 if (require && backing_file && !backing_fmt) {
5414 return -EINVAL;
e54ee1b3
EB
5415 }
5416
756e6736 5417 if (drv->bdrv_change_backing_file != NULL) {
469ef350 5418 ret = drv->bdrv_change_backing_file(bs, backing_file, backing_fmt);
756e6736 5419 } else {
469ef350 5420 ret = -ENOTSUP;
756e6736 5421 }
469ef350
PB
5422
5423 if (ret == 0) {
5424 pstrcpy(bs->backing_file, sizeof(bs->backing_file), backing_file ?: "");
5425 pstrcpy(bs->backing_format, sizeof(bs->backing_format), backing_fmt ?: "");
998c2019
HR
5426 pstrcpy(bs->auto_backing_file, sizeof(bs->auto_backing_file),
5427 backing_file ?: "");
469ef350
PB
5428 }
5429 return ret;
756e6736
KW
5430}
5431
6ebdcee2 5432/*
dcf3f9b2
HR
5433 * Finds the first non-filter node above bs in the chain between
5434 * active and bs. The returned node is either an immediate parent of
5435 * bs, or there are only filter nodes between the two.
6ebdcee2
JC
5436 *
5437 * Returns NULL if bs is not found in active's image chain,
5438 * or if active == bs.
4caf0fcd
JC
5439 *
5440 * Returns the bottommost base image if bs == NULL.
6ebdcee2
JC
5441 */
5442BlockDriverState *bdrv_find_overlay(BlockDriverState *active,
5443 BlockDriverState *bs)
5444{
f791bf7f
EGE
5445
5446 GLOBAL_STATE_CODE();
5447
dcf3f9b2
HR
5448 bs = bdrv_skip_filters(bs);
5449 active = bdrv_skip_filters(active);
5450
5451 while (active) {
5452 BlockDriverState *next = bdrv_backing_chain_next(active);
5453 if (bs == next) {
5454 return active;
5455 }
5456 active = next;
6ebdcee2
JC
5457 }
5458
dcf3f9b2 5459 return NULL;
4caf0fcd 5460}
6ebdcee2 5461
4caf0fcd
JC
5462/* Given a BDS, searches for the base layer. */
5463BlockDriverState *bdrv_find_base(BlockDriverState *bs)
5464{
f791bf7f
EGE
5465 GLOBAL_STATE_CODE();
5466
4caf0fcd 5467 return bdrv_find_overlay(bs, NULL);
6ebdcee2
JC
5468}
5469
2cad1ebe 5470/*
7b99a266
HR
5471 * Return true if at least one of the COW (backing) and filter links
5472 * between @bs and @base is frozen. @errp is set if that's the case.
0f0998f6 5473 * @base must be reachable from @bs, or NULL.
2cad1ebe
AG
5474 */
5475bool bdrv_is_backing_chain_frozen(BlockDriverState *bs, BlockDriverState *base,
5476 Error **errp)
5477{
5478 BlockDriverState *i;
7b99a266 5479 BdrvChild *child;
2cad1ebe 5480
f791bf7f
EGE
5481 GLOBAL_STATE_CODE();
5482
7b99a266
HR
5483 for (i = bs; i != base; i = child_bs(child)) {
5484 child = bdrv_filter_or_cow_child(i);
5485
5486 if (child && child->frozen) {
2cad1ebe 5487 error_setg(errp, "Cannot change '%s' link from '%s' to '%s'",
7b99a266 5488 child->name, i->node_name, child->bs->node_name);
2cad1ebe
AG
5489 return true;
5490 }
5491 }
5492
5493 return false;
5494}
5495
5496/*
7b99a266 5497 * Freeze all COW (backing) and filter links between @bs and @base.
2cad1ebe
AG
5498 * If any of the links is already frozen the operation is aborted and
5499 * none of the links are modified.
0f0998f6 5500 * @base must be reachable from @bs, or NULL.
2cad1ebe
AG
5501 * Returns 0 on success. On failure returns < 0 and sets @errp.
5502 */
5503int bdrv_freeze_backing_chain(BlockDriverState *bs, BlockDriverState *base,
5504 Error **errp)
5505{
5506 BlockDriverState *i;
7b99a266 5507 BdrvChild *child;
2cad1ebe 5508
f791bf7f
EGE
5509 GLOBAL_STATE_CODE();
5510
2cad1ebe
AG
5511 if (bdrv_is_backing_chain_frozen(bs, base, errp)) {
5512 return -EPERM;
5513 }
5514
7b99a266
HR
5515 for (i = bs; i != base; i = child_bs(child)) {
5516 child = bdrv_filter_or_cow_child(i);
5517 if (child && child->bs->never_freeze) {
e5182c1c 5518 error_setg(errp, "Cannot freeze '%s' link to '%s'",
7b99a266 5519 child->name, child->bs->node_name);
e5182c1c
HR
5520 return -EPERM;
5521 }
5522 }
5523
7b99a266
HR
5524 for (i = bs; i != base; i = child_bs(child)) {
5525 child = bdrv_filter_or_cow_child(i);
5526 if (child) {
5527 child->frozen = true;
0f0998f6 5528 }
2cad1ebe
AG
5529 }
5530
5531 return 0;
5532}
5533
5534/*
7b99a266
HR
5535 * Unfreeze all COW (backing) and filter links between @bs and @base.
5536 * The caller must ensure that all links are frozen before using this
5537 * function.
0f0998f6 5538 * @base must be reachable from @bs, or NULL.
2cad1ebe
AG
5539 */
5540void bdrv_unfreeze_backing_chain(BlockDriverState *bs, BlockDriverState *base)
5541{
5542 BlockDriverState *i;
7b99a266 5543 BdrvChild *child;
2cad1ebe 5544
f791bf7f
EGE
5545 GLOBAL_STATE_CODE();
5546
7b99a266
HR
5547 for (i = bs; i != base; i = child_bs(child)) {
5548 child = bdrv_filter_or_cow_child(i);
5549 if (child) {
5550 assert(child->frozen);
5551 child->frozen = false;
0f0998f6 5552 }
2cad1ebe
AG
5553 }
5554}
5555
6ebdcee2
JC
5556/*
5557 * Drops images above 'base' up to and including 'top', and sets the image
5558 * above 'top' to have base as its backing file.
5559 *
5560 * Requires that the overlay to 'top' is opened r/w, so that the backing file
5561 * information in 'bs' can be properly updated.
5562 *
5563 * E.g., this will convert the following chain:
5564 * bottom <- base <- intermediate <- top <- active
5565 *
5566 * to
5567 *
5568 * bottom <- base <- active
5569 *
5570 * It is allowed for bottom==base, in which case it converts:
5571 *
5572 * base <- intermediate <- top <- active
5573 *
5574 * to
5575 *
5576 * base <- active
5577 *
54e26900
JC
5578 * If backing_file_str is non-NULL, it will be used when modifying top's
5579 * overlay image metadata.
5580 *
6ebdcee2
JC
5581 * Error conditions:
5582 * if active == top, that is considered an error
5583 *
5584 */
bde70715
KW
5585int bdrv_drop_intermediate(BlockDriverState *top, BlockDriverState *base,
5586 const char *backing_file_str)
6ebdcee2 5587{
6bd858b3
AG
5588 BlockDriverState *explicit_top = top;
5589 bool update_inherits_from;
d669ed6a 5590 BdrvChild *c;
12fa4af6 5591 Error *local_err = NULL;
6ebdcee2 5592 int ret = -EIO;
d669ed6a
VSO
5593 g_autoptr(GSList) updated_children = NULL;
5594 GSList *p;
6ebdcee2 5595
f791bf7f
EGE
5596 GLOBAL_STATE_CODE();
5597
6858eba0 5598 bdrv_ref(top);
637d54a5 5599 bdrv_subtree_drained_begin(top);
6858eba0 5600
6ebdcee2
JC
5601 if (!top->drv || !base->drv) {
5602 goto exit;
5603 }
5604
5db15a57
KW
5605 /* Make sure that base is in the backing chain of top */
5606 if (!bdrv_chain_contains(top, base)) {
6ebdcee2
JC
5607 goto exit;
5608 }
5609
6bd858b3
AG
5610 /* If 'base' recursively inherits from 'top' then we should set
5611 * base->inherits_from to top->inherits_from after 'top' and all
5612 * other intermediate nodes have been dropped.
5613 * If 'top' is an implicit node (e.g. "commit_top") we should skip
5614 * it because no one inherits from it. We use explicit_top for that. */
dcf3f9b2 5615 explicit_top = bdrv_skip_implicit_filters(explicit_top);
6bd858b3
AG
5616 update_inherits_from = bdrv_inherits_from_recursive(base, explicit_top);
5617
6ebdcee2 5618 /* success - we can delete the intermediate states, and link top->base */
f30c66ba
HR
5619 if (!backing_file_str) {
5620 bdrv_refresh_filename(base);
5621 backing_file_str = base->filename;
5622 }
61f09cea 5623
d669ed6a
VSO
5624 QLIST_FOREACH(c, &top->parents, next_parent) {
5625 updated_children = g_slist_prepend(updated_children, c);
5626 }
5627
3108a15c
VSO
5628 /*
5629 * It seems correct to pass detach_subchain=true here, but it triggers
5630 * one more yet not fixed bug, when due to nested aio_poll loop we switch to
5631 * another drained section, which modify the graph (for example, removing
5632 * the child, which we keep in updated_children list). So, it's a TODO.
5633 *
5634 * Note, bug triggered if pass detach_subchain=true here and run
5635 * test-bdrv-drain. test_drop_intermediate_poll() test-case will crash.
5636 * That's a FIXME.
5637 */
5638 bdrv_replace_node_common(top, base, false, false, &local_err);
d669ed6a
VSO
5639 if (local_err) {
5640 error_report_err(local_err);
5641 goto exit;
5642 }
5643
5644 for (p = updated_children; p; p = p->next) {
5645 c = p->data;
12fa4af6 5646
bd86fb99
HR
5647 if (c->klass->update_filename) {
5648 ret = c->klass->update_filename(c, base, backing_file_str,
5649 &local_err);
61f09cea 5650 if (ret < 0) {
d669ed6a
VSO
5651 /*
5652 * TODO: Actually, we want to rollback all previous iterations
5653 * of this loop, and (which is almost impossible) previous
5654 * bdrv_replace_node()...
5655 *
5656 * Note, that c->klass->update_filename may lead to permission
5657 * update, so it's a bad idea to call it inside permission
5658 * update transaction of bdrv_replace_node.
5659 */
61f09cea
KW
5660 error_report_err(local_err);
5661 goto exit;
5662 }
5663 }
12fa4af6 5664 }
6ebdcee2 5665
6bd858b3
AG
5666 if (update_inherits_from) {
5667 base->inherits_from = explicit_top->inherits_from;
5668 }
5669
6ebdcee2 5670 ret = 0;
6ebdcee2 5671exit:
637d54a5 5672 bdrv_subtree_drained_end(top);
6858eba0 5673 bdrv_unref(top);
6ebdcee2
JC
5674 return ret;
5675}
5676
081e4650
HR
5677/**
5678 * Implementation of BlockDriver.bdrv_get_allocated_file_size() that
5679 * sums the size of all data-bearing children. (This excludes backing
5680 * children.)
5681 */
5682static int64_t bdrv_sum_allocated_file_size(BlockDriverState *bs)
5683{
5684 BdrvChild *child;
5685 int64_t child_size, sum = 0;
5686
5687 QLIST_FOREACH(child, &bs->children, next) {
5688 if (child->role & (BDRV_CHILD_DATA | BDRV_CHILD_METADATA |
5689 BDRV_CHILD_FILTERED))
5690 {
5691 child_size = bdrv_get_allocated_file_size(child->bs);
5692 if (child_size < 0) {
5693 return child_size;
5694 }
5695 sum += child_size;
5696 }
5697 }
5698
5699 return sum;
5700}
5701
61007b31
SH
5702/**
5703 * Length of a allocated file in bytes. Sparse files are counted by actual
5704 * allocated space. Return < 0 if error or unknown.
5705 */
5706int64_t bdrv_get_allocated_file_size(BlockDriverState *bs)
71d0770c 5707{
61007b31 5708 BlockDriver *drv = bs->drv;
384a48fb
EGE
5709 IO_CODE();
5710
61007b31
SH
5711 if (!drv) {
5712 return -ENOMEDIUM;
8f4754ed 5713 }
61007b31
SH
5714 if (drv->bdrv_get_allocated_file_size) {
5715 return drv->bdrv_get_allocated_file_size(bs);
5716 }
081e4650
HR
5717
5718 if (drv->bdrv_file_open) {
5719 /*
5720 * Protocol drivers default to -ENOTSUP (most of their data is
5721 * not stored in any of their children (if they even have any),
5722 * so there is no generic way to figure it out).
5723 */
5724 return -ENOTSUP;
5725 } else if (drv->is_filter) {
5726 /* Filter drivers default to the size of their filtered child */
5727 return bdrv_get_allocated_file_size(bdrv_filter_bs(bs));
5728 } else {
5729 /* Other drivers default to summing their children's sizes */
5730 return bdrv_sum_allocated_file_size(bs);
1c9805a3
SH
5731 }
5732}
e7a8a783 5733
90880ff1
SH
5734/*
5735 * bdrv_measure:
5736 * @drv: Format driver
5737 * @opts: Creation options for new image
5738 * @in_bs: Existing image containing data for new image (may be NULL)
5739 * @errp: Error object
5740 * Returns: A #BlockMeasureInfo (free using qapi_free_BlockMeasureInfo())
5741 * or NULL on error
5742 *
5743 * Calculate file size required to create a new image.
5744 *
5745 * If @in_bs is given then space for allocated clusters and zero clusters
5746 * from that image are included in the calculation. If @opts contains a
5747 * backing file that is shared by @in_bs then backing clusters may be omitted
5748 * from the calculation.
5749 *
5750 * If @in_bs is NULL then the calculation includes no allocated clusters
5751 * unless a preallocation option is given in @opts.
5752 *
5753 * Note that @in_bs may use a different BlockDriver from @drv.
5754 *
5755 * If an error occurs the @errp pointer is set.
5756 */
5757BlockMeasureInfo *bdrv_measure(BlockDriver *drv, QemuOpts *opts,
5758 BlockDriverState *in_bs, Error **errp)
5759{
384a48fb 5760 IO_CODE();
90880ff1
SH
5761 if (!drv->bdrv_measure) {
5762 error_setg(errp, "Block driver '%s' does not support size measurement",
5763 drv->format_name);
5764 return NULL;
5765 }
5766
5767 return drv->bdrv_measure(opts, in_bs, errp);
5768}
5769
61007b31
SH
5770/**
5771 * Return number of sectors on success, -errno on error.
1c9805a3 5772 */
61007b31 5773int64_t bdrv_nb_sectors(BlockDriverState *bs)
1c9805a3 5774{
61007b31 5775 BlockDriver *drv = bs->drv;
384a48fb 5776 IO_CODE();
498e386c 5777
61007b31
SH
5778 if (!drv)
5779 return -ENOMEDIUM;
2572b37a 5780
61007b31
SH
5781 if (drv->has_variable_length) {
5782 int ret = refresh_total_sectors(bs, bs->total_sectors);
5783 if (ret < 0) {
5784 return ret;
1c9805a3
SH
5785 }
5786 }
61007b31 5787 return bs->total_sectors;
1c9805a3 5788}
b338082b 5789
61007b31
SH
5790/**
5791 * Return length in bytes on success, -errno on error.
5792 * The length is always a multiple of BDRV_SECTOR_SIZE.
8d3b1a2d 5793 */
61007b31 5794int64_t bdrv_getlength(BlockDriverState *bs)
8d3b1a2d 5795{
61007b31 5796 int64_t ret = bdrv_nb_sectors(bs);
384a48fb 5797 IO_CODE();
8d3b1a2d 5798
122860ba
EB
5799 if (ret < 0) {
5800 return ret;
5801 }
5802 if (ret > INT64_MAX / BDRV_SECTOR_SIZE) {
5803 return -EFBIG;
5804 }
5805 return ret * BDRV_SECTOR_SIZE;
fc01f7e7
FB
5806}
5807
61007b31
SH
5808/* return 0 as number of sectors if no device present or error */
5809void bdrv_get_geometry(BlockDriverState *bs, uint64_t *nb_sectors_ptr)
07d27a44 5810{
61007b31 5811 int64_t nb_sectors = bdrv_nb_sectors(bs);
384a48fb 5812 IO_CODE();
07d27a44 5813
61007b31 5814 *nb_sectors_ptr = nb_sectors < 0 ? 0 : nb_sectors;
07d27a44
MA
5815}
5816
54115412 5817bool bdrv_is_sg(BlockDriverState *bs)
f08145fe 5818{
384a48fb 5819 IO_CODE();
61007b31 5820 return bs->sg;
f08145fe
KW
5821}
5822
ae23f786
HR
5823/**
5824 * Return whether the given node supports compressed writes.
5825 */
5826bool bdrv_supports_compressed_writes(BlockDriverState *bs)
5827{
5828 BlockDriverState *filtered;
384a48fb 5829 IO_CODE();
ae23f786
HR
5830
5831 if (!bs->drv || !block_driver_can_compress(bs->drv)) {
5832 return false;
5833 }
5834
5835 filtered = bdrv_filter_bs(bs);
5836 if (filtered) {
5837 /*
5838 * Filters can only forward compressed writes, so we have to
5839 * check the child.
5840 */
5841 return bdrv_supports_compressed_writes(filtered);
5842 }
5843
5844 return true;
5845}
5846
61007b31 5847const char *bdrv_get_format_name(BlockDriverState *bs)
40b4f539 5848{
384a48fb 5849 IO_CODE();
61007b31 5850 return bs->drv ? bs->drv->format_name : NULL;
40b4f539
KW
5851}
5852
61007b31 5853static int qsort_strcmp(const void *a, const void *b)
40b4f539 5854{
ceff5bd7 5855 return strcmp(*(char *const *)a, *(char *const *)b);
40b4f539
KW
5856}
5857
61007b31 5858void bdrv_iterate_format(void (*it)(void *opaque, const char *name),
9ac404c5 5859 void *opaque, bool read_only)
40b4f539 5860{
61007b31
SH
5861 BlockDriver *drv;
5862 int count = 0;
5863 int i;
5864 const char **formats = NULL;
40b4f539 5865
f791bf7f
EGE
5866 GLOBAL_STATE_CODE();
5867
61007b31
SH
5868 QLIST_FOREACH(drv, &bdrv_drivers, list) {
5869 if (drv->format_name) {
5870 bool found = false;
5871 int i = count;
9ac404c5
AS
5872
5873 if (use_bdrv_whitelist && !bdrv_is_whitelisted(drv, read_only)) {
5874 continue;
5875 }
5876
61007b31
SH
5877 while (formats && i && !found) {
5878 found = !strcmp(formats[--i], drv->format_name);
5879 }
e2a305fb 5880
61007b31
SH
5881 if (!found) {
5882 formats = g_renew(const char *, formats, count + 1);
5883 formats[count++] = drv->format_name;
5884 }
6c5a42ac 5885 }
61007b31 5886 }
6c5a42ac 5887
eb0df69f
HR
5888 for (i = 0; i < (int)ARRAY_SIZE(block_driver_modules); i++) {
5889 const char *format_name = block_driver_modules[i].format_name;
5890
5891 if (format_name) {
5892 bool found = false;
5893 int j = count;
5894
9ac404c5
AS
5895 if (use_bdrv_whitelist &&
5896 !bdrv_format_is_whitelisted(format_name, read_only)) {
5897 continue;
5898 }
5899
eb0df69f
HR
5900 while (formats && j && !found) {
5901 found = !strcmp(formats[--j], format_name);
5902 }
5903
5904 if (!found) {
5905 formats = g_renew(const char *, formats, count + 1);
5906 formats[count++] = format_name;
5907 }
5908 }
5909 }
5910
61007b31 5911 qsort(formats, count, sizeof(formats[0]), qsort_strcmp);
40b4f539 5912
61007b31
SH
5913 for (i = 0; i < count; i++) {
5914 it(opaque, formats[i]);
5915 }
40b4f539 5916
61007b31
SH
5917 g_free(formats);
5918}
40b4f539 5919
61007b31
SH
5920/* This function is to find a node in the bs graph */
5921BlockDriverState *bdrv_find_node(const char *node_name)
5922{
5923 BlockDriverState *bs;
391827eb 5924
61007b31 5925 assert(node_name);
f791bf7f 5926 GLOBAL_STATE_CODE();
40b4f539 5927
61007b31
SH
5928 QTAILQ_FOREACH(bs, &graph_bdrv_states, node_list) {
5929 if (!strcmp(node_name, bs->node_name)) {
5930 return bs;
40b4f539
KW
5931 }
5932 }
61007b31 5933 return NULL;
40b4f539
KW
5934}
5935
61007b31 5936/* Put this QMP function here so it can access the static graph_bdrv_states. */
facda544
PK
5937BlockDeviceInfoList *bdrv_named_nodes_list(bool flat,
5938 Error **errp)
40b4f539 5939{
9812e712 5940 BlockDeviceInfoList *list;
61007b31 5941 BlockDriverState *bs;
40b4f539 5942
f791bf7f
EGE
5943 GLOBAL_STATE_CODE();
5944
61007b31
SH
5945 list = NULL;
5946 QTAILQ_FOREACH(bs, &graph_bdrv_states, node_list) {
facda544 5947 BlockDeviceInfo *info = bdrv_block_device_info(NULL, bs, flat, errp);
61007b31
SH
5948 if (!info) {
5949 qapi_free_BlockDeviceInfoList(list);
5950 return NULL;
301db7c2 5951 }
9812e712 5952 QAPI_LIST_PREPEND(list, info);
301db7c2
RH
5953 }
5954
61007b31
SH
5955 return list;
5956}
40b4f539 5957
5d3b4e99
VSO
5958typedef struct XDbgBlockGraphConstructor {
5959 XDbgBlockGraph *graph;
5960 GHashTable *graph_nodes;
5961} XDbgBlockGraphConstructor;
5962
5963static XDbgBlockGraphConstructor *xdbg_graph_new(void)
5964{
5965 XDbgBlockGraphConstructor *gr = g_new(XDbgBlockGraphConstructor, 1);
5966
5967 gr->graph = g_new0(XDbgBlockGraph, 1);
5968 gr->graph_nodes = g_hash_table_new(NULL, NULL);
5969
5970 return gr;
5971}
5972
5973static XDbgBlockGraph *xdbg_graph_finalize(XDbgBlockGraphConstructor *gr)
5974{
5975 XDbgBlockGraph *graph = gr->graph;
5976
5977 g_hash_table_destroy(gr->graph_nodes);
5978 g_free(gr);
5979
5980 return graph;
5981}
5982
5983static uintptr_t xdbg_graph_node_num(XDbgBlockGraphConstructor *gr, void *node)
5984{
5985 uintptr_t ret = (uintptr_t)g_hash_table_lookup(gr->graph_nodes, node);
5986
5987 if (ret != 0) {
5988 return ret;
5989 }
5990
5991 /*
5992 * Start counting from 1, not 0, because 0 interferes with not-found (NULL)
5993 * answer of g_hash_table_lookup.
5994 */
5995 ret = g_hash_table_size(gr->graph_nodes) + 1;
5996 g_hash_table_insert(gr->graph_nodes, node, (void *)ret);
5997
5998 return ret;
5999}
6000
6001static void xdbg_graph_add_node(XDbgBlockGraphConstructor *gr, void *node,
6002 XDbgBlockGraphNodeType type, const char *name)
6003{
6004 XDbgBlockGraphNode *n;
6005
6006 n = g_new0(XDbgBlockGraphNode, 1);
6007
6008 n->id = xdbg_graph_node_num(gr, node);
6009 n->type = type;
6010 n->name = g_strdup(name);
6011
9812e712 6012 QAPI_LIST_PREPEND(gr->graph->nodes, n);
5d3b4e99
VSO
6013}
6014
6015static void xdbg_graph_add_edge(XDbgBlockGraphConstructor *gr, void *parent,
6016 const BdrvChild *child)
6017{
cdb1cec8 6018 BlockPermission qapi_perm;
5d3b4e99 6019 XDbgBlockGraphEdge *edge;
862fded9 6020 GLOBAL_STATE_CODE();
5d3b4e99 6021
5d3b4e99
VSO
6022 edge = g_new0(XDbgBlockGraphEdge, 1);
6023
6024 edge->parent = xdbg_graph_node_num(gr, parent);
6025 edge->child = xdbg_graph_node_num(gr, child->bs);
6026 edge->name = g_strdup(child->name);
6027
cdb1cec8
HR
6028 for (qapi_perm = 0; qapi_perm < BLOCK_PERMISSION__MAX; qapi_perm++) {
6029 uint64_t flag = bdrv_qapi_perm_to_blk_perm(qapi_perm);
6030
6031 if (flag & child->perm) {
9812e712 6032 QAPI_LIST_PREPEND(edge->perm, qapi_perm);
5d3b4e99 6033 }
cdb1cec8 6034 if (flag & child->shared_perm) {
9812e712 6035 QAPI_LIST_PREPEND(edge->shared_perm, qapi_perm);
5d3b4e99
VSO
6036 }
6037 }
6038
9812e712 6039 QAPI_LIST_PREPEND(gr->graph->edges, edge);
5d3b4e99
VSO
6040}
6041
6042
6043XDbgBlockGraph *bdrv_get_xdbg_block_graph(Error **errp)
6044{
6045 BlockBackend *blk;
6046 BlockJob *job;
6047 BlockDriverState *bs;
6048 BdrvChild *child;
6049 XDbgBlockGraphConstructor *gr = xdbg_graph_new();
6050
f791bf7f
EGE
6051 GLOBAL_STATE_CODE();
6052
5d3b4e99
VSO
6053 for (blk = blk_all_next(NULL); blk; blk = blk_all_next(blk)) {
6054 char *allocated_name = NULL;
6055 const char *name = blk_name(blk);
6056
6057 if (!*name) {
6058 name = allocated_name = blk_get_attached_dev_id(blk);
6059 }
6060 xdbg_graph_add_node(gr, blk, X_DBG_BLOCK_GRAPH_NODE_TYPE_BLOCK_BACKEND,
6061 name);
6062 g_free(allocated_name);
6063 if (blk_root(blk)) {
6064 xdbg_graph_add_edge(gr, blk, blk_root(blk));
6065 }
6066 }
6067
880eeec6
EGE
6068 WITH_JOB_LOCK_GUARD() {
6069 for (job = block_job_next_locked(NULL); job;
6070 job = block_job_next_locked(job)) {
6071 GSList *el;
5d3b4e99 6072
880eeec6
EGE
6073 xdbg_graph_add_node(gr, job, X_DBG_BLOCK_GRAPH_NODE_TYPE_BLOCK_JOB,
6074 job->job.id);
6075 for (el = job->nodes; el; el = el->next) {
6076 xdbg_graph_add_edge(gr, job, (BdrvChild *)el->data);
6077 }
5d3b4e99
VSO
6078 }
6079 }
6080
6081 QTAILQ_FOREACH(bs, &graph_bdrv_states, node_list) {
6082 xdbg_graph_add_node(gr, bs, X_DBG_BLOCK_GRAPH_NODE_TYPE_BLOCK_DRIVER,
6083 bs->node_name);
6084 QLIST_FOREACH(child, &bs->children, next) {
6085 xdbg_graph_add_edge(gr, bs, child);
6086 }
6087 }
6088
6089 return xdbg_graph_finalize(gr);
6090}
6091
61007b31
SH
6092BlockDriverState *bdrv_lookup_bs(const char *device,
6093 const char *node_name,
6094 Error **errp)
6095{
6096 BlockBackend *blk;
6097 BlockDriverState *bs;
40b4f539 6098
f791bf7f
EGE
6099 GLOBAL_STATE_CODE();
6100
61007b31
SH
6101 if (device) {
6102 blk = blk_by_name(device);
40b4f539 6103
61007b31 6104 if (blk) {
9f4ed6fb
AG
6105 bs = blk_bs(blk);
6106 if (!bs) {
5433c24f 6107 error_setg(errp, "Device '%s' has no medium", device);
5433c24f
HR
6108 }
6109
9f4ed6fb 6110 return bs;
61007b31
SH
6111 }
6112 }
40b4f539 6113
61007b31
SH
6114 if (node_name) {
6115 bs = bdrv_find_node(node_name);
6d519a5f 6116
61007b31
SH
6117 if (bs) {
6118 return bs;
6119 }
40b4f539
KW
6120 }
6121
785ec4b1 6122 error_setg(errp, "Cannot find device=\'%s\' nor node-name=\'%s\'",
61007b31
SH
6123 device ? device : "",
6124 node_name ? node_name : "");
6125 return NULL;
40b4f539
KW
6126}
6127
61007b31
SH
6128/* If 'base' is in the same chain as 'top', return true. Otherwise,
6129 * return false. If either argument is NULL, return false. */
6130bool bdrv_chain_contains(BlockDriverState *top, BlockDriverState *base)
83f64091 6131{
f791bf7f
EGE
6132
6133 GLOBAL_STATE_CODE();
6134
61007b31 6135 while (top && top != base) {
dcf3f9b2 6136 top = bdrv_filter_or_cow_bs(top);
02c50efe 6137 }
61007b31
SH
6138
6139 return top != NULL;
02c50efe
FZ
6140}
6141
61007b31 6142BlockDriverState *bdrv_next_node(BlockDriverState *bs)
02c50efe 6143{
f791bf7f 6144 GLOBAL_STATE_CODE();
61007b31
SH
6145 if (!bs) {
6146 return QTAILQ_FIRST(&graph_bdrv_states);
02c50efe 6147 }
61007b31 6148 return QTAILQ_NEXT(bs, node_list);
83f64091
FB
6149}
6150
0f12264e
KW
6151BlockDriverState *bdrv_next_all_states(BlockDriverState *bs)
6152{
f791bf7f 6153 GLOBAL_STATE_CODE();
0f12264e
KW
6154 if (!bs) {
6155 return QTAILQ_FIRST(&all_bdrv_states);
6156 }
6157 return QTAILQ_NEXT(bs, bs_list);
6158}
6159
61007b31 6160const char *bdrv_get_node_name(const BlockDriverState *bs)
83f64091 6161{
384a48fb 6162 IO_CODE();
61007b31 6163 return bs->node_name;
beac80cd
FB
6164}
6165
1f0c461b 6166const char *bdrv_get_parent_name(const BlockDriverState *bs)
4c265bf9
KW
6167{
6168 BdrvChild *c;
6169 const char *name;
967d7905 6170 IO_CODE();
4c265bf9
KW
6171
6172 /* If multiple parents have a name, just pick the first one. */
6173 QLIST_FOREACH(c, &bs->parents, next_parent) {
bd86fb99
HR
6174 if (c->klass->get_name) {
6175 name = c->klass->get_name(c);
4c265bf9
KW
6176 if (name && *name) {
6177 return name;
6178 }
6179 }
6180 }
6181
6182 return NULL;
6183}
6184
61007b31
SH
6185/* TODO check what callers really want: bs->node_name or blk_name() */
6186const char *bdrv_get_device_name(const BlockDriverState *bs)
beac80cd 6187{
384a48fb 6188 IO_CODE();
4c265bf9 6189 return bdrv_get_parent_name(bs) ?: "";
f141eafe 6190}
83f64091 6191
61007b31
SH
6192/* This can be used to identify nodes that might not have a device
6193 * name associated. Since node and device names live in the same
6194 * namespace, the result is unambiguous. The exception is if both are
6195 * absent, then this returns an empty (non-null) string. */
6196const char *bdrv_get_device_or_node_name(const BlockDriverState *bs)
f141eafe 6197{
384a48fb 6198 IO_CODE();
4c265bf9 6199 return bdrv_get_parent_name(bs) ?: bs->node_name;
beac80cd 6200}
beac80cd 6201
61007b31 6202int bdrv_get_flags(BlockDriverState *bs)
0b5a2445 6203{
15aee7ac 6204 IO_CODE();
61007b31 6205 return bs->open_flags;
0b5a2445
PB
6206}
6207
61007b31 6208int bdrv_has_zero_init_1(BlockDriverState *bs)
68485420 6209{
f791bf7f 6210 GLOBAL_STATE_CODE();
61007b31 6211 return 1;
0b5a2445
PB
6212}
6213
61007b31 6214int bdrv_has_zero_init(BlockDriverState *bs)
0b5a2445 6215{
93393e69 6216 BlockDriverState *filtered;
f791bf7f 6217 GLOBAL_STATE_CODE();
93393e69 6218
d470ad42
HR
6219 if (!bs->drv) {
6220 return 0;
6221 }
0b5a2445 6222
61007b31
SH
6223 /* If BS is a copy on write image, it is initialized to
6224 the contents of the base image, which may not be zeroes. */
34778172 6225 if (bdrv_cow_child(bs)) {
61007b31
SH
6226 return 0;
6227 }
6228 if (bs->drv->bdrv_has_zero_init) {
6229 return bs->drv->bdrv_has_zero_init(bs);
0b5a2445 6230 }
93393e69
HR
6231
6232 filtered = bdrv_filter_bs(bs);
6233 if (filtered) {
6234 return bdrv_has_zero_init(filtered);
5a612c00 6235 }
61007b31
SH
6236
6237 /* safe default */
6238 return 0;
68485420
KW
6239}
6240
61007b31 6241bool bdrv_can_write_zeroes_with_unmap(BlockDriverState *bs)
68485420 6242{
384a48fb 6243 IO_CODE();
2f0342ef 6244 if (!(bs->open_flags & BDRV_O_UNMAP)) {
61007b31
SH
6245 return false;
6246 }
68485420 6247
e24d813b 6248 return bs->supported_zero_flags & BDRV_REQ_MAY_UNMAP;
68485420
KW
6249}
6250
61007b31
SH
6251void bdrv_get_backing_filename(BlockDriverState *bs,
6252 char *filename, int filename_size)
016f5cf6 6253{
384a48fb 6254 IO_CODE();
61007b31
SH
6255 pstrcpy(filename, filename_size, bs->backing_file);
6256}
d318aea9 6257
61007b31
SH
6258int bdrv_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
6259{
8b117001 6260 int ret;
61007b31 6261 BlockDriver *drv = bs->drv;
384a48fb 6262 IO_CODE();
5a612c00
MP
6263 /* if bs->drv == NULL, bs is closed, so there's nothing to do here */
6264 if (!drv) {
61007b31 6265 return -ENOMEDIUM;
5a612c00
MP
6266 }
6267 if (!drv->bdrv_get_info) {
93393e69
HR
6268 BlockDriverState *filtered = bdrv_filter_bs(bs);
6269 if (filtered) {
6270 return bdrv_get_info(filtered, bdi);
5a612c00 6271 }
61007b31 6272 return -ENOTSUP;
5a612c00 6273 }
61007b31 6274 memset(bdi, 0, sizeof(*bdi));
8b117001
VSO
6275 ret = drv->bdrv_get_info(bs, bdi);
6276 if (ret < 0) {
6277 return ret;
6278 }
6279
6280 if (bdi->cluster_size > BDRV_MAX_ALIGNMENT) {
6281 return -EINVAL;
6282 }
6283
6284 return 0;
61007b31 6285}
016f5cf6 6286
1bf6e9ca
AS
6287ImageInfoSpecific *bdrv_get_specific_info(BlockDriverState *bs,
6288 Error **errp)
61007b31
SH
6289{
6290 BlockDriver *drv = bs->drv;
384a48fb 6291 IO_CODE();
61007b31 6292 if (drv && drv->bdrv_get_specific_info) {
1bf6e9ca 6293 return drv->bdrv_get_specific_info(bs, errp);
61007b31
SH
6294 }
6295 return NULL;
016f5cf6
AG
6296}
6297
d9245599
AN
6298BlockStatsSpecific *bdrv_get_specific_stats(BlockDriverState *bs)
6299{
6300 BlockDriver *drv = bs->drv;
384a48fb 6301 IO_CODE();
d9245599
AN
6302 if (!drv || !drv->bdrv_get_specific_stats) {
6303 return NULL;
6304 }
6305 return drv->bdrv_get_specific_stats(bs);
6306}
6307
a31939e6 6308void bdrv_debug_event(BlockDriverState *bs, BlkdebugEvent event)
4265d620 6309{
384a48fb 6310 IO_CODE();
61007b31
SH
6311 if (!bs || !bs->drv || !bs->drv->bdrv_debug_event) {
6312 return;
6313 }
4265d620 6314
61007b31 6315 bs->drv->bdrv_debug_event(bs, event);
4265d620
PB
6316}
6317
d10529a2 6318static BlockDriverState *bdrv_find_debug_node(BlockDriverState *bs)
4265d620 6319{
bdb73476 6320 GLOBAL_STATE_CODE();
61007b31 6321 while (bs && bs->drv && !bs->drv->bdrv_debug_breakpoint) {
f706a92f 6322 bs = bdrv_primary_bs(bs);
61007b31 6323 }
4265d620 6324
61007b31 6325 if (bs && bs->drv && bs->drv->bdrv_debug_breakpoint) {
d10529a2
VSO
6326 assert(bs->drv->bdrv_debug_remove_breakpoint);
6327 return bs;
6328 }
6329
6330 return NULL;
6331}
6332
6333int bdrv_debug_breakpoint(BlockDriverState *bs, const char *event,
6334 const char *tag)
6335{
f791bf7f 6336 GLOBAL_STATE_CODE();
d10529a2
VSO
6337 bs = bdrv_find_debug_node(bs);
6338 if (bs) {
61007b31
SH
6339 return bs->drv->bdrv_debug_breakpoint(bs, event, tag);
6340 }
4265d620 6341
61007b31 6342 return -ENOTSUP;
4265d620
PB
6343}
6344
61007b31 6345int bdrv_debug_remove_breakpoint(BlockDriverState *bs, const char *tag)
ea2384d3 6346{
f791bf7f 6347 GLOBAL_STATE_CODE();
d10529a2
VSO
6348 bs = bdrv_find_debug_node(bs);
6349 if (bs) {
61007b31
SH
6350 return bs->drv->bdrv_debug_remove_breakpoint(bs, tag);
6351 }
6352
6353 return -ENOTSUP;
eb852011
MA
6354}
6355
61007b31 6356int bdrv_debug_resume(BlockDriverState *bs, const char *tag)
ce1a14dc 6357{
f791bf7f 6358 GLOBAL_STATE_CODE();
61007b31 6359 while (bs && (!bs->drv || !bs->drv->bdrv_debug_resume)) {
f706a92f 6360 bs = bdrv_primary_bs(bs);
61007b31 6361 }
ce1a14dc 6362
61007b31
SH
6363 if (bs && bs->drv && bs->drv->bdrv_debug_resume) {
6364 return bs->drv->bdrv_debug_resume(bs, tag);
6365 }
ce1a14dc 6366
61007b31 6367 return -ENOTSUP;
f197fe2b
FZ
6368}
6369
61007b31 6370bool bdrv_debug_is_suspended(BlockDriverState *bs, const char *tag)
ce1a14dc 6371{
f791bf7f 6372 GLOBAL_STATE_CODE();
61007b31 6373 while (bs && bs->drv && !bs->drv->bdrv_debug_is_suspended) {
f706a92f 6374 bs = bdrv_primary_bs(bs);
f197fe2b 6375 }
19cb3738 6376
61007b31
SH
6377 if (bs && bs->drv && bs->drv->bdrv_debug_is_suspended) {
6378 return bs->drv->bdrv_debug_is_suspended(bs, tag);
6379 }
f9f05dc5 6380
61007b31
SH
6381 return false;
6382}
f9f05dc5 6383
61007b31
SH
6384/* backing_file can either be relative, or absolute, or a protocol. If it is
6385 * relative, it must be relative to the chain. So, passing in bs->filename
6386 * from a BDS as backing_file should not be done, as that may be relative to
6387 * the CWD rather than the chain. */
6388BlockDriverState *bdrv_find_backing_image(BlockDriverState *bs,
6389 const char *backing_file)
f9f05dc5 6390{
61007b31
SH
6391 char *filename_full = NULL;
6392 char *backing_file_full = NULL;
6393 char *filename_tmp = NULL;
6394 int is_protocol = 0;
0b877d09 6395 bool filenames_refreshed = false;
61007b31
SH
6396 BlockDriverState *curr_bs = NULL;
6397 BlockDriverState *retval = NULL;
dcf3f9b2 6398 BlockDriverState *bs_below;
f9f05dc5 6399
f791bf7f
EGE
6400 GLOBAL_STATE_CODE();
6401
61007b31
SH
6402 if (!bs || !bs->drv || !backing_file) {
6403 return NULL;
f9f05dc5
KW
6404 }
6405
61007b31
SH
6406 filename_full = g_malloc(PATH_MAX);
6407 backing_file_full = g_malloc(PATH_MAX);
f9f05dc5 6408
61007b31 6409 is_protocol = path_has_protocol(backing_file);
f9f05dc5 6410
dcf3f9b2
HR
6411 /*
6412 * Being largely a legacy function, skip any filters here
6413 * (because filters do not have normal filenames, so they cannot
6414 * match anyway; and allowing json:{} filenames is a bit out of
6415 * scope).
6416 */
6417 for (curr_bs = bdrv_skip_filters(bs);
6418 bdrv_cow_child(curr_bs) != NULL;
6419 curr_bs = bs_below)
6420 {
6421 bs_below = bdrv_backing_chain_next(curr_bs);
f9f05dc5 6422
0b877d09
HR
6423 if (bdrv_backing_overridden(curr_bs)) {
6424 /*
6425 * If the backing file was overridden, we can only compare
6426 * directly against the backing node's filename.
6427 */
6428
6429 if (!filenames_refreshed) {
6430 /*
6431 * This will automatically refresh all of the
6432 * filenames in the rest of the backing chain, so we
6433 * only need to do this once.
6434 */
6435 bdrv_refresh_filename(bs_below);
6436 filenames_refreshed = true;
6437 }
6438
6439 if (strcmp(backing_file, bs_below->filename) == 0) {
6440 retval = bs_below;
6441 break;
6442 }
6443 } else if (is_protocol || path_has_protocol(curr_bs->backing_file)) {
6444 /*
6445 * If either of the filename paths is actually a protocol, then
6446 * compare unmodified paths; otherwise make paths relative.
6447 */
6b6833c1
HR
6448 char *backing_file_full_ret;
6449
61007b31 6450 if (strcmp(backing_file, curr_bs->backing_file) == 0) {
dcf3f9b2 6451 retval = bs_below;
61007b31
SH
6452 break;
6453 }
418661e0 6454 /* Also check against the full backing filename for the image */
6b6833c1
HR
6455 backing_file_full_ret = bdrv_get_full_backing_filename(curr_bs,
6456 NULL);
6457 if (backing_file_full_ret) {
6458 bool equal = strcmp(backing_file, backing_file_full_ret) == 0;
6459 g_free(backing_file_full_ret);
6460 if (equal) {
dcf3f9b2 6461 retval = bs_below;
418661e0
JC
6462 break;
6463 }
418661e0 6464 }
61007b31
SH
6465 } else {
6466 /* If not an absolute filename path, make it relative to the current
6467 * image's filename path */
2d9158ce
HR
6468 filename_tmp = bdrv_make_absolute_filename(curr_bs, backing_file,
6469 NULL);
6470 /* We are going to compare canonicalized absolute pathnames */
6471 if (!filename_tmp || !realpath(filename_tmp, filename_full)) {
6472 g_free(filename_tmp);
61007b31
SH
6473 continue;
6474 }
2d9158ce 6475 g_free(filename_tmp);
07f07615 6476
61007b31
SH
6477 /* We need to make sure the backing filename we are comparing against
6478 * is relative to the current image filename (or absolute) */
2d9158ce
HR
6479 filename_tmp = bdrv_get_full_backing_filename(curr_bs, NULL);
6480 if (!filename_tmp || !realpath(filename_tmp, backing_file_full)) {
6481 g_free(filename_tmp);
61007b31
SH
6482 continue;
6483 }
2d9158ce 6484 g_free(filename_tmp);
eb489bb1 6485
61007b31 6486 if (strcmp(backing_file_full, filename_full) == 0) {
dcf3f9b2 6487 retval = bs_below;
61007b31
SH
6488 break;
6489 }
6490 }
eb489bb1
KW
6491 }
6492
61007b31
SH
6493 g_free(filename_full);
6494 g_free(backing_file_full);
61007b31
SH
6495 return retval;
6496}
6497
61007b31
SH
6498void bdrv_init(void)
6499{
e5f05f8c
KW
6500#ifdef CONFIG_BDRV_WHITELIST_TOOLS
6501 use_bdrv_whitelist = 1;
6502#endif
61007b31
SH
6503 module_call_init(MODULE_INIT_BLOCK);
6504}
29cdb251 6505
61007b31
SH
6506void bdrv_init_with_whitelist(void)
6507{
6508 use_bdrv_whitelist = 1;
6509 bdrv_init();
07f07615
PB
6510}
6511
a94750d9 6512int bdrv_activate(BlockDriverState *bs, Error **errp)
0f15423c 6513{
4417ab7a 6514 BdrvChild *child, *parent;
5a8a30db
KW
6515 Error *local_err = NULL;
6516 int ret;
9c98f145 6517 BdrvDirtyBitmap *bm;
5a8a30db 6518
f791bf7f
EGE
6519 GLOBAL_STATE_CODE();
6520
3456a8d1 6521 if (!bs->drv) {
5416645f 6522 return -ENOMEDIUM;
3456a8d1
KW
6523 }
6524
16e977d5 6525 QLIST_FOREACH(child, &bs->children, next) {
11d0c9b3 6526 bdrv_activate(child->bs, &local_err);
0d1c5c91 6527 if (local_err) {
0d1c5c91 6528 error_propagate(errp, local_err);
5416645f 6529 return -EINVAL;
0d1c5c91 6530 }
5a8a30db 6531 }
0d1c5c91 6532
dafe0960
KW
6533 /*
6534 * Update permissions, they may differ for inactive nodes.
6535 *
6536 * Note that the required permissions of inactive images are always a
6537 * subset of the permissions required after activating the image. This
6538 * allows us to just get the permissions upfront without restricting
11d0c9b3 6539 * bdrv_co_invalidate_cache().
dafe0960
KW
6540 *
6541 * It also means that in error cases, we don't have to try and revert to
6542 * the old permissions (which is an operation that could fail, too). We can
6543 * just keep the extended permissions for the next time that an activation
6544 * of the image is tried.
6545 */
7bb4941a
KW
6546 if (bs->open_flags & BDRV_O_INACTIVE) {
6547 bs->open_flags &= ~BDRV_O_INACTIVE;
f1316edb 6548 ret = bdrv_refresh_perms(bs, NULL, errp);
7bb4941a 6549 if (ret < 0) {
0d1c5c91 6550 bs->open_flags |= BDRV_O_INACTIVE;
5416645f 6551 return ret;
0d1c5c91 6552 }
3456a8d1 6553
11d0c9b3
EGE
6554 ret = bdrv_invalidate_cache(bs, errp);
6555 if (ret < 0) {
6556 bs->open_flags |= BDRV_O_INACTIVE;
6557 return ret;
7bb4941a 6558 }
9c98f145 6559
7bb4941a
KW
6560 FOR_EACH_DIRTY_BITMAP(bs, bm) {
6561 bdrv_dirty_bitmap_skip_store(bm, false);
6562 }
6563
6564 ret = refresh_total_sectors(bs, bs->total_sectors);
6565 if (ret < 0) {
6566 bs->open_flags |= BDRV_O_INACTIVE;
6567 error_setg_errno(errp, -ret, "Could not refresh total sector count");
5416645f 6568 return ret;
7bb4941a 6569 }
5a8a30db 6570 }
4417ab7a
KW
6571
6572 QLIST_FOREACH(parent, &bs->parents, next_parent) {
bd86fb99
HR
6573 if (parent->klass->activate) {
6574 parent->klass->activate(parent, &local_err);
4417ab7a 6575 if (local_err) {
78fc3b3a 6576 bs->open_flags |= BDRV_O_INACTIVE;
4417ab7a 6577 error_propagate(errp, local_err);
5416645f 6578 return -EINVAL;
4417ab7a
KW
6579 }
6580 }
6581 }
5416645f
VSO
6582
6583 return 0;
0f15423c
AL
6584}
6585
11d0c9b3
EGE
6586int coroutine_fn bdrv_co_invalidate_cache(BlockDriverState *bs, Error **errp)
6587{
6588 Error *local_err = NULL;
1581a70d 6589 IO_CODE();
11d0c9b3
EGE
6590
6591 assert(!(bs->open_flags & BDRV_O_INACTIVE));
6592
6593 if (bs->drv->bdrv_co_invalidate_cache) {
6594 bs->drv->bdrv_co_invalidate_cache(bs, &local_err);
6595 if (local_err) {
6596 error_propagate(errp, local_err);
6597 return -EINVAL;
6598 }
6599 }
6600
6601 return 0;
6602}
6603
3b717194 6604void bdrv_activate_all(Error **errp)
0f15423c 6605{
7c8eece4 6606 BlockDriverState *bs;
88be7b4b 6607 BdrvNextIterator it;
0f15423c 6608
f791bf7f
EGE
6609 GLOBAL_STATE_CODE();
6610
88be7b4b 6611 for (bs = bdrv_first(&it); bs; bs = bdrv_next(&it)) {
ed78cda3 6612 AioContext *aio_context = bdrv_get_aio_context(bs);
5416645f 6613 int ret;
ed78cda3
SH
6614
6615 aio_context_acquire(aio_context);
a94750d9 6616 ret = bdrv_activate(bs, errp);
ed78cda3 6617 aio_context_release(aio_context);
5416645f 6618 if (ret < 0) {
5e003f17 6619 bdrv_next_cleanup(&it);
5a8a30db
KW
6620 return;
6621 }
0f15423c
AL
6622 }
6623}
6624
9e37271f
KW
6625static bool bdrv_has_bds_parent(BlockDriverState *bs, bool only_active)
6626{
6627 BdrvChild *parent;
bdb73476 6628 GLOBAL_STATE_CODE();
9e37271f
KW
6629
6630 QLIST_FOREACH(parent, &bs->parents, next_parent) {
bd86fb99 6631 if (parent->klass->parent_is_bds) {
9e37271f
KW
6632 BlockDriverState *parent_bs = parent->opaque;
6633 if (!only_active || !(parent_bs->open_flags & BDRV_O_INACTIVE)) {
6634 return true;
6635 }
6636 }
6637 }
6638
6639 return false;
6640}
6641
6642static int bdrv_inactivate_recurse(BlockDriverState *bs)
76b1c7fe 6643{
cfa1a572 6644 BdrvChild *child, *parent;
76b1c7fe 6645 int ret;
a13de40a 6646 uint64_t cumulative_perms, cumulative_shared_perms;
76b1c7fe 6647
da359909
EGE
6648 GLOBAL_STATE_CODE();
6649
d470ad42
HR
6650 if (!bs->drv) {
6651 return -ENOMEDIUM;
6652 }
6653
9e37271f
KW
6654 /* Make sure that we don't inactivate a child before its parent.
6655 * It will be covered by recursion from the yet active parent. */
6656 if (bdrv_has_bds_parent(bs, true)) {
6657 return 0;
6658 }
6659
6660 assert(!(bs->open_flags & BDRV_O_INACTIVE));
6661
6662 /* Inactivate this node */
6663 if (bs->drv->bdrv_inactivate) {
76b1c7fe
KW
6664 ret = bs->drv->bdrv_inactivate(bs);
6665 if (ret < 0) {
6666 return ret;
6667 }
6668 }
6669
9e37271f 6670 QLIST_FOREACH(parent, &bs->parents, next_parent) {
bd86fb99
HR
6671 if (parent->klass->inactivate) {
6672 ret = parent->klass->inactivate(parent);
9e37271f
KW
6673 if (ret < 0) {
6674 return ret;
cfa1a572
KW
6675 }
6676 }
9e37271f 6677 }
9c5e6594 6678
a13de40a
VSO
6679 bdrv_get_cumulative_perm(bs, &cumulative_perms,
6680 &cumulative_shared_perms);
6681 if (cumulative_perms & (BLK_PERM_WRITE | BLK_PERM_WRITE_UNCHANGED)) {
6682 /* Our inactive parents still need write access. Inactivation failed. */
6683 return -EPERM;
6684 }
6685
9e37271f 6686 bs->open_flags |= BDRV_O_INACTIVE;
7d5b5261 6687
bb87e4d1
VSO
6688 /*
6689 * Update permissions, they may differ for inactive nodes.
6690 * We only tried to loosen restrictions, so errors are not fatal, ignore
6691 * them.
6692 */
f1316edb 6693 bdrv_refresh_perms(bs, NULL, NULL);
9e37271f
KW
6694
6695 /* Recursively inactivate children */
38701b6a 6696 QLIST_FOREACH(child, &bs->children, next) {
9e37271f 6697 ret = bdrv_inactivate_recurse(child->bs);
38701b6a
KW
6698 if (ret < 0) {
6699 return ret;
6700 }
6701 }
6702
76b1c7fe
KW
6703 return 0;
6704}
6705
6706int bdrv_inactivate_all(void)
6707{
79720af6 6708 BlockDriverState *bs = NULL;
88be7b4b 6709 BdrvNextIterator it;
aad0b7a0 6710 int ret = 0;
bd6458e4 6711 GSList *aio_ctxs = NULL, *ctx;
76b1c7fe 6712
f791bf7f
EGE
6713 GLOBAL_STATE_CODE();
6714
88be7b4b 6715 for (bs = bdrv_first(&it); bs; bs = bdrv_next(&it)) {
bd6458e4
PB
6716 AioContext *aio_context = bdrv_get_aio_context(bs);
6717
6718 if (!g_slist_find(aio_ctxs, aio_context)) {
6719 aio_ctxs = g_slist_prepend(aio_ctxs, aio_context);
6720 aio_context_acquire(aio_context);
6721 }
aad0b7a0 6722 }
76b1c7fe 6723
9e37271f
KW
6724 for (bs = bdrv_first(&it); bs; bs = bdrv_next(&it)) {
6725 /* Nodes with BDS parents are covered by recursion from the last
6726 * parent that gets inactivated. Don't inactivate them a second
6727 * time if that has already happened. */
6728 if (bdrv_has_bds_parent(bs, false)) {
6729 continue;
6730 }
6731 ret = bdrv_inactivate_recurse(bs);
6732 if (ret < 0) {
6733 bdrv_next_cleanup(&it);
6734 goto out;
76b1c7fe
KW
6735 }
6736 }
6737
aad0b7a0 6738out:
bd6458e4
PB
6739 for (ctx = aio_ctxs; ctx != NULL; ctx = ctx->next) {
6740 AioContext *aio_context = ctx->data;
6741 aio_context_release(aio_context);
aad0b7a0 6742 }
bd6458e4 6743 g_slist_free(aio_ctxs);
aad0b7a0
FZ
6744
6745 return ret;
76b1c7fe
KW
6746}
6747
19cb3738
FB
6748/**************************************************************/
6749/* removable device support */
6750
6751/**
6752 * Return TRUE if the media is present
6753 */
e031f750 6754bool bdrv_is_inserted(BlockDriverState *bs)
19cb3738
FB
6755{
6756 BlockDriver *drv = bs->drv;
28d7a789 6757 BdrvChild *child;
384a48fb 6758 IO_CODE();
a1aff5bf 6759
e031f750
HR
6760 if (!drv) {
6761 return false;
6762 }
28d7a789
HR
6763 if (drv->bdrv_is_inserted) {
6764 return drv->bdrv_is_inserted(bs);
6765 }
6766 QLIST_FOREACH(child, &bs->children, next) {
6767 if (!bdrv_is_inserted(child->bs)) {
6768 return false;
6769 }
e031f750 6770 }
28d7a789 6771 return true;
19cb3738
FB
6772}
6773
19cb3738
FB
6774/**
6775 * If eject_flag is TRUE, eject the media. Otherwise, close the tray
6776 */
f36f3949 6777void bdrv_eject(BlockDriverState *bs, bool eject_flag)
19cb3738
FB
6778{
6779 BlockDriver *drv = bs->drv;
384a48fb 6780 IO_CODE();
19cb3738 6781
822e1cd1
MA
6782 if (drv && drv->bdrv_eject) {
6783 drv->bdrv_eject(bs, eject_flag);
19cb3738
FB
6784 }
6785}
6786
19cb3738
FB
6787/**
6788 * Lock or unlock the media (if it is locked, the user won't be able
6789 * to eject it manually).
6790 */
025e849a 6791void bdrv_lock_medium(BlockDriverState *bs, bool locked)
19cb3738
FB
6792{
6793 BlockDriver *drv = bs->drv;
384a48fb 6794 IO_CODE();
025e849a 6795 trace_bdrv_lock_medium(bs, locked);
b8c6d095 6796
025e849a
MA
6797 if (drv && drv->bdrv_lock_medium) {
6798 drv->bdrv_lock_medium(bs, locked);
19cb3738
FB
6799 }
6800}
985a03b0 6801
9fcb0251
FZ
6802/* Get a reference to bs */
6803void bdrv_ref(BlockDriverState *bs)
6804{
f791bf7f 6805 GLOBAL_STATE_CODE();
9fcb0251
FZ
6806 bs->refcnt++;
6807}
6808
6809/* Release a previously grabbed reference to bs.
6810 * If after releasing, reference count is zero, the BlockDriverState is
6811 * deleted. */
6812void bdrv_unref(BlockDriverState *bs)
6813{
f791bf7f 6814 GLOBAL_STATE_CODE();
9a4d5ca6
JC
6815 if (!bs) {
6816 return;
6817 }
9fcb0251
FZ
6818 assert(bs->refcnt > 0);
6819 if (--bs->refcnt == 0) {
6820 bdrv_delete(bs);
6821 }
6822}
6823
fbe40ff7
FZ
6824struct BdrvOpBlocker {
6825 Error *reason;
6826 QLIST_ENTRY(BdrvOpBlocker) list;
6827};
6828
6829bool bdrv_op_is_blocked(BlockDriverState *bs, BlockOpType op, Error **errp)
6830{
6831 BdrvOpBlocker *blocker;
f791bf7f 6832 GLOBAL_STATE_CODE();
fbe40ff7
FZ
6833 assert((int) op >= 0 && op < BLOCK_OP_TYPE_MAX);
6834 if (!QLIST_EMPTY(&bs->op_blockers[op])) {
6835 blocker = QLIST_FIRST(&bs->op_blockers[op]);
4b576648
MA
6836 error_propagate_prepend(errp, error_copy(blocker->reason),
6837 "Node '%s' is busy: ",
6838 bdrv_get_device_or_node_name(bs));
fbe40ff7
FZ
6839 return true;
6840 }
6841 return false;
6842}
6843
6844void bdrv_op_block(BlockDriverState *bs, BlockOpType op, Error *reason)
6845{
6846 BdrvOpBlocker *blocker;
f791bf7f 6847 GLOBAL_STATE_CODE();
fbe40ff7
FZ
6848 assert((int) op >= 0 && op < BLOCK_OP_TYPE_MAX);
6849
5839e53b 6850 blocker = g_new0(BdrvOpBlocker, 1);
fbe40ff7
FZ
6851 blocker->reason = reason;
6852 QLIST_INSERT_HEAD(&bs->op_blockers[op], blocker, list);
6853}
6854
6855void bdrv_op_unblock(BlockDriverState *bs, BlockOpType op, Error *reason)
6856{
6857 BdrvOpBlocker *blocker, *next;
f791bf7f 6858 GLOBAL_STATE_CODE();
fbe40ff7
FZ
6859 assert((int) op >= 0 && op < BLOCK_OP_TYPE_MAX);
6860 QLIST_FOREACH_SAFE(blocker, &bs->op_blockers[op], list, next) {
6861 if (blocker->reason == reason) {
6862 QLIST_REMOVE(blocker, list);
6863 g_free(blocker);
6864 }
6865 }
6866}
6867
6868void bdrv_op_block_all(BlockDriverState *bs, Error *reason)
6869{
6870 int i;
f791bf7f 6871 GLOBAL_STATE_CODE();
fbe40ff7
FZ
6872 for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
6873 bdrv_op_block(bs, i, reason);
6874 }
6875}
6876
6877void bdrv_op_unblock_all(BlockDriverState *bs, Error *reason)
6878{
6879 int i;
f791bf7f 6880 GLOBAL_STATE_CODE();
fbe40ff7
FZ
6881 for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
6882 bdrv_op_unblock(bs, i, reason);
6883 }
6884}
6885
6886bool bdrv_op_blocker_is_empty(BlockDriverState *bs)
6887{
6888 int i;
f791bf7f 6889 GLOBAL_STATE_CODE();
fbe40ff7
FZ
6890 for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
6891 if (!QLIST_EMPTY(&bs->op_blockers[i])) {
6892 return false;
6893 }
6894 }
6895 return true;
6896}
6897
d92ada22
LC
6898void bdrv_img_create(const char *filename, const char *fmt,
6899 const char *base_filename, const char *base_fmt,
9217283d
FZ
6900 char *options, uint64_t img_size, int flags, bool quiet,
6901 Error **errp)
f88e1a42 6902{
83d0521a
CL
6903 QemuOptsList *create_opts = NULL;
6904 QemuOpts *opts = NULL;
6905 const char *backing_fmt, *backing_file;
6906 int64_t size;
f88e1a42 6907 BlockDriver *drv, *proto_drv;
cc84d90f 6908 Error *local_err = NULL;
f88e1a42
JS
6909 int ret = 0;
6910
f791bf7f
EGE
6911 GLOBAL_STATE_CODE();
6912
f88e1a42
JS
6913 /* Find driver and parse its options */
6914 drv = bdrv_find_format(fmt);
6915 if (!drv) {
71c79813 6916 error_setg(errp, "Unknown file format '%s'", fmt);
d92ada22 6917 return;
f88e1a42
JS
6918 }
6919
b65a5e12 6920 proto_drv = bdrv_find_protocol(filename, true, errp);
f88e1a42 6921 if (!proto_drv) {
d92ada22 6922 return;
f88e1a42
JS
6923 }
6924
c6149724
HR
6925 if (!drv->create_opts) {
6926 error_setg(errp, "Format driver '%s' does not support image creation",
6927 drv->format_name);
6928 return;
6929 }
6930
5a5e7f8c
ML
6931 if (!proto_drv->create_opts) {
6932 error_setg(errp, "Protocol driver '%s' does not support image creation",
6933 proto_drv->format_name);
6934 return;
6935 }
6936
f6dc1c31 6937 /* Create parameter list */
c282e1fd 6938 create_opts = qemu_opts_append(create_opts, drv->create_opts);
5a5e7f8c 6939 create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
f88e1a42 6940
83d0521a 6941 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
f88e1a42
JS
6942
6943 /* Parse -o options */
6944 if (options) {
a5f9b9df 6945 if (!qemu_opts_do_parse(opts, options, NULL, errp)) {
f88e1a42
JS
6946 goto out;
6947 }
6948 }
6949
f6dc1c31
KW
6950 if (!qemu_opt_get(opts, BLOCK_OPT_SIZE)) {
6951 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, img_size, &error_abort);
6952 } else if (img_size != UINT64_C(-1)) {
6953 error_setg(errp, "The image size must be specified only once");
6954 goto out;
6955 }
6956
f88e1a42 6957 if (base_filename) {
235e59cf 6958 if (!qemu_opt_set(opts, BLOCK_OPT_BACKING_FILE, base_filename,
3882578b 6959 NULL)) {
71c79813
LC
6960 error_setg(errp, "Backing file not supported for file format '%s'",
6961 fmt);
f88e1a42
JS
6962 goto out;
6963 }
6964 }
6965
6966 if (base_fmt) {
3882578b 6967 if (!qemu_opt_set(opts, BLOCK_OPT_BACKING_FMT, base_fmt, NULL)) {
71c79813
LC
6968 error_setg(errp, "Backing file format not supported for file "
6969 "format '%s'", fmt);
f88e1a42
JS
6970 goto out;
6971 }
6972 }
6973
83d0521a
CL
6974 backing_file = qemu_opt_get(opts, BLOCK_OPT_BACKING_FILE);
6975 if (backing_file) {
6976 if (!strcmp(filename, backing_file)) {
71c79813
LC
6977 error_setg(errp, "Error: Trying to create an image with the "
6978 "same filename as the backing file");
792da93a
JS
6979 goto out;
6980 }
975a7bd2
CK
6981 if (backing_file[0] == '\0') {
6982 error_setg(errp, "Expected backing file name, got empty string");
6983 goto out;
6984 }
792da93a
JS
6985 }
6986
83d0521a 6987 backing_fmt = qemu_opt_get(opts, BLOCK_OPT_BACKING_FMT);
f88e1a42 6988
6e6e55f5
JS
6989 /* The size for the image must always be specified, unless we have a backing
6990 * file and we have not been forbidden from opening it. */
a8b42a1c 6991 size = qemu_opt_get_size(opts, BLOCK_OPT_SIZE, img_size);
6e6e55f5
JS
6992 if (backing_file && !(flags & BDRV_O_NO_BACKING)) {
6993 BlockDriverState *bs;
645ae7d8 6994 char *full_backing;
6e6e55f5
JS
6995 int back_flags;
6996 QDict *backing_options = NULL;
6997
645ae7d8
HR
6998 full_backing =
6999 bdrv_get_full_backing_filename_from_filename(filename, backing_file,
7000 &local_err);
6e6e55f5 7001 if (local_err) {
6e6e55f5
JS
7002 goto out;
7003 }
645ae7d8 7004 assert(full_backing);
29168018 7005
d5b23994
HR
7006 /*
7007 * No need to do I/O here, which allows us to open encrypted
7008 * backing images without needing the secret
7009 */
6e6e55f5
JS
7010 back_flags = flags;
7011 back_flags &= ~(BDRV_O_RDWR | BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING);
d5b23994 7012 back_flags |= BDRV_O_NO_IO;
f88e1a42 7013
cc954f01 7014 backing_options = qdict_new();
6e6e55f5 7015 if (backing_fmt) {
6e6e55f5
JS
7016 qdict_put_str(backing_options, "driver", backing_fmt);
7017 }
cc954f01 7018 qdict_put_bool(backing_options, BDRV_OPT_FORCE_SHARE, true);
e6641719 7019
6e6e55f5
JS
7020 bs = bdrv_open(full_backing, NULL, backing_options, back_flags,
7021 &local_err);
7022 g_free(full_backing);
add8200d
EB
7023 if (!bs) {
7024 error_append_hint(&local_err, "Could not open backing image.\n");
6e6e55f5
JS
7025 goto out;
7026 } else {
d9f059aa 7027 if (!backing_fmt) {
497a30db
EB
7028 error_setg(&local_err,
7029 "Backing file specified without backing format");
7030 error_append_hint(&local_err, "Detected format of %s.",
7031 bs->drv->format_name);
7032 goto out;
d9f059aa 7033 }
6e6e55f5
JS
7034 if (size == -1) {
7035 /* Opened BS, have no size */
7036 size = bdrv_getlength(bs);
7037 if (size < 0) {
7038 error_setg_errno(errp, -size, "Could not get size of '%s'",
7039 backing_file);
7040 bdrv_unref(bs);
7041 goto out;
7042 }
7043 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, size, &error_abort);
52bf1e72 7044 }
66f6b814 7045 bdrv_unref(bs);
f88e1a42 7046 }
d9f059aa
EB
7047 /* (backing_file && !(flags & BDRV_O_NO_BACKING)) */
7048 } else if (backing_file && !backing_fmt) {
497a30db
EB
7049 error_setg(&local_err,
7050 "Backing file specified without backing format");
7051 goto out;
d9f059aa 7052 }
6e6e55f5
JS
7053
7054 if (size == -1) {
7055 error_setg(errp, "Image creation needs a size parameter");
7056 goto out;
f88e1a42
JS
7057 }
7058
f382d43a 7059 if (!quiet) {
fe646693 7060 printf("Formatting '%s', fmt=%s ", filename, fmt);
43c5d8f8 7061 qemu_opts_print(opts, " ");
f382d43a 7062 puts("");
4e2f4418 7063 fflush(stdout);
f382d43a 7064 }
83d0521a 7065
c282e1fd 7066 ret = bdrv_create(drv, filename, opts, &local_err);
83d0521a 7067
cc84d90f
HR
7068 if (ret == -EFBIG) {
7069 /* This is generally a better message than whatever the driver would
7070 * deliver (especially because of the cluster_size_hint), since that
7071 * is most probably not much different from "image too large". */
7072 const char *cluster_size_hint = "";
83d0521a 7073 if (qemu_opt_get_size(opts, BLOCK_OPT_CLUSTER_SIZE, 0)) {
cc84d90f 7074 cluster_size_hint = " (try using a larger cluster size)";
f88e1a42 7075 }
cc84d90f
HR
7076 error_setg(errp, "The image size is too large for file format '%s'"
7077 "%s", fmt, cluster_size_hint);
7078 error_free(local_err);
7079 local_err = NULL;
f88e1a42
JS
7080 }
7081
7082out:
83d0521a
CL
7083 qemu_opts_del(opts);
7084 qemu_opts_free(create_opts);
621ff94d 7085 error_propagate(errp, local_err);
f88e1a42 7086}
85d126f3
SH
7087
7088AioContext *bdrv_get_aio_context(BlockDriverState *bs)
7089{
384a48fb 7090 IO_CODE();
33f2a757 7091 return bs ? bs->aio_context : qemu_get_aio_context();
dcd04228
SH
7092}
7093
e336fd4c
KW
7094AioContext *coroutine_fn bdrv_co_enter(BlockDriverState *bs)
7095{
7096 Coroutine *self = qemu_coroutine_self();
7097 AioContext *old_ctx = qemu_coroutine_get_aio_context(self);
7098 AioContext *new_ctx;
384a48fb 7099 IO_CODE();
e336fd4c
KW
7100
7101 /*
7102 * Increase bs->in_flight to ensure that this operation is completed before
7103 * moving the node to a different AioContext. Read new_ctx only afterwards.
7104 */
7105 bdrv_inc_in_flight(bs);
7106
7107 new_ctx = bdrv_get_aio_context(bs);
7108 aio_co_reschedule_self(new_ctx);
7109 return old_ctx;
7110}
7111
7112void coroutine_fn bdrv_co_leave(BlockDriverState *bs, AioContext *old_ctx)
7113{
384a48fb 7114 IO_CODE();
e336fd4c
KW
7115 aio_co_reschedule_self(old_ctx);
7116 bdrv_dec_in_flight(bs);
7117}
7118
18c6ac1c
KW
7119void coroutine_fn bdrv_co_lock(BlockDriverState *bs)
7120{
7121 AioContext *ctx = bdrv_get_aio_context(bs);
7122
7123 /* In the main thread, bs->aio_context won't change concurrently */
7124 assert(qemu_get_current_aio_context() == qemu_get_aio_context());
7125
7126 /*
7127 * We're in coroutine context, so we already hold the lock of the main
7128 * loop AioContext. Don't lock it twice to avoid deadlocks.
7129 */
7130 assert(qemu_in_coroutine());
7131 if (ctx != qemu_get_aio_context()) {
7132 aio_context_acquire(ctx);
7133 }
7134}
7135
7136void coroutine_fn bdrv_co_unlock(BlockDriverState *bs)
7137{
7138 AioContext *ctx = bdrv_get_aio_context(bs);
7139
7140 assert(qemu_in_coroutine());
7141 if (ctx != qemu_get_aio_context()) {
7142 aio_context_release(ctx);
7143 }
7144}
7145
052a7572
FZ
7146void bdrv_coroutine_enter(BlockDriverState *bs, Coroutine *co)
7147{
384a48fb 7148 IO_CODE();
052a7572
FZ
7149 aio_co_enter(bdrv_get_aio_context(bs), co);
7150}
7151
e8a095da
SH
7152static void bdrv_do_remove_aio_context_notifier(BdrvAioNotifier *ban)
7153{
bdb73476 7154 GLOBAL_STATE_CODE();
e8a095da
SH
7155 QLIST_REMOVE(ban, list);
7156 g_free(ban);
7157}
7158
a3a683c3 7159static void bdrv_detach_aio_context(BlockDriverState *bs)
dcd04228 7160{
e8a095da 7161 BdrvAioNotifier *baf, *baf_tmp;
33384421 7162
e8a095da 7163 assert(!bs->walking_aio_notifiers);
da359909 7164 GLOBAL_STATE_CODE();
e8a095da
SH
7165 bs->walking_aio_notifiers = true;
7166 QLIST_FOREACH_SAFE(baf, &bs->aio_notifiers, list, baf_tmp) {
7167 if (baf->deleted) {
7168 bdrv_do_remove_aio_context_notifier(baf);
7169 } else {
7170 baf->detach_aio_context(baf->opaque);
7171 }
33384421 7172 }
e8a095da
SH
7173 /* Never mind iterating again to check for ->deleted. bdrv_close() will
7174 * remove remaining aio notifiers if we aren't called again.
7175 */
7176 bs->walking_aio_notifiers = false;
33384421 7177
1bffe1ae 7178 if (bs->drv && bs->drv->bdrv_detach_aio_context) {
dcd04228
SH
7179 bs->drv->bdrv_detach_aio_context(bs);
7180 }
dcd04228 7181
e64f25f3
KW
7182 if (bs->quiesce_counter) {
7183 aio_enable_external(bs->aio_context);
7184 }
7f898610 7185 assert_bdrv_graph_writable(bs);
dcd04228
SH
7186 bs->aio_context = NULL;
7187}
7188
a3a683c3
KW
7189static void bdrv_attach_aio_context(BlockDriverState *bs,
7190 AioContext *new_context)
dcd04228 7191{
e8a095da 7192 BdrvAioNotifier *ban, *ban_tmp;
da359909 7193 GLOBAL_STATE_CODE();
33384421 7194
e64f25f3
KW
7195 if (bs->quiesce_counter) {
7196 aio_disable_external(new_context);
7197 }
7198
7f898610 7199 assert_bdrv_graph_writable(bs);
dcd04228
SH
7200 bs->aio_context = new_context;
7201
1bffe1ae 7202 if (bs->drv && bs->drv->bdrv_attach_aio_context) {
dcd04228
SH
7203 bs->drv->bdrv_attach_aio_context(bs, new_context);
7204 }
33384421 7205
e8a095da
SH
7206 assert(!bs->walking_aio_notifiers);
7207 bs->walking_aio_notifiers = true;
7208 QLIST_FOREACH_SAFE(ban, &bs->aio_notifiers, list, ban_tmp) {
7209 if (ban->deleted) {
7210 bdrv_do_remove_aio_context_notifier(ban);
7211 } else {
7212 ban->attached_aio_context(new_context, ban->opaque);
7213 }
33384421 7214 }
e8a095da 7215 bs->walking_aio_notifiers = false;
dcd04228
SH
7216}
7217
7e8c182f
EGE
7218typedef struct BdrvStateSetAioContext {
7219 AioContext *new_ctx;
7220 BlockDriverState *bs;
7221} BdrvStateSetAioContext;
d616b224 7222
7e8c182f 7223static bool bdrv_parent_change_aio_context(BdrvChild *c, AioContext *ctx,
e08cc001
EGE
7224 GHashTable *visited,
7225 Transaction *tran,
7e8c182f 7226 Error **errp)
5d231849 7227{
f0c28327 7228 GLOBAL_STATE_CODE();
e08cc001 7229 if (g_hash_table_contains(visited, c)) {
5d231849
KW
7230 return true;
7231 }
e08cc001 7232 g_hash_table_add(visited, c);
5d231849 7233
bd86fb99
HR
7234 /*
7235 * A BdrvChildClass that doesn't handle AioContext changes cannot
7236 * tolerate any AioContext changes
7237 */
7e8c182f 7238 if (!c->klass->change_aio_ctx) {
5d231849
KW
7239 char *user = bdrv_child_user_desc(c);
7240 error_setg(errp, "Changing iothreads is not supported by %s", user);
7241 g_free(user);
7242 return false;
7243 }
7e8c182f 7244 if (!c->klass->change_aio_ctx(c, ctx, visited, tran, errp)) {
5d231849
KW
7245 assert(!errp || *errp);
7246 return false;
7247 }
7248 return true;
7249}
7250
7e8c182f 7251bool bdrv_child_change_aio_context(BdrvChild *c, AioContext *ctx,
e08cc001 7252 GHashTable *visited, Transaction *tran,
7e8c182f 7253 Error **errp)
5d231849 7254{
f791bf7f 7255 GLOBAL_STATE_CODE();
e08cc001 7256 if (g_hash_table_contains(visited, c)) {
5d231849
KW
7257 return true;
7258 }
e08cc001 7259 g_hash_table_add(visited, c);
7e8c182f 7260 return bdrv_change_aio_context(c->bs, ctx, visited, tran, errp);
5d231849
KW
7261}
7262
7e8c182f
EGE
7263static void bdrv_set_aio_context_clean(void *opaque)
7264{
7265 BdrvStateSetAioContext *state = (BdrvStateSetAioContext *) opaque;
7266 BlockDriverState *bs = (BlockDriverState *) state->bs;
7267
7268 /* Paired with bdrv_drained_begin in bdrv_change_aio_context() */
7269 bdrv_drained_end(bs);
7270
7271 g_free(state);
7272}
7273
7274static void bdrv_set_aio_context_commit(void *opaque)
7275{
7276 BdrvStateSetAioContext *state = (BdrvStateSetAioContext *) opaque;
7277 BlockDriverState *bs = (BlockDriverState *) state->bs;
7278 AioContext *new_context = state->new_ctx;
7279 AioContext *old_context = bdrv_get_aio_context(bs);
7280 assert_bdrv_graph_writable(bs);
7281
7282 /*
7283 * Take the old AioContex when detaching it from bs.
7284 * At this point, new_context lock is already acquired, and we are now
7285 * also taking old_context. This is safe as long as bdrv_detach_aio_context
7286 * does not call AIO_POLL_WHILE().
7287 */
7288 if (old_context != qemu_get_aio_context()) {
7289 aio_context_acquire(old_context);
7290 }
7291 bdrv_detach_aio_context(bs);
7292 if (old_context != qemu_get_aio_context()) {
7293 aio_context_release(old_context);
7294 }
7295 bdrv_attach_aio_context(bs, new_context);
7296}
7297
7298static TransactionActionDrv set_aio_context = {
7299 .commit = bdrv_set_aio_context_commit,
7300 .clean = bdrv_set_aio_context_clean,
7301};
7302
7303/*
7304 * Changes the AioContext used for fd handlers, timers, and BHs by this
7305 * BlockDriverState and all its children and parents.
7306 *
7307 * Must be called from the main AioContext.
7308 *
7309 * The caller must own the AioContext lock for the old AioContext of bs, but it
7310 * must not own the AioContext lock for new_context (unless new_context is the
7311 * same as the current context of bs).
7312 *
7313 * @visited will accumulate all visited BdrvChild objects. The caller is
7314 * responsible for freeing the list afterwards.
7315 */
7316static bool bdrv_change_aio_context(BlockDriverState *bs, AioContext *ctx,
e08cc001 7317 GHashTable *visited, Transaction *tran,
7e8c182f 7318 Error **errp)
5d231849
KW
7319{
7320 BdrvChild *c;
7e8c182f
EGE
7321 BdrvStateSetAioContext *state;
7322
7323 GLOBAL_STATE_CODE();
5d231849
KW
7324
7325 if (bdrv_get_aio_context(bs) == ctx) {
7326 return true;
7327 }
7328
7329 QLIST_FOREACH(c, &bs->parents, next_parent) {
7e8c182f 7330 if (!bdrv_parent_change_aio_context(c, ctx, visited, tran, errp)) {
5d231849
KW
7331 return false;
7332 }
7333 }
7e8c182f 7334
5d231849 7335 QLIST_FOREACH(c, &bs->children, next) {
7e8c182f 7336 if (!bdrv_child_change_aio_context(c, ctx, visited, tran, errp)) {
5d231849
KW
7337 return false;
7338 }
7339 }
7340
7e8c182f
EGE
7341 state = g_new(BdrvStateSetAioContext, 1);
7342 *state = (BdrvStateSetAioContext) {
7343 .new_ctx = ctx,
7344 .bs = bs,
7345 };
7346
7347 /* Paired with bdrv_drained_end in bdrv_set_aio_context_clean() */
7348 bdrv_drained_begin(bs);
7349
7350 tran_add(tran, &set_aio_context, state);
7351
5d231849
KW
7352 return true;
7353}
7354
7e8c182f
EGE
7355/*
7356 * Change bs's and recursively all of its parents' and children's AioContext
7357 * to the given new context, returning an error if that isn't possible.
7358 *
7359 * If ignore_child is not NULL, that child (and its subgraph) will not
7360 * be touched.
7361 *
7362 * This function still requires the caller to take the bs current
7363 * AioContext lock, otherwise draining will fail since AIO_WAIT_WHILE
7364 * assumes the lock is always held if bs is in another AioContext.
7365 * For the same reason, it temporarily also holds the new AioContext, since
7366 * bdrv_drained_end calls BDRV_POLL_WHILE that assumes the lock is taken too.
7367 * Therefore the new AioContext lock must not be taken by the caller.
7368 */
a41cfda1
EGE
7369int bdrv_try_change_aio_context(BlockDriverState *bs, AioContext *ctx,
7370 BdrvChild *ignore_child, Error **errp)
5d231849 7371{
7e8c182f 7372 Transaction *tran;
e08cc001 7373 GHashTable *visited;
7e8c182f
EGE
7374 int ret;
7375 AioContext *old_context = bdrv_get_aio_context(bs);
f791bf7f
EGE
7376 GLOBAL_STATE_CODE();
7377
7e8c182f
EGE
7378 /*
7379 * Recursion phase: go through all nodes of the graph.
7380 * Take care of checking that all nodes support changing AioContext
7381 * and drain them, builing a linear list of callbacks to run if everything
7382 * is successful (the transaction itself).
7383 */
7384 tran = tran_new();
e08cc001
EGE
7385 visited = g_hash_table_new(NULL, NULL);
7386 if (ignore_child) {
7387 g_hash_table_add(visited, ignore_child);
7388 }
7389 ret = bdrv_change_aio_context(bs, ctx, visited, tran, errp);
7390 g_hash_table_destroy(visited);
7e8c182f
EGE
7391
7392 /*
7393 * Linear phase: go through all callbacks collected in the transaction.
7394 * Run all callbacks collected in the recursion to switch all nodes
7395 * AioContext lock (transaction commit), or undo all changes done in the
7396 * recursion (transaction abort).
7397 */
5d231849
KW
7398
7399 if (!ret) {
7e8c182f
EGE
7400 /* Just run clean() callbacks. No AioContext changed. */
7401 tran_abort(tran);
5d231849
KW
7402 return -EPERM;
7403 }
7404
7e8c182f
EGE
7405 /*
7406 * Release old AioContext, it won't be needed anymore, as all
7407 * bdrv_drained_begin() have been called already.
7408 */
7409 if (qemu_get_aio_context() != old_context) {
7410 aio_context_release(old_context);
7411 }
7412
7413 /*
7414 * Acquire new AioContext since bdrv_drained_end() is going to be called
7415 * after we switched all nodes in the new AioContext, and the function
7416 * assumes that the lock of the bs is always taken.
7417 */
7418 if (qemu_get_aio_context() != ctx) {
7419 aio_context_acquire(ctx);
7420 }
53a7d041 7421
7e8c182f 7422 tran_commit(tran);
5d231849 7423
7e8c182f
EGE
7424 if (qemu_get_aio_context() != ctx) {
7425 aio_context_release(ctx);
7426 }
7427
7428 /* Re-acquire the old AioContext, since the caller takes and releases it. */
7429 if (qemu_get_aio_context() != old_context) {
7430 aio_context_acquire(old_context);
7431 }
7432
7433 return 0;
5d231849
KW
7434}
7435
33384421
HR
7436void bdrv_add_aio_context_notifier(BlockDriverState *bs,
7437 void (*attached_aio_context)(AioContext *new_context, void *opaque),
7438 void (*detach_aio_context)(void *opaque), void *opaque)
7439{
7440 BdrvAioNotifier *ban = g_new(BdrvAioNotifier, 1);
7441 *ban = (BdrvAioNotifier){
7442 .attached_aio_context = attached_aio_context,
7443 .detach_aio_context = detach_aio_context,
7444 .opaque = opaque
7445 };
f791bf7f 7446 GLOBAL_STATE_CODE();
33384421
HR
7447
7448 QLIST_INSERT_HEAD(&bs->aio_notifiers, ban, list);
7449}
7450
7451void bdrv_remove_aio_context_notifier(BlockDriverState *bs,
7452 void (*attached_aio_context)(AioContext *,
7453 void *),
7454 void (*detach_aio_context)(void *),
7455 void *opaque)
7456{
7457 BdrvAioNotifier *ban, *ban_next;
f791bf7f 7458 GLOBAL_STATE_CODE();
33384421
HR
7459
7460 QLIST_FOREACH_SAFE(ban, &bs->aio_notifiers, list, ban_next) {
7461 if (ban->attached_aio_context == attached_aio_context &&
7462 ban->detach_aio_context == detach_aio_context &&
e8a095da
SH
7463 ban->opaque == opaque &&
7464 ban->deleted == false)
33384421 7465 {
e8a095da
SH
7466 if (bs->walking_aio_notifiers) {
7467 ban->deleted = true;
7468 } else {
7469 bdrv_do_remove_aio_context_notifier(ban);
7470 }
33384421
HR
7471 return;
7472 }
7473 }
7474
7475 abort();
7476}
7477
77485434 7478int bdrv_amend_options(BlockDriverState *bs, QemuOpts *opts,
d1402b50 7479 BlockDriverAmendStatusCB *status_cb, void *cb_opaque,
a3579bfa 7480 bool force,
d1402b50 7481 Error **errp)
6f176b48 7482{
f791bf7f 7483 GLOBAL_STATE_CODE();
d470ad42 7484 if (!bs->drv) {
d1402b50 7485 error_setg(errp, "Node is ejected");
d470ad42
HR
7486 return -ENOMEDIUM;
7487 }
c282e1fd 7488 if (!bs->drv->bdrv_amend_options) {
d1402b50
HR
7489 error_setg(errp, "Block driver '%s' does not support option amendment",
7490 bs->drv->format_name);
6f176b48
HR
7491 return -ENOTSUP;
7492 }
a3579bfa
ML
7493 return bs->drv->bdrv_amend_options(bs, opts, status_cb,
7494 cb_opaque, force, errp);
6f176b48 7495}
f6186f49 7496
5d69b5ab
HR
7497/*
7498 * This function checks whether the given @to_replace is allowed to be
7499 * replaced by a node that always shows the same data as @bs. This is
7500 * used for example to verify whether the mirror job can replace
7501 * @to_replace by the target mirrored from @bs.
7502 * To be replaceable, @bs and @to_replace may either be guaranteed to
7503 * always show the same data (because they are only connected through
7504 * filters), or some driver may allow replacing one of its children
7505 * because it can guarantee that this child's data is not visible at
7506 * all (for example, for dissenting quorum children that have no other
7507 * parents).
7508 */
7509bool bdrv_recurse_can_replace(BlockDriverState *bs,
7510 BlockDriverState *to_replace)
7511{
93393e69
HR
7512 BlockDriverState *filtered;
7513
b4ad82aa
EGE
7514 GLOBAL_STATE_CODE();
7515
5d69b5ab
HR
7516 if (!bs || !bs->drv) {
7517 return false;
7518 }
7519
7520 if (bs == to_replace) {
7521 return true;
7522 }
7523
7524 /* See what the driver can do */
7525 if (bs->drv->bdrv_recurse_can_replace) {
7526 return bs->drv->bdrv_recurse_can_replace(bs, to_replace);
7527 }
7528
7529 /* For filters without an own implementation, we can recurse on our own */
93393e69
HR
7530 filtered = bdrv_filter_bs(bs);
7531 if (filtered) {
7532 return bdrv_recurse_can_replace(filtered, to_replace);
5d69b5ab
HR
7533 }
7534
7535 /* Safe default */
7536 return false;
7537}
7538
810803a8
HR
7539/*
7540 * Check whether the given @node_name can be replaced by a node that
7541 * has the same data as @parent_bs. If so, return @node_name's BDS;
7542 * NULL otherwise.
7543 *
7544 * @node_name must be a (recursive) *child of @parent_bs (or this
7545 * function will return NULL).
7546 *
7547 * The result (whether the node can be replaced or not) is only valid
7548 * for as long as no graph or permission changes occur.
7549 */
e12f3784
WC
7550BlockDriverState *check_to_replace_node(BlockDriverState *parent_bs,
7551 const char *node_name, Error **errp)
09158f00
BC
7552{
7553 BlockDriverState *to_replace_bs = bdrv_find_node(node_name);
5a7e7a0b
SH
7554 AioContext *aio_context;
7555
f791bf7f
EGE
7556 GLOBAL_STATE_CODE();
7557
09158f00 7558 if (!to_replace_bs) {
785ec4b1 7559 error_setg(errp, "Failed to find node with node-name='%s'", node_name);
09158f00
BC
7560 return NULL;
7561 }
7562
5a7e7a0b
SH
7563 aio_context = bdrv_get_aio_context(to_replace_bs);
7564 aio_context_acquire(aio_context);
7565
09158f00 7566 if (bdrv_op_is_blocked(to_replace_bs, BLOCK_OP_TYPE_REPLACE, errp)) {
5a7e7a0b
SH
7567 to_replace_bs = NULL;
7568 goto out;
09158f00
BC
7569 }
7570
7571 /* We don't want arbitrary node of the BDS chain to be replaced only the top
7572 * most non filter in order to prevent data corruption.
7573 * Another benefit is that this tests exclude backing files which are
7574 * blocked by the backing blockers.
7575 */
810803a8
HR
7576 if (!bdrv_recurse_can_replace(parent_bs, to_replace_bs)) {
7577 error_setg(errp, "Cannot replace '%s' by a node mirrored from '%s', "
7578 "because it cannot be guaranteed that doing so would not "
7579 "lead to an abrupt change of visible data",
7580 node_name, parent_bs->node_name);
5a7e7a0b
SH
7581 to_replace_bs = NULL;
7582 goto out;
09158f00
BC
7583 }
7584
5a7e7a0b
SH
7585out:
7586 aio_context_release(aio_context);
09158f00
BC
7587 return to_replace_bs;
7588}
448ad91d 7589
97e2f021
HR
7590/**
7591 * Iterates through the list of runtime option keys that are said to
7592 * be "strong" for a BDS. An option is called "strong" if it changes
7593 * a BDS's data. For example, the null block driver's "size" and
7594 * "read-zeroes" options are strong, but its "latency-ns" option is
7595 * not.
7596 *
7597 * If a key returned by this function ends with a dot, all options
7598 * starting with that prefix are strong.
7599 */
7600static const char *const *strong_options(BlockDriverState *bs,
7601 const char *const *curopt)
7602{
7603 static const char *const global_options[] = {
7604 "driver", "filename", NULL
7605 };
7606
7607 if (!curopt) {
7608 return &global_options[0];
7609 }
7610
7611 curopt++;
7612 if (curopt == &global_options[ARRAY_SIZE(global_options) - 1] && bs->drv) {
7613 curopt = bs->drv->strong_runtime_opts;
7614 }
7615
7616 return (curopt && *curopt) ? curopt : NULL;
7617}
7618
7619/**
7620 * Copies all strong runtime options from bs->options to the given
7621 * QDict. The set of strong option keys is determined by invoking
7622 * strong_options().
7623 *
7624 * Returns true iff any strong option was present in bs->options (and
7625 * thus copied to the target QDict) with the exception of "filename"
7626 * and "driver". The caller is expected to use this value to decide
7627 * whether the existence of strong options prevents the generation of
7628 * a plain filename.
7629 */
7630static bool append_strong_runtime_options(QDict *d, BlockDriverState *bs)
7631{
7632 bool found_any = false;
7633 const char *const *option_name = NULL;
7634
7635 if (!bs->drv) {
7636 return false;
7637 }
7638
7639 while ((option_name = strong_options(bs, option_name))) {
7640 bool option_given = false;
7641
7642 assert(strlen(*option_name) > 0);
7643 if ((*option_name)[strlen(*option_name) - 1] != '.') {
7644 QObject *entry = qdict_get(bs->options, *option_name);
7645 if (!entry) {
7646 continue;
7647 }
7648
7649 qdict_put_obj(d, *option_name, qobject_ref(entry));
7650 option_given = true;
7651 } else {
7652 const QDictEntry *entry;
7653 for (entry = qdict_first(bs->options); entry;
7654 entry = qdict_next(bs->options, entry))
7655 {
7656 if (strstart(qdict_entry_key(entry), *option_name, NULL)) {
7657 qdict_put_obj(d, qdict_entry_key(entry),
7658 qobject_ref(qdict_entry_value(entry)));
7659 option_given = true;
7660 }
7661 }
7662 }
7663
7664 /* While "driver" and "filename" need to be included in a JSON filename,
7665 * their existence does not prohibit generation of a plain filename. */
7666 if (!found_any && option_given &&
7667 strcmp(*option_name, "driver") && strcmp(*option_name, "filename"))
7668 {
7669 found_any = true;
7670 }
7671 }
7672
62a01a27
HR
7673 if (!qdict_haskey(d, "driver")) {
7674 /* Drivers created with bdrv_new_open_driver() may not have a
7675 * @driver option. Add it here. */
7676 qdict_put_str(d, "driver", bs->drv->format_name);
7677 }
7678
97e2f021
HR
7679 return found_any;
7680}
7681
90993623
HR
7682/* Note: This function may return false positives; it may return true
7683 * even if opening the backing file specified by bs's image header
7684 * would result in exactly bs->backing. */
fa8fc1d0 7685static bool bdrv_backing_overridden(BlockDriverState *bs)
90993623 7686{
b4ad82aa 7687 GLOBAL_STATE_CODE();
90993623
HR
7688 if (bs->backing) {
7689 return strcmp(bs->auto_backing_file,
7690 bs->backing->bs->filename);
7691 } else {
7692 /* No backing BDS, so if the image header reports any backing
7693 * file, it must have been suppressed */
7694 return bs->auto_backing_file[0] != '\0';
7695 }
7696}
7697
91af7014
HR
7698/* Updates the following BDS fields:
7699 * - exact_filename: A filename which may be used for opening a block device
7700 * which (mostly) equals the given BDS (even without any
7701 * other options; so reading and writing must return the same
7702 * results, but caching etc. may be different)
7703 * - full_open_options: Options which, when given when opening a block device
7704 * (without a filename), result in a BDS (mostly)
7705 * equalling the given one
7706 * - filename: If exact_filename is set, it is copied here. Otherwise,
7707 * full_open_options is converted to a JSON object, prefixed with
7708 * "json:" (for use through the JSON pseudo protocol) and put here.
7709 */
7710void bdrv_refresh_filename(BlockDriverState *bs)
7711{
7712 BlockDriver *drv = bs->drv;
e24518e3 7713 BdrvChild *child;
52f72d6f 7714 BlockDriverState *primary_child_bs;
91af7014 7715 QDict *opts;
90993623 7716 bool backing_overridden;
998b3a1e
HR
7717 bool generate_json_filename; /* Whether our default implementation should
7718 fill exact_filename (false) or not (true) */
91af7014 7719
f791bf7f
EGE
7720 GLOBAL_STATE_CODE();
7721
91af7014
HR
7722 if (!drv) {
7723 return;
7724 }
7725
e24518e3
HR
7726 /* This BDS's file name may depend on any of its children's file names, so
7727 * refresh those first */
7728 QLIST_FOREACH(child, &bs->children, next) {
7729 bdrv_refresh_filename(child->bs);
91af7014
HR
7730 }
7731
bb808d5f
HR
7732 if (bs->implicit) {
7733 /* For implicit nodes, just copy everything from the single child */
7734 child = QLIST_FIRST(&bs->children);
7735 assert(QLIST_NEXT(child, next) == NULL);
7736
7737 pstrcpy(bs->exact_filename, sizeof(bs->exact_filename),
7738 child->bs->exact_filename);
7739 pstrcpy(bs->filename, sizeof(bs->filename), child->bs->filename);
7740
cb895614 7741 qobject_unref(bs->full_open_options);
bb808d5f
HR
7742 bs->full_open_options = qobject_ref(child->bs->full_open_options);
7743
7744 return;
7745 }
7746
90993623
HR
7747 backing_overridden = bdrv_backing_overridden(bs);
7748
7749 if (bs->open_flags & BDRV_O_NO_IO) {
7750 /* Without I/O, the backing file does not change anything.
7751 * Therefore, in such a case (primarily qemu-img), we can
7752 * pretend the backing file has not been overridden even if
7753 * it technically has been. */
7754 backing_overridden = false;
7755 }
7756
97e2f021
HR
7757 /* Gather the options QDict */
7758 opts = qdict_new();
998b3a1e
HR
7759 generate_json_filename = append_strong_runtime_options(opts, bs);
7760 generate_json_filename |= backing_overridden;
97e2f021
HR
7761
7762 if (drv->bdrv_gather_child_options) {
7763 /* Some block drivers may not want to present all of their children's
7764 * options, or name them differently from BdrvChild.name */
7765 drv->bdrv_gather_child_options(bs, opts, backing_overridden);
7766 } else {
7767 QLIST_FOREACH(child, &bs->children, next) {
25191e5f 7768 if (child == bs->backing && !backing_overridden) {
97e2f021
HR
7769 /* We can skip the backing BDS if it has not been overridden */
7770 continue;
7771 }
7772
7773 qdict_put(opts, child->name,
7774 qobject_ref(child->bs->full_open_options));
7775 }
7776
7777 if (backing_overridden && !bs->backing) {
7778 /* Force no backing file */
7779 qdict_put_null(opts, "backing");
7780 }
7781 }
7782
7783 qobject_unref(bs->full_open_options);
7784 bs->full_open_options = opts;
7785
52f72d6f
HR
7786 primary_child_bs = bdrv_primary_bs(bs);
7787
998b3a1e
HR
7788 if (drv->bdrv_refresh_filename) {
7789 /* Obsolete information is of no use here, so drop the old file name
7790 * information before refreshing it */
7791 bs->exact_filename[0] = '\0';
7792
7793 drv->bdrv_refresh_filename(bs);
52f72d6f
HR
7794 } else if (primary_child_bs) {
7795 /*
7796 * Try to reconstruct valid information from the underlying
7797 * file -- this only works for format nodes (filter nodes
7798 * cannot be probed and as such must be selected by the user
7799 * either through an options dict, or through a special
7800 * filename which the filter driver must construct in its
7801 * .bdrv_refresh_filename() implementation).
7802 */
998b3a1e
HR
7803
7804 bs->exact_filename[0] = '\0';
7805
fb695c74
HR
7806 /*
7807 * We can use the underlying file's filename if:
7808 * - it has a filename,
52f72d6f 7809 * - the current BDS is not a filter,
fb695c74
HR
7810 * - the file is a protocol BDS, and
7811 * - opening that file (as this BDS's format) will automatically create
7812 * the BDS tree we have right now, that is:
7813 * - the user did not significantly change this BDS's behavior with
7814 * some explicit (strong) options
7815 * - no non-file child of this BDS has been overridden by the user
7816 * Both of these conditions are represented by generate_json_filename.
7817 */
52f72d6f
HR
7818 if (primary_child_bs->exact_filename[0] &&
7819 primary_child_bs->drv->bdrv_file_open &&
7820 !drv->is_filter && !generate_json_filename)
fb695c74 7821 {
52f72d6f 7822 strcpy(bs->exact_filename, primary_child_bs->exact_filename);
998b3a1e
HR
7823 }
7824 }
7825
91af7014
HR
7826 if (bs->exact_filename[0]) {
7827 pstrcpy(bs->filename, sizeof(bs->filename), bs->exact_filename);
97e2f021 7828 } else {
eab3a467 7829 GString *json = qobject_to_json(QOBJECT(bs->full_open_options));
5c86bdf1 7830 if (snprintf(bs->filename, sizeof(bs->filename), "json:%s",
eab3a467 7831 json->str) >= sizeof(bs->filename)) {
5c86bdf1
EB
7832 /* Give user a hint if we truncated things. */
7833 strcpy(bs->filename + sizeof(bs->filename) - 4, "...");
7834 }
eab3a467 7835 g_string_free(json, true);
91af7014
HR
7836 }
7837}
e06018ad 7838
1e89d0f9
HR
7839char *bdrv_dirname(BlockDriverState *bs, Error **errp)
7840{
7841 BlockDriver *drv = bs->drv;
52f72d6f 7842 BlockDriverState *child_bs;
1e89d0f9 7843
f791bf7f
EGE
7844 GLOBAL_STATE_CODE();
7845
1e89d0f9
HR
7846 if (!drv) {
7847 error_setg(errp, "Node '%s' is ejected", bs->node_name);
7848 return NULL;
7849 }
7850
7851 if (drv->bdrv_dirname) {
7852 return drv->bdrv_dirname(bs, errp);
7853 }
7854
52f72d6f
HR
7855 child_bs = bdrv_primary_bs(bs);
7856 if (child_bs) {
7857 return bdrv_dirname(child_bs, errp);
1e89d0f9
HR
7858 }
7859
7860 bdrv_refresh_filename(bs);
7861 if (bs->exact_filename[0] != '\0') {
7862 return path_combine(bs->exact_filename, "");
7863 }
7864
7865 error_setg(errp, "Cannot generate a base directory for %s nodes",
7866 drv->format_name);
7867 return NULL;
7868}
7869
e06018ad
WC
7870/*
7871 * Hot add/remove a BDS's child. So the user can take a child offline when
7872 * it is broken and take a new child online
7873 */
7874void bdrv_add_child(BlockDriverState *parent_bs, BlockDriverState *child_bs,
7875 Error **errp)
7876{
f791bf7f 7877 GLOBAL_STATE_CODE();
e06018ad
WC
7878 if (!parent_bs->drv || !parent_bs->drv->bdrv_add_child) {
7879 error_setg(errp, "The node %s does not support adding a child",
7880 bdrv_get_device_or_node_name(parent_bs));
7881 return;
7882 }
7883
7884 if (!QLIST_EMPTY(&child_bs->parents)) {
7885 error_setg(errp, "The node %s already has a parent",
7886 child_bs->node_name);
7887 return;
7888 }
7889
7890 parent_bs->drv->bdrv_add_child(parent_bs, child_bs, errp);
7891}
7892
7893void bdrv_del_child(BlockDriverState *parent_bs, BdrvChild *child, Error **errp)
7894{
7895 BdrvChild *tmp;
7896
f791bf7f 7897 GLOBAL_STATE_CODE();
e06018ad
WC
7898 if (!parent_bs->drv || !parent_bs->drv->bdrv_del_child) {
7899 error_setg(errp, "The node %s does not support removing a child",
7900 bdrv_get_device_or_node_name(parent_bs));
7901 return;
7902 }
7903
7904 QLIST_FOREACH(tmp, &parent_bs->children, next) {
7905 if (tmp == child) {
7906 break;
7907 }
7908 }
7909
7910 if (!tmp) {
7911 error_setg(errp, "The node %s does not have a child named %s",
7912 bdrv_get_device_or_node_name(parent_bs),
7913 bdrv_get_device_or_node_name(child->bs));
7914 return;
7915 }
7916
7917 parent_bs->drv->bdrv_del_child(parent_bs, child, errp);
7918}
6f7a3b53
HR
7919
7920int bdrv_make_empty(BdrvChild *c, Error **errp)
7921{
7922 BlockDriver *drv = c->bs->drv;
7923 int ret;
7924
f791bf7f 7925 GLOBAL_STATE_CODE();
6f7a3b53
HR
7926 assert(c->perm & (BLK_PERM_WRITE | BLK_PERM_WRITE_UNCHANGED));
7927
7928 if (!drv->bdrv_make_empty) {
7929 error_setg(errp, "%s does not support emptying nodes",
7930 drv->format_name);
7931 return -ENOTSUP;
7932 }
7933
7934 ret = drv->bdrv_make_empty(c->bs);
7935 if (ret < 0) {
7936 error_setg_errno(errp, -ret, "Failed to empty %s",
7937 c->bs->filename);
7938 return ret;
7939 }
7940
7941 return 0;
7942}
9a6fc887
HR
7943
7944/*
7945 * Return the child that @bs acts as an overlay for, and from which data may be
7946 * copied in COW or COR operations. Usually this is the backing file.
7947 */
7948BdrvChild *bdrv_cow_child(BlockDriverState *bs)
7949{
967d7905
EGE
7950 IO_CODE();
7951
9a6fc887
HR
7952 if (!bs || !bs->drv) {
7953 return NULL;
7954 }
7955
7956 if (bs->drv->is_filter) {
7957 return NULL;
7958 }
7959
7960 if (!bs->backing) {
7961 return NULL;
7962 }
7963
7964 assert(bs->backing->role & BDRV_CHILD_COW);
7965 return bs->backing;
7966}
7967
7968/*
7969 * If @bs acts as a filter for exactly one of its children, return
7970 * that child.
7971 */
7972BdrvChild *bdrv_filter_child(BlockDriverState *bs)
7973{
7974 BdrvChild *c;
967d7905 7975 IO_CODE();
9a6fc887
HR
7976
7977 if (!bs || !bs->drv) {
7978 return NULL;
7979 }
7980
7981 if (!bs->drv->is_filter) {
7982 return NULL;
7983 }
7984
7985 /* Only one of @backing or @file may be used */
7986 assert(!(bs->backing && bs->file));
7987
7988 c = bs->backing ?: bs->file;
7989 if (!c) {
7990 return NULL;
7991 }
7992
7993 assert(c->role & BDRV_CHILD_FILTERED);
7994 return c;
7995}
7996
7997/*
7998 * Return either the result of bdrv_cow_child() or bdrv_filter_child(),
7999 * whichever is non-NULL.
8000 *
8001 * Return NULL if both are NULL.
8002 */
8003BdrvChild *bdrv_filter_or_cow_child(BlockDriverState *bs)
8004{
8005 BdrvChild *cow_child = bdrv_cow_child(bs);
8006 BdrvChild *filter_child = bdrv_filter_child(bs);
967d7905 8007 IO_CODE();
9a6fc887
HR
8008
8009 /* Filter nodes cannot have COW backing files */
8010 assert(!(cow_child && filter_child));
8011
8012 return cow_child ?: filter_child;
8013}
8014
8015/*
8016 * Return the primary child of this node: For filters, that is the
8017 * filtered child. For other nodes, that is usually the child storing
8018 * metadata.
8019 * (A generally more helpful description is that this is (usually) the
8020 * child that has the same filename as @bs.)
8021 *
8022 * Drivers do not necessarily have a primary child; for example quorum
8023 * does not.
8024 */
8025BdrvChild *bdrv_primary_child(BlockDriverState *bs)
8026{
8027 BdrvChild *c, *found = NULL;
967d7905 8028 IO_CODE();
9a6fc887
HR
8029
8030 QLIST_FOREACH(c, &bs->children, next) {
8031 if (c->role & BDRV_CHILD_PRIMARY) {
8032 assert(!found);
8033 found = c;
8034 }
8035 }
8036
8037 return found;
8038}
d38d7eb8
HR
8039
8040static BlockDriverState *bdrv_do_skip_filters(BlockDriverState *bs,
8041 bool stop_on_explicit_filter)
8042{
8043 BdrvChild *c;
8044
8045 if (!bs) {
8046 return NULL;
8047 }
8048
8049 while (!(stop_on_explicit_filter && !bs->implicit)) {
8050 c = bdrv_filter_child(bs);
8051 if (!c) {
8052 /*
8053 * A filter that is embedded in a working block graph must
8054 * have a child. Assert this here so this function does
8055 * not return a filter node that is not expected by the
8056 * caller.
8057 */
8058 assert(!bs->drv || !bs->drv->is_filter);
8059 break;
8060 }
8061 bs = c->bs;
8062 }
8063 /*
8064 * Note that this treats nodes with bs->drv == NULL as not being
8065 * filters (bs->drv == NULL should be replaced by something else
8066 * anyway).
8067 * The advantage of this behavior is that this function will thus
8068 * always return a non-NULL value (given a non-NULL @bs).
8069 */
8070
8071 return bs;
8072}
8073
8074/*
8075 * Return the first BDS that has not been added implicitly or that
8076 * does not have a filtered child down the chain starting from @bs
8077 * (including @bs itself).
8078 */
8079BlockDriverState *bdrv_skip_implicit_filters(BlockDriverState *bs)
8080{
b4ad82aa 8081 GLOBAL_STATE_CODE();
d38d7eb8
HR
8082 return bdrv_do_skip_filters(bs, true);
8083}
8084
8085/*
8086 * Return the first BDS that does not have a filtered child down the
8087 * chain starting from @bs (including @bs itself).
8088 */
8089BlockDriverState *bdrv_skip_filters(BlockDriverState *bs)
8090{
967d7905 8091 IO_CODE();
d38d7eb8
HR
8092 return bdrv_do_skip_filters(bs, false);
8093}
8094
8095/*
8096 * For a backing chain, return the first non-filter backing image of
8097 * the first non-filter image.
8098 */
8099BlockDriverState *bdrv_backing_chain_next(BlockDriverState *bs)
8100{
967d7905 8101 IO_CODE();
d38d7eb8
HR
8102 return bdrv_skip_filters(bdrv_cow_bs(bdrv_skip_filters(bs)));
8103}
0bc329fb
HR
8104
8105/**
8106 * Check whether [offset, offset + bytes) overlaps with the cached
8107 * block-status data region.
8108 *
8109 * If so, and @pnum is not NULL, set *pnum to `bsc.data_end - offset`,
8110 * which is what bdrv_bsc_is_data()'s interface needs.
8111 * Otherwise, *pnum is not touched.
8112 */
8113static bool bdrv_bsc_range_overlaps_locked(BlockDriverState *bs,
8114 int64_t offset, int64_t bytes,
8115 int64_t *pnum)
8116{
8117 BdrvBlockStatusCache *bsc = qatomic_rcu_read(&bs->block_status_cache);
8118 bool overlaps;
8119
8120 overlaps =
8121 qatomic_read(&bsc->valid) &&
8122 ranges_overlap(offset, bytes, bsc->data_start,
8123 bsc->data_end - bsc->data_start);
8124
8125 if (overlaps && pnum) {
8126 *pnum = bsc->data_end - offset;
8127 }
8128
8129 return overlaps;
8130}
8131
8132/**
8133 * See block_int.h for this function's documentation.
8134 */
8135bool bdrv_bsc_is_data(BlockDriverState *bs, int64_t offset, int64_t *pnum)
8136{
967d7905 8137 IO_CODE();
0bc329fb 8138 RCU_READ_LOCK_GUARD();
0bc329fb
HR
8139 return bdrv_bsc_range_overlaps_locked(bs, offset, 1, pnum);
8140}
8141
8142/**
8143 * See block_int.h for this function's documentation.
8144 */
8145void bdrv_bsc_invalidate_range(BlockDriverState *bs,
8146 int64_t offset, int64_t bytes)
8147{
967d7905 8148 IO_CODE();
0bc329fb
HR
8149 RCU_READ_LOCK_GUARD();
8150
8151 if (bdrv_bsc_range_overlaps_locked(bs, offset, bytes, NULL)) {
8152 qatomic_set(&bs->block_status_cache->valid, false);
8153 }
8154}
8155
8156/**
8157 * See block_int.h for this function's documentation.
8158 */
8159void bdrv_bsc_fill(BlockDriverState *bs, int64_t offset, int64_t bytes)
8160{
8161 BdrvBlockStatusCache *new_bsc = g_new(BdrvBlockStatusCache, 1);
8162 BdrvBlockStatusCache *old_bsc;
967d7905 8163 IO_CODE();
0bc329fb
HR
8164
8165 *new_bsc = (BdrvBlockStatusCache) {
8166 .valid = true,
8167 .data_start = offset,
8168 .data_end = offset + bytes,
8169 };
8170
8171 QEMU_LOCK_GUARD(&bs->bsc_modify_lock);
8172
8173 old_bsc = qatomic_rcu_read(&bs->block_status_cache);
8174 qatomic_rcu_set(&bs->block_status_cache, new_bsc);
8175 if (old_bsc) {
8176 g_free_rcu(old_bsc, rcu);
8177 }
8178}
This page took 2.863763 seconds and 4 git commands to generate.