]> Git Repo - qemu.git/blame - block.c
block: drop bdrv_remove_filter_or_cow_child
[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
KW
1715 for (i = 0; i < bs->quiesce_counter; i++) {
1716 if (drv->bdrv_co_drain_begin) {
1717 drv->bdrv_co_drain_begin(bs);
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
25409807
VSO
2524static int bdrv_list_refresh_perms(GSList *list, BlockReopenQueue *q,
2525 Transaction *tran, Error **errp)
bd57f8f7
VSO
2526{
2527 int ret;
b1d2bbeb 2528 BlockDriverState *bs;
862fded9 2529 GLOBAL_STATE_CODE();
bd57f8f7 2530
b1d2bbeb
VSO
2531 for ( ; list; list = list->next) {
2532 bs = list->data;
2533
9397c14f 2534 if (bdrv_parent_perms_conflict(bs, errp)) {
b1d2bbeb 2535 return -EINVAL;
bd57f8f7
VSO
2536 }
2537
c20555e1 2538 ret = bdrv_node_refresh_perm(bs, q, tran, errp);
33a610c3
KW
2539 if (ret < 0) {
2540 return ret;
2541 }
2542 }
2543
2544 return 0;
2545}
2546
c7a0f2be
KW
2547void bdrv_get_cumulative_perm(BlockDriverState *bs, uint64_t *perm,
2548 uint64_t *shared_perm)
33a610c3
KW
2549{
2550 BdrvChild *c;
2551 uint64_t cumulative_perms = 0;
2552 uint64_t cumulative_shared_perms = BLK_PERM_ALL;
2553
b4ad82aa
EGE
2554 GLOBAL_STATE_CODE();
2555
33a610c3
KW
2556 QLIST_FOREACH(c, &bs->parents, next_parent) {
2557 cumulative_perms |= c->perm;
2558 cumulative_shared_perms &= c->shared_perm;
2559 }
2560
2561 *perm = cumulative_perms;
2562 *shared_perm = cumulative_shared_perms;
2563}
2564
5176196c 2565char *bdrv_perm_names(uint64_t perm)
d083319f
KW
2566{
2567 struct perm_name {
2568 uint64_t perm;
2569 const char *name;
2570 } permissions[] = {
2571 { BLK_PERM_CONSISTENT_READ, "consistent read" },
2572 { BLK_PERM_WRITE, "write" },
2573 { BLK_PERM_WRITE_UNCHANGED, "write unchanged" },
2574 { BLK_PERM_RESIZE, "resize" },
d083319f
KW
2575 { 0, NULL }
2576 };
2577
e2a7423a 2578 GString *result = g_string_sized_new(30);
d083319f
KW
2579 struct perm_name *p;
2580
2581 for (p = permissions; p->name; p++) {
2582 if (perm & p->perm) {
e2a7423a
AG
2583 if (result->len > 0) {
2584 g_string_append(result, ", ");
2585 }
2586 g_string_append(result, p->name);
d083319f
KW
2587 }
2588 }
2589
e2a7423a 2590 return g_string_free(result, FALSE);
d083319f
KW
2591}
2592
33a610c3 2593
071b474f 2594static int bdrv_refresh_perms(BlockDriverState *bs, Error **errp)
bb87e4d1
VSO
2595{
2596 int ret;
b1d2bbeb
VSO
2597 Transaction *tran = tran_new();
2598 g_autoptr(GSList) list = bdrv_topological_dfs(NULL, NULL, bs);
862fded9 2599 GLOBAL_STATE_CODE();
bb87e4d1 2600
b1d2bbeb
VSO
2601 ret = bdrv_list_refresh_perms(list, NULL, tran, errp);
2602 tran_finalize(tran, ret);
bb87e4d1 2603
b1d2bbeb 2604 return ret;
bb87e4d1
VSO
2605}
2606
33a610c3
KW
2607int bdrv_child_try_set_perm(BdrvChild *c, uint64_t perm, uint64_t shared,
2608 Error **errp)
2609{
1046779e 2610 Error *local_err = NULL;
83928dc4 2611 Transaction *tran = tran_new();
33a610c3
KW
2612 int ret;
2613
b4ad82aa
EGE
2614 GLOBAL_STATE_CODE();
2615
ecb776bd 2616 bdrv_child_set_perm(c, perm, shared, tran);
83928dc4
VSO
2617
2618 ret = bdrv_refresh_perms(c->bs, &local_err);
2619
2620 tran_finalize(tran, ret);
2621
33a610c3 2622 if (ret < 0) {
071b474f
VSO
2623 if ((perm & ~c->perm) || (c->shared_perm & ~shared)) {
2624 /* tighten permissions */
1046779e
HR
2625 error_propagate(errp, local_err);
2626 } else {
2627 /*
2628 * Our caller may intend to only loosen restrictions and
2629 * does not expect this function to fail. Errors are not
2630 * fatal in such a case, so we can just hide them from our
2631 * caller.
2632 */
2633 error_free(local_err);
2634 ret = 0;
2635 }
33a610c3
KW
2636 }
2637
83928dc4 2638 return ret;
d5e6f437
KW
2639}
2640
c1087f12
HR
2641int bdrv_child_refresh_perms(BlockDriverState *bs, BdrvChild *c, Error **errp)
2642{
2643 uint64_t parent_perms, parent_shared;
2644 uint64_t perms, shared;
2645
b4ad82aa
EGE
2646 GLOBAL_STATE_CODE();
2647
c1087f12 2648 bdrv_get_cumulative_perm(bs, &parent_perms, &parent_shared);
e5d8a406 2649 bdrv_child_perm(bs, c->bs, c, c->role, NULL,
bf8e925e 2650 parent_perms, parent_shared, &perms, &shared);
c1087f12
HR
2651
2652 return bdrv_child_try_set_perm(c, perms, shared, errp);
2653}
2654
87278af1
HR
2655/*
2656 * Default implementation for .bdrv_child_perm() for block filters:
2657 * Forward CONSISTENT_READ, WRITE, WRITE_UNCHANGED, and RESIZE to the
2658 * filtered child.
2659 */
2660static void bdrv_filter_default_perms(BlockDriverState *bs, BdrvChild *c,
87278af1
HR
2661 BdrvChildRole role,
2662 BlockReopenQueue *reopen_queue,
2663 uint64_t perm, uint64_t shared,
2664 uint64_t *nperm, uint64_t *nshared)
6a1b9ee1 2665{
862fded9 2666 GLOBAL_STATE_CODE();
e444fa83
KW
2667 *nperm = perm & DEFAULT_PERM_PASSTHROUGH;
2668 *nshared = (shared & DEFAULT_PERM_PASSTHROUGH) | DEFAULT_PERM_UNCHANGED;
6a1b9ee1
KW
2669}
2670
70082db4 2671static void bdrv_default_perms_for_cow(BlockDriverState *bs, BdrvChild *c,
70082db4
HR
2672 BdrvChildRole role,
2673 BlockReopenQueue *reopen_queue,
2674 uint64_t perm, uint64_t shared,
2675 uint64_t *nperm, uint64_t *nshared)
2676{
e5d8a406 2677 assert(role & BDRV_CHILD_COW);
862fded9 2678 GLOBAL_STATE_CODE();
70082db4
HR
2679
2680 /*
2681 * We want consistent read from backing files if the parent needs it.
2682 * No other operations are performed on backing files.
2683 */
2684 perm &= BLK_PERM_CONSISTENT_READ;
2685
2686 /*
2687 * If the parent can deal with changing data, we're okay with a
2688 * writable and resizable backing file.
2689 * TODO Require !(perm & BLK_PERM_CONSISTENT_READ), too?
2690 */
2691 if (shared & BLK_PERM_WRITE) {
2692 shared = BLK_PERM_WRITE | BLK_PERM_RESIZE;
2693 } else {
2694 shared = 0;
2695 }
2696
64631f36 2697 shared |= BLK_PERM_CONSISTENT_READ | BLK_PERM_WRITE_UNCHANGED;
70082db4
HR
2698
2699 if (bs->open_flags & BDRV_O_INACTIVE) {
2700 shared |= BLK_PERM_WRITE | BLK_PERM_RESIZE;
2701 }
2702
2703 *nperm = perm;
2704 *nshared = shared;
2705}
2706
6f838a4b 2707static void bdrv_default_perms_for_storage(BlockDriverState *bs, BdrvChild *c,
6f838a4b
HR
2708 BdrvChildRole role,
2709 BlockReopenQueue *reopen_queue,
2710 uint64_t perm, uint64_t shared,
2711 uint64_t *nperm, uint64_t *nshared)
2712{
2713 int flags;
2714
862fded9 2715 GLOBAL_STATE_CODE();
e5d8a406 2716 assert(role & (BDRV_CHILD_METADATA | BDRV_CHILD_DATA));
6f838a4b
HR
2717
2718 flags = bdrv_reopen_get_flags(reopen_queue, bs);
2719
2720 /*
2721 * Apart from the modifications below, the same permissions are
2722 * forwarded and left alone as for filters
2723 */
e5d8a406 2724 bdrv_filter_default_perms(bs, c, role, reopen_queue,
6f838a4b
HR
2725 perm, shared, &perm, &shared);
2726
f889054f
HR
2727 if (role & BDRV_CHILD_METADATA) {
2728 /* Format drivers may touch metadata even if the guest doesn't write */
2729 if (bdrv_is_writable_after_reopen(bs, reopen_queue)) {
2730 perm |= BLK_PERM_WRITE | BLK_PERM_RESIZE;
2731 }
2732
2733 /*
2734 * bs->file always needs to be consistent because of the
2735 * metadata. We can never allow other users to resize or write
2736 * to it.
2737 */
2738 if (!(flags & BDRV_O_NO_IO)) {
2739 perm |= BLK_PERM_CONSISTENT_READ;
2740 }
2741 shared &= ~(BLK_PERM_WRITE | BLK_PERM_RESIZE);
6f838a4b
HR
2742 }
2743
f889054f
HR
2744 if (role & BDRV_CHILD_DATA) {
2745 /*
2746 * Technically, everything in this block is a subset of the
2747 * BDRV_CHILD_METADATA path taken above, and so this could
2748 * be an "else if" branch. However, that is not obvious, and
2749 * this function is not performance critical, therefore we let
2750 * this be an independent "if".
2751 */
2752
2753 /*
2754 * We cannot allow other users to resize the file because the
2755 * format driver might have some assumptions about the size
2756 * (e.g. because it is stored in metadata, or because the file
2757 * is split into fixed-size data files).
2758 */
2759 shared &= ~BLK_PERM_RESIZE;
2760
2761 /*
2762 * WRITE_UNCHANGED often cannot be performed as such on the
2763 * data file. For example, the qcow2 driver may still need to
2764 * write copied clusters on copy-on-read.
2765 */
2766 if (perm & BLK_PERM_WRITE_UNCHANGED) {
2767 perm |= BLK_PERM_WRITE;
2768 }
2769
2770 /*
2771 * If the data file is written to, the format driver may
2772 * expect to be able to resize it by writing beyond the EOF.
2773 */
2774 if (perm & BLK_PERM_WRITE) {
2775 perm |= BLK_PERM_RESIZE;
2776 }
6f838a4b 2777 }
6f838a4b
HR
2778
2779 if (bs->open_flags & BDRV_O_INACTIVE) {
2780 shared |= BLK_PERM_WRITE | BLK_PERM_RESIZE;
2781 }
2782
2783 *nperm = perm;
2784 *nshared = shared;
2785}
2786
2519f549 2787void bdrv_default_perms(BlockDriverState *bs, BdrvChild *c,
e5d8a406 2788 BdrvChildRole role, BlockReopenQueue *reopen_queue,
2519f549
HR
2789 uint64_t perm, uint64_t shared,
2790 uint64_t *nperm, uint64_t *nshared)
2791{
b4ad82aa 2792 GLOBAL_STATE_CODE();
2519f549
HR
2793 if (role & BDRV_CHILD_FILTERED) {
2794 assert(!(role & (BDRV_CHILD_DATA | BDRV_CHILD_METADATA |
2795 BDRV_CHILD_COW)));
e5d8a406 2796 bdrv_filter_default_perms(bs, c, role, reopen_queue,
2519f549
HR
2797 perm, shared, nperm, nshared);
2798 } else if (role & BDRV_CHILD_COW) {
2799 assert(!(role & (BDRV_CHILD_DATA | BDRV_CHILD_METADATA)));
e5d8a406 2800 bdrv_default_perms_for_cow(bs, c, role, reopen_queue,
2519f549
HR
2801 perm, shared, nperm, nshared);
2802 } else if (role & (BDRV_CHILD_METADATA | BDRV_CHILD_DATA)) {
e5d8a406 2803 bdrv_default_perms_for_storage(bs, c, role, reopen_queue,
2519f549
HR
2804 perm, shared, nperm, nshared);
2805 } else {
2806 g_assert_not_reached();
2807 }
2808}
2809
7b1d9c4d
HR
2810uint64_t bdrv_qapi_perm_to_blk_perm(BlockPermission qapi_perm)
2811{
2812 static const uint64_t permissions[] = {
2813 [BLOCK_PERMISSION_CONSISTENT_READ] = BLK_PERM_CONSISTENT_READ,
2814 [BLOCK_PERMISSION_WRITE] = BLK_PERM_WRITE,
2815 [BLOCK_PERMISSION_WRITE_UNCHANGED] = BLK_PERM_WRITE_UNCHANGED,
2816 [BLOCK_PERMISSION_RESIZE] = BLK_PERM_RESIZE,
7b1d9c4d
HR
2817 };
2818
2819 QEMU_BUILD_BUG_ON(ARRAY_SIZE(permissions) != BLOCK_PERMISSION__MAX);
2820 QEMU_BUILD_BUG_ON(1UL << ARRAY_SIZE(permissions) != BLK_PERM_ALL + 1);
2821
2822 assert(qapi_perm < BLOCK_PERMISSION__MAX);
2823
2824 return permissions[qapi_perm];
2825}
2826
544acc7d 2827static void bdrv_replace_child_noperm(BdrvChild *child,
4eba825a 2828 BlockDriverState *new_bs)
e9740bc6
KW
2829{
2830 BlockDriverState *old_bs = child->bs;
debc2927
HR
2831 int new_bs_quiesce_counter;
2832 int drain_saldo;
e9740bc6 2833
2cad1ebe 2834 assert(!child->frozen);
bfb8aa6d 2835 assert(old_bs != new_bs);
f0c28327 2836 GLOBAL_STATE_CODE();
2cad1ebe 2837
bb2614e9
FZ
2838 if (old_bs && new_bs) {
2839 assert(bdrv_get_aio_context(old_bs) == bdrv_get_aio_context(new_bs));
2840 }
debc2927
HR
2841
2842 new_bs_quiesce_counter = (new_bs ? new_bs->quiesce_counter : 0);
2843 drain_saldo = new_bs_quiesce_counter - child->parent_quiesce_counter;
2844
2845 /*
2846 * If the new child node is drained but the old one was not, flush
2847 * all outstanding requests to the old child node.
2848 */
bd86fb99 2849 while (drain_saldo > 0 && child->klass->drained_begin) {
debc2927
HR
2850 bdrv_parent_drained_begin_single(child, true);
2851 drain_saldo--;
2852 }
2853
e9740bc6 2854 if (old_bs) {
d736f119
KW
2855 /* Detach first so that the recursive drain sections coming from @child
2856 * are already gone and we only end the drain sections that came from
2857 * elsewhere. */
bd86fb99
HR
2858 if (child->klass->detach) {
2859 child->klass->detach(child);
d736f119 2860 }
696bf4c7 2861 assert_bdrv_graph_writable(old_bs);
e9740bc6
KW
2862 QLIST_REMOVE(child, next_parent);
2863 }
36fe1331
KW
2864
2865 child->bs = new_bs;
2866
e9740bc6 2867 if (new_bs) {
696bf4c7 2868 assert_bdrv_graph_writable(new_bs);
e9740bc6 2869 QLIST_INSERT_HEAD(&new_bs->parents, child, next_parent);
debc2927
HR
2870
2871 /*
2872 * Detaching the old node may have led to the new node's
2873 * quiesce_counter having been decreased. Not a problem, we
2874 * just need to recognize this here and then invoke
2875 * drained_end appropriately more often.
2876 */
2877 assert(new_bs->quiesce_counter <= new_bs_quiesce_counter);
2878 drain_saldo += new_bs->quiesce_counter - new_bs_quiesce_counter;
33a610c3 2879
d736f119
KW
2880 /* Attach only after starting new drained sections, so that recursive
2881 * drain sections coming from @child don't get an extra .drained_begin
2882 * callback. */
bd86fb99
HR
2883 if (child->klass->attach) {
2884 child->klass->attach(child);
8ee03995
KW
2885 }
2886 }
debc2927
HR
2887
2888 /*
2889 * If the old child node was drained but the new one is not, allow
2890 * requests to come in only after the new node has been attached.
2891 */
bd86fb99 2892 while (drain_saldo < 0 && child->klass->drained_end) {
debc2927
HR
2893 bdrv_parent_drained_end_single(child);
2894 drain_saldo++;
2895 }
8ee03995 2896}
33a610c3 2897
04c9c3a5
HR
2898/**
2899 * Free the given @child.
2900 *
2901 * The child must be empty (i.e. `child->bs == NULL`) and it must be
2902 * unused (i.e. not in a children list).
2903 */
2904static void bdrv_child_free(BdrvChild *child)
df581792 2905{
548a74c0 2906 assert(!child->bs);
bdb73476 2907 GLOBAL_STATE_CODE();
a225369b 2908 assert(!child->next.le_prev); /* not in children list */
04c9c3a5
HR
2909
2910 g_free(child->name);
2911 g_free(child);
548a74c0 2912}
d5e6f437 2913
548a74c0 2914typedef struct BdrvAttachChildCommonState {
5bb04747 2915 BdrvChild *child;
548a74c0
VSO
2916 AioContext *old_parent_ctx;
2917 AioContext *old_child_ctx;
2918} BdrvAttachChildCommonState;
2919
2920static void bdrv_attach_child_common_abort(void *opaque)
2921{
2922 BdrvAttachChildCommonState *s = opaque;
5bb04747 2923 BlockDriverState *bs = s->child->bs;
548a74c0 2924
f0c28327 2925 GLOBAL_STATE_CODE();
5bb04747 2926 bdrv_replace_child_noperm(s->child, NULL);
548a74c0
VSO
2927
2928 if (bdrv_get_aio_context(bs) != s->old_child_ctx) {
142e6907 2929 bdrv_try_change_aio_context(bs, s->old_child_ctx, NULL, &error_abort);
548a74c0
VSO
2930 }
2931
5bb04747 2932 if (bdrv_child_get_parent_aio_context(s->child) != s->old_parent_ctx) {
f8be48ad
EGE
2933 Transaction *tran;
2934 GHashTable *visited;
2935 bool ret;
548a74c0 2936
f8be48ad 2937 tran = tran_new();
548a74c0 2938
f8be48ad
EGE
2939 /* No need to visit `child`, because it has been detached already */
2940 visited = g_hash_table_new(NULL, NULL);
2941 ret = s->child->klass->change_aio_ctx(s->child, s->old_parent_ctx,
2942 visited, tran, &error_abort);
2943 g_hash_table_destroy(visited);
2944
2945 /* transaction is supposed to always succeed */
2946 assert(ret == true);
2947 tran_commit(tran);
d5e6f437
KW
2948 }
2949
548a74c0 2950 bdrv_unref(bs);
5bb04747 2951 bdrv_child_free(s->child);
548a74c0
VSO
2952}
2953
2954static TransactionActionDrv bdrv_attach_child_common_drv = {
2955 .abort = bdrv_attach_child_common_abort,
2956 .clean = g_free,
2957};
2958
2959/*
2960 * Common part of attaching bdrv child to bs or to blk or to job
f8d2ad78 2961 *
7ec390d5 2962 * Function doesn't update permissions, caller is responsible for this.
5bb04747
VSO
2963 *
2964 * Returns new created child.
548a74c0 2965 */
5bb04747
VSO
2966static BdrvChild *bdrv_attach_child_common(BlockDriverState *child_bs,
2967 const char *child_name,
2968 const BdrvChildClass *child_class,
2969 BdrvChildRole child_role,
2970 uint64_t perm, uint64_t shared_perm,
2971 void *opaque,
2972 Transaction *tran, Error **errp)
548a74c0
VSO
2973{
2974 BdrvChild *new_child;
2975 AioContext *parent_ctx;
2976 AioContext *child_ctx = bdrv_get_aio_context(child_bs);
2977
da261b69 2978 assert(child_class->get_parent_desc);
bdb73476 2979 GLOBAL_STATE_CODE();
548a74c0
VSO
2980
2981 new_child = g_new(BdrvChild, 1);
2982 *new_child = (BdrvChild) {
d5e6f437
KW
2983 .bs = NULL,
2984 .name = g_strdup(child_name),
bd86fb99 2985 .klass = child_class,
258b7765 2986 .role = child_role,
d5e6f437
KW
2987 .perm = perm,
2988 .shared_perm = shared_perm,
2989 .opaque = opaque,
df581792
KW
2990 };
2991
548a74c0
VSO
2992 /*
2993 * If the AioContexts don't match, first try to move the subtree of
132ada80 2994 * child_bs into the AioContext of the new parent. If this doesn't work,
548a74c0
VSO
2995 * try moving the parent into the AioContext of child_bs instead.
2996 */
2997 parent_ctx = bdrv_child_get_parent_aio_context(new_child);
2998 if (child_ctx != parent_ctx) {
2999 Error *local_err = NULL;
142e6907
EGE
3000 int ret = bdrv_try_change_aio_context(child_bs, parent_ctx, NULL,
3001 &local_err);
548a74c0 3002
f8be48ad
EGE
3003 if (ret < 0 && child_class->change_aio_ctx) {
3004 Transaction *tran = tran_new();
3005 GHashTable *visited = g_hash_table_new(NULL, NULL);
3006 bool ret_child;
3007
3008 g_hash_table_add(visited, new_child);
3009 ret_child = child_class->change_aio_ctx(new_child, child_ctx,
3010 visited, tran, NULL);
3011 if (ret_child == true) {
132ada80
KW
3012 error_free(local_err);
3013 ret = 0;
132ada80 3014 }
f8be48ad
EGE
3015 tran_finalize(tran, ret_child == true ? 0 : -1);
3016 g_hash_table_destroy(visited);
132ada80 3017 }
548a74c0 3018
132ada80
KW
3019 if (ret < 0) {
3020 error_propagate(errp, local_err);
04c9c3a5 3021 bdrv_child_free(new_child);
5bb04747 3022 return NULL;
132ada80
KW
3023 }
3024 }
3025
548a74c0 3026 bdrv_ref(child_bs);
544acc7d 3027 bdrv_replace_child_noperm(new_child, child_bs);
b4b059f6 3028
548a74c0
VSO
3029 BdrvAttachChildCommonState *s = g_new(BdrvAttachChildCommonState, 1);
3030 *s = (BdrvAttachChildCommonState) {
5bb04747 3031 .child = new_child,
548a74c0
VSO
3032 .old_parent_ctx = parent_ctx,
3033 .old_child_ctx = child_ctx,
3034 };
3035 tran_add(tran, &bdrv_attach_child_common_drv, s);
3036
5bb04747 3037 return new_child;
548a74c0
VSO
3038}
3039
f8d2ad78 3040/*
7ec390d5 3041 * Function doesn't update permissions, caller is responsible for this.
f8d2ad78 3042 */
5bb04747
VSO
3043static BdrvChild *bdrv_attach_child_noperm(BlockDriverState *parent_bs,
3044 BlockDriverState *child_bs,
3045 const char *child_name,
3046 const BdrvChildClass *child_class,
3047 BdrvChildRole child_role,
3048 Transaction *tran,
3049 Error **errp)
aa5a04c7 3050{
aa5a04c7
VSO
3051 uint64_t perm, shared_perm;
3052
3053 assert(parent_bs->drv);
bdb73476 3054 GLOBAL_STATE_CODE();
aa5a04c7 3055
bfb8aa6d
KW
3056 if (bdrv_recurse_has_child(child_bs, parent_bs)) {
3057 error_setg(errp, "Making '%s' a %s child of '%s' would create a cycle",
3058 child_bs->node_name, child_name, parent_bs->node_name);
5bb04747 3059 return NULL;
bfb8aa6d
KW
3060 }
3061
aa5a04c7
VSO
3062 bdrv_get_cumulative_perm(parent_bs, &perm, &shared_perm);
3063 bdrv_child_perm(parent_bs, child_bs, NULL, child_role, NULL,
3064 perm, shared_perm, &perm, &shared_perm);
3065
5bb04747
VSO
3066 return bdrv_attach_child_common(child_bs, child_name, child_class,
3067 child_role, perm, shared_perm, parent_bs,
3068 tran, errp);
aa5a04c7
VSO
3069}
3070
548a74c0
VSO
3071/*
3072 * This function steals the reference to child_bs from the caller.
3073 * That reference is later dropped by bdrv_root_unref_child().
3074 *
3075 * On failure NULL is returned, errp is set and the reference to
3076 * child_bs is also dropped.
3077 *
3078 * The caller must hold the AioContext lock @child_bs, but not that of @ctx
3079 * (unless @child_bs is already in @ctx).
3080 */
3081BdrvChild *bdrv_root_attach_child(BlockDriverState *child_bs,
3082 const char *child_name,
3083 const BdrvChildClass *child_class,
3084 BdrvChildRole child_role,
3085 uint64_t perm, uint64_t shared_perm,
3086 void *opaque, Error **errp)
3087{
3088 int ret;
5bb04747 3089 BdrvChild *child;
548a74c0
VSO
3090 Transaction *tran = tran_new();
3091
b4ad82aa
EGE
3092 GLOBAL_STATE_CODE();
3093
5bb04747 3094 child = bdrv_attach_child_common(child_bs, child_name, child_class,
548a74c0 3095 child_role, perm, shared_perm, opaque,
5bb04747
VSO
3096 tran, errp);
3097 if (!child) {
3098 ret = -EINVAL;
e878bb12 3099 goto out;
548a74c0
VSO
3100 }
3101
3102 ret = bdrv_refresh_perms(child_bs, errp);
548a74c0 3103
e878bb12
KW
3104out:
3105 tran_finalize(tran, ret);
f8d2ad78 3106
548a74c0 3107 bdrv_unref(child_bs);
5bb04747
VSO
3108
3109 return ret < 0 ? NULL : child;
df581792
KW
3110}
3111
b441dc71
AG
3112/*
3113 * This function transfers the reference to child_bs from the caller
3114 * to parent_bs. That reference is later dropped by parent_bs on
3115 * bdrv_close() or if someone calls bdrv_unref_child().
3116 *
3117 * On failure NULL is returned, errp is set and the reference to
3118 * child_bs is also dropped.
132ada80
KW
3119 *
3120 * If @parent_bs and @child_bs are in different AioContexts, the caller must
3121 * hold the AioContext lock for @child_bs, but not for @parent_bs.
b441dc71 3122 */
98292c61
WC
3123BdrvChild *bdrv_attach_child(BlockDriverState *parent_bs,
3124 BlockDriverState *child_bs,
3125 const char *child_name,
bd86fb99 3126 const BdrvChildClass *child_class,
258b7765 3127 BdrvChildRole child_role,
8b2ff529 3128 Error **errp)
f21d96d0 3129{
aa5a04c7 3130 int ret;
5bb04747 3131 BdrvChild *child;
aa5a04c7 3132 Transaction *tran = tran_new();
f68c598b 3133
f791bf7f
EGE
3134 GLOBAL_STATE_CODE();
3135
5bb04747
VSO
3136 child = bdrv_attach_child_noperm(parent_bs, child_bs, child_name,
3137 child_class, child_role, tran, errp);
3138 if (!child) {
3139 ret = -EINVAL;
aa5a04c7
VSO
3140 goto out;
3141 }
d5e6f437 3142
aa5a04c7
VSO
3143 ret = bdrv_refresh_perms(parent_bs, errp);
3144 if (ret < 0) {
3145 goto out;
d5e6f437
KW
3146 }
3147
aa5a04c7
VSO
3148out:
3149 tran_finalize(tran, ret);
3150
3151 bdrv_unref(child_bs);
3152
5bb04747 3153 return ret < 0 ? NULL : child;
f21d96d0
KW
3154}
3155
7b99a266 3156/* Callers must ensure that child->frozen is false. */
f21d96d0 3157void bdrv_root_unref_child(BdrvChild *child)
33a60407 3158{
00eb93b5 3159 BlockDriverState *child_bs = child->bs;
779020cb 3160
f791bf7f 3161 GLOBAL_STATE_CODE();
00eb93b5
VSO
3162 bdrv_replace_child_noperm(child, NULL);
3163 bdrv_child_free(child);
3164
3165 if (child_bs) {
3166 /*
3167 * Update permissions for old node. We're just taking a parent away, so
3168 * we're loosening restrictions. Errors of permission update are not
3169 * fatal in this case, ignore them.
3170 */
3171 bdrv_refresh_perms(child_bs, NULL);
3172
3173 /*
3174 * When the parent requiring a non-default AioContext is removed, the
3175 * node moves back to the main AioContext
3176 */
3177 bdrv_try_change_aio_context(child_bs, qemu_get_aio_context(), NULL,
3178 NULL);
3179 }
f791bf7f 3180
f21d96d0
KW
3181 bdrv_unref(child_bs);
3182}
3183
332b3a17
VSO
3184typedef struct BdrvSetInheritsFrom {
3185 BlockDriverState *bs;
3186 BlockDriverState *old_inherits_from;
3187} BdrvSetInheritsFrom;
3188
3189static void bdrv_set_inherits_from_abort(void *opaque)
3190{
3191 BdrvSetInheritsFrom *s = opaque;
3192
3193 s->bs->inherits_from = s->old_inherits_from;
3194}
3195
3196static TransactionActionDrv bdrv_set_inherits_from_drv = {
3197 .abort = bdrv_set_inherits_from_abort,
3198 .clean = g_free,
3199};
3200
3201/* @tran is allowed to be NULL. In this case no rollback is possible */
3202static void bdrv_set_inherits_from(BlockDriverState *bs,
3203 BlockDriverState *new_inherits_from,
3204 Transaction *tran)
3205{
3206 if (tran) {
3207 BdrvSetInheritsFrom *s = g_new(BdrvSetInheritsFrom, 1);
3208
3209 *s = (BdrvSetInheritsFrom) {
3210 .bs = bs,
3211 .old_inherits_from = bs->inherits_from,
3212 };
3213
3214 tran_add(tran, &bdrv_set_inherits_from_drv, s);
3215 }
3216
3217 bs->inherits_from = new_inherits_from;
3218}
3219
3cf746b3
HR
3220/**
3221 * Clear all inherits_from pointers from children and grandchildren of
3222 * @root that point to @root, where necessary.
332b3a17 3223 * @tran is allowed to be NULL. In this case no rollback is possible
3cf746b3 3224 */
332b3a17
VSO
3225static void bdrv_unset_inherits_from(BlockDriverState *root, BdrvChild *child,
3226 Transaction *tran)
f21d96d0 3227{
3cf746b3 3228 BdrvChild *c;
4e4bf5c4 3229
3cf746b3
HR
3230 if (child->bs->inherits_from == root) {
3231 /*
3232 * Remove inherits_from only when the last reference between root and
3233 * child->bs goes away.
3234 */
3235 QLIST_FOREACH(c, &root->children, next) {
4e4bf5c4
KW
3236 if (c != child && c->bs == child->bs) {
3237 break;
3238 }
3239 }
3240 if (c == NULL) {
332b3a17 3241 bdrv_set_inherits_from(child->bs, NULL, tran);
4e4bf5c4 3242 }
33a60407
KW
3243 }
3244
3cf746b3 3245 QLIST_FOREACH(c, &child->bs->children, next) {
332b3a17 3246 bdrv_unset_inherits_from(root, c, tran);
3cf746b3
HR
3247 }
3248}
3249
7b99a266 3250/* Callers must ensure that child->frozen is false. */
3cf746b3
HR
3251void bdrv_unref_child(BlockDriverState *parent, BdrvChild *child)
3252{
f791bf7f 3253 GLOBAL_STATE_CODE();
3cf746b3
HR
3254 if (child == NULL) {
3255 return;
3256 }
3257
332b3a17 3258 bdrv_unset_inherits_from(parent, child, NULL);
f21d96d0 3259 bdrv_root_unref_child(child);
33a60407
KW
3260}
3261
5c8cab48
KW
3262
3263static void bdrv_parent_cb_change_media(BlockDriverState *bs, bool load)
3264{
3265 BdrvChild *c;
f0c28327 3266 GLOBAL_STATE_CODE();
5c8cab48 3267 QLIST_FOREACH(c, &bs->parents, next_parent) {
bd86fb99
HR
3268 if (c->klass->change_media) {
3269 c->klass->change_media(c, load);
5c8cab48
KW
3270 }
3271 }
3272}
3273
0065c455
AG
3274/* Return true if you can reach parent going through child->inherits_from
3275 * recursively. If parent or child are NULL, return false */
3276static bool bdrv_inherits_from_recursive(BlockDriverState *child,
3277 BlockDriverState *parent)
3278{
3279 while (child && child != parent) {
3280 child = child->inherits_from;
3281 }
3282
3283 return child != NULL;
3284}
3285
25191e5f
HR
3286/*
3287 * Return the BdrvChildRole for @bs's backing child. bs->backing is
3288 * mostly used for COW backing children (role = COW), but also for
3289 * filtered children (role = FILTERED | PRIMARY).
3290 */
3291static BdrvChildRole bdrv_backing_role(BlockDriverState *bs)
3292{
3293 if (bs->drv && bs->drv->is_filter) {
3294 return BDRV_CHILD_FILTERED | BDRV_CHILD_PRIMARY;
3295 } else {
3296 return BDRV_CHILD_COW;
3297 }
3298}
3299
5db15a57 3300/*
e9238278
VSO
3301 * Sets the bs->backing or bs->file link of a BDS. A new reference is created;
3302 * callers which don't need their own reference any more must call bdrv_unref().
7ec390d5
VSO
3303 *
3304 * Function doesn't update permissions, caller is responsible for this.
5db15a57 3305 */
e9238278
VSO
3306static int bdrv_set_file_or_backing_noperm(BlockDriverState *parent_bs,
3307 BlockDriverState *child_bs,
3308 bool is_backing,
3309 Transaction *tran, Error **errp)
8d24cce1 3310{
e9238278
VSO
3311 bool update_inherits_from =
3312 bdrv_inherits_from_recursive(child_bs, parent_bs);
3313 BdrvChild *child = is_backing ? parent_bs->backing : parent_bs->file;
3314 BdrvChildRole role;
0065c455 3315
bdb73476
EGE
3316 GLOBAL_STATE_CODE();
3317
e9238278
VSO
3318 if (!parent_bs->drv) {
3319 /*
3320 * Node without drv is an object without a class :/. TODO: finally fix
3321 * qcow2 driver to never clear bs->drv and implement format corruption
3322 * handling in other way.
3323 */
3324 error_setg(errp, "Node corrupted");
3325 return -EINVAL;
3326 }
3327
3328 if (child && child->frozen) {
3329 error_setg(errp, "Cannot change frozen '%s' link from '%s' to '%s'",
3330 child->name, parent_bs->node_name, child->bs->node_name);
a1e708fc 3331 return -EPERM;
2cad1ebe
AG
3332 }
3333
25f78d9e
VSO
3334 if (is_backing && !parent_bs->drv->is_filter &&
3335 !parent_bs->drv->supports_backing)
3336 {
3337 error_setg(errp, "Driver '%s' of node '%s' does not support backing "
3338 "files", parent_bs->drv->format_name, parent_bs->node_name);
3339 return -EINVAL;
3340 }
3341
e9238278
VSO
3342 if (parent_bs->drv->is_filter) {
3343 role = BDRV_CHILD_FILTERED | BDRV_CHILD_PRIMARY;
3344 } else if (is_backing) {
3345 role = BDRV_CHILD_COW;
3346 } else {
3347 /*
3348 * We only can use same role as it is in existing child. We don't have
3349 * infrastructure to determine role of file child in generic way
3350 */
3351 if (!child) {
3352 error_setg(errp, "Cannot set file child to format node without "
3353 "file child");
3354 return -EINVAL;
3355 }
3356 role = child->role;
826b6ca0
FZ
3357 }
3358
e9238278
VSO
3359 if (child) {
3360 bdrv_unset_inherits_from(parent_bs, child, tran);
57f08941 3361 bdrv_remove_child(child, tran);
e9238278
VSO
3362 }
3363
3364 if (!child_bs) {
8d24cce1
FZ
3365 goto out;
3366 }
12fa4af6 3367
5bb04747
VSO
3368 child = bdrv_attach_child_noperm(parent_bs, child_bs,
3369 is_backing ? "backing" : "file",
3370 &child_of_bds, role,
3371 tran, errp);
3372 if (!child) {
3373 return -EINVAL;
a1e708fc
VSO
3374 }
3375
160333e1
VSO
3376
3377 /*
e9238278 3378 * If inherits_from pointed recursively to bs then let's update it to
160333e1
VSO
3379 * point directly to bs (else it will become NULL).
3380 */
a1e708fc 3381 if (update_inherits_from) {
e9238278 3382 bdrv_set_inherits_from(child_bs, parent_bs, tran);
0065c455 3383 }
826b6ca0 3384
8d24cce1 3385out:
e9238278 3386 bdrv_refresh_limits(parent_bs, tran, NULL);
160333e1
VSO
3387
3388 return 0;
3389}
3390
e9238278
VSO
3391static int bdrv_set_backing_noperm(BlockDriverState *bs,
3392 BlockDriverState *backing_hd,
3393 Transaction *tran, Error **errp)
3394{
bdb73476 3395 GLOBAL_STATE_CODE();
e9238278
VSO
3396 return bdrv_set_file_or_backing_noperm(bs, backing_hd, true, tran, errp);
3397}
3398
160333e1
VSO
3399int bdrv_set_backing_hd(BlockDriverState *bs, BlockDriverState *backing_hd,
3400 Error **errp)
3401{
3402 int ret;
3403 Transaction *tran = tran_new();
3404
f791bf7f 3405 GLOBAL_STATE_CODE();
c0829cb1
VSO
3406 bdrv_drained_begin(bs);
3407
160333e1
VSO
3408 ret = bdrv_set_backing_noperm(bs, backing_hd, tran, errp);
3409 if (ret < 0) {
3410 goto out;
3411 }
3412
3413 ret = bdrv_refresh_perms(bs, errp);
3414out:
3415 tran_finalize(tran, ret);
a1e708fc 3416
c0829cb1
VSO
3417 bdrv_drained_end(bs);
3418
a1e708fc 3419 return ret;
8d24cce1
FZ
3420}
3421
31ca6d07
KW
3422/*
3423 * Opens the backing file for a BlockDriverState if not yet open
3424 *
d9b7b057
KW
3425 * bdref_key specifies the key for the image's BlockdevRef in the options QDict.
3426 * That QDict has to be flattened; therefore, if the BlockdevRef is a QDict
3427 * itself, all options starting with "${bdref_key}." are considered part of the
3428 * BlockdevRef.
3429 *
3430 * TODO Can this be unified with bdrv_open_image()?
31ca6d07 3431 */
d9b7b057
KW
3432int bdrv_open_backing_file(BlockDriverState *bs, QDict *parent_options,
3433 const char *bdref_key, Error **errp)
9156df12 3434{
6b6833c1 3435 char *backing_filename = NULL;
d9b7b057
KW
3436 char *bdref_key_dot;
3437 const char *reference = NULL;
317fc44e 3438 int ret = 0;
998c2019 3439 bool implicit_backing = false;
8d24cce1 3440 BlockDriverState *backing_hd;
d9b7b057
KW
3441 QDict *options;
3442 QDict *tmp_parent_options = NULL;
34b5d2c6 3443 Error *local_err = NULL;
9156df12 3444
f791bf7f
EGE
3445 GLOBAL_STATE_CODE();
3446
760e0063 3447 if (bs->backing != NULL) {
1ba4b6a5 3448 goto free_exit;
9156df12
PB
3449 }
3450
31ca6d07 3451 /* NULL means an empty set of options */
d9b7b057
KW
3452 if (parent_options == NULL) {
3453 tmp_parent_options = qdict_new();
3454 parent_options = tmp_parent_options;
31ca6d07
KW
3455 }
3456
9156df12 3457 bs->open_flags &= ~BDRV_O_NO_BACKING;
d9b7b057
KW
3458
3459 bdref_key_dot = g_strdup_printf("%s.", bdref_key);
3460 qdict_extract_subqdict(parent_options, &options, bdref_key_dot);
3461 g_free(bdref_key_dot);
3462
129c7d1c
MA
3463 /*
3464 * Caution: while qdict_get_try_str() is fine, getting non-string
3465 * types would require more care. When @parent_options come from
3466 * -blockdev or blockdev_add, its members are typed according to
3467 * the QAPI schema, but when they come from -drive, they're all
3468 * QString.
3469 */
d9b7b057
KW
3470 reference = qdict_get_try_str(parent_options, bdref_key);
3471 if (reference || qdict_haskey(options, "file.filename")) {
6b6833c1 3472 /* keep backing_filename NULL */
1cb6f506 3473 } else if (bs->backing_file[0] == '\0' && qdict_size(options) == 0) {
cb3e7f08 3474 qobject_unref(options);
1ba4b6a5 3475 goto free_exit;
dbecebdd 3476 } else {
998c2019
HR
3477 if (qdict_size(options) == 0) {
3478 /* If the user specifies options that do not modify the
3479 * backing file's behavior, we might still consider it the
3480 * implicit backing file. But it's easier this way, and
3481 * just specifying some of the backing BDS's options is
3482 * only possible with -drive anyway (otherwise the QAPI
3483 * schema forces the user to specify everything). */
3484 implicit_backing = !strcmp(bs->auto_backing_file, bs->backing_file);
3485 }
3486
6b6833c1 3487 backing_filename = bdrv_get_full_backing_filename(bs, &local_err);
9f07429e
HR
3488 if (local_err) {
3489 ret = -EINVAL;
3490 error_propagate(errp, local_err);
cb3e7f08 3491 qobject_unref(options);
9f07429e
HR
3492 goto free_exit;
3493 }
9156df12
PB
3494 }
3495
8ee79e70
KW
3496 if (!bs->drv || !bs->drv->supports_backing) {
3497 ret = -EINVAL;
3498 error_setg(errp, "Driver doesn't support backing files");
cb3e7f08 3499 qobject_unref(options);
8ee79e70
KW
3500 goto free_exit;
3501 }
3502
6bff597b
PK
3503 if (!reference &&
3504 bs->backing_format[0] != '\0' && !qdict_haskey(options, "driver")) {
46f5ac20 3505 qdict_put_str(options, "driver", bs->backing_format);
9156df12
PB
3506 }
3507
6b6833c1 3508 backing_hd = bdrv_open_inherit(backing_filename, reference, options, 0, bs,
25191e5f 3509 &child_of_bds, bdrv_backing_role(bs), errp);
5b363937 3510 if (!backing_hd) {
9156df12 3511 bs->open_flags |= BDRV_O_NO_BACKING;
e43bfd9c 3512 error_prepend(errp, "Could not open backing file: ");
5b363937 3513 ret = -EINVAL;
1ba4b6a5 3514 goto free_exit;
9156df12 3515 }
df581792 3516
998c2019
HR
3517 if (implicit_backing) {
3518 bdrv_refresh_filename(backing_hd);
3519 pstrcpy(bs->auto_backing_file, sizeof(bs->auto_backing_file),
3520 backing_hd->filename);
3521 }
3522
5db15a57
KW
3523 /* Hook up the backing file link; drop our reference, bs owns the
3524 * backing_hd reference now */
dc9c10a1 3525 ret = bdrv_set_backing_hd(bs, backing_hd, errp);
5db15a57 3526 bdrv_unref(backing_hd);
dc9c10a1 3527 if (ret < 0) {
12fa4af6
KW
3528 goto free_exit;
3529 }
d80ac658 3530
d9b7b057
KW
3531 qdict_del(parent_options, bdref_key);
3532
1ba4b6a5
BC
3533free_exit:
3534 g_free(backing_filename);
cb3e7f08 3535 qobject_unref(tmp_parent_options);
1ba4b6a5 3536 return ret;
9156df12
PB
3537}
3538
2d6b86af
KW
3539static BlockDriverState *
3540bdrv_open_child_bs(const char *filename, QDict *options, const char *bdref_key,
bd86fb99 3541 BlockDriverState *parent, const BdrvChildClass *child_class,
272c02ea 3542 BdrvChildRole child_role, bool allow_none, Error **errp)
da557aac 3543{
2d6b86af 3544 BlockDriverState *bs = NULL;
da557aac 3545 QDict *image_options;
da557aac
HR
3546 char *bdref_key_dot;
3547 const char *reference;
3548
bd86fb99 3549 assert(child_class != NULL);
f67503e5 3550
da557aac
HR
3551 bdref_key_dot = g_strdup_printf("%s.", bdref_key);
3552 qdict_extract_subqdict(options, &image_options, bdref_key_dot);
3553 g_free(bdref_key_dot);
3554
129c7d1c
MA
3555 /*
3556 * Caution: while qdict_get_try_str() is fine, getting non-string
3557 * types would require more care. When @options come from
3558 * -blockdev or blockdev_add, its members are typed according to
3559 * the QAPI schema, but when they come from -drive, they're all
3560 * QString.
3561 */
da557aac
HR
3562 reference = qdict_get_try_str(options, bdref_key);
3563 if (!filename && !reference && !qdict_size(image_options)) {
b4b059f6 3564 if (!allow_none) {
da557aac
HR
3565 error_setg(errp, "A block device must be specified for \"%s\"",
3566 bdref_key);
da557aac 3567 }
cb3e7f08 3568 qobject_unref(image_options);
da557aac
HR
3569 goto done;
3570 }
3571
5b363937 3572 bs = bdrv_open_inherit(filename, reference, image_options, 0,
272c02ea 3573 parent, child_class, child_role, errp);
5b363937 3574 if (!bs) {
df581792
KW
3575 goto done;
3576 }
3577
da557aac
HR
3578done:
3579 qdict_del(options, bdref_key);
2d6b86af
KW
3580 return bs;
3581}
3582
3583/*
3584 * Opens a disk image whose options are given as BlockdevRef in another block
3585 * device's options.
3586 *
3587 * If allow_none is true, no image will be opened if filename is false and no
3588 * BlockdevRef is given. NULL will be returned, but errp remains unset.
3589 *
3590 * bdrev_key specifies the key for the image's BlockdevRef in the options QDict.
3591 * That QDict has to be flattened; therefore, if the BlockdevRef is a QDict
3592 * itself, all options starting with "${bdref_key}." are considered part of the
3593 * BlockdevRef.
3594 *
3595 * The BlockdevRef will be removed from the options QDict.
3596 */
3597BdrvChild *bdrv_open_child(const char *filename,
3598 QDict *options, const char *bdref_key,
3599 BlockDriverState *parent,
bd86fb99 3600 const BdrvChildClass *child_class,
258b7765 3601 BdrvChildRole child_role,
2d6b86af
KW
3602 bool allow_none, Error **errp)
3603{
3604 BlockDriverState *bs;
3605
f791bf7f
EGE
3606 GLOBAL_STATE_CODE();
3607
bd86fb99 3608 bs = bdrv_open_child_bs(filename, options, bdref_key, parent, child_class,
272c02ea 3609 child_role, allow_none, errp);
2d6b86af
KW
3610 if (bs == NULL) {
3611 return NULL;
3612 }
3613
258b7765
HR
3614 return bdrv_attach_child(parent, bs, bdref_key, child_class, child_role,
3615 errp);
b4b059f6
KW
3616}
3617
83930780
VSO
3618/*
3619 * Wrapper on bdrv_open_child() for most popular case: open primary child of bs.
3620 */
3621int bdrv_open_file_child(const char *filename,
3622 QDict *options, const char *bdref_key,
3623 BlockDriverState *parent, Error **errp)
3624{
3625 BdrvChildRole role;
3626
3627 /* commit_top and mirror_top don't use this function */
3628 assert(!parent->drv->filtered_child_is_backing);
83930780
VSO
3629 role = parent->drv->is_filter ?
3630 (BDRV_CHILD_FILTERED | BDRV_CHILD_PRIMARY) : BDRV_CHILD_IMAGE;
3631
5bb04747
VSO
3632 if (!bdrv_open_child(filename, options, bdref_key, parent,
3633 &child_of_bds, role, false, errp))
3634 {
3635 return -EINVAL;
3636 }
83930780 3637
5bb04747 3638 return 0;
83930780
VSO
3639}
3640
bd86fb99
HR
3641/*
3642 * TODO Future callers may need to specify parent/child_class in order for
3643 * option inheritance to work. Existing callers use it for the root node.
3644 */
e1d74bc6
KW
3645BlockDriverState *bdrv_open_blockdev_ref(BlockdevRef *ref, Error **errp)
3646{
3647 BlockDriverState *bs = NULL;
e1d74bc6
KW
3648 QObject *obj = NULL;
3649 QDict *qdict = NULL;
3650 const char *reference = NULL;
3651 Visitor *v = NULL;
3652
f791bf7f
EGE
3653 GLOBAL_STATE_CODE();
3654
e1d74bc6
KW
3655 if (ref->type == QTYPE_QSTRING) {
3656 reference = ref->u.reference;
3657 } else {
3658 BlockdevOptions *options = &ref->u.definition;
3659 assert(ref->type == QTYPE_QDICT);
3660
3661 v = qobject_output_visitor_new(&obj);
1f584248 3662 visit_type_BlockdevOptions(v, NULL, &options, &error_abort);
e1d74bc6
KW
3663 visit_complete(v, &obj);
3664
7dc847eb 3665 qdict = qobject_to(QDict, obj);
e1d74bc6
KW
3666 qdict_flatten(qdict);
3667
3668 /* bdrv_open_inherit() defaults to the values in bdrv_flags (for
3669 * compatibility with other callers) rather than what we want as the
3670 * real defaults. Apply the defaults here instead. */
3671 qdict_set_default_str(qdict, BDRV_OPT_CACHE_DIRECT, "off");
3672 qdict_set_default_str(qdict, BDRV_OPT_CACHE_NO_FLUSH, "off");
3673 qdict_set_default_str(qdict, BDRV_OPT_READ_ONLY, "off");
e35bdc12
KW
3674 qdict_set_default_str(qdict, BDRV_OPT_AUTO_READ_ONLY, "off");
3675
e1d74bc6
KW
3676 }
3677
272c02ea 3678 bs = bdrv_open_inherit(NULL, reference, qdict, 0, NULL, NULL, 0, errp);
e1d74bc6 3679 obj = NULL;
cb3e7f08 3680 qobject_unref(obj);
e1d74bc6
KW
3681 visit_free(v);
3682 return bs;
3683}
3684
66836189
HR
3685static BlockDriverState *bdrv_append_temp_snapshot(BlockDriverState *bs,
3686 int flags,
3687 QDict *snapshot_options,
3688 Error **errp)
b998875d 3689{
69fbfff9 3690 g_autofree char *tmp_filename = NULL;
b998875d 3691 int64_t total_size;
83d0521a 3692 QemuOpts *opts = NULL;
ff6ed714 3693 BlockDriverState *bs_snapshot = NULL;
b998875d
KW
3694 int ret;
3695
bdb73476
EGE
3696 GLOBAL_STATE_CODE();
3697
b998875d
KW
3698 /* if snapshot, we create a temporary backing file and open it
3699 instead of opening 'filename' directly */
3700
3701 /* Get the required size from the image */
f187743a
KW
3702 total_size = bdrv_getlength(bs);
3703 if (total_size < 0) {
3704 error_setg_errno(errp, -total_size, "Could not get image size");
1ba4b6a5 3705 goto out;
f187743a 3706 }
b998875d
KW
3707
3708 /* Create the temporary image */
69fbfff9
BM
3709 tmp_filename = create_tmp_file(errp);
3710 if (!tmp_filename) {
1ba4b6a5 3711 goto out;
b998875d
KW
3712 }
3713
ef810437 3714 opts = qemu_opts_create(bdrv_qcow2.create_opts, NULL, 0,
c282e1fd 3715 &error_abort);
39101f25 3716 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, total_size, &error_abort);
e43bfd9c 3717 ret = bdrv_create(&bdrv_qcow2, tmp_filename, opts, errp);
83d0521a 3718 qemu_opts_del(opts);
b998875d 3719 if (ret < 0) {
e43bfd9c
MA
3720 error_prepend(errp, "Could not create temporary overlay '%s': ",
3721 tmp_filename);
1ba4b6a5 3722 goto out;
b998875d
KW
3723 }
3724
73176bee 3725 /* Prepare options QDict for the temporary file */
46f5ac20
EB
3726 qdict_put_str(snapshot_options, "file.driver", "file");
3727 qdict_put_str(snapshot_options, "file.filename", tmp_filename);
3728 qdict_put_str(snapshot_options, "driver", "qcow2");
b998875d 3729
5b363937 3730 bs_snapshot = bdrv_open(NULL, NULL, snapshot_options, flags, errp);
73176bee 3731 snapshot_options = NULL;
5b363937 3732 if (!bs_snapshot) {
1ba4b6a5 3733 goto out;
b998875d
KW
3734 }
3735
934aee14
VSO
3736 ret = bdrv_append(bs_snapshot, bs, errp);
3737 if (ret < 0) {
ff6ed714 3738 bs_snapshot = NULL;
b2c2832c
KW
3739 goto out;
3740 }
1ba4b6a5
BC
3741
3742out:
cb3e7f08 3743 qobject_unref(snapshot_options);
ff6ed714 3744 return bs_snapshot;
b998875d
KW
3745}
3746
b6ce07aa
KW
3747/*
3748 * Opens a disk image (raw, qcow2, vmdk, ...)
de9c0cec
KW
3749 *
3750 * options is a QDict of options to pass to the block drivers, or NULL for an
3751 * empty set of options. The reference to the QDict belongs to the block layer
3752 * after the call (even on failure), so if the caller intends to reuse the
cb3e7f08 3753 * dictionary, it needs to use qobject_ref() before calling bdrv_open.
f67503e5
HR
3754 *
3755 * If *pbs is NULL, a new BDS will be created with a pointer to it stored there.
3756 * If it is not NULL, the referenced BDS will be reused.
ddf5636d
HR
3757 *
3758 * The reference parameter may be used to specify an existing block device which
3759 * should be opened. If specified, neither options nor a filename may be given,
3760 * nor can an existing BDS be reused (that is, *pbs has to be NULL).
b6ce07aa 3761 */
5b363937
HR
3762static BlockDriverState *bdrv_open_inherit(const char *filename,
3763 const char *reference,
3764 QDict *options, int flags,
3765 BlockDriverState *parent,
bd86fb99 3766 const BdrvChildClass *child_class,
272c02ea 3767 BdrvChildRole child_role,
5b363937 3768 Error **errp)
ea2384d3 3769{
b6ce07aa 3770 int ret;
5696c6e3 3771 BlockBackend *file = NULL;
9a4f4c31 3772 BlockDriverState *bs;
ce343771 3773 BlockDriver *drv = NULL;
2f624b80 3774 BdrvChild *child;
74fe54f2 3775 const char *drvname;
3e8c2e57 3776 const char *backing;
34b5d2c6 3777 Error *local_err = NULL;
73176bee 3778 QDict *snapshot_options = NULL;
b1e6fc08 3779 int snapshot_flags = 0;
712e7874 3780
bd86fb99
HR
3781 assert(!child_class || !flags);
3782 assert(!child_class == !parent);
f0c28327 3783 GLOBAL_STATE_CODE();
f67503e5 3784
ddf5636d
HR
3785 if (reference) {
3786 bool options_non_empty = options ? qdict_size(options) : false;
cb3e7f08 3787 qobject_unref(options);
ddf5636d 3788
ddf5636d
HR
3789 if (filename || options_non_empty) {
3790 error_setg(errp, "Cannot reference an existing block device with "
3791 "additional options or a new filename");
5b363937 3792 return NULL;
ddf5636d
HR
3793 }
3794
3795 bs = bdrv_lookup_bs(reference, reference, errp);
3796 if (!bs) {
5b363937 3797 return NULL;
ddf5636d 3798 }
76b22320 3799
ddf5636d 3800 bdrv_ref(bs);
5b363937 3801 return bs;
ddf5636d
HR
3802 }
3803
5b363937 3804 bs = bdrv_new();
f67503e5 3805
de9c0cec
KW
3806 /* NULL means an empty set of options */
3807 if (options == NULL) {
3808 options = qdict_new();
3809 }
3810
145f598e 3811 /* json: syntax counts as explicit options, as if in the QDict */
de3b53f0
KW
3812 parse_json_protocol(options, &filename, &local_err);
3813 if (local_err) {
de3b53f0
KW
3814 goto fail;
3815 }
3816
145f598e
KW
3817 bs->explicit_options = qdict_clone_shallow(options);
3818
bd86fb99 3819 if (child_class) {
3cdc69d3
HR
3820 bool parent_is_format;
3821
3822 if (parent->drv) {
3823 parent_is_format = parent->drv->is_format;
3824 } else {
3825 /*
3826 * parent->drv is not set yet because this node is opened for
3827 * (potential) format probing. That means that @parent is going
3828 * to be a format node.
3829 */
3830 parent_is_format = true;
3831 }
3832
bddcec37 3833 bs->inherits_from = parent;
3cdc69d3
HR
3834 child_class->inherit_options(child_role, parent_is_format,
3835 &flags, options,
bd86fb99 3836 parent->open_flags, parent->options);
f3930ed0
KW
3837 }
3838
de3b53f0 3839 ret = bdrv_fill_options(&options, filename, &flags, &local_err);
dfde483e 3840 if (ret < 0) {
462f5bcf
KW
3841 goto fail;
3842 }
3843
129c7d1c
MA
3844 /*
3845 * Set the BDRV_O_RDWR and BDRV_O_ALLOW_RDWR flags.
3846 * Caution: getting a boolean member of @options requires care.
3847 * When @options come from -blockdev or blockdev_add, members are
3848 * typed according to the QAPI schema, but when they come from
3849 * -drive, they're all QString.
3850 */
f87a0e29
AG
3851 if (g_strcmp0(qdict_get_try_str(options, BDRV_OPT_READ_ONLY), "on") &&
3852 !qdict_get_try_bool(options, BDRV_OPT_READ_ONLY, false)) {
3853 flags |= (BDRV_O_RDWR | BDRV_O_ALLOW_RDWR);
3854 } else {
3855 flags &= ~BDRV_O_RDWR;
14499ea5
AG
3856 }
3857
3858 if (flags & BDRV_O_SNAPSHOT) {
3859 snapshot_options = qdict_new();
3860 bdrv_temp_snapshot_options(&snapshot_flags, snapshot_options,
3861 flags, options);
f87a0e29
AG
3862 /* Let bdrv_backing_options() override "read-only" */
3863 qdict_del(options, BDRV_OPT_READ_ONLY);
00ff7ffd
HR
3864 bdrv_inherited_options(BDRV_CHILD_COW, true,
3865 &flags, options, flags, options);
14499ea5
AG
3866 }
3867
62392ebb
KW
3868 bs->open_flags = flags;
3869 bs->options = options;
3870 options = qdict_clone_shallow(options);
3871
76c591b0 3872 /* Find the right image format driver */
129c7d1c 3873 /* See cautionary note on accessing @options above */
76c591b0
KW
3874 drvname = qdict_get_try_str(options, "driver");
3875 if (drvname) {
3876 drv = bdrv_find_format(drvname);
76c591b0
KW
3877 if (!drv) {
3878 error_setg(errp, "Unknown driver: '%s'", drvname);
76c591b0
KW
3879 goto fail;
3880 }
3881 }
3882
3883 assert(drvname || !(flags & BDRV_O_PROTOCOL));
76c591b0 3884
129c7d1c 3885 /* See cautionary note on accessing @options above */
3e8c2e57 3886 backing = qdict_get_try_str(options, "backing");
e59a0cf1
HR
3887 if (qobject_to(QNull, qdict_get(options, "backing")) != NULL ||
3888 (backing && *backing == '\0'))
3889 {
4f7be280
HR
3890 if (backing) {
3891 warn_report("Use of \"backing\": \"\" is deprecated; "
3892 "use \"backing\": null instead");
3893 }
3e8c2e57 3894 flags |= BDRV_O_NO_BACKING;
ae0f57f0
KW
3895 qdict_del(bs->explicit_options, "backing");
3896 qdict_del(bs->options, "backing");
3e8c2e57
AG
3897 qdict_del(options, "backing");
3898 }
3899
5696c6e3 3900 /* Open image file without format layer. This BlockBackend is only used for
4e4bf5c4
KW
3901 * probing, the block drivers will do their own bdrv_open_child() for the
3902 * same BDS, which is why we put the node name back into options. */
f4788adc 3903 if ((flags & BDRV_O_PROTOCOL) == 0) {
5696c6e3
KW
3904 BlockDriverState *file_bs;
3905
3906 file_bs = bdrv_open_child_bs(filename, options, "file", bs,
58944401
HR
3907 &child_of_bds, BDRV_CHILD_IMAGE,
3908 true, &local_err);
1fdd6933 3909 if (local_err) {
f4788adc
KW
3910 goto fail;
3911 }
5696c6e3 3912 if (file_bs != NULL) {
dacaa162
KW
3913 /* Not requesting BLK_PERM_CONSISTENT_READ because we're only
3914 * looking at the header to guess the image format. This works even
3915 * in cases where a guest would not see a consistent state. */
d861ab3a 3916 file = blk_new(bdrv_get_aio_context(file_bs), 0, BLK_PERM_ALL);
d7086422 3917 blk_insert_bs(file, file_bs, &local_err);
5696c6e3 3918 bdrv_unref(file_bs);
d7086422
KW
3919 if (local_err) {
3920 goto fail;
3921 }
5696c6e3 3922
46f5ac20 3923 qdict_put_str(options, "file", bdrv_get_node_name(file_bs));
4e4bf5c4 3924 }
f500a6d3
KW
3925 }
3926
76c591b0 3927 /* Image format probing */
38f3ef57 3928 bs->probed = !drv;
76c591b0 3929 if (!drv && file) {
cf2ab8fc 3930 ret = find_image_format(file, filename, &drv, &local_err);
17b005f1 3931 if (ret < 0) {
8bfea15d 3932 goto fail;
2a05cbe4 3933 }
62392ebb
KW
3934 /*
3935 * This option update would logically belong in bdrv_fill_options(),
3936 * but we first need to open bs->file for the probing to work, while
3937 * opening bs->file already requires the (mostly) final set of options
3938 * so that cache mode etc. can be inherited.
3939 *
3940 * Adding the driver later is somewhat ugly, but it's not an option
3941 * that would ever be inherited, so it's correct. We just need to make
3942 * sure to update both bs->options (which has the full effective
3943 * options for bs) and options (which has file.* already removed).
3944 */
46f5ac20
EB
3945 qdict_put_str(bs->options, "driver", drv->format_name);
3946 qdict_put_str(options, "driver", drv->format_name);
76c591b0 3947 } else if (!drv) {
17b005f1 3948 error_setg(errp, "Must specify either driver or file");
8bfea15d 3949 goto fail;
ea2384d3 3950 }
b6ce07aa 3951
53a29513
HR
3952 /* BDRV_O_PROTOCOL must be set iff a protocol BDS is about to be created */
3953 assert(!!(flags & BDRV_O_PROTOCOL) == !!drv->bdrv_file_open);
3954 /* file must be NULL if a protocol BDS is about to be created
3955 * (the inverse results in an error message from bdrv_open_common()) */
3956 assert(!(flags & BDRV_O_PROTOCOL) || !file);
3957
b6ce07aa 3958 /* Open the image */
82dc8b41 3959 ret = bdrv_open_common(bs, file, options, &local_err);
b6ce07aa 3960 if (ret < 0) {
8bfea15d 3961 goto fail;
6987307c
CH
3962 }
3963
4e4bf5c4 3964 if (file) {
5696c6e3 3965 blk_unref(file);
f500a6d3
KW
3966 file = NULL;
3967 }
3968
b6ce07aa 3969 /* If there is a backing file, use it */
9156df12 3970 if ((flags & BDRV_O_NO_BACKING) == 0) {
d9b7b057 3971 ret = bdrv_open_backing_file(bs, options, "backing", &local_err);
b6ce07aa 3972 if (ret < 0) {
b6ad491a 3973 goto close_and_fail;
b6ce07aa 3974 }
b6ce07aa
KW
3975 }
3976
50196d7a
AG
3977 /* Remove all children options and references
3978 * from bs->options and bs->explicit_options */
2f624b80
AG
3979 QLIST_FOREACH(child, &bs->children, next) {
3980 char *child_key_dot;
3981 child_key_dot = g_strdup_printf("%s.", child->name);
3982 qdict_extract_subqdict(bs->explicit_options, NULL, child_key_dot);
3983 qdict_extract_subqdict(bs->options, NULL, child_key_dot);
50196d7a
AG
3984 qdict_del(bs->explicit_options, child->name);
3985 qdict_del(bs->options, child->name);
2f624b80
AG
3986 g_free(child_key_dot);
3987 }
3988
b6ad491a 3989 /* Check if any unknown options were used */
7ad2757f 3990 if (qdict_size(options) != 0) {
b6ad491a 3991 const QDictEntry *entry = qdict_first(options);
5acd9d81
HR
3992 if (flags & BDRV_O_PROTOCOL) {
3993 error_setg(errp, "Block protocol '%s' doesn't support the option "
3994 "'%s'", drv->format_name, entry->key);
3995 } else {
d0e46a55
HR
3996 error_setg(errp,
3997 "Block format '%s' does not support the option '%s'",
3998 drv->format_name, entry->key);
5acd9d81 3999 }
b6ad491a 4000
b6ad491a
KW
4001 goto close_and_fail;
4002 }
b6ad491a 4003
c01c214b 4004 bdrv_parent_cb_change_media(bs, true);
b6ce07aa 4005
cb3e7f08 4006 qobject_unref(options);
8961be33 4007 options = NULL;
dd62f1ca
KW
4008
4009 /* For snapshot=on, create a temporary qcow2 overlay. bs points to the
4010 * temporary snapshot afterwards. */
4011 if (snapshot_flags) {
66836189
HR
4012 BlockDriverState *snapshot_bs;
4013 snapshot_bs = bdrv_append_temp_snapshot(bs, snapshot_flags,
4014 snapshot_options, &local_err);
73176bee 4015 snapshot_options = NULL;
dd62f1ca
KW
4016 if (local_err) {
4017 goto close_and_fail;
4018 }
5b363937
HR
4019 /* We are not going to return bs but the overlay on top of it
4020 * (snapshot_bs); thus, we have to drop the strong reference to bs
4021 * (which we obtained by calling bdrv_new()). bs will not be deleted,
4022 * though, because the overlay still has a reference to it. */
4023 bdrv_unref(bs);
4024 bs = snapshot_bs;
dd62f1ca
KW
4025 }
4026
5b363937 4027 return bs;
b6ce07aa 4028
8bfea15d 4029fail:
5696c6e3 4030 blk_unref(file);
cb3e7f08
MAL
4031 qobject_unref(snapshot_options);
4032 qobject_unref(bs->explicit_options);
4033 qobject_unref(bs->options);
4034 qobject_unref(options);
de9c0cec 4035 bs->options = NULL;
998cbd6a 4036 bs->explicit_options = NULL;
5b363937 4037 bdrv_unref(bs);
621ff94d 4038 error_propagate(errp, local_err);
5b363937 4039 return NULL;
de9c0cec 4040
b6ad491a 4041close_and_fail:
5b363937 4042 bdrv_unref(bs);
cb3e7f08
MAL
4043 qobject_unref(snapshot_options);
4044 qobject_unref(options);
621ff94d 4045 error_propagate(errp, local_err);
5b363937 4046 return NULL;
b6ce07aa
KW
4047}
4048
5b363937
HR
4049BlockDriverState *bdrv_open(const char *filename, const char *reference,
4050 QDict *options, int flags, Error **errp)
f3930ed0 4051{
f791bf7f
EGE
4052 GLOBAL_STATE_CODE();
4053
5b363937 4054 return bdrv_open_inherit(filename, reference, options, flags, NULL,
272c02ea 4055 NULL, 0, errp);
f3930ed0
KW
4056}
4057
faf116b4
AG
4058/* Return true if the NULL-terminated @list contains @str */
4059static bool is_str_in_list(const char *str, const char *const *list)
4060{
4061 if (str && list) {
4062 int i;
4063 for (i = 0; list[i] != NULL; i++) {
4064 if (!strcmp(str, list[i])) {
4065 return true;
4066 }
4067 }
4068 }
4069 return false;
4070}
4071
4072/*
4073 * Check that every option set in @bs->options is also set in
4074 * @new_opts.
4075 *
4076 * Options listed in the common_options list and in
4077 * @bs->drv->mutable_opts are skipped.
4078 *
4079 * Return 0 on success, otherwise return -EINVAL and set @errp.
4080 */
4081static int bdrv_reset_options_allowed(BlockDriverState *bs,
4082 const QDict *new_opts, Error **errp)
4083{
4084 const QDictEntry *e;
4085 /* These options are common to all block drivers and are handled
4086 * in bdrv_reopen_prepare() so they can be left out of @new_opts */
4087 const char *const common_options[] = {
4088 "node-name", "discard", "cache.direct", "cache.no-flush",
4089 "read-only", "auto-read-only", "detect-zeroes", NULL
4090 };
4091
4092 for (e = qdict_first(bs->options); e; e = qdict_next(bs->options, e)) {
4093 if (!qdict_haskey(new_opts, e->key) &&
4094 !is_str_in_list(e->key, common_options) &&
4095 !is_str_in_list(e->key, bs->drv->mutable_opts)) {
4096 error_setg(errp, "Option '%s' cannot be reset "
4097 "to its default value", e->key);
4098 return -EINVAL;
4099 }
4100 }
4101
4102 return 0;
4103}
4104
cb828c31
AG
4105/*
4106 * Returns true if @child can be reached recursively from @bs
4107 */
4108static bool bdrv_recurse_has_child(BlockDriverState *bs,
4109 BlockDriverState *child)
4110{
4111 BdrvChild *c;
4112
4113 if (bs == child) {
4114 return true;
4115 }
4116
4117 QLIST_FOREACH(c, &bs->children, next) {
4118 if (bdrv_recurse_has_child(c->bs, child)) {
4119 return true;
4120 }
4121 }
4122
4123 return false;
4124}
4125
e971aa12
JC
4126/*
4127 * Adds a BlockDriverState to a simple queue for an atomic, transactional
4128 * reopen of multiple devices.
4129 *
859443b0 4130 * bs_queue can either be an existing BlockReopenQueue that has had QTAILQ_INIT
e971aa12
JC
4131 * already performed, or alternatively may be NULL a new BlockReopenQueue will
4132 * be created and initialized. This newly created BlockReopenQueue should be
4133 * passed back in for subsequent calls that are intended to be of the same
4134 * atomic 'set'.
4135 *
4136 * bs is the BlockDriverState to add to the reopen queue.
4137 *
4d2cb092
KW
4138 * options contains the changed options for the associated bs
4139 * (the BlockReopenQueue takes ownership)
4140 *
e971aa12
JC
4141 * flags contains the open flags for the associated bs
4142 *
4143 * returns a pointer to bs_queue, which is either the newly allocated
4144 * bs_queue, or the existing bs_queue being used.
4145 *
1a63a907 4146 * bs must be drained between bdrv_reopen_queue() and bdrv_reopen_multiple().
e971aa12 4147 */
28518102
KW
4148static BlockReopenQueue *bdrv_reopen_queue_child(BlockReopenQueue *bs_queue,
4149 BlockDriverState *bs,
4150 QDict *options,
bd86fb99 4151 const BdrvChildClass *klass,
272c02ea 4152 BdrvChildRole role,
3cdc69d3 4153 bool parent_is_format,
28518102 4154 QDict *parent_options,
077e8e20
AG
4155 int parent_flags,
4156 bool keep_old_opts)
e971aa12
JC
4157{
4158 assert(bs != NULL);
4159
4160 BlockReopenQueueEntry *bs_entry;
67251a31 4161 BdrvChild *child;
9aa09ddd
AG
4162 QDict *old_options, *explicit_options, *options_copy;
4163 int flags;
4164 QemuOpts *opts;
67251a31 4165
1a63a907
KW
4166 /* Make sure that the caller remembered to use a drained section. This is
4167 * important to avoid graph changes between the recursive queuing here and
4168 * bdrv_reopen_multiple(). */
4169 assert(bs->quiesce_counter > 0);
f0c28327 4170 GLOBAL_STATE_CODE();
1a63a907 4171
e971aa12
JC
4172 if (bs_queue == NULL) {
4173 bs_queue = g_new0(BlockReopenQueue, 1);
859443b0 4174 QTAILQ_INIT(bs_queue);
e971aa12
JC
4175 }
4176
4d2cb092
KW
4177 if (!options) {
4178 options = qdict_new();
4179 }
4180
5b7ba05f 4181 /* Check if this BlockDriverState is already in the queue */
859443b0 4182 QTAILQ_FOREACH(bs_entry, bs_queue, entry) {
5b7ba05f
AG
4183 if (bs == bs_entry->state.bs) {
4184 break;
4185 }
4186 }
4187
28518102
KW
4188 /*
4189 * Precedence of options:
4190 * 1. Explicitly passed in options (highest)
9aa09ddd
AG
4191 * 2. Retained from explicitly set options of bs
4192 * 3. Inherited from parent node
4193 * 4. Retained from effective options of bs
28518102
KW
4194 */
4195
145f598e 4196 /* Old explicitly set values (don't overwrite by inherited value) */
077e8e20
AG
4197 if (bs_entry || keep_old_opts) {
4198 old_options = qdict_clone_shallow(bs_entry ?
4199 bs_entry->state.explicit_options :
4200 bs->explicit_options);
4201 bdrv_join_options(bs, options, old_options);
4202 qobject_unref(old_options);
5b7ba05f 4203 }
145f598e
KW
4204
4205 explicit_options = qdict_clone_shallow(options);
4206
28518102
KW
4207 /* Inherit from parent node */
4208 if (parent_options) {
9aa09ddd 4209 flags = 0;
3cdc69d3 4210 klass->inherit_options(role, parent_is_format, &flags, options,
272c02ea 4211 parent_flags, parent_options);
9aa09ddd
AG
4212 } else {
4213 flags = bdrv_get_flags(bs);
28518102
KW
4214 }
4215
077e8e20
AG
4216 if (keep_old_opts) {
4217 /* Old values are used for options that aren't set yet */
4218 old_options = qdict_clone_shallow(bs->options);
4219 bdrv_join_options(bs, options, old_options);
4220 qobject_unref(old_options);
4221 }
4d2cb092 4222
9aa09ddd
AG
4223 /* We have the final set of options so let's update the flags */
4224 options_copy = qdict_clone_shallow(options);
4225 opts = qemu_opts_create(&bdrv_runtime_opts, NULL, 0, &error_abort);
4226 qemu_opts_absorb_qdict(opts, options_copy, NULL);
4227 update_flags_from_options(&flags, opts);
4228 qemu_opts_del(opts);
4229 qobject_unref(options_copy);
4230
fd452021 4231 /* bdrv_open_inherit() sets and clears some additional flags internally */
f1f25a2e 4232 flags &= ~BDRV_O_PROTOCOL;
fd452021
KW
4233 if (flags & BDRV_O_RDWR) {
4234 flags |= BDRV_O_ALLOW_RDWR;
4235 }
f1f25a2e 4236
1857c97b
KW
4237 if (!bs_entry) {
4238 bs_entry = g_new0(BlockReopenQueueEntry, 1);
859443b0 4239 QTAILQ_INSERT_TAIL(bs_queue, bs_entry, entry);
1857c97b 4240 } else {
cb3e7f08
MAL
4241 qobject_unref(bs_entry->state.options);
4242 qobject_unref(bs_entry->state.explicit_options);
1857c97b
KW
4243 }
4244
4245 bs_entry->state.bs = bs;
4246 bs_entry->state.options = options;
4247 bs_entry->state.explicit_options = explicit_options;
4248 bs_entry->state.flags = flags;
4249
8546632e
AG
4250 /*
4251 * If keep_old_opts is false then it means that unspecified
4252 * options must be reset to their original value. We don't allow
4253 * resetting 'backing' but we need to know if the option is
4254 * missing in order to decide if we have to return an error.
4255 */
4256 if (!keep_old_opts) {
4257 bs_entry->state.backing_missing =
4258 !qdict_haskey(options, "backing") &&
4259 !qdict_haskey(options, "backing.driver");
4260 }
4261
67251a31 4262 QLIST_FOREACH(child, &bs->children, next) {
8546632e
AG
4263 QDict *new_child_options = NULL;
4264 bool child_keep_old = keep_old_opts;
67251a31 4265
4c9dfe5d
KW
4266 /* reopen can only change the options of block devices that were
4267 * implicitly created and inherited options. For other (referenced)
4268 * block devices, a syntax like "backing.foo" results in an error. */
67251a31
KW
4269 if (child->bs->inherits_from != bs) {
4270 continue;
4271 }
4272
8546632e
AG
4273 /* Check if the options contain a child reference */
4274 if (qdict_haskey(options, child->name)) {
4275 const char *childref = qdict_get_try_str(options, child->name);
4276 /*
4277 * The current child must not be reopened if the child
4278 * reference is null or points to a different node.
4279 */
4280 if (g_strcmp0(childref, child->bs->node_name)) {
4281 continue;
4282 }
4283 /*
4284 * If the child reference points to the current child then
4285 * reopen it with its existing set of options (note that
4286 * it can still inherit new options from the parent).
4287 */
4288 child_keep_old = true;
4289 } else {
4290 /* Extract child options ("child-name.*") */
4291 char *child_key_dot = g_strdup_printf("%s.", child->name);
4292 qdict_extract_subqdict(explicit_options, NULL, child_key_dot);
4293 qdict_extract_subqdict(options, &new_child_options, child_key_dot);
4294 g_free(child_key_dot);
4295 }
4c9dfe5d 4296
9aa09ddd 4297 bdrv_reopen_queue_child(bs_queue, child->bs, new_child_options,
3cdc69d3
HR
4298 child->klass, child->role, bs->drv->is_format,
4299 options, flags, child_keep_old);
e971aa12
JC
4300 }
4301
e971aa12
JC
4302 return bs_queue;
4303}
4304
28518102
KW
4305BlockReopenQueue *bdrv_reopen_queue(BlockReopenQueue *bs_queue,
4306 BlockDriverState *bs,
077e8e20 4307 QDict *options, bool keep_old_opts)
28518102 4308{
f791bf7f
EGE
4309 GLOBAL_STATE_CODE();
4310
3cdc69d3
HR
4311 return bdrv_reopen_queue_child(bs_queue, bs, options, NULL, 0, false,
4312 NULL, 0, keep_old_opts);
28518102
KW
4313}
4314
ab5b5228
AG
4315void bdrv_reopen_queue_free(BlockReopenQueue *bs_queue)
4316{
f791bf7f 4317 GLOBAL_STATE_CODE();
ab5b5228
AG
4318 if (bs_queue) {
4319 BlockReopenQueueEntry *bs_entry, *next;
4320 QTAILQ_FOREACH_SAFE(bs_entry, bs_queue, entry, next) {
4321 qobject_unref(bs_entry->state.explicit_options);
4322 qobject_unref(bs_entry->state.options);
4323 g_free(bs_entry);
4324 }
4325 g_free(bs_queue);
4326 }
4327}
4328
e971aa12
JC
4329/*
4330 * Reopen multiple BlockDriverStates atomically & transactionally.
4331 *
4332 * The queue passed in (bs_queue) must have been built up previous
4333 * via bdrv_reopen_queue().
4334 *
4335 * Reopens all BDS specified in the queue, with the appropriate
4336 * flags. All devices are prepared for reopen, and failure of any
50d6a8a3 4337 * device will cause all device changes to be abandoned, and intermediate
e971aa12
JC
4338 * data cleaned up.
4339 *
4340 * If all devices prepare successfully, then the changes are committed
4341 * to all devices.
4342 *
1a63a907
KW
4343 * All affected nodes must be drained between bdrv_reopen_queue() and
4344 * bdrv_reopen_multiple().
6cf42ca2
KW
4345 *
4346 * To be called from the main thread, with all other AioContexts unlocked.
e971aa12 4347 */
5019aece 4348int bdrv_reopen_multiple(BlockReopenQueue *bs_queue, Error **errp)
e971aa12
JC
4349{
4350 int ret = -1;
4351 BlockReopenQueueEntry *bs_entry, *next;
6cf42ca2 4352 AioContext *ctx;
72373e40
VSO
4353 Transaction *tran = tran_new();
4354 g_autoptr(GHashTable) found = NULL;
4355 g_autoptr(GSList) refresh_list = NULL;
e971aa12 4356
6cf42ca2 4357 assert(qemu_get_current_aio_context() == qemu_get_aio_context());
e971aa12 4358 assert(bs_queue != NULL);
da359909 4359 GLOBAL_STATE_CODE();
e971aa12 4360
a2aabf88 4361 QTAILQ_FOREACH(bs_entry, bs_queue, entry) {
6cf42ca2
KW
4362 ctx = bdrv_get_aio_context(bs_entry->state.bs);
4363 aio_context_acquire(ctx);
a2aabf88 4364 ret = bdrv_flush(bs_entry->state.bs);
6cf42ca2 4365 aio_context_release(ctx);
a2aabf88
VSO
4366 if (ret < 0) {
4367 error_setg_errno(errp, -ret, "Error flushing drive");
e3fc91aa 4368 goto abort;
a2aabf88
VSO
4369 }
4370 }
4371
859443b0 4372 QTAILQ_FOREACH(bs_entry, bs_queue, entry) {
1a63a907 4373 assert(bs_entry->state.bs->quiesce_counter > 0);
6cf42ca2
KW
4374 ctx = bdrv_get_aio_context(bs_entry->state.bs);
4375 aio_context_acquire(ctx);
72373e40 4376 ret = bdrv_reopen_prepare(&bs_entry->state, bs_queue, tran, errp);
6cf42ca2 4377 aio_context_release(ctx);
72373e40
VSO
4378 if (ret < 0) {
4379 goto abort;
e971aa12
JC
4380 }
4381 bs_entry->prepared = true;
4382 }
4383
72373e40 4384 found = g_hash_table_new(NULL, NULL);
859443b0 4385 QTAILQ_FOREACH(bs_entry, bs_queue, entry) {
69b736e7 4386 BDRVReopenState *state = &bs_entry->state;
72373e40
VSO
4387
4388 refresh_list = bdrv_topological_dfs(refresh_list, found, state->bs);
4389 if (state->old_backing_bs) {
4390 refresh_list = bdrv_topological_dfs(refresh_list, found,
4391 state->old_backing_bs);
cb828c31 4392 }
ecd30d2d
AG
4393 if (state->old_file_bs) {
4394 refresh_list = bdrv_topological_dfs(refresh_list, found,
4395 state->old_file_bs);
4396 }
72373e40
VSO
4397 }
4398
4399 /*
4400 * Note that file-posix driver rely on permission update done during reopen
4401 * (even if no permission changed), because it wants "new" permissions for
4402 * reconfiguring the fd and that's why it does it in raw_check_perm(), not
4403 * in raw_reopen_prepare() which is called with "old" permissions.
4404 */
4405 ret = bdrv_list_refresh_perms(refresh_list, bs_queue, tran, errp);
4406 if (ret < 0) {
4407 goto abort;
69b736e7
KW
4408 }
4409
fcd6a4f4
VSO
4410 /*
4411 * If we reach this point, we have success and just need to apply the
4412 * changes.
4413 *
4414 * Reverse order is used to comfort qcow2 driver: on commit it need to write
4415 * IN_USE flag to the image, to mark bitmaps in the image as invalid. But
4416 * children are usually goes after parents in reopen-queue, so go from last
4417 * to first element.
e971aa12 4418 */
fcd6a4f4 4419 QTAILQ_FOREACH_REVERSE(bs_entry, bs_queue, entry) {
6cf42ca2
KW
4420 ctx = bdrv_get_aio_context(bs_entry->state.bs);
4421 aio_context_acquire(ctx);
e971aa12 4422 bdrv_reopen_commit(&bs_entry->state);
6cf42ca2 4423 aio_context_release(ctx);
e971aa12
JC
4424 }
4425
72373e40 4426 tran_commit(tran);
69b736e7 4427
72373e40
VSO
4428 QTAILQ_FOREACH_REVERSE(bs_entry, bs_queue, entry) {
4429 BlockDriverState *bs = bs_entry->state.bs;
74ad9a3b 4430
72373e40 4431 if (bs->drv->bdrv_reopen_commit_post) {
6cf42ca2
KW
4432 ctx = bdrv_get_aio_context(bs);
4433 aio_context_acquire(ctx);
72373e40 4434 bs->drv->bdrv_reopen_commit_post(&bs_entry->state);
6cf42ca2 4435 aio_context_release(ctx);
69b736e7
KW
4436 }
4437 }
17e1e2be 4438
72373e40
VSO
4439 ret = 0;
4440 goto cleanup;
17e1e2be 4441
72373e40
VSO
4442abort:
4443 tran_abort(tran);
4444 QTAILQ_FOREACH_SAFE(bs_entry, bs_queue, entry, next) {
4445 if (bs_entry->prepared) {
6cf42ca2
KW
4446 ctx = bdrv_get_aio_context(bs_entry->state.bs);
4447 aio_context_acquire(ctx);
72373e40 4448 bdrv_reopen_abort(&bs_entry->state);
6cf42ca2 4449 aio_context_release(ctx);
17e1e2be
PK
4450 }
4451 }
72373e40 4452
e971aa12 4453cleanup:
ab5b5228 4454 bdrv_reopen_queue_free(bs_queue);
40840e41 4455
e971aa12
JC
4456 return ret;
4457}
4458
6cf42ca2
KW
4459int bdrv_reopen(BlockDriverState *bs, QDict *opts, bool keep_old_opts,
4460 Error **errp)
6e1000a8 4461{
6cf42ca2 4462 AioContext *ctx = bdrv_get_aio_context(bs);
6e1000a8 4463 BlockReopenQueue *queue;
6cf42ca2 4464 int ret;
6e1000a8 4465
f791bf7f
EGE
4466 GLOBAL_STATE_CODE();
4467
6e1000a8 4468 bdrv_subtree_drained_begin(bs);
6cf42ca2
KW
4469 if (ctx != qemu_get_aio_context()) {
4470 aio_context_release(ctx);
4471 }
4472
4473 queue = bdrv_reopen_queue(NULL, bs, opts, keep_old_opts);
5019aece 4474 ret = bdrv_reopen_multiple(queue, errp);
6cf42ca2
KW
4475
4476 if (ctx != qemu_get_aio_context()) {
4477 aio_context_acquire(ctx);
4478 }
6e1000a8
AG
4479 bdrv_subtree_drained_end(bs);
4480
4481 return ret;
4482}
4483
6cf42ca2
KW
4484int bdrv_reopen_set_read_only(BlockDriverState *bs, bool read_only,
4485 Error **errp)
4486{
4487 QDict *opts = qdict_new();
4488
f791bf7f
EGE
4489 GLOBAL_STATE_CODE();
4490
6cf42ca2
KW
4491 qdict_put_bool(opts, BDRV_OPT_READ_ONLY, read_only);
4492
4493 return bdrv_reopen(bs, opts, true, errp);
4494}
4495
cb828c31
AG
4496/*
4497 * Take a BDRVReopenState and check if the value of 'backing' in the
4498 * reopen_state->options QDict is valid or not.
4499 *
4500 * If 'backing' is missing from the QDict then return 0.
4501 *
4502 * If 'backing' contains the node name of the backing file of
4503 * reopen_state->bs then return 0.
4504 *
4505 * If 'backing' contains a different node name (or is null) then check
4506 * whether the current backing file can be replaced with the new one.
4507 * If that's the case then reopen_state->replace_backing_bs is set to
4508 * true and reopen_state->new_backing_bs contains a pointer to the new
4509 * backing BlockDriverState (or NULL).
4510 *
4511 * Return 0 on success, otherwise return < 0 and set @errp.
4512 */
ecd30d2d
AG
4513static int bdrv_reopen_parse_file_or_backing(BDRVReopenState *reopen_state,
4514 bool is_backing, Transaction *tran,
4515 Error **errp)
cb828c31
AG
4516{
4517 BlockDriverState *bs = reopen_state->bs;
ecd30d2d
AG
4518 BlockDriverState *new_child_bs;
4519 BlockDriverState *old_child_bs = is_backing ? child_bs(bs->backing) :
4520 child_bs(bs->file);
4521 const char *child_name = is_backing ? "backing" : "file";
cb828c31
AG
4522 QObject *value;
4523 const char *str;
4524
bdb73476
EGE
4525 GLOBAL_STATE_CODE();
4526
ecd30d2d 4527 value = qdict_get(reopen_state->options, child_name);
cb828c31
AG
4528 if (value == NULL) {
4529 return 0;
4530 }
4531
4532 switch (qobject_type(value)) {
4533 case QTYPE_QNULL:
ecd30d2d
AG
4534 assert(is_backing); /* The 'file' option does not allow a null value */
4535 new_child_bs = NULL;
cb828c31
AG
4536 break;
4537 case QTYPE_QSTRING:
410f44f5 4538 str = qstring_get_str(qobject_to(QString, value));
ecd30d2d
AG
4539 new_child_bs = bdrv_lookup_bs(NULL, str, errp);
4540 if (new_child_bs == NULL) {
cb828c31 4541 return -EINVAL;
ecd30d2d
AG
4542 } else if (bdrv_recurse_has_child(new_child_bs, bs)) {
4543 error_setg(errp, "Making '%s' a %s child of '%s' would create a "
4544 "cycle", str, child_name, bs->node_name);
cb828c31
AG
4545 return -EINVAL;
4546 }
4547 break;
4548 default:
ecd30d2d
AG
4549 /*
4550 * The options QDict has been flattened, so 'backing' and 'file'
4551 * do not allow any other data type here.
4552 */
cb828c31
AG
4553 g_assert_not_reached();
4554 }
4555
ecd30d2d
AG
4556 if (old_child_bs == new_child_bs) {
4557 return 0;
4558 }
4559
4560 if (old_child_bs) {
4561 if (bdrv_skip_implicit_filters(old_child_bs) == new_child_bs) {
cbfdb98c
VSO
4562 return 0;
4563 }
4564
ecd30d2d
AG
4565 if (old_child_bs->implicit) {
4566 error_setg(errp, "Cannot replace implicit %s child of %s",
4567 child_name, bs->node_name);
cbfdb98c
VSO
4568 return -EPERM;
4569 }
4570 }
4571
ecd30d2d 4572 if (bs->drv->is_filter && !old_child_bs) {
25f78d9e
VSO
4573 /*
4574 * Filters always have a file or a backing child, so we are trying to
4575 * change wrong child
4576 */
4577 error_setg(errp, "'%s' is a %s filter node that does not support a "
ecd30d2d 4578 "%s child", bs->node_name, bs->drv->format_name, child_name);
1d42f48c
HR
4579 return -EINVAL;
4580 }
4581
ecd30d2d
AG
4582 if (is_backing) {
4583 reopen_state->old_backing_bs = old_child_bs;
4584 } else {
4585 reopen_state->old_file_bs = old_child_bs;
4586 }
4587
4588 return bdrv_set_file_or_backing_noperm(bs, new_child_bs, is_backing,
4589 tran, errp);
cb828c31
AG
4590}
4591
e971aa12
JC
4592/*
4593 * Prepares a BlockDriverState for reopen. All changes are staged in the
4594 * 'opaque' field of the BDRVReopenState, which is used and allocated by
4595 * the block driver layer .bdrv_reopen_prepare()
4596 *
4597 * bs is the BlockDriverState to reopen
4598 * flags are the new open flags
4599 * queue is the reopen queue
4600 *
4601 * Returns 0 on success, non-zero on error. On error errp will be set
4602 * as well.
4603 *
4604 * On failure, bdrv_reopen_abort() will be called to clean up any data.
4605 * It is the responsibility of the caller to then call the abort() or
4606 * commit() for any other BDS that have been left in a prepare() state
4607 *
4608 */
53e96d1e 4609static int bdrv_reopen_prepare(BDRVReopenState *reopen_state,
72373e40 4610 BlockReopenQueue *queue,
ecd30d2d 4611 Transaction *change_child_tran, Error **errp)
e971aa12
JC
4612{
4613 int ret = -1;
e6d79c41 4614 int old_flags;
e971aa12
JC
4615 Error *local_err = NULL;
4616 BlockDriver *drv;
ccf9dc07 4617 QemuOpts *opts;
4c8350fe 4618 QDict *orig_reopen_opts;
593b3071 4619 char *discard = NULL;
3d8ce171 4620 bool read_only;
9ad08c44 4621 bool drv_prepared = false;
e971aa12
JC
4622
4623 assert(reopen_state != NULL);
4624 assert(reopen_state->bs->drv != NULL);
da359909 4625 GLOBAL_STATE_CODE();
e971aa12
JC
4626 drv = reopen_state->bs->drv;
4627
4c8350fe
AG
4628 /* This function and each driver's bdrv_reopen_prepare() remove
4629 * entries from reopen_state->options as they are processed, so
4630 * we need to make a copy of the original QDict. */
4631 orig_reopen_opts = qdict_clone_shallow(reopen_state->options);
4632
ccf9dc07
KW
4633 /* Process generic block layer options */
4634 opts = qemu_opts_create(&bdrv_runtime_opts, NULL, 0, &error_abort);
af175e85 4635 if (!qemu_opts_absorb_qdict(opts, reopen_state->options, errp)) {
ccf9dc07
KW
4636 ret = -EINVAL;
4637 goto error;
4638 }
4639
e6d79c41
AG
4640 /* This was already called in bdrv_reopen_queue_child() so the flags
4641 * are up-to-date. This time we simply want to remove the options from
4642 * QemuOpts in order to indicate that they have been processed. */
4643 old_flags = reopen_state->flags;
91a097e7 4644 update_flags_from_options(&reopen_state->flags, opts);
e6d79c41 4645 assert(old_flags == reopen_state->flags);
91a097e7 4646
415bbca8 4647 discard = qemu_opt_get_del(opts, BDRV_OPT_DISCARD);
593b3071
AG
4648 if (discard != NULL) {
4649 if (bdrv_parse_discard_flags(discard, &reopen_state->flags) != 0) {
4650 error_setg(errp, "Invalid discard option");
4651 ret = -EINVAL;
4652 goto error;
4653 }
4654 }
4655
543770bd
AG
4656 reopen_state->detect_zeroes =
4657 bdrv_parse_detect_zeroes(opts, reopen_state->flags, &local_err);
4658 if (local_err) {
4659 error_propagate(errp, local_err);
4660 ret = -EINVAL;
4661 goto error;
4662 }
4663
57f9db9a
AG
4664 /* All other options (including node-name and driver) must be unchanged.
4665 * Put them back into the QDict, so that they are checked at the end
4666 * of this function. */
4667 qemu_opts_to_qdict(opts, reopen_state->options);
ccf9dc07 4668
3d8ce171
JC
4669 /* If we are to stay read-only, do not allow permission change
4670 * to r/w. Attempting to set to r/w may fail if either BDRV_O_ALLOW_RDWR is
4671 * not set, or if the BDS still has copy_on_read enabled */
4672 read_only = !(reopen_state->flags & BDRV_O_RDWR);
54a32bfe 4673 ret = bdrv_can_set_read_only(reopen_state->bs, read_only, true, &local_err);
3d8ce171
JC
4674 if (local_err) {
4675 error_propagate(errp, local_err);
e971aa12
JC
4676 goto error;
4677 }
4678
e971aa12 4679 if (drv->bdrv_reopen_prepare) {
faf116b4
AG
4680 /*
4681 * If a driver-specific option is missing, it means that we
4682 * should reset it to its default value.
4683 * But not all options allow that, so we need to check it first.
4684 */
4685 ret = bdrv_reset_options_allowed(reopen_state->bs,
4686 reopen_state->options, errp);
4687 if (ret) {
4688 goto error;
4689 }
4690
e971aa12
JC
4691 ret = drv->bdrv_reopen_prepare(reopen_state, queue, &local_err);
4692 if (ret) {
4693 if (local_err != NULL) {
4694 error_propagate(errp, local_err);
4695 } else {
f30c66ba 4696 bdrv_refresh_filename(reopen_state->bs);
d8b6895f
LC
4697 error_setg(errp, "failed while preparing to reopen image '%s'",
4698 reopen_state->bs->filename);
e971aa12
JC
4699 }
4700 goto error;
4701 }
4702 } else {
4703 /* It is currently mandatory to have a bdrv_reopen_prepare()
4704 * handler for each supported drv. */
81e5f78a
AG
4705 error_setg(errp, "Block format '%s' used by node '%s' "
4706 "does not support reopening files", drv->format_name,
4707 bdrv_get_device_or_node_name(reopen_state->bs));
e971aa12
JC
4708 ret = -1;
4709 goto error;
4710 }
4711
9ad08c44
HR
4712 drv_prepared = true;
4713
bacd9b87
AG
4714 /*
4715 * We must provide the 'backing' option if the BDS has a backing
4716 * file or if the image file has a backing file name as part of
4717 * its metadata. Otherwise the 'backing' option can be omitted.
4718 */
4719 if (drv->supports_backing && reopen_state->backing_missing &&
1d42f48c 4720 (reopen_state->bs->backing || reopen_state->bs->backing_file[0])) {
8546632e
AG
4721 error_setg(errp, "backing is missing for '%s'",
4722 reopen_state->bs->node_name);
4723 ret = -EINVAL;
4724 goto error;
4725 }
4726
cb828c31
AG
4727 /*
4728 * Allow changing the 'backing' option. The new value can be
4729 * either a reference to an existing node (using its node name)
4730 * or NULL to simply detach the current backing file.
4731 */
ecd30d2d
AG
4732 ret = bdrv_reopen_parse_file_or_backing(reopen_state, true,
4733 change_child_tran, errp);
cb828c31
AG
4734 if (ret < 0) {
4735 goto error;
4736 }
4737 qdict_del(reopen_state->options, "backing");
4738
ecd30d2d
AG
4739 /* Allow changing the 'file' option. In this case NULL is not allowed */
4740 ret = bdrv_reopen_parse_file_or_backing(reopen_state, false,
4741 change_child_tran, errp);
4742 if (ret < 0) {
4743 goto error;
4744 }
4745 qdict_del(reopen_state->options, "file");
4746
4d2cb092
KW
4747 /* Options that are not handled are only okay if they are unchanged
4748 * compared to the old state. It is expected that some options are only
4749 * used for the initial open, but not reopen (e.g. filename) */
4750 if (qdict_size(reopen_state->options)) {
4751 const QDictEntry *entry = qdict_first(reopen_state->options);
4752
4753 do {
54fd1b0d
HR
4754 QObject *new = entry->value;
4755 QObject *old = qdict_get(reopen_state->bs->options, entry->key);
4756
db905283
AG
4757 /* Allow child references (child_name=node_name) as long as they
4758 * point to the current child (i.e. everything stays the same). */
4759 if (qobject_type(new) == QTYPE_QSTRING) {
4760 BdrvChild *child;
4761 QLIST_FOREACH(child, &reopen_state->bs->children, next) {
4762 if (!strcmp(child->name, entry->key)) {
4763 break;
4764 }
4765 }
4766
4767 if (child) {
410f44f5
MA
4768 if (!strcmp(child->bs->node_name,
4769 qstring_get_str(qobject_to(QString, new)))) {
db905283
AG
4770 continue; /* Found child with this name, skip option */
4771 }
4772 }
4773 }
4774
129c7d1c 4775 /*
54fd1b0d
HR
4776 * TODO: When using -drive to specify blockdev options, all values
4777 * will be strings; however, when using -blockdev, blockdev-add or
4778 * filenames using the json:{} pseudo-protocol, they will be
4779 * correctly typed.
4780 * In contrast, reopening options are (currently) always strings
4781 * (because you can only specify them through qemu-io; all other
4782 * callers do not specify any options).
4783 * Therefore, when using anything other than -drive to create a BDS,
4784 * this cannot detect non-string options as unchanged, because
4785 * qobject_is_equal() always returns false for objects of different
4786 * type. In the future, this should be remedied by correctly typing
4787 * all options. For now, this is not too big of an issue because
4788 * the user can simply omit options which cannot be changed anyway,
4789 * so they will stay unchanged.
129c7d1c 4790 */
54fd1b0d 4791 if (!qobject_is_equal(new, old)) {
4d2cb092
KW
4792 error_setg(errp, "Cannot change the option '%s'", entry->key);
4793 ret = -EINVAL;
4794 goto error;
4795 }
4796 } while ((entry = qdict_next(reopen_state->options, entry)));
4797 }
4798
e971aa12
JC
4799 ret = 0;
4800
4c8350fe
AG
4801 /* Restore the original reopen_state->options QDict */
4802 qobject_unref(reopen_state->options);
4803 reopen_state->options = qobject_ref(orig_reopen_opts);
4804
e971aa12 4805error:
9ad08c44
HR
4806 if (ret < 0 && drv_prepared) {
4807 /* drv->bdrv_reopen_prepare() has succeeded, so we need to
4808 * call drv->bdrv_reopen_abort() before signaling an error
4809 * (bdrv_reopen_multiple() will not call bdrv_reopen_abort()
4810 * when the respective bdrv_reopen_prepare() has failed) */
4811 if (drv->bdrv_reopen_abort) {
4812 drv->bdrv_reopen_abort(reopen_state);
4813 }
4814 }
ccf9dc07 4815 qemu_opts_del(opts);
4c8350fe 4816 qobject_unref(orig_reopen_opts);
593b3071 4817 g_free(discard);
e971aa12
JC
4818 return ret;
4819}
4820
4821/*
4822 * Takes the staged changes for the reopen from bdrv_reopen_prepare(), and
4823 * makes them final by swapping the staging BlockDriverState contents into
4824 * the active BlockDriverState contents.
4825 */
53e96d1e 4826static void bdrv_reopen_commit(BDRVReopenState *reopen_state)
e971aa12
JC
4827{
4828 BlockDriver *drv;
50bf65ba 4829 BlockDriverState *bs;
50196d7a 4830 BdrvChild *child;
e971aa12
JC
4831
4832 assert(reopen_state != NULL);
50bf65ba
VSO
4833 bs = reopen_state->bs;
4834 drv = bs->drv;
e971aa12 4835 assert(drv != NULL);
da359909 4836 GLOBAL_STATE_CODE();
e971aa12
JC
4837
4838 /* If there are any driver level actions to take */
4839 if (drv->bdrv_reopen_commit) {
4840 drv->bdrv_reopen_commit(reopen_state);
4841 }
4842
4843 /* set BDS specific flags now */
cb3e7f08 4844 qobject_unref(bs->explicit_options);
4c8350fe 4845 qobject_unref(bs->options);
ab5b5228
AG
4846 qobject_ref(reopen_state->explicit_options);
4847 qobject_ref(reopen_state->options);
145f598e 4848
50bf65ba 4849 bs->explicit_options = reopen_state->explicit_options;
4c8350fe 4850 bs->options = reopen_state->options;
50bf65ba 4851 bs->open_flags = reopen_state->flags;
543770bd 4852 bs->detect_zeroes = reopen_state->detect_zeroes;
355ef4ac 4853
50196d7a
AG
4854 /* Remove child references from bs->options and bs->explicit_options.
4855 * Child options were already removed in bdrv_reopen_queue_child() */
4856 QLIST_FOREACH(child, &bs->children, next) {
4857 qdict_del(bs->explicit_options, child->name);
4858 qdict_del(bs->options, child->name);
4859 }
3d0e8743
VSO
4860 /* backing is probably removed, so it's not handled by previous loop */
4861 qdict_del(bs->explicit_options, "backing");
4862 qdict_del(bs->options, "backing");
4863
1e4c797c 4864 bdrv_refresh_limits(bs, NULL, NULL);
e971aa12
JC
4865}
4866
4867/*
4868 * Abort the reopen, and delete and free the staged changes in
4869 * reopen_state
4870 */
53e96d1e 4871static void bdrv_reopen_abort(BDRVReopenState *reopen_state)
e971aa12
JC
4872{
4873 BlockDriver *drv;
4874
4875 assert(reopen_state != NULL);
4876 drv = reopen_state->bs->drv;
4877 assert(drv != NULL);
da359909 4878 GLOBAL_STATE_CODE();
e971aa12
JC
4879
4880 if (drv->bdrv_reopen_abort) {
4881 drv->bdrv_reopen_abort(reopen_state);
4882 }
4883}
4884
4885
64dff520 4886static void bdrv_close(BlockDriverState *bs)
fc01f7e7 4887{
33384421 4888 BdrvAioNotifier *ban, *ban_next;
50a3efb0 4889 BdrvChild *child, *next;
33384421 4890
f791bf7f 4891 GLOBAL_STATE_CODE();
30f55fb8 4892 assert(!bs->refcnt);
99b7e775 4893
fc27291d 4894 bdrv_drained_begin(bs); /* complete I/O */
58fda173 4895 bdrv_flush(bs);
53ec73e2 4896 bdrv_drain(bs); /* in case flush left pending I/O */
fc27291d 4897
3cbc002c 4898 if (bs->drv) {
3c005293 4899 if (bs->drv->bdrv_close) {
7b99a266 4900 /* Must unfreeze all children, so bdrv_unref_child() works */
3c005293
VSO
4901 bs->drv->bdrv_close(bs);
4902 }
9a4f4c31 4903 bs->drv = NULL;
50a3efb0 4904 }
9a7dedbc 4905
50a3efb0 4906 QLIST_FOREACH_SAFE(child, &bs->children, next, next) {
dd4118c7 4907 bdrv_unref_child(bs, child);
b338082b 4908 }
98f90dba 4909
5bb04747
VSO
4910 assert(!bs->backing);
4911 assert(!bs->file);
50a3efb0
AG
4912 g_free(bs->opaque);
4913 bs->opaque = NULL;
d73415a3 4914 qatomic_set(&bs->copy_on_read, 0);
50a3efb0
AG
4915 bs->backing_file[0] = '\0';
4916 bs->backing_format[0] = '\0';
4917 bs->total_sectors = 0;
4918 bs->encrypted = false;
4919 bs->sg = false;
cb3e7f08
MAL
4920 qobject_unref(bs->options);
4921 qobject_unref(bs->explicit_options);
50a3efb0
AG
4922 bs->options = NULL;
4923 bs->explicit_options = NULL;
cb3e7f08 4924 qobject_unref(bs->full_open_options);
50a3efb0 4925 bs->full_open_options = NULL;
0bc329fb
HR
4926 g_free(bs->block_status_cache);
4927 bs->block_status_cache = NULL;
50a3efb0 4928
cca43ae1
VSO
4929 bdrv_release_named_dirty_bitmaps(bs);
4930 assert(QLIST_EMPTY(&bs->dirty_bitmaps));
4931
33384421
HR
4932 QLIST_FOREACH_SAFE(ban, &bs->aio_notifiers, list, ban_next) {
4933 g_free(ban);
4934 }
4935 QLIST_INIT(&bs->aio_notifiers);
fc27291d 4936 bdrv_drained_end(bs);
1a6d3bd2
GK
4937
4938 /*
4939 * If we're still inside some bdrv_drain_all_begin()/end() sections, end
4940 * them now since this BDS won't exist anymore when bdrv_drain_all_end()
4941 * gets called.
4942 */
4943 if (bs->quiesce_counter) {
4944 bdrv_drain_all_end_quiesce(bs);
4945 }
b338082b
FB
4946}
4947
2bc93fed
MK
4948void bdrv_close_all(void)
4949{
f791bf7f 4950 GLOBAL_STATE_CODE();
880eeec6 4951 assert(job_next(NULL) == NULL);
ca9bd24c
HR
4952
4953 /* Drop references from requests still in flight, such as canceled block
4954 * jobs whose AIO context has not been polled yet */
4955 bdrv_drain_all();
2bc93fed 4956
ca9bd24c
HR
4957 blk_remove_all_bs();
4958 blockdev_close_all_bdrv_states();
ed78cda3 4959
a1a2af07 4960 assert(QTAILQ_EMPTY(&all_bdrv_states));
2bc93fed
MK
4961}
4962
d0ac0380
KW
4963static bool should_update_child(BdrvChild *c, BlockDriverState *to)
4964{
2f30b7c3
VSO
4965 GQueue *queue;
4966 GHashTable *found;
4967 bool ret;
d0ac0380 4968
bd86fb99 4969 if (c->klass->stay_at_node) {
d0ac0380
KW
4970 return false;
4971 }
4972
ec9f10fe
HR
4973 /* If the child @c belongs to the BDS @to, replacing the current
4974 * c->bs by @to would mean to create a loop.
4975 *
4976 * Such a case occurs when appending a BDS to a backing chain.
4977 * For instance, imagine the following chain:
4978 *
4979 * guest device -> node A -> further backing chain...
4980 *
4981 * Now we create a new BDS B which we want to put on top of this
4982 * chain, so we first attach A as its backing node:
4983 *
4984 * node B
4985 * |
4986 * v
4987 * guest device -> node A -> further backing chain...
4988 *
4989 * Finally we want to replace A by B. When doing that, we want to
4990 * replace all pointers to A by pointers to B -- except for the
4991 * pointer from B because (1) that would create a loop, and (2)
4992 * that pointer should simply stay intact:
4993 *
4994 * guest device -> node B
4995 * |
4996 * v
4997 * node A -> further backing chain...
4998 *
4999 * In general, when replacing a node A (c->bs) by a node B (@to),
5000 * if A is a child of B, that means we cannot replace A by B there
5001 * because that would create a loop. Silently detaching A from B
5002 * is also not really an option. So overall just leaving A in
2f30b7c3
VSO
5003 * place there is the most sensible choice.
5004 *
5005 * We would also create a loop in any cases where @c is only
5006 * indirectly referenced by @to. Prevent this by returning false
5007 * if @c is found (by breadth-first search) anywhere in the whole
5008 * subtree of @to.
5009 */
5010
5011 ret = true;
5012 found = g_hash_table_new(NULL, NULL);
5013 g_hash_table_add(found, to);
5014 queue = g_queue_new();
5015 g_queue_push_tail(queue, to);
5016
5017 while (!g_queue_is_empty(queue)) {
5018 BlockDriverState *v = g_queue_pop_head(queue);
5019 BdrvChild *c2;
5020
5021 QLIST_FOREACH(c2, &v->children, next) {
5022 if (c2 == c) {
5023 ret = false;
5024 break;
5025 }
5026
5027 if (g_hash_table_contains(found, c2->bs)) {
5028 continue;
5029 }
5030
5031 g_queue_push_tail(queue, c2->bs);
5032 g_hash_table_add(found, c2->bs);
d0ac0380
KW
5033 }
5034 }
5035
2f30b7c3
VSO
5036 g_queue_free(queue);
5037 g_hash_table_destroy(found);
5038
5039 return ret;
d0ac0380
KW
5040}
5041
57f08941 5042static void bdrv_remove_child_commit(void *opaque)
46541ee5 5043{
bdb73476 5044 GLOBAL_STATE_CODE();
5bb04747 5045 bdrv_child_free(opaque);
82b54cf5
HR
5046}
5047
57f08941
VSO
5048static TransactionActionDrv bdrv_remove_child_drv = {
5049 .commit = bdrv_remove_child_commit,
46541ee5
VSO
5050};
5051
57f08941
VSO
5052/* Function doesn't update permissions, caller is responsible for this. */
5053static void bdrv_remove_child(BdrvChild *child, Transaction *tran)
46541ee5 5054{
46541ee5
VSO
5055 if (!child) {
5056 return;
5057 }
5058
5059 if (child->bs) {
a2c37a30 5060 bdrv_replace_child_tran(child, NULL, tran);
46541ee5
VSO
5061 }
5062
57f08941 5063 tran_add(tran, &bdrv_remove_child_drv, child);
46541ee5
VSO
5064}
5065
117caba9
VSO
5066static int bdrv_replace_node_noperm(BlockDriverState *from,
5067 BlockDriverState *to,
5068 bool auto_skip, Transaction *tran,
5069 Error **errp)
5070{
5071 BdrvChild *c, *next;
5072
bdb73476 5073 GLOBAL_STATE_CODE();
82b54cf5 5074
117caba9
VSO
5075 QLIST_FOREACH_SAFE(c, &from->parents, next_parent, next) {
5076 assert(c->bs == from);
5077 if (!should_update_child(c, to)) {
5078 if (auto_skip) {
5079 continue;
5080 }
5081 error_setg(errp, "Should not change '%s' link to '%s'",
5082 c->name, from->node_name);
5083 return -EINVAL;
5084 }
5085 if (c->frozen) {
5086 error_setg(errp, "Cannot change '%s' link to '%s'",
5087 c->name, from->node_name);
5088 return -EPERM;
5089 }
0f0b1e29 5090 bdrv_replace_child_tran(c, to, tran);
117caba9
VSO
5091 }
5092
5093 return 0;
5094}
5095
313274bb
VSO
5096/*
5097 * With auto_skip=true bdrv_replace_node_common skips updating from parents
5098 * if it creates a parent-child relation loop or if parent is block-job.
5099 *
5100 * With auto_skip=false the error is returned if from has a parent which should
5101 * not be updated.
3108a15c
VSO
5102 *
5103 * With @detach_subchain=true @to must be in a backing chain of @from. In this
5104 * case backing link of the cow-parent of @to is removed.
313274bb 5105 */
a1e708fc
VSO
5106static int bdrv_replace_node_common(BlockDriverState *from,
5107 BlockDriverState *to,
3108a15c
VSO
5108 bool auto_skip, bool detach_subchain,
5109 Error **errp)
dd62f1ca 5110{
3bb0e298
VSO
5111 Transaction *tran = tran_new();
5112 g_autoptr(GHashTable) found = NULL;
5113 g_autoptr(GSList) refresh_list = NULL;
2d369d6e 5114 BlockDriverState *to_cow_parent = NULL;
234ac1a9
KW
5115 int ret;
5116
bdb73476 5117 GLOBAL_STATE_CODE();
82b54cf5 5118
3108a15c
VSO
5119 if (detach_subchain) {
5120 assert(bdrv_chain_contains(from, to));
5121 assert(from != to);
5122 for (to_cow_parent = from;
5123 bdrv_filter_or_cow_bs(to_cow_parent) != to;
5124 to_cow_parent = bdrv_filter_or_cow_bs(to_cow_parent))
5125 {
5126 ;
5127 }
5128 }
5129
234ac1a9
KW
5130 /* Make sure that @from doesn't go away until we have successfully attached
5131 * all of its parents to @to. */
5132 bdrv_ref(from);
dd62f1ca 5133
f871abd6 5134 assert(qemu_get_current_aio_context() == qemu_get_aio_context());
30dd65f3 5135 assert(bdrv_get_aio_context(from) == bdrv_get_aio_context(to));
f871abd6
KW
5136 bdrv_drained_begin(from);
5137
3bb0e298
VSO
5138 /*
5139 * Do the replacement without permission update.
5140 * Replacement may influence the permissions, we should calculate new
5141 * permissions based on new graph. If we fail, we'll roll-back the
5142 * replacement.
5143 */
117caba9
VSO
5144 ret = bdrv_replace_node_noperm(from, to, auto_skip, tran, errp);
5145 if (ret < 0) {
5146 goto out;
234ac1a9
KW
5147 }
5148
3108a15c 5149 if (detach_subchain) {
f38eaec4 5150 bdrv_remove_child(bdrv_filter_or_cow_child(to_cow_parent), tran);
3108a15c
VSO
5151 }
5152
3bb0e298 5153 found = g_hash_table_new(NULL, NULL);
234ac1a9 5154
3bb0e298
VSO
5155 refresh_list = bdrv_topological_dfs(refresh_list, found, to);
5156 refresh_list = bdrv_topological_dfs(refresh_list, found, from);
9bd910e2 5157
3bb0e298
VSO
5158 ret = bdrv_list_refresh_perms(refresh_list, NULL, tran, errp);
5159 if (ret < 0) {
5160 goto out;
dd62f1ca 5161 }
234ac1a9 5162
a1e708fc
VSO
5163 ret = 0;
5164
234ac1a9 5165out:
3bb0e298
VSO
5166 tran_finalize(tran, ret);
5167
f871abd6 5168 bdrv_drained_end(from);
234ac1a9 5169 bdrv_unref(from);
a1e708fc
VSO
5170
5171 return ret;
dd62f1ca
KW
5172}
5173
a1e708fc
VSO
5174int bdrv_replace_node(BlockDriverState *from, BlockDriverState *to,
5175 Error **errp)
313274bb 5176{
f791bf7f
EGE
5177 GLOBAL_STATE_CODE();
5178
3108a15c
VSO
5179 return bdrv_replace_node_common(from, to, true, false, errp);
5180}
5181
5182int bdrv_drop_filter(BlockDriverState *bs, Error **errp)
5183{
f791bf7f
EGE
5184 GLOBAL_STATE_CODE();
5185
3108a15c
VSO
5186 return bdrv_replace_node_common(bs, bdrv_filter_or_cow_bs(bs), true, true,
5187 errp);
313274bb
VSO
5188}
5189
4ddc07ca
PB
5190/*
5191 * Add new bs contents at the top of an image chain while the chain is
5192 * live, while keeping required fields on the top layer.
5193 *
5194 * This will modify the BlockDriverState fields, and swap contents
5195 * between bs_new and bs_top. Both bs_new and bs_top are modified.
5196 *
2272edcf
VSO
5197 * bs_new must not be attached to a BlockBackend and must not have backing
5198 * child.
4ddc07ca
PB
5199 *
5200 * This function does not create any image files.
5201 */
a1e708fc
VSO
5202int bdrv_append(BlockDriverState *bs_new, BlockDriverState *bs_top,
5203 Error **errp)
4ddc07ca 5204{
2272edcf 5205 int ret;
5bb04747 5206 BdrvChild *child;
2272edcf
VSO
5207 Transaction *tran = tran_new();
5208
f791bf7f
EGE
5209 GLOBAL_STATE_CODE();
5210
2272edcf
VSO
5211 assert(!bs_new->backing);
5212
5bb04747
VSO
5213 child = bdrv_attach_child_noperm(bs_new, bs_top, "backing",
5214 &child_of_bds, bdrv_backing_role(bs_new),
5215 tran, errp);
5216 if (!child) {
5217 ret = -EINVAL;
2272edcf 5218 goto out;
b2c2832c 5219 }
dd62f1ca 5220
2272edcf 5221 ret = bdrv_replace_node_noperm(bs_top, bs_new, true, tran, errp);
a1e708fc 5222 if (ret < 0) {
2272edcf 5223 goto out;
234ac1a9 5224 }
4ddc07ca 5225
2272edcf
VSO
5226 ret = bdrv_refresh_perms(bs_new, errp);
5227out:
5228 tran_finalize(tran, ret);
5229
1e4c797c 5230 bdrv_refresh_limits(bs_top, NULL, NULL);
2272edcf
VSO
5231
5232 return ret;
8802d1fd
JC
5233}
5234
bd8f4c42
VSO
5235/* Not for empty child */
5236int bdrv_replace_child_bs(BdrvChild *child, BlockDriverState *new_bs,
5237 Error **errp)
5238{
5239 int ret;
5240 Transaction *tran = tran_new();
5241 g_autoptr(GHashTable) found = NULL;
5242 g_autoptr(GSList) refresh_list = NULL;
5243 BlockDriverState *old_bs = child->bs;
5244
f791bf7f
EGE
5245 GLOBAL_STATE_CODE();
5246
bd8f4c42
VSO
5247 bdrv_ref(old_bs);
5248 bdrv_drained_begin(old_bs);
5249 bdrv_drained_begin(new_bs);
5250
0f0b1e29 5251 bdrv_replace_child_tran(child, new_bs, tran);
bd8f4c42
VSO
5252
5253 found = g_hash_table_new(NULL, NULL);
5254 refresh_list = bdrv_topological_dfs(refresh_list, found, old_bs);
5255 refresh_list = bdrv_topological_dfs(refresh_list, found, new_bs);
5256
5257 ret = bdrv_list_refresh_perms(refresh_list, NULL, tran, errp);
5258
5259 tran_finalize(tran, ret);
5260
5261 bdrv_drained_end(old_bs);
5262 bdrv_drained_end(new_bs);
5263 bdrv_unref(old_bs);
5264
5265 return ret;
5266}
5267
4f6fd349 5268static void bdrv_delete(BlockDriverState *bs)
b338082b 5269{
3718d8ab 5270 assert(bdrv_op_blocker_is_empty(bs));
4f6fd349 5271 assert(!bs->refcnt);
f791bf7f 5272 GLOBAL_STATE_CODE();
18846dee 5273
1b7bdbc1 5274 /* remove from list, if necessary */
63eaaae0
KW
5275 if (bs->node_name[0] != '\0') {
5276 QTAILQ_REMOVE(&graph_bdrv_states, bs, node_list);
5277 }
2c1d04e0
HR
5278 QTAILQ_REMOVE(&all_bdrv_states, bs, bs_list);
5279
30c321f9
AK
5280 bdrv_close(bs);
5281
7267c094 5282 g_free(bs);
fc01f7e7
FB
5283}
5284
96796fae
VSO
5285
5286/*
5287 * Replace @bs by newly created block node.
5288 *
5289 * @options is a QDict of options to pass to the block drivers, or NULL for an
5290 * empty set of options. The reference to the QDict belongs to the block layer
5291 * after the call (even on failure), so if the caller intends to reuse the
5292 * dictionary, it needs to use qobject_ref() before calling bdrv_open.
5293 */
5294BlockDriverState *bdrv_insert_node(BlockDriverState *bs, QDict *options,
8872ef78
AS
5295 int flags, Error **errp)
5296{
f053b7e8
VSO
5297 ERRP_GUARD();
5298 int ret;
b11c8739
VSO
5299 BlockDriverState *new_node_bs = NULL;
5300 const char *drvname, *node_name;
5301 BlockDriver *drv;
5302
5303 drvname = qdict_get_try_str(options, "driver");
5304 if (!drvname) {
5305 error_setg(errp, "driver is not specified");
5306 goto fail;
5307 }
5308
5309 drv = bdrv_find_format(drvname);
5310 if (!drv) {
5311 error_setg(errp, "Unknown driver: '%s'", drvname);
5312 goto fail;
5313 }
8872ef78 5314
b11c8739
VSO
5315 node_name = qdict_get_try_str(options, "node-name");
5316
f791bf7f
EGE
5317 GLOBAL_STATE_CODE();
5318
b11c8739
VSO
5319 new_node_bs = bdrv_new_open_driver_opts(drv, node_name, options, flags,
5320 errp);
5321 options = NULL; /* bdrv_new_open_driver() eats options */
5322 if (!new_node_bs) {
8872ef78 5323 error_prepend(errp, "Could not create node: ");
b11c8739 5324 goto fail;
8872ef78
AS
5325 }
5326
5327 bdrv_drained_begin(bs);
f053b7e8 5328 ret = bdrv_replace_node(bs, new_node_bs, errp);
8872ef78
AS
5329 bdrv_drained_end(bs);
5330
f053b7e8
VSO
5331 if (ret < 0) {
5332 error_prepend(errp, "Could not replace node: ");
b11c8739 5333 goto fail;
8872ef78
AS
5334 }
5335
5336 return new_node_bs;
b11c8739
VSO
5337
5338fail:
5339 qobject_unref(options);
5340 bdrv_unref(new_node_bs);
5341 return NULL;
8872ef78
AS
5342}
5343
e97fc193
AL
5344/*
5345 * Run consistency checks on an image
5346 *
e076f338 5347 * Returns 0 if the check could be completed (it doesn't mean that the image is
a1c7273b 5348 * free of errors) or -errno when an internal error occurred. The results of the
e076f338 5349 * check are stored in res.
e97fc193 5350 */
21c2283e
VSO
5351int coroutine_fn bdrv_co_check(BlockDriverState *bs,
5352 BdrvCheckResult *res, BdrvCheckMode fix)
e97fc193 5353{
1581a70d 5354 IO_CODE();
908bcd54
HR
5355 if (bs->drv == NULL) {
5356 return -ENOMEDIUM;
5357 }
2fd61638 5358 if (bs->drv->bdrv_co_check == NULL) {
e97fc193
AL
5359 return -ENOTSUP;
5360 }
5361
e076f338 5362 memset(res, 0, sizeof(*res));
2fd61638
PB
5363 return bs->drv->bdrv_co_check(bs, res, fix);
5364}
5365
756e6736
KW
5366/*
5367 * Return values:
5368 * 0 - success
5369 * -EINVAL - backing format specified, but no file
5370 * -ENOSPC - can't update the backing file because no space is left in the
5371 * image file header
5372 * -ENOTSUP - format driver doesn't support changing the backing file
5373 */
e54ee1b3 5374int bdrv_change_backing_file(BlockDriverState *bs, const char *backing_file,
497a30db 5375 const char *backing_fmt, bool require)
756e6736
KW
5376{
5377 BlockDriver *drv = bs->drv;
469ef350 5378 int ret;
756e6736 5379
f791bf7f
EGE
5380 GLOBAL_STATE_CODE();
5381
d470ad42
HR
5382 if (!drv) {
5383 return -ENOMEDIUM;
5384 }
5385
5f377794
PB
5386 /* Backing file format doesn't make sense without a backing file */
5387 if (backing_fmt && !backing_file) {
5388 return -EINVAL;
5389 }
5390
497a30db
EB
5391 if (require && backing_file && !backing_fmt) {
5392 return -EINVAL;
e54ee1b3
EB
5393 }
5394
756e6736 5395 if (drv->bdrv_change_backing_file != NULL) {
469ef350 5396 ret = drv->bdrv_change_backing_file(bs, backing_file, backing_fmt);
756e6736 5397 } else {
469ef350 5398 ret = -ENOTSUP;
756e6736 5399 }
469ef350
PB
5400
5401 if (ret == 0) {
5402 pstrcpy(bs->backing_file, sizeof(bs->backing_file), backing_file ?: "");
5403 pstrcpy(bs->backing_format, sizeof(bs->backing_format), backing_fmt ?: "");
998c2019
HR
5404 pstrcpy(bs->auto_backing_file, sizeof(bs->auto_backing_file),
5405 backing_file ?: "");
469ef350
PB
5406 }
5407 return ret;
756e6736
KW
5408}
5409
6ebdcee2 5410/*
dcf3f9b2
HR
5411 * Finds the first non-filter node above bs in the chain between
5412 * active and bs. The returned node is either an immediate parent of
5413 * bs, or there are only filter nodes between the two.
6ebdcee2
JC
5414 *
5415 * Returns NULL if bs is not found in active's image chain,
5416 * or if active == bs.
4caf0fcd
JC
5417 *
5418 * Returns the bottommost base image if bs == NULL.
6ebdcee2
JC
5419 */
5420BlockDriverState *bdrv_find_overlay(BlockDriverState *active,
5421 BlockDriverState *bs)
5422{
f791bf7f
EGE
5423
5424 GLOBAL_STATE_CODE();
5425
dcf3f9b2
HR
5426 bs = bdrv_skip_filters(bs);
5427 active = bdrv_skip_filters(active);
5428
5429 while (active) {
5430 BlockDriverState *next = bdrv_backing_chain_next(active);
5431 if (bs == next) {
5432 return active;
5433 }
5434 active = next;
6ebdcee2
JC
5435 }
5436
dcf3f9b2 5437 return NULL;
4caf0fcd 5438}
6ebdcee2 5439
4caf0fcd
JC
5440/* Given a BDS, searches for the base layer. */
5441BlockDriverState *bdrv_find_base(BlockDriverState *bs)
5442{
f791bf7f
EGE
5443 GLOBAL_STATE_CODE();
5444
4caf0fcd 5445 return bdrv_find_overlay(bs, NULL);
6ebdcee2
JC
5446}
5447
2cad1ebe 5448/*
7b99a266
HR
5449 * Return true if at least one of the COW (backing) and filter links
5450 * between @bs and @base is frozen. @errp is set if that's the case.
0f0998f6 5451 * @base must be reachable from @bs, or NULL.
2cad1ebe
AG
5452 */
5453bool bdrv_is_backing_chain_frozen(BlockDriverState *bs, BlockDriverState *base,
5454 Error **errp)
5455{
5456 BlockDriverState *i;
7b99a266 5457 BdrvChild *child;
2cad1ebe 5458
f791bf7f
EGE
5459 GLOBAL_STATE_CODE();
5460
7b99a266
HR
5461 for (i = bs; i != base; i = child_bs(child)) {
5462 child = bdrv_filter_or_cow_child(i);
5463
5464 if (child && child->frozen) {
2cad1ebe 5465 error_setg(errp, "Cannot change '%s' link from '%s' to '%s'",
7b99a266 5466 child->name, i->node_name, child->bs->node_name);
2cad1ebe
AG
5467 return true;
5468 }
5469 }
5470
5471 return false;
5472}
5473
5474/*
7b99a266 5475 * Freeze all COW (backing) and filter links between @bs and @base.
2cad1ebe
AG
5476 * If any of the links is already frozen the operation is aborted and
5477 * none of the links are modified.
0f0998f6 5478 * @base must be reachable from @bs, or NULL.
2cad1ebe
AG
5479 * Returns 0 on success. On failure returns < 0 and sets @errp.
5480 */
5481int bdrv_freeze_backing_chain(BlockDriverState *bs, BlockDriverState *base,
5482 Error **errp)
5483{
5484 BlockDriverState *i;
7b99a266 5485 BdrvChild *child;
2cad1ebe 5486
f791bf7f
EGE
5487 GLOBAL_STATE_CODE();
5488
2cad1ebe
AG
5489 if (bdrv_is_backing_chain_frozen(bs, base, errp)) {
5490 return -EPERM;
5491 }
5492
7b99a266
HR
5493 for (i = bs; i != base; i = child_bs(child)) {
5494 child = bdrv_filter_or_cow_child(i);
5495 if (child && child->bs->never_freeze) {
e5182c1c 5496 error_setg(errp, "Cannot freeze '%s' link to '%s'",
7b99a266 5497 child->name, child->bs->node_name);
e5182c1c
HR
5498 return -EPERM;
5499 }
5500 }
5501
7b99a266
HR
5502 for (i = bs; i != base; i = child_bs(child)) {
5503 child = bdrv_filter_or_cow_child(i);
5504 if (child) {
5505 child->frozen = true;
0f0998f6 5506 }
2cad1ebe
AG
5507 }
5508
5509 return 0;
5510}
5511
5512/*
7b99a266
HR
5513 * Unfreeze all COW (backing) and filter links between @bs and @base.
5514 * The caller must ensure that all links are frozen before using this
5515 * function.
0f0998f6 5516 * @base must be reachable from @bs, or NULL.
2cad1ebe
AG
5517 */
5518void bdrv_unfreeze_backing_chain(BlockDriverState *bs, BlockDriverState *base)
5519{
5520 BlockDriverState *i;
7b99a266 5521 BdrvChild *child;
2cad1ebe 5522
f791bf7f
EGE
5523 GLOBAL_STATE_CODE();
5524
7b99a266
HR
5525 for (i = bs; i != base; i = child_bs(child)) {
5526 child = bdrv_filter_or_cow_child(i);
5527 if (child) {
5528 assert(child->frozen);
5529 child->frozen = false;
0f0998f6 5530 }
2cad1ebe
AG
5531 }
5532}
5533
6ebdcee2
JC
5534/*
5535 * Drops images above 'base' up to and including 'top', and sets the image
5536 * above 'top' to have base as its backing file.
5537 *
5538 * Requires that the overlay to 'top' is opened r/w, so that the backing file
5539 * information in 'bs' can be properly updated.
5540 *
5541 * E.g., this will convert the following chain:
5542 * bottom <- base <- intermediate <- top <- active
5543 *
5544 * to
5545 *
5546 * bottom <- base <- active
5547 *
5548 * It is allowed for bottom==base, in which case it converts:
5549 *
5550 * base <- intermediate <- top <- active
5551 *
5552 * to
5553 *
5554 * base <- active
5555 *
54e26900
JC
5556 * If backing_file_str is non-NULL, it will be used when modifying top's
5557 * overlay image metadata.
5558 *
6ebdcee2
JC
5559 * Error conditions:
5560 * if active == top, that is considered an error
5561 *
5562 */
bde70715
KW
5563int bdrv_drop_intermediate(BlockDriverState *top, BlockDriverState *base,
5564 const char *backing_file_str)
6ebdcee2 5565{
6bd858b3
AG
5566 BlockDriverState *explicit_top = top;
5567 bool update_inherits_from;
d669ed6a 5568 BdrvChild *c;
12fa4af6 5569 Error *local_err = NULL;
6ebdcee2 5570 int ret = -EIO;
d669ed6a
VSO
5571 g_autoptr(GSList) updated_children = NULL;
5572 GSList *p;
6ebdcee2 5573
f791bf7f
EGE
5574 GLOBAL_STATE_CODE();
5575
6858eba0 5576 bdrv_ref(top);
637d54a5 5577 bdrv_subtree_drained_begin(top);
6858eba0 5578
6ebdcee2
JC
5579 if (!top->drv || !base->drv) {
5580 goto exit;
5581 }
5582
5db15a57
KW
5583 /* Make sure that base is in the backing chain of top */
5584 if (!bdrv_chain_contains(top, base)) {
6ebdcee2
JC
5585 goto exit;
5586 }
5587
6bd858b3
AG
5588 /* If 'base' recursively inherits from 'top' then we should set
5589 * base->inherits_from to top->inherits_from after 'top' and all
5590 * other intermediate nodes have been dropped.
5591 * If 'top' is an implicit node (e.g. "commit_top") we should skip
5592 * it because no one inherits from it. We use explicit_top for that. */
dcf3f9b2 5593 explicit_top = bdrv_skip_implicit_filters(explicit_top);
6bd858b3
AG
5594 update_inherits_from = bdrv_inherits_from_recursive(base, explicit_top);
5595
6ebdcee2 5596 /* success - we can delete the intermediate states, and link top->base */
f30c66ba
HR
5597 if (!backing_file_str) {
5598 bdrv_refresh_filename(base);
5599 backing_file_str = base->filename;
5600 }
61f09cea 5601
d669ed6a
VSO
5602 QLIST_FOREACH(c, &top->parents, next_parent) {
5603 updated_children = g_slist_prepend(updated_children, c);
5604 }
5605
3108a15c
VSO
5606 /*
5607 * It seems correct to pass detach_subchain=true here, but it triggers
5608 * one more yet not fixed bug, when due to nested aio_poll loop we switch to
5609 * another drained section, which modify the graph (for example, removing
5610 * the child, which we keep in updated_children list). So, it's a TODO.
5611 *
5612 * Note, bug triggered if pass detach_subchain=true here and run
5613 * test-bdrv-drain. test_drop_intermediate_poll() test-case will crash.
5614 * That's a FIXME.
5615 */
5616 bdrv_replace_node_common(top, base, false, false, &local_err);
d669ed6a
VSO
5617 if (local_err) {
5618 error_report_err(local_err);
5619 goto exit;
5620 }
5621
5622 for (p = updated_children; p; p = p->next) {
5623 c = p->data;
12fa4af6 5624
bd86fb99
HR
5625 if (c->klass->update_filename) {
5626 ret = c->klass->update_filename(c, base, backing_file_str,
5627 &local_err);
61f09cea 5628 if (ret < 0) {
d669ed6a
VSO
5629 /*
5630 * TODO: Actually, we want to rollback all previous iterations
5631 * of this loop, and (which is almost impossible) previous
5632 * bdrv_replace_node()...
5633 *
5634 * Note, that c->klass->update_filename may lead to permission
5635 * update, so it's a bad idea to call it inside permission
5636 * update transaction of bdrv_replace_node.
5637 */
61f09cea
KW
5638 error_report_err(local_err);
5639 goto exit;
5640 }
5641 }
12fa4af6 5642 }
6ebdcee2 5643
6bd858b3
AG
5644 if (update_inherits_from) {
5645 base->inherits_from = explicit_top->inherits_from;
5646 }
5647
6ebdcee2 5648 ret = 0;
6ebdcee2 5649exit:
637d54a5 5650 bdrv_subtree_drained_end(top);
6858eba0 5651 bdrv_unref(top);
6ebdcee2
JC
5652 return ret;
5653}
5654
081e4650
HR
5655/**
5656 * Implementation of BlockDriver.bdrv_get_allocated_file_size() that
5657 * sums the size of all data-bearing children. (This excludes backing
5658 * children.)
5659 */
5660static int64_t bdrv_sum_allocated_file_size(BlockDriverState *bs)
5661{
5662 BdrvChild *child;
5663 int64_t child_size, sum = 0;
5664
5665 QLIST_FOREACH(child, &bs->children, next) {
5666 if (child->role & (BDRV_CHILD_DATA | BDRV_CHILD_METADATA |
5667 BDRV_CHILD_FILTERED))
5668 {
5669 child_size = bdrv_get_allocated_file_size(child->bs);
5670 if (child_size < 0) {
5671 return child_size;
5672 }
5673 sum += child_size;
5674 }
5675 }
5676
5677 return sum;
5678}
5679
61007b31
SH
5680/**
5681 * Length of a allocated file in bytes. Sparse files are counted by actual
5682 * allocated space. Return < 0 if error or unknown.
5683 */
5684int64_t bdrv_get_allocated_file_size(BlockDriverState *bs)
71d0770c 5685{
61007b31 5686 BlockDriver *drv = bs->drv;
384a48fb
EGE
5687 IO_CODE();
5688
61007b31
SH
5689 if (!drv) {
5690 return -ENOMEDIUM;
8f4754ed 5691 }
61007b31
SH
5692 if (drv->bdrv_get_allocated_file_size) {
5693 return drv->bdrv_get_allocated_file_size(bs);
5694 }
081e4650
HR
5695
5696 if (drv->bdrv_file_open) {
5697 /*
5698 * Protocol drivers default to -ENOTSUP (most of their data is
5699 * not stored in any of their children (if they even have any),
5700 * so there is no generic way to figure it out).
5701 */
5702 return -ENOTSUP;
5703 } else if (drv->is_filter) {
5704 /* Filter drivers default to the size of their filtered child */
5705 return bdrv_get_allocated_file_size(bdrv_filter_bs(bs));
5706 } else {
5707 /* Other drivers default to summing their children's sizes */
5708 return bdrv_sum_allocated_file_size(bs);
1c9805a3
SH
5709 }
5710}
e7a8a783 5711
90880ff1
SH
5712/*
5713 * bdrv_measure:
5714 * @drv: Format driver
5715 * @opts: Creation options for new image
5716 * @in_bs: Existing image containing data for new image (may be NULL)
5717 * @errp: Error object
5718 * Returns: A #BlockMeasureInfo (free using qapi_free_BlockMeasureInfo())
5719 * or NULL on error
5720 *
5721 * Calculate file size required to create a new image.
5722 *
5723 * If @in_bs is given then space for allocated clusters and zero clusters
5724 * from that image are included in the calculation. If @opts contains a
5725 * backing file that is shared by @in_bs then backing clusters may be omitted
5726 * from the calculation.
5727 *
5728 * If @in_bs is NULL then the calculation includes no allocated clusters
5729 * unless a preallocation option is given in @opts.
5730 *
5731 * Note that @in_bs may use a different BlockDriver from @drv.
5732 *
5733 * If an error occurs the @errp pointer is set.
5734 */
5735BlockMeasureInfo *bdrv_measure(BlockDriver *drv, QemuOpts *opts,
5736 BlockDriverState *in_bs, Error **errp)
5737{
384a48fb 5738 IO_CODE();
90880ff1
SH
5739 if (!drv->bdrv_measure) {
5740 error_setg(errp, "Block driver '%s' does not support size measurement",
5741 drv->format_name);
5742 return NULL;
5743 }
5744
5745 return drv->bdrv_measure(opts, in_bs, errp);
5746}
5747
61007b31
SH
5748/**
5749 * Return number of sectors on success, -errno on error.
1c9805a3 5750 */
61007b31 5751int64_t bdrv_nb_sectors(BlockDriverState *bs)
1c9805a3 5752{
61007b31 5753 BlockDriver *drv = bs->drv;
384a48fb 5754 IO_CODE();
498e386c 5755
61007b31
SH
5756 if (!drv)
5757 return -ENOMEDIUM;
2572b37a 5758
61007b31
SH
5759 if (drv->has_variable_length) {
5760 int ret = refresh_total_sectors(bs, bs->total_sectors);
5761 if (ret < 0) {
5762 return ret;
1c9805a3
SH
5763 }
5764 }
61007b31 5765 return bs->total_sectors;
1c9805a3 5766}
b338082b 5767
61007b31
SH
5768/**
5769 * Return length in bytes on success, -errno on error.
5770 * The length is always a multiple of BDRV_SECTOR_SIZE.
8d3b1a2d 5771 */
61007b31 5772int64_t bdrv_getlength(BlockDriverState *bs)
8d3b1a2d 5773{
61007b31 5774 int64_t ret = bdrv_nb_sectors(bs);
384a48fb 5775 IO_CODE();
8d3b1a2d 5776
122860ba
EB
5777 if (ret < 0) {
5778 return ret;
5779 }
5780 if (ret > INT64_MAX / BDRV_SECTOR_SIZE) {
5781 return -EFBIG;
5782 }
5783 return ret * BDRV_SECTOR_SIZE;
fc01f7e7
FB
5784}
5785
61007b31
SH
5786/* return 0 as number of sectors if no device present or error */
5787void bdrv_get_geometry(BlockDriverState *bs, uint64_t *nb_sectors_ptr)
07d27a44 5788{
61007b31 5789 int64_t nb_sectors = bdrv_nb_sectors(bs);
384a48fb 5790 IO_CODE();
07d27a44 5791
61007b31 5792 *nb_sectors_ptr = nb_sectors < 0 ? 0 : nb_sectors;
07d27a44
MA
5793}
5794
54115412 5795bool bdrv_is_sg(BlockDriverState *bs)
f08145fe 5796{
384a48fb 5797 IO_CODE();
61007b31 5798 return bs->sg;
f08145fe
KW
5799}
5800
ae23f786
HR
5801/**
5802 * Return whether the given node supports compressed writes.
5803 */
5804bool bdrv_supports_compressed_writes(BlockDriverState *bs)
5805{
5806 BlockDriverState *filtered;
384a48fb 5807 IO_CODE();
ae23f786
HR
5808
5809 if (!bs->drv || !block_driver_can_compress(bs->drv)) {
5810 return false;
5811 }
5812
5813 filtered = bdrv_filter_bs(bs);
5814 if (filtered) {
5815 /*
5816 * Filters can only forward compressed writes, so we have to
5817 * check the child.
5818 */
5819 return bdrv_supports_compressed_writes(filtered);
5820 }
5821
5822 return true;
5823}
5824
61007b31 5825const char *bdrv_get_format_name(BlockDriverState *bs)
40b4f539 5826{
384a48fb 5827 IO_CODE();
61007b31 5828 return bs->drv ? bs->drv->format_name : NULL;
40b4f539
KW
5829}
5830
61007b31 5831static int qsort_strcmp(const void *a, const void *b)
40b4f539 5832{
ceff5bd7 5833 return strcmp(*(char *const *)a, *(char *const *)b);
40b4f539
KW
5834}
5835
61007b31 5836void bdrv_iterate_format(void (*it)(void *opaque, const char *name),
9ac404c5 5837 void *opaque, bool read_only)
40b4f539 5838{
61007b31
SH
5839 BlockDriver *drv;
5840 int count = 0;
5841 int i;
5842 const char **formats = NULL;
40b4f539 5843
f791bf7f
EGE
5844 GLOBAL_STATE_CODE();
5845
61007b31
SH
5846 QLIST_FOREACH(drv, &bdrv_drivers, list) {
5847 if (drv->format_name) {
5848 bool found = false;
5849 int i = count;
9ac404c5
AS
5850
5851 if (use_bdrv_whitelist && !bdrv_is_whitelisted(drv, read_only)) {
5852 continue;
5853 }
5854
61007b31
SH
5855 while (formats && i && !found) {
5856 found = !strcmp(formats[--i], drv->format_name);
5857 }
e2a305fb 5858
61007b31
SH
5859 if (!found) {
5860 formats = g_renew(const char *, formats, count + 1);
5861 formats[count++] = drv->format_name;
5862 }
6c5a42ac 5863 }
61007b31 5864 }
6c5a42ac 5865
eb0df69f
HR
5866 for (i = 0; i < (int)ARRAY_SIZE(block_driver_modules); i++) {
5867 const char *format_name = block_driver_modules[i].format_name;
5868
5869 if (format_name) {
5870 bool found = false;
5871 int j = count;
5872
9ac404c5
AS
5873 if (use_bdrv_whitelist &&
5874 !bdrv_format_is_whitelisted(format_name, read_only)) {
5875 continue;
5876 }
5877
eb0df69f
HR
5878 while (formats && j && !found) {
5879 found = !strcmp(formats[--j], format_name);
5880 }
5881
5882 if (!found) {
5883 formats = g_renew(const char *, formats, count + 1);
5884 formats[count++] = format_name;
5885 }
5886 }
5887 }
5888
61007b31 5889 qsort(formats, count, sizeof(formats[0]), qsort_strcmp);
40b4f539 5890
61007b31
SH
5891 for (i = 0; i < count; i++) {
5892 it(opaque, formats[i]);
5893 }
40b4f539 5894
61007b31
SH
5895 g_free(formats);
5896}
40b4f539 5897
61007b31
SH
5898/* This function is to find a node in the bs graph */
5899BlockDriverState *bdrv_find_node(const char *node_name)
5900{
5901 BlockDriverState *bs;
391827eb 5902
61007b31 5903 assert(node_name);
f791bf7f 5904 GLOBAL_STATE_CODE();
40b4f539 5905
61007b31
SH
5906 QTAILQ_FOREACH(bs, &graph_bdrv_states, node_list) {
5907 if (!strcmp(node_name, bs->node_name)) {
5908 return bs;
40b4f539
KW
5909 }
5910 }
61007b31 5911 return NULL;
40b4f539
KW
5912}
5913
61007b31 5914/* Put this QMP function here so it can access the static graph_bdrv_states. */
facda544
PK
5915BlockDeviceInfoList *bdrv_named_nodes_list(bool flat,
5916 Error **errp)
40b4f539 5917{
9812e712 5918 BlockDeviceInfoList *list;
61007b31 5919 BlockDriverState *bs;
40b4f539 5920
f791bf7f
EGE
5921 GLOBAL_STATE_CODE();
5922
61007b31
SH
5923 list = NULL;
5924 QTAILQ_FOREACH(bs, &graph_bdrv_states, node_list) {
facda544 5925 BlockDeviceInfo *info = bdrv_block_device_info(NULL, bs, flat, errp);
61007b31
SH
5926 if (!info) {
5927 qapi_free_BlockDeviceInfoList(list);
5928 return NULL;
301db7c2 5929 }
9812e712 5930 QAPI_LIST_PREPEND(list, info);
301db7c2
RH
5931 }
5932
61007b31
SH
5933 return list;
5934}
40b4f539 5935
5d3b4e99
VSO
5936typedef struct XDbgBlockGraphConstructor {
5937 XDbgBlockGraph *graph;
5938 GHashTable *graph_nodes;
5939} XDbgBlockGraphConstructor;
5940
5941static XDbgBlockGraphConstructor *xdbg_graph_new(void)
5942{
5943 XDbgBlockGraphConstructor *gr = g_new(XDbgBlockGraphConstructor, 1);
5944
5945 gr->graph = g_new0(XDbgBlockGraph, 1);
5946 gr->graph_nodes = g_hash_table_new(NULL, NULL);
5947
5948 return gr;
5949}
5950
5951static XDbgBlockGraph *xdbg_graph_finalize(XDbgBlockGraphConstructor *gr)
5952{
5953 XDbgBlockGraph *graph = gr->graph;
5954
5955 g_hash_table_destroy(gr->graph_nodes);
5956 g_free(gr);
5957
5958 return graph;
5959}
5960
5961static uintptr_t xdbg_graph_node_num(XDbgBlockGraphConstructor *gr, void *node)
5962{
5963 uintptr_t ret = (uintptr_t)g_hash_table_lookup(gr->graph_nodes, node);
5964
5965 if (ret != 0) {
5966 return ret;
5967 }
5968
5969 /*
5970 * Start counting from 1, not 0, because 0 interferes with not-found (NULL)
5971 * answer of g_hash_table_lookup.
5972 */
5973 ret = g_hash_table_size(gr->graph_nodes) + 1;
5974 g_hash_table_insert(gr->graph_nodes, node, (void *)ret);
5975
5976 return ret;
5977}
5978
5979static void xdbg_graph_add_node(XDbgBlockGraphConstructor *gr, void *node,
5980 XDbgBlockGraphNodeType type, const char *name)
5981{
5982 XDbgBlockGraphNode *n;
5983
5984 n = g_new0(XDbgBlockGraphNode, 1);
5985
5986 n->id = xdbg_graph_node_num(gr, node);
5987 n->type = type;
5988 n->name = g_strdup(name);
5989
9812e712 5990 QAPI_LIST_PREPEND(gr->graph->nodes, n);
5d3b4e99
VSO
5991}
5992
5993static void xdbg_graph_add_edge(XDbgBlockGraphConstructor *gr, void *parent,
5994 const BdrvChild *child)
5995{
cdb1cec8 5996 BlockPermission qapi_perm;
5d3b4e99 5997 XDbgBlockGraphEdge *edge;
862fded9 5998 GLOBAL_STATE_CODE();
5d3b4e99 5999
5d3b4e99
VSO
6000 edge = g_new0(XDbgBlockGraphEdge, 1);
6001
6002 edge->parent = xdbg_graph_node_num(gr, parent);
6003 edge->child = xdbg_graph_node_num(gr, child->bs);
6004 edge->name = g_strdup(child->name);
6005
cdb1cec8
HR
6006 for (qapi_perm = 0; qapi_perm < BLOCK_PERMISSION__MAX; qapi_perm++) {
6007 uint64_t flag = bdrv_qapi_perm_to_blk_perm(qapi_perm);
6008
6009 if (flag & child->perm) {
9812e712 6010 QAPI_LIST_PREPEND(edge->perm, qapi_perm);
5d3b4e99 6011 }
cdb1cec8 6012 if (flag & child->shared_perm) {
9812e712 6013 QAPI_LIST_PREPEND(edge->shared_perm, qapi_perm);
5d3b4e99
VSO
6014 }
6015 }
6016
9812e712 6017 QAPI_LIST_PREPEND(gr->graph->edges, edge);
5d3b4e99
VSO
6018}
6019
6020
6021XDbgBlockGraph *bdrv_get_xdbg_block_graph(Error **errp)
6022{
6023 BlockBackend *blk;
6024 BlockJob *job;
6025 BlockDriverState *bs;
6026 BdrvChild *child;
6027 XDbgBlockGraphConstructor *gr = xdbg_graph_new();
6028
f791bf7f
EGE
6029 GLOBAL_STATE_CODE();
6030
5d3b4e99
VSO
6031 for (blk = blk_all_next(NULL); blk; blk = blk_all_next(blk)) {
6032 char *allocated_name = NULL;
6033 const char *name = blk_name(blk);
6034
6035 if (!*name) {
6036 name = allocated_name = blk_get_attached_dev_id(blk);
6037 }
6038 xdbg_graph_add_node(gr, blk, X_DBG_BLOCK_GRAPH_NODE_TYPE_BLOCK_BACKEND,
6039 name);
6040 g_free(allocated_name);
6041 if (blk_root(blk)) {
6042 xdbg_graph_add_edge(gr, blk, blk_root(blk));
6043 }
6044 }
6045
880eeec6
EGE
6046 WITH_JOB_LOCK_GUARD() {
6047 for (job = block_job_next_locked(NULL); job;
6048 job = block_job_next_locked(job)) {
6049 GSList *el;
5d3b4e99 6050
880eeec6
EGE
6051 xdbg_graph_add_node(gr, job, X_DBG_BLOCK_GRAPH_NODE_TYPE_BLOCK_JOB,
6052 job->job.id);
6053 for (el = job->nodes; el; el = el->next) {
6054 xdbg_graph_add_edge(gr, job, (BdrvChild *)el->data);
6055 }
5d3b4e99
VSO
6056 }
6057 }
6058
6059 QTAILQ_FOREACH(bs, &graph_bdrv_states, node_list) {
6060 xdbg_graph_add_node(gr, bs, X_DBG_BLOCK_GRAPH_NODE_TYPE_BLOCK_DRIVER,
6061 bs->node_name);
6062 QLIST_FOREACH(child, &bs->children, next) {
6063 xdbg_graph_add_edge(gr, bs, child);
6064 }
6065 }
6066
6067 return xdbg_graph_finalize(gr);
6068}
6069
61007b31
SH
6070BlockDriverState *bdrv_lookup_bs(const char *device,
6071 const char *node_name,
6072 Error **errp)
6073{
6074 BlockBackend *blk;
6075 BlockDriverState *bs;
40b4f539 6076
f791bf7f
EGE
6077 GLOBAL_STATE_CODE();
6078
61007b31
SH
6079 if (device) {
6080 blk = blk_by_name(device);
40b4f539 6081
61007b31 6082 if (blk) {
9f4ed6fb
AG
6083 bs = blk_bs(blk);
6084 if (!bs) {
5433c24f 6085 error_setg(errp, "Device '%s' has no medium", device);
5433c24f
HR
6086 }
6087
9f4ed6fb 6088 return bs;
61007b31
SH
6089 }
6090 }
40b4f539 6091
61007b31
SH
6092 if (node_name) {
6093 bs = bdrv_find_node(node_name);
6d519a5f 6094
61007b31
SH
6095 if (bs) {
6096 return bs;
6097 }
40b4f539
KW
6098 }
6099
785ec4b1 6100 error_setg(errp, "Cannot find device=\'%s\' nor node-name=\'%s\'",
61007b31
SH
6101 device ? device : "",
6102 node_name ? node_name : "");
6103 return NULL;
40b4f539
KW
6104}
6105
61007b31
SH
6106/* If 'base' is in the same chain as 'top', return true. Otherwise,
6107 * return false. If either argument is NULL, return false. */
6108bool bdrv_chain_contains(BlockDriverState *top, BlockDriverState *base)
83f64091 6109{
f791bf7f
EGE
6110
6111 GLOBAL_STATE_CODE();
6112
61007b31 6113 while (top && top != base) {
dcf3f9b2 6114 top = bdrv_filter_or_cow_bs(top);
02c50efe 6115 }
61007b31
SH
6116
6117 return top != NULL;
02c50efe
FZ
6118}
6119
61007b31 6120BlockDriverState *bdrv_next_node(BlockDriverState *bs)
02c50efe 6121{
f791bf7f 6122 GLOBAL_STATE_CODE();
61007b31
SH
6123 if (!bs) {
6124 return QTAILQ_FIRST(&graph_bdrv_states);
02c50efe 6125 }
61007b31 6126 return QTAILQ_NEXT(bs, node_list);
83f64091
FB
6127}
6128
0f12264e
KW
6129BlockDriverState *bdrv_next_all_states(BlockDriverState *bs)
6130{
f791bf7f 6131 GLOBAL_STATE_CODE();
0f12264e
KW
6132 if (!bs) {
6133 return QTAILQ_FIRST(&all_bdrv_states);
6134 }
6135 return QTAILQ_NEXT(bs, bs_list);
6136}
6137
61007b31 6138const char *bdrv_get_node_name(const BlockDriverState *bs)
83f64091 6139{
384a48fb 6140 IO_CODE();
61007b31 6141 return bs->node_name;
beac80cd
FB
6142}
6143
1f0c461b 6144const char *bdrv_get_parent_name(const BlockDriverState *bs)
4c265bf9
KW
6145{
6146 BdrvChild *c;
6147 const char *name;
967d7905 6148 IO_CODE();
4c265bf9
KW
6149
6150 /* If multiple parents have a name, just pick the first one. */
6151 QLIST_FOREACH(c, &bs->parents, next_parent) {
bd86fb99
HR
6152 if (c->klass->get_name) {
6153 name = c->klass->get_name(c);
4c265bf9
KW
6154 if (name && *name) {
6155 return name;
6156 }
6157 }
6158 }
6159
6160 return NULL;
6161}
6162
61007b31
SH
6163/* TODO check what callers really want: bs->node_name or blk_name() */
6164const char *bdrv_get_device_name(const BlockDriverState *bs)
beac80cd 6165{
384a48fb 6166 IO_CODE();
4c265bf9 6167 return bdrv_get_parent_name(bs) ?: "";
f141eafe 6168}
83f64091 6169
61007b31
SH
6170/* This can be used to identify nodes that might not have a device
6171 * name associated. Since node and device names live in the same
6172 * namespace, the result is unambiguous. The exception is if both are
6173 * absent, then this returns an empty (non-null) string. */
6174const char *bdrv_get_device_or_node_name(const BlockDriverState *bs)
f141eafe 6175{
384a48fb 6176 IO_CODE();
4c265bf9 6177 return bdrv_get_parent_name(bs) ?: bs->node_name;
beac80cd 6178}
beac80cd 6179
61007b31 6180int bdrv_get_flags(BlockDriverState *bs)
0b5a2445 6181{
15aee7ac 6182 IO_CODE();
61007b31 6183 return bs->open_flags;
0b5a2445
PB
6184}
6185
61007b31 6186int bdrv_has_zero_init_1(BlockDriverState *bs)
68485420 6187{
f791bf7f 6188 GLOBAL_STATE_CODE();
61007b31 6189 return 1;
0b5a2445
PB
6190}
6191
61007b31 6192int bdrv_has_zero_init(BlockDriverState *bs)
0b5a2445 6193{
93393e69 6194 BlockDriverState *filtered;
f791bf7f 6195 GLOBAL_STATE_CODE();
93393e69 6196
d470ad42
HR
6197 if (!bs->drv) {
6198 return 0;
6199 }
0b5a2445 6200
61007b31
SH
6201 /* If BS is a copy on write image, it is initialized to
6202 the contents of the base image, which may not be zeroes. */
34778172 6203 if (bdrv_cow_child(bs)) {
61007b31
SH
6204 return 0;
6205 }
6206 if (bs->drv->bdrv_has_zero_init) {
6207 return bs->drv->bdrv_has_zero_init(bs);
0b5a2445 6208 }
93393e69
HR
6209
6210 filtered = bdrv_filter_bs(bs);
6211 if (filtered) {
6212 return bdrv_has_zero_init(filtered);
5a612c00 6213 }
61007b31
SH
6214
6215 /* safe default */
6216 return 0;
68485420
KW
6217}
6218
61007b31 6219bool bdrv_can_write_zeroes_with_unmap(BlockDriverState *bs)
68485420 6220{
384a48fb 6221 IO_CODE();
2f0342ef 6222 if (!(bs->open_flags & BDRV_O_UNMAP)) {
61007b31
SH
6223 return false;
6224 }
68485420 6225
e24d813b 6226 return bs->supported_zero_flags & BDRV_REQ_MAY_UNMAP;
68485420
KW
6227}
6228
61007b31
SH
6229void bdrv_get_backing_filename(BlockDriverState *bs,
6230 char *filename, int filename_size)
016f5cf6 6231{
384a48fb 6232 IO_CODE();
61007b31
SH
6233 pstrcpy(filename, filename_size, bs->backing_file);
6234}
d318aea9 6235
61007b31
SH
6236int bdrv_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
6237{
8b117001 6238 int ret;
61007b31 6239 BlockDriver *drv = bs->drv;
384a48fb 6240 IO_CODE();
5a612c00
MP
6241 /* if bs->drv == NULL, bs is closed, so there's nothing to do here */
6242 if (!drv) {
61007b31 6243 return -ENOMEDIUM;
5a612c00
MP
6244 }
6245 if (!drv->bdrv_get_info) {
93393e69
HR
6246 BlockDriverState *filtered = bdrv_filter_bs(bs);
6247 if (filtered) {
6248 return bdrv_get_info(filtered, bdi);
5a612c00 6249 }
61007b31 6250 return -ENOTSUP;
5a612c00 6251 }
61007b31 6252 memset(bdi, 0, sizeof(*bdi));
8b117001
VSO
6253 ret = drv->bdrv_get_info(bs, bdi);
6254 if (ret < 0) {
6255 return ret;
6256 }
6257
6258 if (bdi->cluster_size > BDRV_MAX_ALIGNMENT) {
6259 return -EINVAL;
6260 }
6261
6262 return 0;
61007b31 6263}
016f5cf6 6264
1bf6e9ca
AS
6265ImageInfoSpecific *bdrv_get_specific_info(BlockDriverState *bs,
6266 Error **errp)
61007b31
SH
6267{
6268 BlockDriver *drv = bs->drv;
384a48fb 6269 IO_CODE();
61007b31 6270 if (drv && drv->bdrv_get_specific_info) {
1bf6e9ca 6271 return drv->bdrv_get_specific_info(bs, errp);
61007b31
SH
6272 }
6273 return NULL;
016f5cf6
AG
6274}
6275
d9245599
AN
6276BlockStatsSpecific *bdrv_get_specific_stats(BlockDriverState *bs)
6277{
6278 BlockDriver *drv = bs->drv;
384a48fb 6279 IO_CODE();
d9245599
AN
6280 if (!drv || !drv->bdrv_get_specific_stats) {
6281 return NULL;
6282 }
6283 return drv->bdrv_get_specific_stats(bs);
6284}
6285
a31939e6 6286void bdrv_debug_event(BlockDriverState *bs, BlkdebugEvent event)
4265d620 6287{
384a48fb 6288 IO_CODE();
61007b31
SH
6289 if (!bs || !bs->drv || !bs->drv->bdrv_debug_event) {
6290 return;
6291 }
4265d620 6292
61007b31 6293 bs->drv->bdrv_debug_event(bs, event);
4265d620
PB
6294}
6295
d10529a2 6296static BlockDriverState *bdrv_find_debug_node(BlockDriverState *bs)
4265d620 6297{
bdb73476 6298 GLOBAL_STATE_CODE();
61007b31 6299 while (bs && bs->drv && !bs->drv->bdrv_debug_breakpoint) {
f706a92f 6300 bs = bdrv_primary_bs(bs);
61007b31 6301 }
4265d620 6302
61007b31 6303 if (bs && bs->drv && bs->drv->bdrv_debug_breakpoint) {
d10529a2
VSO
6304 assert(bs->drv->bdrv_debug_remove_breakpoint);
6305 return bs;
6306 }
6307
6308 return NULL;
6309}
6310
6311int bdrv_debug_breakpoint(BlockDriverState *bs, const char *event,
6312 const char *tag)
6313{
f791bf7f 6314 GLOBAL_STATE_CODE();
d10529a2
VSO
6315 bs = bdrv_find_debug_node(bs);
6316 if (bs) {
61007b31
SH
6317 return bs->drv->bdrv_debug_breakpoint(bs, event, tag);
6318 }
4265d620 6319
61007b31 6320 return -ENOTSUP;
4265d620
PB
6321}
6322
61007b31 6323int bdrv_debug_remove_breakpoint(BlockDriverState *bs, const char *tag)
ea2384d3 6324{
f791bf7f 6325 GLOBAL_STATE_CODE();
d10529a2
VSO
6326 bs = bdrv_find_debug_node(bs);
6327 if (bs) {
61007b31
SH
6328 return bs->drv->bdrv_debug_remove_breakpoint(bs, tag);
6329 }
6330
6331 return -ENOTSUP;
eb852011
MA
6332}
6333
61007b31 6334int bdrv_debug_resume(BlockDriverState *bs, const char *tag)
ce1a14dc 6335{
f791bf7f 6336 GLOBAL_STATE_CODE();
61007b31 6337 while (bs && (!bs->drv || !bs->drv->bdrv_debug_resume)) {
f706a92f 6338 bs = bdrv_primary_bs(bs);
61007b31 6339 }
ce1a14dc 6340
61007b31
SH
6341 if (bs && bs->drv && bs->drv->bdrv_debug_resume) {
6342 return bs->drv->bdrv_debug_resume(bs, tag);
6343 }
ce1a14dc 6344
61007b31 6345 return -ENOTSUP;
f197fe2b
FZ
6346}
6347
61007b31 6348bool bdrv_debug_is_suspended(BlockDriverState *bs, const char *tag)
ce1a14dc 6349{
f791bf7f 6350 GLOBAL_STATE_CODE();
61007b31 6351 while (bs && bs->drv && !bs->drv->bdrv_debug_is_suspended) {
f706a92f 6352 bs = bdrv_primary_bs(bs);
f197fe2b 6353 }
19cb3738 6354
61007b31
SH
6355 if (bs && bs->drv && bs->drv->bdrv_debug_is_suspended) {
6356 return bs->drv->bdrv_debug_is_suspended(bs, tag);
6357 }
f9f05dc5 6358
61007b31
SH
6359 return false;
6360}
f9f05dc5 6361
61007b31
SH
6362/* backing_file can either be relative, or absolute, or a protocol. If it is
6363 * relative, it must be relative to the chain. So, passing in bs->filename
6364 * from a BDS as backing_file should not be done, as that may be relative to
6365 * the CWD rather than the chain. */
6366BlockDriverState *bdrv_find_backing_image(BlockDriverState *bs,
6367 const char *backing_file)
f9f05dc5 6368{
61007b31
SH
6369 char *filename_full = NULL;
6370 char *backing_file_full = NULL;
6371 char *filename_tmp = NULL;
6372 int is_protocol = 0;
0b877d09 6373 bool filenames_refreshed = false;
61007b31
SH
6374 BlockDriverState *curr_bs = NULL;
6375 BlockDriverState *retval = NULL;
dcf3f9b2 6376 BlockDriverState *bs_below;
f9f05dc5 6377
f791bf7f
EGE
6378 GLOBAL_STATE_CODE();
6379
61007b31
SH
6380 if (!bs || !bs->drv || !backing_file) {
6381 return NULL;
f9f05dc5
KW
6382 }
6383
61007b31
SH
6384 filename_full = g_malloc(PATH_MAX);
6385 backing_file_full = g_malloc(PATH_MAX);
f9f05dc5 6386
61007b31 6387 is_protocol = path_has_protocol(backing_file);
f9f05dc5 6388
dcf3f9b2
HR
6389 /*
6390 * Being largely a legacy function, skip any filters here
6391 * (because filters do not have normal filenames, so they cannot
6392 * match anyway; and allowing json:{} filenames is a bit out of
6393 * scope).
6394 */
6395 for (curr_bs = bdrv_skip_filters(bs);
6396 bdrv_cow_child(curr_bs) != NULL;
6397 curr_bs = bs_below)
6398 {
6399 bs_below = bdrv_backing_chain_next(curr_bs);
f9f05dc5 6400
0b877d09
HR
6401 if (bdrv_backing_overridden(curr_bs)) {
6402 /*
6403 * If the backing file was overridden, we can only compare
6404 * directly against the backing node's filename.
6405 */
6406
6407 if (!filenames_refreshed) {
6408 /*
6409 * This will automatically refresh all of the
6410 * filenames in the rest of the backing chain, so we
6411 * only need to do this once.
6412 */
6413 bdrv_refresh_filename(bs_below);
6414 filenames_refreshed = true;
6415 }
6416
6417 if (strcmp(backing_file, bs_below->filename) == 0) {
6418 retval = bs_below;
6419 break;
6420 }
6421 } else if (is_protocol || path_has_protocol(curr_bs->backing_file)) {
6422 /*
6423 * If either of the filename paths is actually a protocol, then
6424 * compare unmodified paths; otherwise make paths relative.
6425 */
6b6833c1
HR
6426 char *backing_file_full_ret;
6427
61007b31 6428 if (strcmp(backing_file, curr_bs->backing_file) == 0) {
dcf3f9b2 6429 retval = bs_below;
61007b31
SH
6430 break;
6431 }
418661e0 6432 /* Also check against the full backing filename for the image */
6b6833c1
HR
6433 backing_file_full_ret = bdrv_get_full_backing_filename(curr_bs,
6434 NULL);
6435 if (backing_file_full_ret) {
6436 bool equal = strcmp(backing_file, backing_file_full_ret) == 0;
6437 g_free(backing_file_full_ret);
6438 if (equal) {
dcf3f9b2 6439 retval = bs_below;
418661e0
JC
6440 break;
6441 }
418661e0 6442 }
61007b31
SH
6443 } else {
6444 /* If not an absolute filename path, make it relative to the current
6445 * image's filename path */
2d9158ce
HR
6446 filename_tmp = bdrv_make_absolute_filename(curr_bs, backing_file,
6447 NULL);
6448 /* We are going to compare canonicalized absolute pathnames */
6449 if (!filename_tmp || !realpath(filename_tmp, filename_full)) {
6450 g_free(filename_tmp);
61007b31
SH
6451 continue;
6452 }
2d9158ce 6453 g_free(filename_tmp);
07f07615 6454
61007b31
SH
6455 /* We need to make sure the backing filename we are comparing against
6456 * is relative to the current image filename (or absolute) */
2d9158ce
HR
6457 filename_tmp = bdrv_get_full_backing_filename(curr_bs, NULL);
6458 if (!filename_tmp || !realpath(filename_tmp, backing_file_full)) {
6459 g_free(filename_tmp);
61007b31
SH
6460 continue;
6461 }
2d9158ce 6462 g_free(filename_tmp);
eb489bb1 6463
61007b31 6464 if (strcmp(backing_file_full, filename_full) == 0) {
dcf3f9b2 6465 retval = bs_below;
61007b31
SH
6466 break;
6467 }
6468 }
eb489bb1
KW
6469 }
6470
61007b31
SH
6471 g_free(filename_full);
6472 g_free(backing_file_full);
61007b31
SH
6473 return retval;
6474}
6475
61007b31
SH
6476void bdrv_init(void)
6477{
e5f05f8c
KW
6478#ifdef CONFIG_BDRV_WHITELIST_TOOLS
6479 use_bdrv_whitelist = 1;
6480#endif
61007b31
SH
6481 module_call_init(MODULE_INIT_BLOCK);
6482}
29cdb251 6483
61007b31
SH
6484void bdrv_init_with_whitelist(void)
6485{
6486 use_bdrv_whitelist = 1;
6487 bdrv_init();
07f07615
PB
6488}
6489
a94750d9 6490int bdrv_activate(BlockDriverState *bs, Error **errp)
0f15423c 6491{
4417ab7a 6492 BdrvChild *child, *parent;
5a8a30db
KW
6493 Error *local_err = NULL;
6494 int ret;
9c98f145 6495 BdrvDirtyBitmap *bm;
5a8a30db 6496
f791bf7f
EGE
6497 GLOBAL_STATE_CODE();
6498
3456a8d1 6499 if (!bs->drv) {
5416645f 6500 return -ENOMEDIUM;
3456a8d1
KW
6501 }
6502
16e977d5 6503 QLIST_FOREACH(child, &bs->children, next) {
11d0c9b3 6504 bdrv_activate(child->bs, &local_err);
0d1c5c91 6505 if (local_err) {
0d1c5c91 6506 error_propagate(errp, local_err);
5416645f 6507 return -EINVAL;
0d1c5c91 6508 }
5a8a30db 6509 }
0d1c5c91 6510
dafe0960
KW
6511 /*
6512 * Update permissions, they may differ for inactive nodes.
6513 *
6514 * Note that the required permissions of inactive images are always a
6515 * subset of the permissions required after activating the image. This
6516 * allows us to just get the permissions upfront without restricting
11d0c9b3 6517 * bdrv_co_invalidate_cache().
dafe0960
KW
6518 *
6519 * It also means that in error cases, we don't have to try and revert to
6520 * the old permissions (which is an operation that could fail, too). We can
6521 * just keep the extended permissions for the next time that an activation
6522 * of the image is tried.
6523 */
7bb4941a
KW
6524 if (bs->open_flags & BDRV_O_INACTIVE) {
6525 bs->open_flags &= ~BDRV_O_INACTIVE;
071b474f 6526 ret = bdrv_refresh_perms(bs, errp);
7bb4941a 6527 if (ret < 0) {
0d1c5c91 6528 bs->open_flags |= BDRV_O_INACTIVE;
5416645f 6529 return ret;
0d1c5c91 6530 }
3456a8d1 6531
11d0c9b3
EGE
6532 ret = bdrv_invalidate_cache(bs, errp);
6533 if (ret < 0) {
6534 bs->open_flags |= BDRV_O_INACTIVE;
6535 return ret;
7bb4941a 6536 }
9c98f145 6537
7bb4941a
KW
6538 FOR_EACH_DIRTY_BITMAP(bs, bm) {
6539 bdrv_dirty_bitmap_skip_store(bm, false);
6540 }
6541
6542 ret = refresh_total_sectors(bs, bs->total_sectors);
6543 if (ret < 0) {
6544 bs->open_flags |= BDRV_O_INACTIVE;
6545 error_setg_errno(errp, -ret, "Could not refresh total sector count");
5416645f 6546 return ret;
7bb4941a 6547 }
5a8a30db 6548 }
4417ab7a
KW
6549
6550 QLIST_FOREACH(parent, &bs->parents, next_parent) {
bd86fb99
HR
6551 if (parent->klass->activate) {
6552 parent->klass->activate(parent, &local_err);
4417ab7a 6553 if (local_err) {
78fc3b3a 6554 bs->open_flags |= BDRV_O_INACTIVE;
4417ab7a 6555 error_propagate(errp, local_err);
5416645f 6556 return -EINVAL;
4417ab7a
KW
6557 }
6558 }
6559 }
5416645f
VSO
6560
6561 return 0;
0f15423c
AL
6562}
6563
11d0c9b3
EGE
6564int coroutine_fn bdrv_co_invalidate_cache(BlockDriverState *bs, Error **errp)
6565{
6566 Error *local_err = NULL;
1581a70d 6567 IO_CODE();
11d0c9b3
EGE
6568
6569 assert(!(bs->open_flags & BDRV_O_INACTIVE));
6570
6571 if (bs->drv->bdrv_co_invalidate_cache) {
6572 bs->drv->bdrv_co_invalidate_cache(bs, &local_err);
6573 if (local_err) {
6574 error_propagate(errp, local_err);
6575 return -EINVAL;
6576 }
6577 }
6578
6579 return 0;
6580}
6581
3b717194 6582void bdrv_activate_all(Error **errp)
0f15423c 6583{
7c8eece4 6584 BlockDriverState *bs;
88be7b4b 6585 BdrvNextIterator it;
0f15423c 6586
f791bf7f
EGE
6587 GLOBAL_STATE_CODE();
6588
88be7b4b 6589 for (bs = bdrv_first(&it); bs; bs = bdrv_next(&it)) {
ed78cda3 6590 AioContext *aio_context = bdrv_get_aio_context(bs);
5416645f 6591 int ret;
ed78cda3
SH
6592
6593 aio_context_acquire(aio_context);
a94750d9 6594 ret = bdrv_activate(bs, errp);
ed78cda3 6595 aio_context_release(aio_context);
5416645f 6596 if (ret < 0) {
5e003f17 6597 bdrv_next_cleanup(&it);
5a8a30db
KW
6598 return;
6599 }
0f15423c
AL
6600 }
6601}
6602
9e37271f
KW
6603static bool bdrv_has_bds_parent(BlockDriverState *bs, bool only_active)
6604{
6605 BdrvChild *parent;
bdb73476 6606 GLOBAL_STATE_CODE();
9e37271f
KW
6607
6608 QLIST_FOREACH(parent, &bs->parents, next_parent) {
bd86fb99 6609 if (parent->klass->parent_is_bds) {
9e37271f
KW
6610 BlockDriverState *parent_bs = parent->opaque;
6611 if (!only_active || !(parent_bs->open_flags & BDRV_O_INACTIVE)) {
6612 return true;
6613 }
6614 }
6615 }
6616
6617 return false;
6618}
6619
6620static int bdrv_inactivate_recurse(BlockDriverState *bs)
76b1c7fe 6621{
cfa1a572 6622 BdrvChild *child, *parent;
76b1c7fe 6623 int ret;
a13de40a 6624 uint64_t cumulative_perms, cumulative_shared_perms;
76b1c7fe 6625
da359909
EGE
6626 GLOBAL_STATE_CODE();
6627
d470ad42
HR
6628 if (!bs->drv) {
6629 return -ENOMEDIUM;
6630 }
6631
9e37271f
KW
6632 /* Make sure that we don't inactivate a child before its parent.
6633 * It will be covered by recursion from the yet active parent. */
6634 if (bdrv_has_bds_parent(bs, true)) {
6635 return 0;
6636 }
6637
6638 assert(!(bs->open_flags & BDRV_O_INACTIVE));
6639
6640 /* Inactivate this node */
6641 if (bs->drv->bdrv_inactivate) {
76b1c7fe
KW
6642 ret = bs->drv->bdrv_inactivate(bs);
6643 if (ret < 0) {
6644 return ret;
6645 }
6646 }
6647
9e37271f 6648 QLIST_FOREACH(parent, &bs->parents, next_parent) {
bd86fb99
HR
6649 if (parent->klass->inactivate) {
6650 ret = parent->klass->inactivate(parent);
9e37271f
KW
6651 if (ret < 0) {
6652 return ret;
cfa1a572
KW
6653 }
6654 }
9e37271f 6655 }
9c5e6594 6656
a13de40a
VSO
6657 bdrv_get_cumulative_perm(bs, &cumulative_perms,
6658 &cumulative_shared_perms);
6659 if (cumulative_perms & (BLK_PERM_WRITE | BLK_PERM_WRITE_UNCHANGED)) {
6660 /* Our inactive parents still need write access. Inactivation failed. */
6661 return -EPERM;
6662 }
6663
9e37271f 6664 bs->open_flags |= BDRV_O_INACTIVE;
7d5b5261 6665
bb87e4d1
VSO
6666 /*
6667 * Update permissions, they may differ for inactive nodes.
6668 * We only tried to loosen restrictions, so errors are not fatal, ignore
6669 * them.
6670 */
071b474f 6671 bdrv_refresh_perms(bs, NULL);
9e37271f
KW
6672
6673 /* Recursively inactivate children */
38701b6a 6674 QLIST_FOREACH(child, &bs->children, next) {
9e37271f 6675 ret = bdrv_inactivate_recurse(child->bs);
38701b6a
KW
6676 if (ret < 0) {
6677 return ret;
6678 }
6679 }
6680
76b1c7fe
KW
6681 return 0;
6682}
6683
6684int bdrv_inactivate_all(void)
6685{
79720af6 6686 BlockDriverState *bs = NULL;
88be7b4b 6687 BdrvNextIterator it;
aad0b7a0 6688 int ret = 0;
bd6458e4 6689 GSList *aio_ctxs = NULL, *ctx;
76b1c7fe 6690
f791bf7f
EGE
6691 GLOBAL_STATE_CODE();
6692
88be7b4b 6693 for (bs = bdrv_first(&it); bs; bs = bdrv_next(&it)) {
bd6458e4
PB
6694 AioContext *aio_context = bdrv_get_aio_context(bs);
6695
6696 if (!g_slist_find(aio_ctxs, aio_context)) {
6697 aio_ctxs = g_slist_prepend(aio_ctxs, aio_context);
6698 aio_context_acquire(aio_context);
6699 }
aad0b7a0 6700 }
76b1c7fe 6701
9e37271f
KW
6702 for (bs = bdrv_first(&it); bs; bs = bdrv_next(&it)) {
6703 /* Nodes with BDS parents are covered by recursion from the last
6704 * parent that gets inactivated. Don't inactivate them a second
6705 * time if that has already happened. */
6706 if (bdrv_has_bds_parent(bs, false)) {
6707 continue;
6708 }
6709 ret = bdrv_inactivate_recurse(bs);
6710 if (ret < 0) {
6711 bdrv_next_cleanup(&it);
6712 goto out;
76b1c7fe
KW
6713 }
6714 }
6715
aad0b7a0 6716out:
bd6458e4
PB
6717 for (ctx = aio_ctxs; ctx != NULL; ctx = ctx->next) {
6718 AioContext *aio_context = ctx->data;
6719 aio_context_release(aio_context);
aad0b7a0 6720 }
bd6458e4 6721 g_slist_free(aio_ctxs);
aad0b7a0
FZ
6722
6723 return ret;
76b1c7fe
KW
6724}
6725
19cb3738
FB
6726/**************************************************************/
6727/* removable device support */
6728
6729/**
6730 * Return TRUE if the media is present
6731 */
e031f750 6732bool bdrv_is_inserted(BlockDriverState *bs)
19cb3738
FB
6733{
6734 BlockDriver *drv = bs->drv;
28d7a789 6735 BdrvChild *child;
384a48fb 6736 IO_CODE();
a1aff5bf 6737
e031f750
HR
6738 if (!drv) {
6739 return false;
6740 }
28d7a789
HR
6741 if (drv->bdrv_is_inserted) {
6742 return drv->bdrv_is_inserted(bs);
6743 }
6744 QLIST_FOREACH(child, &bs->children, next) {
6745 if (!bdrv_is_inserted(child->bs)) {
6746 return false;
6747 }
e031f750 6748 }
28d7a789 6749 return true;
19cb3738
FB
6750}
6751
19cb3738
FB
6752/**
6753 * If eject_flag is TRUE, eject the media. Otherwise, close the tray
6754 */
f36f3949 6755void bdrv_eject(BlockDriverState *bs, bool eject_flag)
19cb3738
FB
6756{
6757 BlockDriver *drv = bs->drv;
384a48fb 6758 IO_CODE();
19cb3738 6759
822e1cd1
MA
6760 if (drv && drv->bdrv_eject) {
6761 drv->bdrv_eject(bs, eject_flag);
19cb3738
FB
6762 }
6763}
6764
19cb3738
FB
6765/**
6766 * Lock or unlock the media (if it is locked, the user won't be able
6767 * to eject it manually).
6768 */
025e849a 6769void bdrv_lock_medium(BlockDriverState *bs, bool locked)
19cb3738
FB
6770{
6771 BlockDriver *drv = bs->drv;
384a48fb 6772 IO_CODE();
025e849a 6773 trace_bdrv_lock_medium(bs, locked);
b8c6d095 6774
025e849a
MA
6775 if (drv && drv->bdrv_lock_medium) {
6776 drv->bdrv_lock_medium(bs, locked);
19cb3738
FB
6777 }
6778}
985a03b0 6779
9fcb0251
FZ
6780/* Get a reference to bs */
6781void bdrv_ref(BlockDriverState *bs)
6782{
f791bf7f 6783 GLOBAL_STATE_CODE();
9fcb0251
FZ
6784 bs->refcnt++;
6785}
6786
6787/* Release a previously grabbed reference to bs.
6788 * If after releasing, reference count is zero, the BlockDriverState is
6789 * deleted. */
6790void bdrv_unref(BlockDriverState *bs)
6791{
f791bf7f 6792 GLOBAL_STATE_CODE();
9a4d5ca6
JC
6793 if (!bs) {
6794 return;
6795 }
9fcb0251
FZ
6796 assert(bs->refcnt > 0);
6797 if (--bs->refcnt == 0) {
6798 bdrv_delete(bs);
6799 }
6800}
6801
fbe40ff7
FZ
6802struct BdrvOpBlocker {
6803 Error *reason;
6804 QLIST_ENTRY(BdrvOpBlocker) list;
6805};
6806
6807bool bdrv_op_is_blocked(BlockDriverState *bs, BlockOpType op, Error **errp)
6808{
6809 BdrvOpBlocker *blocker;
f791bf7f 6810 GLOBAL_STATE_CODE();
fbe40ff7
FZ
6811 assert((int) op >= 0 && op < BLOCK_OP_TYPE_MAX);
6812 if (!QLIST_EMPTY(&bs->op_blockers[op])) {
6813 blocker = QLIST_FIRST(&bs->op_blockers[op]);
4b576648
MA
6814 error_propagate_prepend(errp, error_copy(blocker->reason),
6815 "Node '%s' is busy: ",
6816 bdrv_get_device_or_node_name(bs));
fbe40ff7
FZ
6817 return true;
6818 }
6819 return false;
6820}
6821
6822void bdrv_op_block(BlockDriverState *bs, BlockOpType op, Error *reason)
6823{
6824 BdrvOpBlocker *blocker;
f791bf7f 6825 GLOBAL_STATE_CODE();
fbe40ff7
FZ
6826 assert((int) op >= 0 && op < BLOCK_OP_TYPE_MAX);
6827
5839e53b 6828 blocker = g_new0(BdrvOpBlocker, 1);
fbe40ff7
FZ
6829 blocker->reason = reason;
6830 QLIST_INSERT_HEAD(&bs->op_blockers[op], blocker, list);
6831}
6832
6833void bdrv_op_unblock(BlockDriverState *bs, BlockOpType op, Error *reason)
6834{
6835 BdrvOpBlocker *blocker, *next;
f791bf7f 6836 GLOBAL_STATE_CODE();
fbe40ff7
FZ
6837 assert((int) op >= 0 && op < BLOCK_OP_TYPE_MAX);
6838 QLIST_FOREACH_SAFE(blocker, &bs->op_blockers[op], list, next) {
6839 if (blocker->reason == reason) {
6840 QLIST_REMOVE(blocker, list);
6841 g_free(blocker);
6842 }
6843 }
6844}
6845
6846void bdrv_op_block_all(BlockDriverState *bs, Error *reason)
6847{
6848 int i;
f791bf7f 6849 GLOBAL_STATE_CODE();
fbe40ff7
FZ
6850 for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
6851 bdrv_op_block(bs, i, reason);
6852 }
6853}
6854
6855void bdrv_op_unblock_all(BlockDriverState *bs, Error *reason)
6856{
6857 int i;
f791bf7f 6858 GLOBAL_STATE_CODE();
fbe40ff7
FZ
6859 for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
6860 bdrv_op_unblock(bs, i, reason);
6861 }
6862}
6863
6864bool bdrv_op_blocker_is_empty(BlockDriverState *bs)
6865{
6866 int i;
f791bf7f 6867 GLOBAL_STATE_CODE();
fbe40ff7
FZ
6868 for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
6869 if (!QLIST_EMPTY(&bs->op_blockers[i])) {
6870 return false;
6871 }
6872 }
6873 return true;
6874}
6875
d92ada22
LC
6876void bdrv_img_create(const char *filename, const char *fmt,
6877 const char *base_filename, const char *base_fmt,
9217283d
FZ
6878 char *options, uint64_t img_size, int flags, bool quiet,
6879 Error **errp)
f88e1a42 6880{
83d0521a
CL
6881 QemuOptsList *create_opts = NULL;
6882 QemuOpts *opts = NULL;
6883 const char *backing_fmt, *backing_file;
6884 int64_t size;
f88e1a42 6885 BlockDriver *drv, *proto_drv;
cc84d90f 6886 Error *local_err = NULL;
f88e1a42
JS
6887 int ret = 0;
6888
f791bf7f
EGE
6889 GLOBAL_STATE_CODE();
6890
f88e1a42
JS
6891 /* Find driver and parse its options */
6892 drv = bdrv_find_format(fmt);
6893 if (!drv) {
71c79813 6894 error_setg(errp, "Unknown file format '%s'", fmt);
d92ada22 6895 return;
f88e1a42
JS
6896 }
6897
b65a5e12 6898 proto_drv = bdrv_find_protocol(filename, true, errp);
f88e1a42 6899 if (!proto_drv) {
d92ada22 6900 return;
f88e1a42
JS
6901 }
6902
c6149724
HR
6903 if (!drv->create_opts) {
6904 error_setg(errp, "Format driver '%s' does not support image creation",
6905 drv->format_name);
6906 return;
6907 }
6908
5a5e7f8c
ML
6909 if (!proto_drv->create_opts) {
6910 error_setg(errp, "Protocol driver '%s' does not support image creation",
6911 proto_drv->format_name);
6912 return;
6913 }
6914
f6dc1c31 6915 /* Create parameter list */
c282e1fd 6916 create_opts = qemu_opts_append(create_opts, drv->create_opts);
5a5e7f8c 6917 create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
f88e1a42 6918
83d0521a 6919 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
f88e1a42
JS
6920
6921 /* Parse -o options */
6922 if (options) {
a5f9b9df 6923 if (!qemu_opts_do_parse(opts, options, NULL, errp)) {
f88e1a42
JS
6924 goto out;
6925 }
6926 }
6927
f6dc1c31
KW
6928 if (!qemu_opt_get(opts, BLOCK_OPT_SIZE)) {
6929 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, img_size, &error_abort);
6930 } else if (img_size != UINT64_C(-1)) {
6931 error_setg(errp, "The image size must be specified only once");
6932 goto out;
6933 }
6934
f88e1a42 6935 if (base_filename) {
235e59cf 6936 if (!qemu_opt_set(opts, BLOCK_OPT_BACKING_FILE, base_filename,
3882578b 6937 NULL)) {
71c79813
LC
6938 error_setg(errp, "Backing file not supported for file format '%s'",
6939 fmt);
f88e1a42
JS
6940 goto out;
6941 }
6942 }
6943
6944 if (base_fmt) {
3882578b 6945 if (!qemu_opt_set(opts, BLOCK_OPT_BACKING_FMT, base_fmt, NULL)) {
71c79813
LC
6946 error_setg(errp, "Backing file format not supported for file "
6947 "format '%s'", fmt);
f88e1a42
JS
6948 goto out;
6949 }
6950 }
6951
83d0521a
CL
6952 backing_file = qemu_opt_get(opts, BLOCK_OPT_BACKING_FILE);
6953 if (backing_file) {
6954 if (!strcmp(filename, backing_file)) {
71c79813
LC
6955 error_setg(errp, "Error: Trying to create an image with the "
6956 "same filename as the backing file");
792da93a
JS
6957 goto out;
6958 }
975a7bd2
CK
6959 if (backing_file[0] == '\0') {
6960 error_setg(errp, "Expected backing file name, got empty string");
6961 goto out;
6962 }
792da93a
JS
6963 }
6964
83d0521a 6965 backing_fmt = qemu_opt_get(opts, BLOCK_OPT_BACKING_FMT);
f88e1a42 6966
6e6e55f5
JS
6967 /* The size for the image must always be specified, unless we have a backing
6968 * file and we have not been forbidden from opening it. */
a8b42a1c 6969 size = qemu_opt_get_size(opts, BLOCK_OPT_SIZE, img_size);
6e6e55f5
JS
6970 if (backing_file && !(flags & BDRV_O_NO_BACKING)) {
6971 BlockDriverState *bs;
645ae7d8 6972 char *full_backing;
6e6e55f5
JS
6973 int back_flags;
6974 QDict *backing_options = NULL;
6975
645ae7d8
HR
6976 full_backing =
6977 bdrv_get_full_backing_filename_from_filename(filename, backing_file,
6978 &local_err);
6e6e55f5 6979 if (local_err) {
6e6e55f5
JS
6980 goto out;
6981 }
645ae7d8 6982 assert(full_backing);
29168018 6983
d5b23994
HR
6984 /*
6985 * No need to do I/O here, which allows us to open encrypted
6986 * backing images without needing the secret
6987 */
6e6e55f5
JS
6988 back_flags = flags;
6989 back_flags &= ~(BDRV_O_RDWR | BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING);
d5b23994 6990 back_flags |= BDRV_O_NO_IO;
f88e1a42 6991
cc954f01 6992 backing_options = qdict_new();
6e6e55f5 6993 if (backing_fmt) {
6e6e55f5
JS
6994 qdict_put_str(backing_options, "driver", backing_fmt);
6995 }
cc954f01 6996 qdict_put_bool(backing_options, BDRV_OPT_FORCE_SHARE, true);
e6641719 6997
6e6e55f5
JS
6998 bs = bdrv_open(full_backing, NULL, backing_options, back_flags,
6999 &local_err);
7000 g_free(full_backing);
add8200d
EB
7001 if (!bs) {
7002 error_append_hint(&local_err, "Could not open backing image.\n");
6e6e55f5
JS
7003 goto out;
7004 } else {
d9f059aa 7005 if (!backing_fmt) {
497a30db
EB
7006 error_setg(&local_err,
7007 "Backing file specified without backing format");
7008 error_append_hint(&local_err, "Detected format of %s.",
7009 bs->drv->format_name);
7010 goto out;
d9f059aa 7011 }
6e6e55f5
JS
7012 if (size == -1) {
7013 /* Opened BS, have no size */
7014 size = bdrv_getlength(bs);
7015 if (size < 0) {
7016 error_setg_errno(errp, -size, "Could not get size of '%s'",
7017 backing_file);
7018 bdrv_unref(bs);
7019 goto out;
7020 }
7021 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, size, &error_abort);
52bf1e72 7022 }
66f6b814 7023 bdrv_unref(bs);
f88e1a42 7024 }
d9f059aa
EB
7025 /* (backing_file && !(flags & BDRV_O_NO_BACKING)) */
7026 } else if (backing_file && !backing_fmt) {
497a30db
EB
7027 error_setg(&local_err,
7028 "Backing file specified without backing format");
7029 goto out;
d9f059aa 7030 }
6e6e55f5
JS
7031
7032 if (size == -1) {
7033 error_setg(errp, "Image creation needs a size parameter");
7034 goto out;
f88e1a42
JS
7035 }
7036
f382d43a 7037 if (!quiet) {
fe646693 7038 printf("Formatting '%s', fmt=%s ", filename, fmt);
43c5d8f8 7039 qemu_opts_print(opts, " ");
f382d43a 7040 puts("");
4e2f4418 7041 fflush(stdout);
f382d43a 7042 }
83d0521a 7043
c282e1fd 7044 ret = bdrv_create(drv, filename, opts, &local_err);
83d0521a 7045
cc84d90f
HR
7046 if (ret == -EFBIG) {
7047 /* This is generally a better message than whatever the driver would
7048 * deliver (especially because of the cluster_size_hint), since that
7049 * is most probably not much different from "image too large". */
7050 const char *cluster_size_hint = "";
83d0521a 7051 if (qemu_opt_get_size(opts, BLOCK_OPT_CLUSTER_SIZE, 0)) {
cc84d90f 7052 cluster_size_hint = " (try using a larger cluster size)";
f88e1a42 7053 }
cc84d90f
HR
7054 error_setg(errp, "The image size is too large for file format '%s'"
7055 "%s", fmt, cluster_size_hint);
7056 error_free(local_err);
7057 local_err = NULL;
f88e1a42
JS
7058 }
7059
7060out:
83d0521a
CL
7061 qemu_opts_del(opts);
7062 qemu_opts_free(create_opts);
621ff94d 7063 error_propagate(errp, local_err);
f88e1a42 7064}
85d126f3
SH
7065
7066AioContext *bdrv_get_aio_context(BlockDriverState *bs)
7067{
384a48fb 7068 IO_CODE();
33f2a757 7069 return bs ? bs->aio_context : qemu_get_aio_context();
dcd04228
SH
7070}
7071
e336fd4c
KW
7072AioContext *coroutine_fn bdrv_co_enter(BlockDriverState *bs)
7073{
7074 Coroutine *self = qemu_coroutine_self();
7075 AioContext *old_ctx = qemu_coroutine_get_aio_context(self);
7076 AioContext *new_ctx;
384a48fb 7077 IO_CODE();
e336fd4c
KW
7078
7079 /*
7080 * Increase bs->in_flight to ensure that this operation is completed before
7081 * moving the node to a different AioContext. Read new_ctx only afterwards.
7082 */
7083 bdrv_inc_in_flight(bs);
7084
7085 new_ctx = bdrv_get_aio_context(bs);
7086 aio_co_reschedule_self(new_ctx);
7087 return old_ctx;
7088}
7089
7090void coroutine_fn bdrv_co_leave(BlockDriverState *bs, AioContext *old_ctx)
7091{
384a48fb 7092 IO_CODE();
e336fd4c
KW
7093 aio_co_reschedule_self(old_ctx);
7094 bdrv_dec_in_flight(bs);
7095}
7096
18c6ac1c
KW
7097void coroutine_fn bdrv_co_lock(BlockDriverState *bs)
7098{
7099 AioContext *ctx = bdrv_get_aio_context(bs);
7100
7101 /* In the main thread, bs->aio_context won't change concurrently */
7102 assert(qemu_get_current_aio_context() == qemu_get_aio_context());
7103
7104 /*
7105 * We're in coroutine context, so we already hold the lock of the main
7106 * loop AioContext. Don't lock it twice to avoid deadlocks.
7107 */
7108 assert(qemu_in_coroutine());
7109 if (ctx != qemu_get_aio_context()) {
7110 aio_context_acquire(ctx);
7111 }
7112}
7113
7114void coroutine_fn bdrv_co_unlock(BlockDriverState *bs)
7115{
7116 AioContext *ctx = bdrv_get_aio_context(bs);
7117
7118 assert(qemu_in_coroutine());
7119 if (ctx != qemu_get_aio_context()) {
7120 aio_context_release(ctx);
7121 }
7122}
7123
052a7572
FZ
7124void bdrv_coroutine_enter(BlockDriverState *bs, Coroutine *co)
7125{
384a48fb 7126 IO_CODE();
052a7572
FZ
7127 aio_co_enter(bdrv_get_aio_context(bs), co);
7128}
7129
e8a095da
SH
7130static void bdrv_do_remove_aio_context_notifier(BdrvAioNotifier *ban)
7131{
bdb73476 7132 GLOBAL_STATE_CODE();
e8a095da
SH
7133 QLIST_REMOVE(ban, list);
7134 g_free(ban);
7135}
7136
a3a683c3 7137static void bdrv_detach_aio_context(BlockDriverState *bs)
dcd04228 7138{
e8a095da 7139 BdrvAioNotifier *baf, *baf_tmp;
33384421 7140
e8a095da 7141 assert(!bs->walking_aio_notifiers);
da359909 7142 GLOBAL_STATE_CODE();
e8a095da
SH
7143 bs->walking_aio_notifiers = true;
7144 QLIST_FOREACH_SAFE(baf, &bs->aio_notifiers, list, baf_tmp) {
7145 if (baf->deleted) {
7146 bdrv_do_remove_aio_context_notifier(baf);
7147 } else {
7148 baf->detach_aio_context(baf->opaque);
7149 }
33384421 7150 }
e8a095da
SH
7151 /* Never mind iterating again to check for ->deleted. bdrv_close() will
7152 * remove remaining aio notifiers if we aren't called again.
7153 */
7154 bs->walking_aio_notifiers = false;
33384421 7155
1bffe1ae 7156 if (bs->drv && bs->drv->bdrv_detach_aio_context) {
dcd04228
SH
7157 bs->drv->bdrv_detach_aio_context(bs);
7158 }
dcd04228 7159
e64f25f3
KW
7160 if (bs->quiesce_counter) {
7161 aio_enable_external(bs->aio_context);
7162 }
7f898610 7163 assert_bdrv_graph_writable(bs);
dcd04228
SH
7164 bs->aio_context = NULL;
7165}
7166
a3a683c3
KW
7167static void bdrv_attach_aio_context(BlockDriverState *bs,
7168 AioContext *new_context)
dcd04228 7169{
e8a095da 7170 BdrvAioNotifier *ban, *ban_tmp;
da359909 7171 GLOBAL_STATE_CODE();
33384421 7172
e64f25f3
KW
7173 if (bs->quiesce_counter) {
7174 aio_disable_external(new_context);
7175 }
7176
7f898610 7177 assert_bdrv_graph_writable(bs);
dcd04228
SH
7178 bs->aio_context = new_context;
7179
1bffe1ae 7180 if (bs->drv && bs->drv->bdrv_attach_aio_context) {
dcd04228
SH
7181 bs->drv->bdrv_attach_aio_context(bs, new_context);
7182 }
33384421 7183
e8a095da
SH
7184 assert(!bs->walking_aio_notifiers);
7185 bs->walking_aio_notifiers = true;
7186 QLIST_FOREACH_SAFE(ban, &bs->aio_notifiers, list, ban_tmp) {
7187 if (ban->deleted) {
7188 bdrv_do_remove_aio_context_notifier(ban);
7189 } else {
7190 ban->attached_aio_context(new_context, ban->opaque);
7191 }
33384421 7192 }
e8a095da 7193 bs->walking_aio_notifiers = false;
dcd04228
SH
7194}
7195
7e8c182f
EGE
7196typedef struct BdrvStateSetAioContext {
7197 AioContext *new_ctx;
7198 BlockDriverState *bs;
7199} BdrvStateSetAioContext;
d616b224 7200
7e8c182f 7201static bool bdrv_parent_change_aio_context(BdrvChild *c, AioContext *ctx,
e08cc001
EGE
7202 GHashTable *visited,
7203 Transaction *tran,
7e8c182f 7204 Error **errp)
5d231849 7205{
f0c28327 7206 GLOBAL_STATE_CODE();
e08cc001 7207 if (g_hash_table_contains(visited, c)) {
5d231849
KW
7208 return true;
7209 }
e08cc001 7210 g_hash_table_add(visited, c);
5d231849 7211
bd86fb99
HR
7212 /*
7213 * A BdrvChildClass that doesn't handle AioContext changes cannot
7214 * tolerate any AioContext changes
7215 */
7e8c182f 7216 if (!c->klass->change_aio_ctx) {
5d231849
KW
7217 char *user = bdrv_child_user_desc(c);
7218 error_setg(errp, "Changing iothreads is not supported by %s", user);
7219 g_free(user);
7220 return false;
7221 }
7e8c182f 7222 if (!c->klass->change_aio_ctx(c, ctx, visited, tran, errp)) {
5d231849
KW
7223 assert(!errp || *errp);
7224 return false;
7225 }
7226 return true;
7227}
7228
7e8c182f 7229bool bdrv_child_change_aio_context(BdrvChild *c, AioContext *ctx,
e08cc001 7230 GHashTable *visited, Transaction *tran,
7e8c182f 7231 Error **errp)
5d231849 7232{
f791bf7f 7233 GLOBAL_STATE_CODE();
e08cc001 7234 if (g_hash_table_contains(visited, c)) {
5d231849
KW
7235 return true;
7236 }
e08cc001 7237 g_hash_table_add(visited, c);
7e8c182f 7238 return bdrv_change_aio_context(c->bs, ctx, visited, tran, errp);
5d231849
KW
7239}
7240
7e8c182f
EGE
7241static void bdrv_set_aio_context_clean(void *opaque)
7242{
7243 BdrvStateSetAioContext *state = (BdrvStateSetAioContext *) opaque;
7244 BlockDriverState *bs = (BlockDriverState *) state->bs;
7245
7246 /* Paired with bdrv_drained_begin in bdrv_change_aio_context() */
7247 bdrv_drained_end(bs);
7248
7249 g_free(state);
7250}
7251
7252static void bdrv_set_aio_context_commit(void *opaque)
7253{
7254 BdrvStateSetAioContext *state = (BdrvStateSetAioContext *) opaque;
7255 BlockDriverState *bs = (BlockDriverState *) state->bs;
7256 AioContext *new_context = state->new_ctx;
7257 AioContext *old_context = bdrv_get_aio_context(bs);
7258 assert_bdrv_graph_writable(bs);
7259
7260 /*
7261 * Take the old AioContex when detaching it from bs.
7262 * At this point, new_context lock is already acquired, and we are now
7263 * also taking old_context. This is safe as long as bdrv_detach_aio_context
7264 * does not call AIO_POLL_WHILE().
7265 */
7266 if (old_context != qemu_get_aio_context()) {
7267 aio_context_acquire(old_context);
7268 }
7269 bdrv_detach_aio_context(bs);
7270 if (old_context != qemu_get_aio_context()) {
7271 aio_context_release(old_context);
7272 }
7273 bdrv_attach_aio_context(bs, new_context);
7274}
7275
7276static TransactionActionDrv set_aio_context = {
7277 .commit = bdrv_set_aio_context_commit,
7278 .clean = bdrv_set_aio_context_clean,
7279};
7280
7281/*
7282 * Changes the AioContext used for fd handlers, timers, and BHs by this
7283 * BlockDriverState and all its children and parents.
7284 *
7285 * Must be called from the main AioContext.
7286 *
7287 * The caller must own the AioContext lock for the old AioContext of bs, but it
7288 * must not own the AioContext lock for new_context (unless new_context is the
7289 * same as the current context of bs).
7290 *
7291 * @visited will accumulate all visited BdrvChild objects. The caller is
7292 * responsible for freeing the list afterwards.
7293 */
7294static bool bdrv_change_aio_context(BlockDriverState *bs, AioContext *ctx,
e08cc001 7295 GHashTable *visited, Transaction *tran,
7e8c182f 7296 Error **errp)
5d231849
KW
7297{
7298 BdrvChild *c;
7e8c182f
EGE
7299 BdrvStateSetAioContext *state;
7300
7301 GLOBAL_STATE_CODE();
5d231849
KW
7302
7303 if (bdrv_get_aio_context(bs) == ctx) {
7304 return true;
7305 }
7306
7307 QLIST_FOREACH(c, &bs->parents, next_parent) {
7e8c182f 7308 if (!bdrv_parent_change_aio_context(c, ctx, visited, tran, errp)) {
5d231849
KW
7309 return false;
7310 }
7311 }
7e8c182f 7312
5d231849 7313 QLIST_FOREACH(c, &bs->children, next) {
7e8c182f 7314 if (!bdrv_child_change_aio_context(c, ctx, visited, tran, errp)) {
5d231849
KW
7315 return false;
7316 }
7317 }
7318
7e8c182f
EGE
7319 state = g_new(BdrvStateSetAioContext, 1);
7320 *state = (BdrvStateSetAioContext) {
7321 .new_ctx = ctx,
7322 .bs = bs,
7323 };
7324
7325 /* Paired with bdrv_drained_end in bdrv_set_aio_context_clean() */
7326 bdrv_drained_begin(bs);
7327
7328 tran_add(tran, &set_aio_context, state);
7329
5d231849
KW
7330 return true;
7331}
7332
7e8c182f
EGE
7333/*
7334 * Change bs's and recursively all of its parents' and children's AioContext
7335 * to the given new context, returning an error if that isn't possible.
7336 *
7337 * If ignore_child is not NULL, that child (and its subgraph) will not
7338 * be touched.
7339 *
7340 * This function still requires the caller to take the bs current
7341 * AioContext lock, otherwise draining will fail since AIO_WAIT_WHILE
7342 * assumes the lock is always held if bs is in another AioContext.
7343 * For the same reason, it temporarily also holds the new AioContext, since
7344 * bdrv_drained_end calls BDRV_POLL_WHILE that assumes the lock is taken too.
7345 * Therefore the new AioContext lock must not be taken by the caller.
7346 */
a41cfda1
EGE
7347int bdrv_try_change_aio_context(BlockDriverState *bs, AioContext *ctx,
7348 BdrvChild *ignore_child, Error **errp)
5d231849 7349{
7e8c182f 7350 Transaction *tran;
e08cc001 7351 GHashTable *visited;
7e8c182f
EGE
7352 int ret;
7353 AioContext *old_context = bdrv_get_aio_context(bs);
f791bf7f
EGE
7354 GLOBAL_STATE_CODE();
7355
7e8c182f
EGE
7356 /*
7357 * Recursion phase: go through all nodes of the graph.
7358 * Take care of checking that all nodes support changing AioContext
7359 * and drain them, builing a linear list of callbacks to run if everything
7360 * is successful (the transaction itself).
7361 */
7362 tran = tran_new();
e08cc001
EGE
7363 visited = g_hash_table_new(NULL, NULL);
7364 if (ignore_child) {
7365 g_hash_table_add(visited, ignore_child);
7366 }
7367 ret = bdrv_change_aio_context(bs, ctx, visited, tran, errp);
7368 g_hash_table_destroy(visited);
7e8c182f
EGE
7369
7370 /*
7371 * Linear phase: go through all callbacks collected in the transaction.
7372 * Run all callbacks collected in the recursion to switch all nodes
7373 * AioContext lock (transaction commit), or undo all changes done in the
7374 * recursion (transaction abort).
7375 */
5d231849
KW
7376
7377 if (!ret) {
7e8c182f
EGE
7378 /* Just run clean() callbacks. No AioContext changed. */
7379 tran_abort(tran);
5d231849
KW
7380 return -EPERM;
7381 }
7382
7e8c182f
EGE
7383 /*
7384 * Release old AioContext, it won't be needed anymore, as all
7385 * bdrv_drained_begin() have been called already.
7386 */
7387 if (qemu_get_aio_context() != old_context) {
7388 aio_context_release(old_context);
7389 }
7390
7391 /*
7392 * Acquire new AioContext since bdrv_drained_end() is going to be called
7393 * after we switched all nodes in the new AioContext, and the function
7394 * assumes that the lock of the bs is always taken.
7395 */
7396 if (qemu_get_aio_context() != ctx) {
7397 aio_context_acquire(ctx);
7398 }
53a7d041 7399
7e8c182f 7400 tran_commit(tran);
5d231849 7401
7e8c182f
EGE
7402 if (qemu_get_aio_context() != ctx) {
7403 aio_context_release(ctx);
7404 }
7405
7406 /* Re-acquire the old AioContext, since the caller takes and releases it. */
7407 if (qemu_get_aio_context() != old_context) {
7408 aio_context_acquire(old_context);
7409 }
7410
7411 return 0;
5d231849
KW
7412}
7413
33384421
HR
7414void bdrv_add_aio_context_notifier(BlockDriverState *bs,
7415 void (*attached_aio_context)(AioContext *new_context, void *opaque),
7416 void (*detach_aio_context)(void *opaque), void *opaque)
7417{
7418 BdrvAioNotifier *ban = g_new(BdrvAioNotifier, 1);
7419 *ban = (BdrvAioNotifier){
7420 .attached_aio_context = attached_aio_context,
7421 .detach_aio_context = detach_aio_context,
7422 .opaque = opaque
7423 };
f791bf7f 7424 GLOBAL_STATE_CODE();
33384421
HR
7425
7426 QLIST_INSERT_HEAD(&bs->aio_notifiers, ban, list);
7427}
7428
7429void bdrv_remove_aio_context_notifier(BlockDriverState *bs,
7430 void (*attached_aio_context)(AioContext *,
7431 void *),
7432 void (*detach_aio_context)(void *),
7433 void *opaque)
7434{
7435 BdrvAioNotifier *ban, *ban_next;
f791bf7f 7436 GLOBAL_STATE_CODE();
33384421
HR
7437
7438 QLIST_FOREACH_SAFE(ban, &bs->aio_notifiers, list, ban_next) {
7439 if (ban->attached_aio_context == attached_aio_context &&
7440 ban->detach_aio_context == detach_aio_context &&
e8a095da
SH
7441 ban->opaque == opaque &&
7442 ban->deleted == false)
33384421 7443 {
e8a095da
SH
7444 if (bs->walking_aio_notifiers) {
7445 ban->deleted = true;
7446 } else {
7447 bdrv_do_remove_aio_context_notifier(ban);
7448 }
33384421
HR
7449 return;
7450 }
7451 }
7452
7453 abort();
7454}
7455
77485434 7456int bdrv_amend_options(BlockDriverState *bs, QemuOpts *opts,
d1402b50 7457 BlockDriverAmendStatusCB *status_cb, void *cb_opaque,
a3579bfa 7458 bool force,
d1402b50 7459 Error **errp)
6f176b48 7460{
f791bf7f 7461 GLOBAL_STATE_CODE();
d470ad42 7462 if (!bs->drv) {
d1402b50 7463 error_setg(errp, "Node is ejected");
d470ad42
HR
7464 return -ENOMEDIUM;
7465 }
c282e1fd 7466 if (!bs->drv->bdrv_amend_options) {
d1402b50
HR
7467 error_setg(errp, "Block driver '%s' does not support option amendment",
7468 bs->drv->format_name);
6f176b48
HR
7469 return -ENOTSUP;
7470 }
a3579bfa
ML
7471 return bs->drv->bdrv_amend_options(bs, opts, status_cb,
7472 cb_opaque, force, errp);
6f176b48 7473}
f6186f49 7474
5d69b5ab
HR
7475/*
7476 * This function checks whether the given @to_replace is allowed to be
7477 * replaced by a node that always shows the same data as @bs. This is
7478 * used for example to verify whether the mirror job can replace
7479 * @to_replace by the target mirrored from @bs.
7480 * To be replaceable, @bs and @to_replace may either be guaranteed to
7481 * always show the same data (because they are only connected through
7482 * filters), or some driver may allow replacing one of its children
7483 * because it can guarantee that this child's data is not visible at
7484 * all (for example, for dissenting quorum children that have no other
7485 * parents).
7486 */
7487bool bdrv_recurse_can_replace(BlockDriverState *bs,
7488 BlockDriverState *to_replace)
7489{
93393e69
HR
7490 BlockDriverState *filtered;
7491
b4ad82aa
EGE
7492 GLOBAL_STATE_CODE();
7493
5d69b5ab
HR
7494 if (!bs || !bs->drv) {
7495 return false;
7496 }
7497
7498 if (bs == to_replace) {
7499 return true;
7500 }
7501
7502 /* See what the driver can do */
7503 if (bs->drv->bdrv_recurse_can_replace) {
7504 return bs->drv->bdrv_recurse_can_replace(bs, to_replace);
7505 }
7506
7507 /* For filters without an own implementation, we can recurse on our own */
93393e69
HR
7508 filtered = bdrv_filter_bs(bs);
7509 if (filtered) {
7510 return bdrv_recurse_can_replace(filtered, to_replace);
5d69b5ab
HR
7511 }
7512
7513 /* Safe default */
7514 return false;
7515}
7516
810803a8
HR
7517/*
7518 * Check whether the given @node_name can be replaced by a node that
7519 * has the same data as @parent_bs. If so, return @node_name's BDS;
7520 * NULL otherwise.
7521 *
7522 * @node_name must be a (recursive) *child of @parent_bs (or this
7523 * function will return NULL).
7524 *
7525 * The result (whether the node can be replaced or not) is only valid
7526 * for as long as no graph or permission changes occur.
7527 */
e12f3784
WC
7528BlockDriverState *check_to_replace_node(BlockDriverState *parent_bs,
7529 const char *node_name, Error **errp)
09158f00
BC
7530{
7531 BlockDriverState *to_replace_bs = bdrv_find_node(node_name);
5a7e7a0b
SH
7532 AioContext *aio_context;
7533
f791bf7f
EGE
7534 GLOBAL_STATE_CODE();
7535
09158f00 7536 if (!to_replace_bs) {
785ec4b1 7537 error_setg(errp, "Failed to find node with node-name='%s'", node_name);
09158f00
BC
7538 return NULL;
7539 }
7540
5a7e7a0b
SH
7541 aio_context = bdrv_get_aio_context(to_replace_bs);
7542 aio_context_acquire(aio_context);
7543
09158f00 7544 if (bdrv_op_is_blocked(to_replace_bs, BLOCK_OP_TYPE_REPLACE, errp)) {
5a7e7a0b
SH
7545 to_replace_bs = NULL;
7546 goto out;
09158f00
BC
7547 }
7548
7549 /* We don't want arbitrary node of the BDS chain to be replaced only the top
7550 * most non filter in order to prevent data corruption.
7551 * Another benefit is that this tests exclude backing files which are
7552 * blocked by the backing blockers.
7553 */
810803a8
HR
7554 if (!bdrv_recurse_can_replace(parent_bs, to_replace_bs)) {
7555 error_setg(errp, "Cannot replace '%s' by a node mirrored from '%s', "
7556 "because it cannot be guaranteed that doing so would not "
7557 "lead to an abrupt change of visible data",
7558 node_name, parent_bs->node_name);
5a7e7a0b
SH
7559 to_replace_bs = NULL;
7560 goto out;
09158f00
BC
7561 }
7562
5a7e7a0b
SH
7563out:
7564 aio_context_release(aio_context);
09158f00
BC
7565 return to_replace_bs;
7566}
448ad91d 7567
97e2f021
HR
7568/**
7569 * Iterates through the list of runtime option keys that are said to
7570 * be "strong" for a BDS. An option is called "strong" if it changes
7571 * a BDS's data. For example, the null block driver's "size" and
7572 * "read-zeroes" options are strong, but its "latency-ns" option is
7573 * not.
7574 *
7575 * If a key returned by this function ends with a dot, all options
7576 * starting with that prefix are strong.
7577 */
7578static const char *const *strong_options(BlockDriverState *bs,
7579 const char *const *curopt)
7580{
7581 static const char *const global_options[] = {
7582 "driver", "filename", NULL
7583 };
7584
7585 if (!curopt) {
7586 return &global_options[0];
7587 }
7588
7589 curopt++;
7590 if (curopt == &global_options[ARRAY_SIZE(global_options) - 1] && bs->drv) {
7591 curopt = bs->drv->strong_runtime_opts;
7592 }
7593
7594 return (curopt && *curopt) ? curopt : NULL;
7595}
7596
7597/**
7598 * Copies all strong runtime options from bs->options to the given
7599 * QDict. The set of strong option keys is determined by invoking
7600 * strong_options().
7601 *
7602 * Returns true iff any strong option was present in bs->options (and
7603 * thus copied to the target QDict) with the exception of "filename"
7604 * and "driver". The caller is expected to use this value to decide
7605 * whether the existence of strong options prevents the generation of
7606 * a plain filename.
7607 */
7608static bool append_strong_runtime_options(QDict *d, BlockDriverState *bs)
7609{
7610 bool found_any = false;
7611 const char *const *option_name = NULL;
7612
7613 if (!bs->drv) {
7614 return false;
7615 }
7616
7617 while ((option_name = strong_options(bs, option_name))) {
7618 bool option_given = false;
7619
7620 assert(strlen(*option_name) > 0);
7621 if ((*option_name)[strlen(*option_name) - 1] != '.') {
7622 QObject *entry = qdict_get(bs->options, *option_name);
7623 if (!entry) {
7624 continue;
7625 }
7626
7627 qdict_put_obj(d, *option_name, qobject_ref(entry));
7628 option_given = true;
7629 } else {
7630 const QDictEntry *entry;
7631 for (entry = qdict_first(bs->options); entry;
7632 entry = qdict_next(bs->options, entry))
7633 {
7634 if (strstart(qdict_entry_key(entry), *option_name, NULL)) {
7635 qdict_put_obj(d, qdict_entry_key(entry),
7636 qobject_ref(qdict_entry_value(entry)));
7637 option_given = true;
7638 }
7639 }
7640 }
7641
7642 /* While "driver" and "filename" need to be included in a JSON filename,
7643 * their existence does not prohibit generation of a plain filename. */
7644 if (!found_any && option_given &&
7645 strcmp(*option_name, "driver") && strcmp(*option_name, "filename"))
7646 {
7647 found_any = true;
7648 }
7649 }
7650
62a01a27
HR
7651 if (!qdict_haskey(d, "driver")) {
7652 /* Drivers created with bdrv_new_open_driver() may not have a
7653 * @driver option. Add it here. */
7654 qdict_put_str(d, "driver", bs->drv->format_name);
7655 }
7656
97e2f021
HR
7657 return found_any;
7658}
7659
90993623
HR
7660/* Note: This function may return false positives; it may return true
7661 * even if opening the backing file specified by bs's image header
7662 * would result in exactly bs->backing. */
fa8fc1d0 7663static bool bdrv_backing_overridden(BlockDriverState *bs)
90993623 7664{
b4ad82aa 7665 GLOBAL_STATE_CODE();
90993623
HR
7666 if (bs->backing) {
7667 return strcmp(bs->auto_backing_file,
7668 bs->backing->bs->filename);
7669 } else {
7670 /* No backing BDS, so if the image header reports any backing
7671 * file, it must have been suppressed */
7672 return bs->auto_backing_file[0] != '\0';
7673 }
7674}
7675
91af7014
HR
7676/* Updates the following BDS fields:
7677 * - exact_filename: A filename which may be used for opening a block device
7678 * which (mostly) equals the given BDS (even without any
7679 * other options; so reading and writing must return the same
7680 * results, but caching etc. may be different)
7681 * - full_open_options: Options which, when given when opening a block device
7682 * (without a filename), result in a BDS (mostly)
7683 * equalling the given one
7684 * - filename: If exact_filename is set, it is copied here. Otherwise,
7685 * full_open_options is converted to a JSON object, prefixed with
7686 * "json:" (for use through the JSON pseudo protocol) and put here.
7687 */
7688void bdrv_refresh_filename(BlockDriverState *bs)
7689{
7690 BlockDriver *drv = bs->drv;
e24518e3 7691 BdrvChild *child;
52f72d6f 7692 BlockDriverState *primary_child_bs;
91af7014 7693 QDict *opts;
90993623 7694 bool backing_overridden;
998b3a1e
HR
7695 bool generate_json_filename; /* Whether our default implementation should
7696 fill exact_filename (false) or not (true) */
91af7014 7697
f791bf7f
EGE
7698 GLOBAL_STATE_CODE();
7699
91af7014
HR
7700 if (!drv) {
7701 return;
7702 }
7703
e24518e3
HR
7704 /* This BDS's file name may depend on any of its children's file names, so
7705 * refresh those first */
7706 QLIST_FOREACH(child, &bs->children, next) {
7707 bdrv_refresh_filename(child->bs);
91af7014
HR
7708 }
7709
bb808d5f
HR
7710 if (bs->implicit) {
7711 /* For implicit nodes, just copy everything from the single child */
7712 child = QLIST_FIRST(&bs->children);
7713 assert(QLIST_NEXT(child, next) == NULL);
7714
7715 pstrcpy(bs->exact_filename, sizeof(bs->exact_filename),
7716 child->bs->exact_filename);
7717 pstrcpy(bs->filename, sizeof(bs->filename), child->bs->filename);
7718
cb895614 7719 qobject_unref(bs->full_open_options);
bb808d5f
HR
7720 bs->full_open_options = qobject_ref(child->bs->full_open_options);
7721
7722 return;
7723 }
7724
90993623
HR
7725 backing_overridden = bdrv_backing_overridden(bs);
7726
7727 if (bs->open_flags & BDRV_O_NO_IO) {
7728 /* Without I/O, the backing file does not change anything.
7729 * Therefore, in such a case (primarily qemu-img), we can
7730 * pretend the backing file has not been overridden even if
7731 * it technically has been. */
7732 backing_overridden = false;
7733 }
7734
97e2f021
HR
7735 /* Gather the options QDict */
7736 opts = qdict_new();
998b3a1e
HR
7737 generate_json_filename = append_strong_runtime_options(opts, bs);
7738 generate_json_filename |= backing_overridden;
97e2f021
HR
7739
7740 if (drv->bdrv_gather_child_options) {
7741 /* Some block drivers may not want to present all of their children's
7742 * options, or name them differently from BdrvChild.name */
7743 drv->bdrv_gather_child_options(bs, opts, backing_overridden);
7744 } else {
7745 QLIST_FOREACH(child, &bs->children, next) {
25191e5f 7746 if (child == bs->backing && !backing_overridden) {
97e2f021
HR
7747 /* We can skip the backing BDS if it has not been overridden */
7748 continue;
7749 }
7750
7751 qdict_put(opts, child->name,
7752 qobject_ref(child->bs->full_open_options));
7753 }
7754
7755 if (backing_overridden && !bs->backing) {
7756 /* Force no backing file */
7757 qdict_put_null(opts, "backing");
7758 }
7759 }
7760
7761 qobject_unref(bs->full_open_options);
7762 bs->full_open_options = opts;
7763
52f72d6f
HR
7764 primary_child_bs = bdrv_primary_bs(bs);
7765
998b3a1e
HR
7766 if (drv->bdrv_refresh_filename) {
7767 /* Obsolete information is of no use here, so drop the old file name
7768 * information before refreshing it */
7769 bs->exact_filename[0] = '\0';
7770
7771 drv->bdrv_refresh_filename(bs);
52f72d6f
HR
7772 } else if (primary_child_bs) {
7773 /*
7774 * Try to reconstruct valid information from the underlying
7775 * file -- this only works for format nodes (filter nodes
7776 * cannot be probed and as such must be selected by the user
7777 * either through an options dict, or through a special
7778 * filename which the filter driver must construct in its
7779 * .bdrv_refresh_filename() implementation).
7780 */
998b3a1e
HR
7781
7782 bs->exact_filename[0] = '\0';
7783
fb695c74
HR
7784 /*
7785 * We can use the underlying file's filename if:
7786 * - it has a filename,
52f72d6f 7787 * - the current BDS is not a filter,
fb695c74
HR
7788 * - the file is a protocol BDS, and
7789 * - opening that file (as this BDS's format) will automatically create
7790 * the BDS tree we have right now, that is:
7791 * - the user did not significantly change this BDS's behavior with
7792 * some explicit (strong) options
7793 * - no non-file child of this BDS has been overridden by the user
7794 * Both of these conditions are represented by generate_json_filename.
7795 */
52f72d6f
HR
7796 if (primary_child_bs->exact_filename[0] &&
7797 primary_child_bs->drv->bdrv_file_open &&
7798 !drv->is_filter && !generate_json_filename)
fb695c74 7799 {
52f72d6f 7800 strcpy(bs->exact_filename, primary_child_bs->exact_filename);
998b3a1e
HR
7801 }
7802 }
7803
91af7014
HR
7804 if (bs->exact_filename[0]) {
7805 pstrcpy(bs->filename, sizeof(bs->filename), bs->exact_filename);
97e2f021 7806 } else {
eab3a467 7807 GString *json = qobject_to_json(QOBJECT(bs->full_open_options));
5c86bdf1 7808 if (snprintf(bs->filename, sizeof(bs->filename), "json:%s",
eab3a467 7809 json->str) >= sizeof(bs->filename)) {
5c86bdf1
EB
7810 /* Give user a hint if we truncated things. */
7811 strcpy(bs->filename + sizeof(bs->filename) - 4, "...");
7812 }
eab3a467 7813 g_string_free(json, true);
91af7014
HR
7814 }
7815}
e06018ad 7816
1e89d0f9
HR
7817char *bdrv_dirname(BlockDriverState *bs, Error **errp)
7818{
7819 BlockDriver *drv = bs->drv;
52f72d6f 7820 BlockDriverState *child_bs;
1e89d0f9 7821
f791bf7f
EGE
7822 GLOBAL_STATE_CODE();
7823
1e89d0f9
HR
7824 if (!drv) {
7825 error_setg(errp, "Node '%s' is ejected", bs->node_name);
7826 return NULL;
7827 }
7828
7829 if (drv->bdrv_dirname) {
7830 return drv->bdrv_dirname(bs, errp);
7831 }
7832
52f72d6f
HR
7833 child_bs = bdrv_primary_bs(bs);
7834 if (child_bs) {
7835 return bdrv_dirname(child_bs, errp);
1e89d0f9
HR
7836 }
7837
7838 bdrv_refresh_filename(bs);
7839 if (bs->exact_filename[0] != '\0') {
7840 return path_combine(bs->exact_filename, "");
7841 }
7842
7843 error_setg(errp, "Cannot generate a base directory for %s nodes",
7844 drv->format_name);
7845 return NULL;
7846}
7847
e06018ad
WC
7848/*
7849 * Hot add/remove a BDS's child. So the user can take a child offline when
7850 * it is broken and take a new child online
7851 */
7852void bdrv_add_child(BlockDriverState *parent_bs, BlockDriverState *child_bs,
7853 Error **errp)
7854{
f791bf7f 7855 GLOBAL_STATE_CODE();
e06018ad
WC
7856 if (!parent_bs->drv || !parent_bs->drv->bdrv_add_child) {
7857 error_setg(errp, "The node %s does not support adding a child",
7858 bdrv_get_device_or_node_name(parent_bs));
7859 return;
7860 }
7861
7862 if (!QLIST_EMPTY(&child_bs->parents)) {
7863 error_setg(errp, "The node %s already has a parent",
7864 child_bs->node_name);
7865 return;
7866 }
7867
7868 parent_bs->drv->bdrv_add_child(parent_bs, child_bs, errp);
7869}
7870
7871void bdrv_del_child(BlockDriverState *parent_bs, BdrvChild *child, Error **errp)
7872{
7873 BdrvChild *tmp;
7874
f791bf7f 7875 GLOBAL_STATE_CODE();
e06018ad
WC
7876 if (!parent_bs->drv || !parent_bs->drv->bdrv_del_child) {
7877 error_setg(errp, "The node %s does not support removing a child",
7878 bdrv_get_device_or_node_name(parent_bs));
7879 return;
7880 }
7881
7882 QLIST_FOREACH(tmp, &parent_bs->children, next) {
7883 if (tmp == child) {
7884 break;
7885 }
7886 }
7887
7888 if (!tmp) {
7889 error_setg(errp, "The node %s does not have a child named %s",
7890 bdrv_get_device_or_node_name(parent_bs),
7891 bdrv_get_device_or_node_name(child->bs));
7892 return;
7893 }
7894
7895 parent_bs->drv->bdrv_del_child(parent_bs, child, errp);
7896}
6f7a3b53
HR
7897
7898int bdrv_make_empty(BdrvChild *c, Error **errp)
7899{
7900 BlockDriver *drv = c->bs->drv;
7901 int ret;
7902
f791bf7f 7903 GLOBAL_STATE_CODE();
6f7a3b53
HR
7904 assert(c->perm & (BLK_PERM_WRITE | BLK_PERM_WRITE_UNCHANGED));
7905
7906 if (!drv->bdrv_make_empty) {
7907 error_setg(errp, "%s does not support emptying nodes",
7908 drv->format_name);
7909 return -ENOTSUP;
7910 }
7911
7912 ret = drv->bdrv_make_empty(c->bs);
7913 if (ret < 0) {
7914 error_setg_errno(errp, -ret, "Failed to empty %s",
7915 c->bs->filename);
7916 return ret;
7917 }
7918
7919 return 0;
7920}
9a6fc887
HR
7921
7922/*
7923 * Return the child that @bs acts as an overlay for, and from which data may be
7924 * copied in COW or COR operations. Usually this is the backing file.
7925 */
7926BdrvChild *bdrv_cow_child(BlockDriverState *bs)
7927{
967d7905
EGE
7928 IO_CODE();
7929
9a6fc887
HR
7930 if (!bs || !bs->drv) {
7931 return NULL;
7932 }
7933
7934 if (bs->drv->is_filter) {
7935 return NULL;
7936 }
7937
7938 if (!bs->backing) {
7939 return NULL;
7940 }
7941
7942 assert(bs->backing->role & BDRV_CHILD_COW);
7943 return bs->backing;
7944}
7945
7946/*
7947 * If @bs acts as a filter for exactly one of its children, return
7948 * that child.
7949 */
7950BdrvChild *bdrv_filter_child(BlockDriverState *bs)
7951{
7952 BdrvChild *c;
967d7905 7953 IO_CODE();
9a6fc887
HR
7954
7955 if (!bs || !bs->drv) {
7956 return NULL;
7957 }
7958
7959 if (!bs->drv->is_filter) {
7960 return NULL;
7961 }
7962
7963 /* Only one of @backing or @file may be used */
7964 assert(!(bs->backing && bs->file));
7965
7966 c = bs->backing ?: bs->file;
7967 if (!c) {
7968 return NULL;
7969 }
7970
7971 assert(c->role & BDRV_CHILD_FILTERED);
7972 return c;
7973}
7974
7975/*
7976 * Return either the result of bdrv_cow_child() or bdrv_filter_child(),
7977 * whichever is non-NULL.
7978 *
7979 * Return NULL if both are NULL.
7980 */
7981BdrvChild *bdrv_filter_or_cow_child(BlockDriverState *bs)
7982{
7983 BdrvChild *cow_child = bdrv_cow_child(bs);
7984 BdrvChild *filter_child = bdrv_filter_child(bs);
967d7905 7985 IO_CODE();
9a6fc887
HR
7986
7987 /* Filter nodes cannot have COW backing files */
7988 assert(!(cow_child && filter_child));
7989
7990 return cow_child ?: filter_child;
7991}
7992
7993/*
7994 * Return the primary child of this node: For filters, that is the
7995 * filtered child. For other nodes, that is usually the child storing
7996 * metadata.
7997 * (A generally more helpful description is that this is (usually) the
7998 * child that has the same filename as @bs.)
7999 *
8000 * Drivers do not necessarily have a primary child; for example quorum
8001 * does not.
8002 */
8003BdrvChild *bdrv_primary_child(BlockDriverState *bs)
8004{
8005 BdrvChild *c, *found = NULL;
967d7905 8006 IO_CODE();
9a6fc887
HR
8007
8008 QLIST_FOREACH(c, &bs->children, next) {
8009 if (c->role & BDRV_CHILD_PRIMARY) {
8010 assert(!found);
8011 found = c;
8012 }
8013 }
8014
8015 return found;
8016}
d38d7eb8
HR
8017
8018static BlockDriverState *bdrv_do_skip_filters(BlockDriverState *bs,
8019 bool stop_on_explicit_filter)
8020{
8021 BdrvChild *c;
8022
8023 if (!bs) {
8024 return NULL;
8025 }
8026
8027 while (!(stop_on_explicit_filter && !bs->implicit)) {
8028 c = bdrv_filter_child(bs);
8029 if (!c) {
8030 /*
8031 * A filter that is embedded in a working block graph must
8032 * have a child. Assert this here so this function does
8033 * not return a filter node that is not expected by the
8034 * caller.
8035 */
8036 assert(!bs->drv || !bs->drv->is_filter);
8037 break;
8038 }
8039 bs = c->bs;
8040 }
8041 /*
8042 * Note that this treats nodes with bs->drv == NULL as not being
8043 * filters (bs->drv == NULL should be replaced by something else
8044 * anyway).
8045 * The advantage of this behavior is that this function will thus
8046 * always return a non-NULL value (given a non-NULL @bs).
8047 */
8048
8049 return bs;
8050}
8051
8052/*
8053 * Return the first BDS that has not been added implicitly or that
8054 * does not have a filtered child down the chain starting from @bs
8055 * (including @bs itself).
8056 */
8057BlockDriverState *bdrv_skip_implicit_filters(BlockDriverState *bs)
8058{
b4ad82aa 8059 GLOBAL_STATE_CODE();
d38d7eb8
HR
8060 return bdrv_do_skip_filters(bs, true);
8061}
8062
8063/*
8064 * Return the first BDS that does not have a filtered child down the
8065 * chain starting from @bs (including @bs itself).
8066 */
8067BlockDriverState *bdrv_skip_filters(BlockDriverState *bs)
8068{
967d7905 8069 IO_CODE();
d38d7eb8
HR
8070 return bdrv_do_skip_filters(bs, false);
8071}
8072
8073/*
8074 * For a backing chain, return the first non-filter backing image of
8075 * the first non-filter image.
8076 */
8077BlockDriverState *bdrv_backing_chain_next(BlockDriverState *bs)
8078{
967d7905 8079 IO_CODE();
d38d7eb8
HR
8080 return bdrv_skip_filters(bdrv_cow_bs(bdrv_skip_filters(bs)));
8081}
0bc329fb
HR
8082
8083/**
8084 * Check whether [offset, offset + bytes) overlaps with the cached
8085 * block-status data region.
8086 *
8087 * If so, and @pnum is not NULL, set *pnum to `bsc.data_end - offset`,
8088 * which is what bdrv_bsc_is_data()'s interface needs.
8089 * Otherwise, *pnum is not touched.
8090 */
8091static bool bdrv_bsc_range_overlaps_locked(BlockDriverState *bs,
8092 int64_t offset, int64_t bytes,
8093 int64_t *pnum)
8094{
8095 BdrvBlockStatusCache *bsc = qatomic_rcu_read(&bs->block_status_cache);
8096 bool overlaps;
8097
8098 overlaps =
8099 qatomic_read(&bsc->valid) &&
8100 ranges_overlap(offset, bytes, bsc->data_start,
8101 bsc->data_end - bsc->data_start);
8102
8103 if (overlaps && pnum) {
8104 *pnum = bsc->data_end - offset;
8105 }
8106
8107 return overlaps;
8108}
8109
8110/**
8111 * See block_int.h for this function's documentation.
8112 */
8113bool bdrv_bsc_is_data(BlockDriverState *bs, int64_t offset, int64_t *pnum)
8114{
967d7905 8115 IO_CODE();
0bc329fb 8116 RCU_READ_LOCK_GUARD();
0bc329fb
HR
8117 return bdrv_bsc_range_overlaps_locked(bs, offset, 1, pnum);
8118}
8119
8120/**
8121 * See block_int.h for this function's documentation.
8122 */
8123void bdrv_bsc_invalidate_range(BlockDriverState *bs,
8124 int64_t offset, int64_t bytes)
8125{
967d7905 8126 IO_CODE();
0bc329fb
HR
8127 RCU_READ_LOCK_GUARD();
8128
8129 if (bdrv_bsc_range_overlaps_locked(bs, offset, bytes, NULL)) {
8130 qatomic_set(&bs->block_status_cache->valid, false);
8131 }
8132}
8133
8134/**
8135 * See block_int.h for this function's documentation.
8136 */
8137void bdrv_bsc_fill(BlockDriverState *bs, int64_t offset, int64_t bytes)
8138{
8139 BdrvBlockStatusCache *new_bsc = g_new(BdrvBlockStatusCache, 1);
8140 BdrvBlockStatusCache *old_bsc;
967d7905 8141 IO_CODE();
0bc329fb
HR
8142
8143 *new_bsc = (BdrvBlockStatusCache) {
8144 .valid = true,
8145 .data_start = offset,
8146 .data_end = offset + bytes,
8147 };
8148
8149 QEMU_LOCK_GUARD(&bs->bsc_modify_lock);
8150
8151 old_bsc = qatomic_rcu_read(&bs->block_status_cache);
8152 qatomic_rcu_set(&bs->block_status_cache, new_bsc);
8153 if (old_bsc) {
8154 g_free_rcu(old_bsc, rcu);
8155 }
8156}
This page took 2.940826 seconds and 4 git commands to generate.