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