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