]> git.ipfire.org Git - thirdparty/qemu.git/blame - block.c
quorum: Implement .bdrv_recurse_can_replace()
[thirdparty/qemu.git] / block.c
CommitLineData
fc01f7e7
FB
1/*
2 * QEMU System Emulator block driver
5fafdf24 3 *
fc01f7e7 4 * Copyright (c) 2003 Fabrice Bellard
5fafdf24 5 *
fc01f7e7
FB
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
12 *
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
15 *
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22 * THE SOFTWARE.
23 */
e688df6b 24
d38ea87a 25#include "qemu/osdep.h"
0ab8ed18 26#include "block/trace.h"
737e150e
PB
27#include "block/block_int.h"
28#include "block/blockjob.h"
cd7fca95 29#include "block/nbd.h"
609f45ea 30#include "block/qdict.h"
d49b6836 31#include "qemu/error-report.h"
88d88798 32#include "module_block.h"
db725815 33#include "qemu/main-loop.h"
1de7afc9 34#include "qemu/module.h"
e688df6b 35#include "qapi/error.h"
452fcdbc 36#include "qapi/qmp/qdict.h"
7b1b5d19 37#include "qapi/qmp/qjson.h"
e59a0cf1 38#include "qapi/qmp/qnull.h"
fc81fa1e 39#include "qapi/qmp/qstring.h"
e1d74bc6
KW
40#include "qapi/qobject-output-visitor.h"
41#include "qapi/qapi-visit-block-core.h"
bfb197e0 42#include "sysemu/block-backend.h"
9c17d615 43#include "sysemu/sysemu.h"
1de7afc9 44#include "qemu/notify.h"
922a01a0 45#include "qemu/option.h"
10817bf0 46#include "qemu/coroutine.h"
c13163fb 47#include "block/qapi.h"
1de7afc9 48#include "qemu/timer.h"
f348b6d1
VB
49#include "qemu/cutils.h"
50#include "qemu/id.h"
fc01f7e7 51
71e72a19 52#ifdef CONFIG_BSD
7674e7bf 53#include <sys/ioctl.h>
72cf2d4f 54#include <sys/queue.h>
c5e97233 55#ifndef __DragonFly__
7674e7bf
FB
56#include <sys/disk.h>
57#endif
c5e97233 58#endif
7674e7bf 59
49dc768d
AL
60#ifdef _WIN32
61#include <windows.h>
62#endif
63
1c9805a3
SH
64#define NOT_DONE 0x7fffffff /* used while emulated sync operation in progress */
65
dc364f4c
BC
66static QTAILQ_HEAD(, BlockDriverState) graph_bdrv_states =
67 QTAILQ_HEAD_INITIALIZER(graph_bdrv_states);
68
2c1d04e0
HR
69static QTAILQ_HEAD(, BlockDriverState) all_bdrv_states =
70 QTAILQ_HEAD_INITIALIZER(all_bdrv_states);
71
8a22f02a
SH
72static QLIST_HEAD(, BlockDriver) bdrv_drivers =
73 QLIST_HEAD_INITIALIZER(bdrv_drivers);
ea2384d3 74
5b363937
HR
75static BlockDriverState *bdrv_open_inherit(const char *filename,
76 const char *reference,
77 QDict *options, int flags,
78 BlockDriverState *parent,
79 const BdrvChildRole *child_role,
80 Error **errp);
f3930ed0 81
eb852011
MA
82/* If non-zero, use only whitelisted block drivers */
83static int use_bdrv_whitelist;
84
9e0b22f4
SH
85#ifdef _WIN32
86static int is_windows_drive_prefix(const char *filename)
87{
88 return (((filename[0] >= 'a' && filename[0] <= 'z') ||
89 (filename[0] >= 'A' && filename[0] <= 'Z')) &&
90 filename[1] == ':');
91}
92
93int is_windows_drive(const char *filename)
94{
95 if (is_windows_drive_prefix(filename) &&
96 filename[2] == '\0')
97 return 1;
98 if (strstart(filename, "\\\\.\\", NULL) ||
99 strstart(filename, "//./", NULL))
100 return 1;
101 return 0;
102}
103#endif
104
339064d5
KW
105size_t bdrv_opt_mem_align(BlockDriverState *bs)
106{
107 if (!bs || !bs->drv) {
459b4e66 108 /* page size or 4k (hdd sector size) should be on the safe side */
038adc2f 109 return MAX(4096, qemu_real_host_page_size);
339064d5
KW
110 }
111
112 return bs->bl.opt_mem_alignment;
113}
114
4196d2f0
DL
115size_t bdrv_min_mem_align(BlockDriverState *bs)
116{
117 if (!bs || !bs->drv) {
459b4e66 118 /* page size or 4k (hdd sector size) should be on the safe side */
038adc2f 119 return MAX(4096, qemu_real_host_page_size);
4196d2f0
DL
120 }
121
122 return bs->bl.min_mem_alignment;
123}
124
9e0b22f4 125/* check if the path starts with "<protocol>:" */
5c98415b 126int path_has_protocol(const char *path)
9e0b22f4 127{
947995c0
PB
128 const char *p;
129
9e0b22f4
SH
130#ifdef _WIN32
131 if (is_windows_drive(path) ||
132 is_windows_drive_prefix(path)) {
133 return 0;
134 }
947995c0
PB
135 p = path + strcspn(path, ":/\\");
136#else
137 p = path + strcspn(path, ":/");
9e0b22f4
SH
138#endif
139
947995c0 140 return *p == ':';
9e0b22f4
SH
141}
142
83f64091 143int path_is_absolute(const char *path)
3b0d4f61 144{
21664424
FB
145#ifdef _WIN32
146 /* specific case for names like: "\\.\d:" */
f53f4da9 147 if (is_windows_drive(path) || is_windows_drive_prefix(path)) {
21664424 148 return 1;
f53f4da9
PB
149 }
150 return (*path == '/' || *path == '\\');
3b9f94e1 151#else
f53f4da9 152 return (*path == '/');
3b9f94e1 153#endif
3b0d4f61
FB
154}
155
009b03aa 156/* if filename is absolute, just return its duplicate. Otherwise, build a
83f64091
FB
157 path to it by considering it is relative to base_path. URL are
158 supported. */
009b03aa 159char *path_combine(const char *base_path, const char *filename)
3b0d4f61 160{
009b03aa 161 const char *protocol_stripped = NULL;
83f64091 162 const char *p, *p1;
009b03aa 163 char *result;
83f64091
FB
164 int len;
165
83f64091 166 if (path_is_absolute(filename)) {
009b03aa
HR
167 return g_strdup(filename);
168 }
0d54a6fe 169
009b03aa
HR
170 if (path_has_protocol(base_path)) {
171 protocol_stripped = strchr(base_path, ':');
172 if (protocol_stripped) {
173 protocol_stripped++;
0d54a6fe 174 }
009b03aa
HR
175 }
176 p = protocol_stripped ?: base_path;
0d54a6fe 177
009b03aa 178 p1 = strrchr(base_path, '/');
3b9f94e1 179#ifdef _WIN32
009b03aa
HR
180 {
181 const char *p2;
182 p2 = strrchr(base_path, '\\');
183 if (!p1 || p2 > p1) {
184 p1 = p2;
3b9f94e1 185 }
009b03aa 186 }
3b9f94e1 187#endif
009b03aa
HR
188 if (p1) {
189 p1++;
190 } else {
191 p1 = base_path;
192 }
193 if (p1 > p) {
194 p = p1;
3b0d4f61 195 }
009b03aa
HR
196 len = p - base_path;
197
198 result = g_malloc(len + strlen(filename) + 1);
199 memcpy(result, base_path, len);
200 strcpy(result + len, filename);
201
202 return result;
203}
204
03c320d8
HR
205/*
206 * Helper function for bdrv_parse_filename() implementations to remove optional
207 * protocol prefixes (especially "file:") from a filename and for putting the
208 * stripped filename into the options QDict if there is such a prefix.
209 */
210void bdrv_parse_filename_strip_prefix(const char *filename, const char *prefix,
211 QDict *options)
212{
213 if (strstart(filename, prefix, &filename)) {
214 /* Stripping the explicit protocol prefix may result in a protocol
215 * prefix being (wrongly) detected (if the filename contains a colon) */
216 if (path_has_protocol(filename)) {
217 QString *fat_filename;
218
219 /* This means there is some colon before the first slash; therefore,
220 * this cannot be an absolute path */
221 assert(!path_is_absolute(filename));
222
223 /* And we can thus fix the protocol detection issue by prefixing it
224 * by "./" */
225 fat_filename = qstring_from_str("./");
226 qstring_append(fat_filename, filename);
227
228 assert(!path_has_protocol(qstring_get_str(fat_filename)));
229
230 qdict_put(options, "filename", fat_filename);
231 } else {
232 /* If no protocol prefix was detected, we can use the shortened
233 * filename as-is */
234 qdict_put_str(options, "filename", filename);
235 }
236 }
237}
238
239
9c5e6594
KW
240/* Returns whether the image file is opened as read-only. Note that this can
241 * return false and writing to the image file is still not possible because the
242 * image is inactivated. */
93ed524e
JC
243bool bdrv_is_read_only(BlockDriverState *bs)
244{
245 return bs->read_only;
246}
247
54a32bfe
KW
248int bdrv_can_set_read_only(BlockDriverState *bs, bool read_only,
249 bool ignore_allow_rdw, Error **errp)
fe5241bf 250{
e2b8247a
JC
251 /* Do not set read_only if copy_on_read is enabled */
252 if (bs->copy_on_read && read_only) {
253 error_setg(errp, "Can't set node '%s' to r/o with copy-on-read enabled",
254 bdrv_get_device_or_node_name(bs));
255 return -EINVAL;
256 }
257
d6fcdf06 258 /* Do not clear read_only if it is prohibited */
54a32bfe
KW
259 if (!read_only && !(bs->open_flags & BDRV_O_ALLOW_RDWR) &&
260 !ignore_allow_rdw)
261 {
d6fcdf06
JC
262 error_setg(errp, "Node '%s' is read only",
263 bdrv_get_device_or_node_name(bs));
264 return -EPERM;
265 }
266
45803a03
JC
267 return 0;
268}
269
eaa2410f
KW
270/*
271 * Called by a driver that can only provide a read-only image.
272 *
273 * Returns 0 if the node is already read-only or it could switch the node to
274 * read-only because BDRV_O_AUTO_RDONLY is set.
275 *
276 * Returns -EACCES if the node is read-write and BDRV_O_AUTO_RDONLY is not set
277 * or bdrv_can_set_read_only() forbids making the node read-only. If @errmsg
278 * is not NULL, it is used as the error message for the Error object.
279 */
280int bdrv_apply_auto_read_only(BlockDriverState *bs, const char *errmsg,
281 Error **errp)
45803a03
JC
282{
283 int ret = 0;
284
eaa2410f
KW
285 if (!(bs->open_flags & BDRV_O_RDWR)) {
286 return 0;
287 }
288 if (!(bs->open_flags & BDRV_O_AUTO_RDONLY)) {
289 goto fail;
45803a03
JC
290 }
291
eaa2410f
KW
292 ret = bdrv_can_set_read_only(bs, true, false, NULL);
293 if (ret < 0) {
294 goto fail;
eeae6a59
KW
295 }
296
eaa2410f
KW
297 bs->read_only = true;
298 bs->open_flags &= ~BDRV_O_RDWR;
299
e2b8247a 300 return 0;
eaa2410f
KW
301
302fail:
303 error_setg(errp, "%s", errmsg ?: "Image is read-only");
304 return -EACCES;
fe5241bf
JC
305}
306
645ae7d8
HR
307/*
308 * If @backing is empty, this function returns NULL without setting
309 * @errp. In all other cases, NULL will only be returned with @errp
310 * set.
311 *
312 * Therefore, a return value of NULL without @errp set means that
313 * there is no backing file; if @errp is set, there is one but its
314 * absolute filename cannot be generated.
315 */
316char *bdrv_get_full_backing_filename_from_filename(const char *backed,
317 const char *backing,
318 Error **errp)
dc5a1371 319{
645ae7d8
HR
320 if (backing[0] == '\0') {
321 return NULL;
322 } else if (path_has_protocol(backing) || path_is_absolute(backing)) {
323 return g_strdup(backing);
9f07429e
HR
324 } else if (backed[0] == '\0' || strstart(backed, "json:", NULL)) {
325 error_setg(errp, "Cannot use relative backing file names for '%s'",
326 backed);
645ae7d8 327 return NULL;
dc5a1371 328 } else {
645ae7d8 329 return path_combine(backed, backing);
dc5a1371
PB
330 }
331}
332
9f4793d8
HR
333/*
334 * If @filename is empty or NULL, this function returns NULL without
335 * setting @errp. In all other cases, NULL will only be returned with
336 * @errp set.
337 */
338static char *bdrv_make_absolute_filename(BlockDriverState *relative_to,
339 const char *filename, Error **errp)
0a82855a 340{
8df68616 341 char *dir, *full_name;
9f4793d8 342
8df68616
HR
343 if (!filename || filename[0] == '\0') {
344 return NULL;
345 } else if (path_has_protocol(filename) || path_is_absolute(filename)) {
346 return g_strdup(filename);
347 }
9f07429e 348
8df68616
HR
349 dir = bdrv_dirname(relative_to, errp);
350 if (!dir) {
351 return NULL;
352 }
f30c66ba 353
8df68616
HR
354 full_name = g_strconcat(dir, filename, NULL);
355 g_free(dir);
356 return full_name;
9f4793d8
HR
357}
358
359char *bdrv_get_full_backing_filename(BlockDriverState *bs, Error **errp)
360{
361 return bdrv_make_absolute_filename(bs, bs->backing_file, errp);
0a82855a
HR
362}
363
0eb7217e
SH
364void bdrv_register(BlockDriver *bdrv)
365{
8a22f02a 366 QLIST_INSERT_HEAD(&bdrv_drivers, bdrv, list);
ea2384d3 367}
b338082b 368
e4e9986b
MA
369BlockDriverState *bdrv_new(void)
370{
371 BlockDriverState *bs;
372 int i;
373
5839e53b 374 bs = g_new0(BlockDriverState, 1);
e4654d2d 375 QLIST_INIT(&bs->dirty_bitmaps);
fbe40ff7
FZ
376 for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
377 QLIST_INIT(&bs->op_blockers[i]);
378 }
d616b224 379 notifier_with_return_list_init(&bs->before_write_notifiers);
3783fa3d 380 qemu_co_mutex_init(&bs->reqs_lock);
2119882c 381 qemu_mutex_init(&bs->dirty_bitmap_mutex);
9fcb0251 382 bs->refcnt = 1;
dcd04228 383 bs->aio_context = qemu_get_aio_context();
d7d512f6 384
3ff2f67a
EY
385 qemu_co_queue_init(&bs->flush_queue);
386
0f12264e
KW
387 for (i = 0; i < bdrv_drain_all_count; i++) {
388 bdrv_drained_begin(bs);
389 }
390
2c1d04e0
HR
391 QTAILQ_INSERT_TAIL(&all_bdrv_states, bs, bs_list);
392
b338082b
FB
393 return bs;
394}
395
88d88798 396static BlockDriver *bdrv_do_find_format(const char *format_name)
ea2384d3
FB
397{
398 BlockDriver *drv1;
88d88798 399
8a22f02a
SH
400 QLIST_FOREACH(drv1, &bdrv_drivers, list) {
401 if (!strcmp(drv1->format_name, format_name)) {
ea2384d3 402 return drv1;
8a22f02a 403 }
ea2384d3 404 }
88d88798 405
ea2384d3
FB
406 return NULL;
407}
408
88d88798
MM
409BlockDriver *bdrv_find_format(const char *format_name)
410{
411 BlockDriver *drv1;
412 int i;
413
414 drv1 = bdrv_do_find_format(format_name);
415 if (drv1) {
416 return drv1;
417 }
418
419 /* The driver isn't registered, maybe we need to load a module */
420 for (i = 0; i < (int)ARRAY_SIZE(block_driver_modules); ++i) {
421 if (!strcmp(block_driver_modules[i].format_name, format_name)) {
422 block_module_load_one(block_driver_modules[i].library_name);
423 break;
424 }
425 }
426
427 return bdrv_do_find_format(format_name);
428}
429
9ac404c5 430static int bdrv_format_is_whitelisted(const char *format_name, bool read_only)
eb852011 431{
b64ec4e4
FZ
432 static const char *whitelist_rw[] = {
433 CONFIG_BDRV_RW_WHITELIST
434 };
435 static const char *whitelist_ro[] = {
436 CONFIG_BDRV_RO_WHITELIST
eb852011
MA
437 };
438 const char **p;
439
b64ec4e4 440 if (!whitelist_rw[0] && !whitelist_ro[0]) {
eb852011 441 return 1; /* no whitelist, anything goes */
b64ec4e4 442 }
eb852011 443
b64ec4e4 444 for (p = whitelist_rw; *p; p++) {
9ac404c5 445 if (!strcmp(format_name, *p)) {
eb852011
MA
446 return 1;
447 }
448 }
b64ec4e4
FZ
449 if (read_only) {
450 for (p = whitelist_ro; *p; p++) {
9ac404c5 451 if (!strcmp(format_name, *p)) {
b64ec4e4
FZ
452 return 1;
453 }
454 }
455 }
eb852011
MA
456 return 0;
457}
458
9ac404c5
AS
459int bdrv_is_whitelisted(BlockDriver *drv, bool read_only)
460{
461 return bdrv_format_is_whitelisted(drv->format_name, read_only);
462}
463
e6ff69bf
DB
464bool bdrv_uses_whitelist(void)
465{
466 return use_bdrv_whitelist;
467}
468
5b7e1542
ZYW
469typedef struct CreateCo {
470 BlockDriver *drv;
471 char *filename;
83d0521a 472 QemuOpts *opts;
5b7e1542 473 int ret;
cc84d90f 474 Error *err;
5b7e1542
ZYW
475} CreateCo;
476
477static void coroutine_fn bdrv_create_co_entry(void *opaque)
478{
cc84d90f
HR
479 Error *local_err = NULL;
480 int ret;
481
5b7e1542
ZYW
482 CreateCo *cco = opaque;
483 assert(cco->drv);
484
efc75e2a 485 ret = cco->drv->bdrv_co_create_opts(cco->filename, cco->opts, &local_err);
621ff94d 486 error_propagate(&cco->err, local_err);
cc84d90f 487 cco->ret = ret;
5b7e1542
ZYW
488}
489
0e7e1989 490int bdrv_create(BlockDriver *drv, const char* filename,
83d0521a 491 QemuOpts *opts, Error **errp)
ea2384d3 492{
5b7e1542
ZYW
493 int ret;
494
495 Coroutine *co;
496 CreateCo cco = {
497 .drv = drv,
498 .filename = g_strdup(filename),
83d0521a 499 .opts = opts,
5b7e1542 500 .ret = NOT_DONE,
cc84d90f 501 .err = NULL,
5b7e1542
ZYW
502 };
503
efc75e2a 504 if (!drv->bdrv_co_create_opts) {
cc84d90f 505 error_setg(errp, "Driver '%s' does not support image creation", drv->format_name);
80168bff
LC
506 ret = -ENOTSUP;
507 goto out;
5b7e1542
ZYW
508 }
509
510 if (qemu_in_coroutine()) {
511 /* Fast-path if already in coroutine context */
512 bdrv_create_co_entry(&cco);
513 } else {
0b8b8753
PB
514 co = qemu_coroutine_create(bdrv_create_co_entry, &cco);
515 qemu_coroutine_enter(co);
5b7e1542 516 while (cco.ret == NOT_DONE) {
b47ec2c4 517 aio_poll(qemu_get_aio_context(), true);
5b7e1542
ZYW
518 }
519 }
520
521 ret = cco.ret;
cc84d90f 522 if (ret < 0) {
84d18f06 523 if (cco.err) {
cc84d90f
HR
524 error_propagate(errp, cco.err);
525 } else {
526 error_setg_errno(errp, -ret, "Could not create image");
527 }
528 }
0e7e1989 529
80168bff
LC
530out:
531 g_free(cco.filename);
5b7e1542 532 return ret;
ea2384d3
FB
533}
534
c282e1fd 535int bdrv_create_file(const char *filename, QemuOpts *opts, Error **errp)
84a12e66
CH
536{
537 BlockDriver *drv;
cc84d90f
HR
538 Error *local_err = NULL;
539 int ret;
84a12e66 540
b65a5e12 541 drv = bdrv_find_protocol(filename, true, errp);
84a12e66 542 if (drv == NULL) {
16905d71 543 return -ENOENT;
84a12e66
CH
544 }
545
c282e1fd 546 ret = bdrv_create(drv, filename, opts, &local_err);
621ff94d 547 error_propagate(errp, local_err);
cc84d90f 548 return ret;
84a12e66
CH
549}
550
892b7de8
ET
551/**
552 * Try to get @bs's logical and physical block size.
553 * On success, store them in @bsz struct and return 0.
554 * On failure return -errno.
555 * @bs must not be empty.
556 */
557int bdrv_probe_blocksizes(BlockDriverState *bs, BlockSizes *bsz)
558{
559 BlockDriver *drv = bs->drv;
560
561 if (drv && drv->bdrv_probe_blocksizes) {
562 return drv->bdrv_probe_blocksizes(bs, bsz);
5a612c00
MP
563 } else if (drv && drv->is_filter && bs->file) {
564 return bdrv_probe_blocksizes(bs->file->bs, bsz);
892b7de8
ET
565 }
566
567 return -ENOTSUP;
568}
569
570/**
571 * Try to get @bs's geometry (cyls, heads, sectors).
572 * On success, store them in @geo struct and return 0.
573 * On failure return -errno.
574 * @bs must not be empty.
575 */
576int bdrv_probe_geometry(BlockDriverState *bs, HDGeometry *geo)
577{
578 BlockDriver *drv = bs->drv;
579
580 if (drv && drv->bdrv_probe_geometry) {
581 return drv->bdrv_probe_geometry(bs, geo);
5a612c00
MP
582 } else if (drv && drv->is_filter && bs->file) {
583 return bdrv_probe_geometry(bs->file->bs, geo);
892b7de8
ET
584 }
585
586 return -ENOTSUP;
587}
588
eba25057
JM
589/*
590 * Create a uniquely-named empty temporary file.
591 * Return 0 upon success, otherwise a negative errno value.
592 */
593int get_tmp_filename(char *filename, int size)
d5249393 594{
eba25057 595#ifdef _WIN32
3b9f94e1 596 char temp_dir[MAX_PATH];
eba25057
JM
597 /* GetTempFileName requires that its output buffer (4th param)
598 have length MAX_PATH or greater. */
599 assert(size >= MAX_PATH);
600 return (GetTempPath(MAX_PATH, temp_dir)
601 && GetTempFileName(temp_dir, "qem", 0, filename)
602 ? 0 : -GetLastError());
d5249393 603#else
67b915a5 604 int fd;
7ccfb2eb 605 const char *tmpdir;
0badc1ee 606 tmpdir = getenv("TMPDIR");
69bef793
AS
607 if (!tmpdir) {
608 tmpdir = "/var/tmp";
609 }
eba25057
JM
610 if (snprintf(filename, size, "%s/vl.XXXXXX", tmpdir) >= size) {
611 return -EOVERFLOW;
612 }
ea2384d3 613 fd = mkstemp(filename);
fe235a06
DH
614 if (fd < 0) {
615 return -errno;
616 }
617 if (close(fd) != 0) {
618 unlink(filename);
eba25057
JM
619 return -errno;
620 }
621 return 0;
d5249393 622#endif
eba25057 623}
fc01f7e7 624
84a12e66
CH
625/*
626 * Detect host devices. By convention, /dev/cdrom[N] is always
627 * recognized as a host CDROM.
628 */
629static BlockDriver *find_hdev_driver(const char *filename)
630{
631 int score_max = 0, score;
632 BlockDriver *drv = NULL, *d;
633
634 QLIST_FOREACH(d, &bdrv_drivers, list) {
635 if (d->bdrv_probe_device) {
636 score = d->bdrv_probe_device(filename);
637 if (score > score_max) {
638 score_max = score;
639 drv = d;
640 }
641 }
642 }
643
644 return drv;
645}
646
88d88798
MM
647static BlockDriver *bdrv_do_find_protocol(const char *protocol)
648{
649 BlockDriver *drv1;
650
651 QLIST_FOREACH(drv1, &bdrv_drivers, list) {
652 if (drv1->protocol_name && !strcmp(drv1->protocol_name, protocol)) {
653 return drv1;
654 }
655 }
656
657 return NULL;
658}
659
98289620 660BlockDriver *bdrv_find_protocol(const char *filename,
b65a5e12
HR
661 bool allow_protocol_prefix,
662 Error **errp)
83f64091
FB
663{
664 BlockDriver *drv1;
665 char protocol[128];
1cec71e3 666 int len;
83f64091 667 const char *p;
88d88798 668 int i;
19cb3738 669
66f82cee
KW
670 /* TODO Drivers without bdrv_file_open must be specified explicitly */
671
39508e7a
CH
672 /*
673 * XXX(hch): we really should not let host device detection
674 * override an explicit protocol specification, but moving this
675 * later breaks access to device names with colons in them.
676 * Thanks to the brain-dead persistent naming schemes on udev-
677 * based Linux systems those actually are quite common.
678 */
679 drv1 = find_hdev_driver(filename);
680 if (drv1) {
681 return drv1;
682 }
683
98289620 684 if (!path_has_protocol(filename) || !allow_protocol_prefix) {
ef810437 685 return &bdrv_file;
84a12e66 686 }
98289620 687
9e0b22f4
SH
688 p = strchr(filename, ':');
689 assert(p != NULL);
1cec71e3
AL
690 len = p - filename;
691 if (len > sizeof(protocol) - 1)
692 len = sizeof(protocol) - 1;
693 memcpy(protocol, filename, len);
694 protocol[len] = '\0';
88d88798
MM
695
696 drv1 = bdrv_do_find_protocol(protocol);
697 if (drv1) {
698 return drv1;
699 }
700
701 for (i = 0; i < (int)ARRAY_SIZE(block_driver_modules); ++i) {
702 if (block_driver_modules[i].protocol_name &&
703 !strcmp(block_driver_modules[i].protocol_name, protocol)) {
704 block_module_load_one(block_driver_modules[i].library_name);
705 break;
8a22f02a 706 }
83f64091 707 }
b65a5e12 708
88d88798
MM
709 drv1 = bdrv_do_find_protocol(protocol);
710 if (!drv1) {
711 error_setg(errp, "Unknown protocol '%s'", protocol);
712 }
713 return drv1;
83f64091
FB
714}
715
c6684249
MA
716/*
717 * Guess image format by probing its contents.
718 * This is not a good idea when your image is raw (CVE-2008-2004), but
719 * we do it anyway for backward compatibility.
720 *
721 * @buf contains the image's first @buf_size bytes.
7cddd372
KW
722 * @buf_size is the buffer size in bytes (generally BLOCK_PROBE_BUF_SIZE,
723 * but can be smaller if the image file is smaller)
c6684249
MA
724 * @filename is its filename.
725 *
726 * For all block drivers, call the bdrv_probe() method to get its
727 * probing score.
728 * Return the first block driver with the highest probing score.
729 */
38f3ef57
KW
730BlockDriver *bdrv_probe_all(const uint8_t *buf, int buf_size,
731 const char *filename)
c6684249
MA
732{
733 int score_max = 0, score;
734 BlockDriver *drv = NULL, *d;
735
736 QLIST_FOREACH(d, &bdrv_drivers, list) {
737 if (d->bdrv_probe) {
738 score = d->bdrv_probe(buf, buf_size, filename);
739 if (score > score_max) {
740 score_max = score;
741 drv = d;
742 }
743 }
744 }
745
746 return drv;
747}
748
5696c6e3 749static int find_image_format(BlockBackend *file, const char *filename,
34b5d2c6 750 BlockDriver **pdrv, Error **errp)
f3a5d3f8 751{
c6684249 752 BlockDriver *drv;
7cddd372 753 uint8_t buf[BLOCK_PROBE_BUF_SIZE];
f500a6d3 754 int ret = 0;
f8ea0b00 755
08a00559 756 /* Return the raw BlockDriver * to scsi-generic devices or empty drives */
5696c6e3 757 if (blk_is_sg(file) || !blk_is_inserted(file) || blk_getlength(file) == 0) {
ef810437 758 *pdrv = &bdrv_raw;
c98ac35d 759 return ret;
1a396859 760 }
f8ea0b00 761
5696c6e3 762 ret = blk_pread(file, 0, buf, sizeof(buf));
83f64091 763 if (ret < 0) {
34b5d2c6
HR
764 error_setg_errno(errp, -ret, "Could not read image for determining its "
765 "format");
c98ac35d
SW
766 *pdrv = NULL;
767 return ret;
83f64091
FB
768 }
769
c6684249 770 drv = bdrv_probe_all(buf, ret, filename);
c98ac35d 771 if (!drv) {
34b5d2c6
HR
772 error_setg(errp, "Could not determine image format: No compatible "
773 "driver found");
c98ac35d
SW
774 ret = -ENOENT;
775 }
776 *pdrv = drv;
777 return ret;
ea2384d3
FB
778}
779
51762288
SH
780/**
781 * Set the current 'total_sectors' value
65a9bb25 782 * Return 0 on success, -errno on error.
51762288 783 */
3d9f2d2a 784int refresh_total_sectors(BlockDriverState *bs, int64_t hint)
51762288
SH
785{
786 BlockDriver *drv = bs->drv;
787
d470ad42
HR
788 if (!drv) {
789 return -ENOMEDIUM;
790 }
791
396759ad 792 /* Do not attempt drv->bdrv_getlength() on scsi-generic devices */
b192af8a 793 if (bdrv_is_sg(bs))
396759ad
NB
794 return 0;
795
51762288
SH
796 /* query actual device if possible, otherwise just trust the hint */
797 if (drv->bdrv_getlength) {
798 int64_t length = drv->bdrv_getlength(bs);
799 if (length < 0) {
800 return length;
801 }
7e382003 802 hint = DIV_ROUND_UP(length, BDRV_SECTOR_SIZE);
51762288
SH
803 }
804
805 bs->total_sectors = hint;
806 return 0;
807}
808
cddff5ba
KW
809/**
810 * Combines a QDict of new block driver @options with any missing options taken
811 * from @old_options, so that leaving out an option defaults to its old value.
812 */
813static void bdrv_join_options(BlockDriverState *bs, QDict *options,
814 QDict *old_options)
815{
816 if (bs->drv && bs->drv->bdrv_join_options) {
817 bs->drv->bdrv_join_options(options, old_options);
818 } else {
819 qdict_join(options, old_options, false);
820 }
821}
822
543770bd
AG
823static BlockdevDetectZeroesOptions bdrv_parse_detect_zeroes(QemuOpts *opts,
824 int open_flags,
825 Error **errp)
826{
827 Error *local_err = NULL;
828 char *value = qemu_opt_get_del(opts, "detect-zeroes");
829 BlockdevDetectZeroesOptions detect_zeroes =
830 qapi_enum_parse(&BlockdevDetectZeroesOptions_lookup, value,
831 BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF, &local_err);
832 g_free(value);
833 if (local_err) {
834 error_propagate(errp, local_err);
835 return detect_zeroes;
836 }
837
838 if (detect_zeroes == BLOCKDEV_DETECT_ZEROES_OPTIONS_UNMAP &&
839 !(open_flags & BDRV_O_UNMAP))
840 {
841 error_setg(errp, "setting detect-zeroes to unmap is not allowed "
842 "without setting discard operation to unmap");
843 }
844
845 return detect_zeroes;
846}
847
f80f2673
AM
848/**
849 * Set open flags for aio engine
850 *
851 * Return 0 on success, -1 if the engine specified is invalid
852 */
853int bdrv_parse_aio(const char *mode, int *flags)
854{
855 if (!strcmp(mode, "threads")) {
856 /* do nothing, default */
857 } else if (!strcmp(mode, "native")) {
858 *flags |= BDRV_O_NATIVE_AIO;
859#ifdef CONFIG_LINUX_IO_URING
860 } else if (!strcmp(mode, "io_uring")) {
861 *flags |= BDRV_O_IO_URING;
862#endif
863 } else {
864 return -1;
865 }
866
867 return 0;
868}
869
9e8f1835
PB
870/**
871 * Set open flags for a given discard mode
872 *
873 * Return 0 on success, -1 if the discard mode was invalid.
874 */
875int bdrv_parse_discard_flags(const char *mode, int *flags)
876{
877 *flags &= ~BDRV_O_UNMAP;
878
879 if (!strcmp(mode, "off") || !strcmp(mode, "ignore")) {
880 /* do nothing */
881 } else if (!strcmp(mode, "on") || !strcmp(mode, "unmap")) {
882 *flags |= BDRV_O_UNMAP;
883 } else {
884 return -1;
885 }
886
887 return 0;
888}
889
c3993cdc
SH
890/**
891 * Set open flags for a given cache mode
892 *
893 * Return 0 on success, -1 if the cache mode was invalid.
894 */
53e8ae01 895int bdrv_parse_cache_mode(const char *mode, int *flags, bool *writethrough)
c3993cdc
SH
896{
897 *flags &= ~BDRV_O_CACHE_MASK;
898
899 if (!strcmp(mode, "off") || !strcmp(mode, "none")) {
53e8ae01
KW
900 *writethrough = false;
901 *flags |= BDRV_O_NOCACHE;
92196b2f 902 } else if (!strcmp(mode, "directsync")) {
53e8ae01 903 *writethrough = true;
92196b2f 904 *flags |= BDRV_O_NOCACHE;
c3993cdc 905 } else if (!strcmp(mode, "writeback")) {
53e8ae01 906 *writethrough = false;
c3993cdc 907 } else if (!strcmp(mode, "unsafe")) {
53e8ae01 908 *writethrough = false;
c3993cdc
SH
909 *flags |= BDRV_O_NO_FLUSH;
910 } else if (!strcmp(mode, "writethrough")) {
53e8ae01 911 *writethrough = true;
c3993cdc
SH
912 } else {
913 return -1;
914 }
915
916 return 0;
917}
918
b5411555
KW
919static char *bdrv_child_get_parent_desc(BdrvChild *c)
920{
921 BlockDriverState *parent = c->opaque;
922 return g_strdup(bdrv_get_device_or_node_name(parent));
923}
924
20018e12
KW
925static void bdrv_child_cb_drained_begin(BdrvChild *child)
926{
927 BlockDriverState *bs = child->opaque;
6cd5c9d7 928 bdrv_do_drained_begin_quiesce(bs, NULL, false);
20018e12
KW
929}
930
89bd0305
KW
931static bool bdrv_child_cb_drained_poll(BdrvChild *child)
932{
933 BlockDriverState *bs = child->opaque;
6cd5c9d7 934 return bdrv_drain_poll(bs, false, NULL, false);
89bd0305
KW
935}
936
e037c09c
HR
937static void bdrv_child_cb_drained_end(BdrvChild *child,
938 int *drained_end_counter)
20018e12
KW
939{
940 BlockDriverState *bs = child->opaque;
e037c09c 941 bdrv_drained_end_no_poll(bs, drained_end_counter);
20018e12
KW
942}
943
d736f119
KW
944static void bdrv_child_cb_attach(BdrvChild *child)
945{
946 BlockDriverState *bs = child->opaque;
947 bdrv_apply_subtree_drain(child, bs);
948}
949
950static void bdrv_child_cb_detach(BdrvChild *child)
951{
952 BlockDriverState *bs = child->opaque;
953 bdrv_unapply_subtree_drain(child, bs);
954}
955
38701b6a
KW
956static int bdrv_child_cb_inactivate(BdrvChild *child)
957{
958 BlockDriverState *bs = child->opaque;
959 assert(bs->open_flags & BDRV_O_INACTIVE);
960 return 0;
961}
962
5d231849
KW
963static bool bdrv_child_cb_can_set_aio_ctx(BdrvChild *child, AioContext *ctx,
964 GSList **ignore, Error **errp)
965{
966 BlockDriverState *bs = child->opaque;
967 return bdrv_can_set_aio_context(bs, ctx, ignore, errp);
968}
969
53a7d041
KW
970static void bdrv_child_cb_set_aio_ctx(BdrvChild *child, AioContext *ctx,
971 GSList **ignore)
972{
973 BlockDriverState *bs = child->opaque;
974 return bdrv_set_aio_context_ignore(bs, ctx, ignore);
975}
976
b1e6fc08 977/*
73176bee
KW
978 * Returns the options and flags that a temporary snapshot should get, based on
979 * the originally requested flags (the originally requested image will have
980 * flags like a backing file)
b1e6fc08 981 */
73176bee
KW
982static void bdrv_temp_snapshot_options(int *child_flags, QDict *child_options,
983 int parent_flags, QDict *parent_options)
b1e6fc08 984{
73176bee
KW
985 *child_flags = (parent_flags & ~BDRV_O_SNAPSHOT) | BDRV_O_TEMPORARY;
986
987 /* For temporary files, unconditional cache=unsafe is fine */
73176bee
KW
988 qdict_set_default_str(child_options, BDRV_OPT_CACHE_DIRECT, "off");
989 qdict_set_default_str(child_options, BDRV_OPT_CACHE_NO_FLUSH, "on");
41869044 990
3f48686f 991 /* Copy the read-only and discard options from the parent */
f87a0e29 992 qdict_copy_default(child_options, parent_options, BDRV_OPT_READ_ONLY);
3f48686f 993 qdict_copy_default(child_options, parent_options, BDRV_OPT_DISCARD);
f87a0e29 994
41869044
KW
995 /* aio=native doesn't work for cache.direct=off, so disable it for the
996 * temporary snapshot */
997 *child_flags &= ~BDRV_O_NATIVE_AIO;
b1e6fc08
KW
998}
999
0b50cc88 1000/*
8e2160e2
KW
1001 * Returns the options and flags that bs->file should get if a protocol driver
1002 * is expected, based on the given options and flags for the parent BDS
0b50cc88 1003 */
8e2160e2
KW
1004static void bdrv_inherited_options(int *child_flags, QDict *child_options,
1005 int parent_flags, QDict *parent_options)
0b50cc88 1006{
8e2160e2
KW
1007 int flags = parent_flags;
1008
0b50cc88
KW
1009 /* Enable protocol handling, disable format probing for bs->file */
1010 flags |= BDRV_O_PROTOCOL;
1011
91a097e7
KW
1012 /* If the cache mode isn't explicitly set, inherit direct and no-flush from
1013 * the parent. */
1014 qdict_copy_default(child_options, parent_options, BDRV_OPT_CACHE_DIRECT);
1015 qdict_copy_default(child_options, parent_options, BDRV_OPT_CACHE_NO_FLUSH);
5a9347c6 1016 qdict_copy_default(child_options, parent_options, BDRV_OPT_FORCE_SHARE);
91a097e7 1017
f87a0e29
AG
1018 /* Inherit the read-only option from the parent if it's not set */
1019 qdict_copy_default(child_options, parent_options, BDRV_OPT_READ_ONLY);
e35bdc12 1020 qdict_copy_default(child_options, parent_options, BDRV_OPT_AUTO_READ_ONLY);
f87a0e29 1021
0b50cc88 1022 /* Our block drivers take care to send flushes and respect unmap policy,
91a097e7
KW
1023 * so we can default to enable both on lower layers regardless of the
1024 * corresponding parent options. */
818584a4 1025 qdict_set_default_str(child_options, BDRV_OPT_DISCARD, "unmap");
0b50cc88 1026
0b50cc88 1027 /* Clear flags that only apply to the top layer */
abb06c5a
DB
1028 flags &= ~(BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING | BDRV_O_COPY_ON_READ |
1029 BDRV_O_NO_IO);
0b50cc88 1030
8e2160e2 1031 *child_flags = flags;
0b50cc88
KW
1032}
1033
f3930ed0 1034const BdrvChildRole child_file = {
6cd5c9d7 1035 .parent_is_bds = true,
b5411555 1036 .get_parent_desc = bdrv_child_get_parent_desc,
8e2160e2 1037 .inherit_options = bdrv_inherited_options,
20018e12 1038 .drained_begin = bdrv_child_cb_drained_begin,
89bd0305 1039 .drained_poll = bdrv_child_cb_drained_poll,
20018e12 1040 .drained_end = bdrv_child_cb_drained_end,
d736f119
KW
1041 .attach = bdrv_child_cb_attach,
1042 .detach = bdrv_child_cb_detach,
38701b6a 1043 .inactivate = bdrv_child_cb_inactivate,
5d231849 1044 .can_set_aio_ctx = bdrv_child_cb_can_set_aio_ctx,
53a7d041 1045 .set_aio_ctx = bdrv_child_cb_set_aio_ctx,
f3930ed0
KW
1046};
1047
1048/*
8e2160e2
KW
1049 * Returns the options and flags that bs->file should get if the use of formats
1050 * (and not only protocols) is permitted for it, based on the given options and
1051 * flags for the parent BDS
f3930ed0 1052 */
8e2160e2
KW
1053static void bdrv_inherited_fmt_options(int *child_flags, QDict *child_options,
1054 int parent_flags, QDict *parent_options)
f3930ed0 1055{
8e2160e2
KW
1056 child_file.inherit_options(child_flags, child_options,
1057 parent_flags, parent_options);
1058
abb06c5a 1059 *child_flags &= ~(BDRV_O_PROTOCOL | BDRV_O_NO_IO);
f3930ed0
KW
1060}
1061
1062const BdrvChildRole child_format = {
6cd5c9d7 1063 .parent_is_bds = true,
b5411555 1064 .get_parent_desc = bdrv_child_get_parent_desc,
8e2160e2 1065 .inherit_options = bdrv_inherited_fmt_options,
20018e12 1066 .drained_begin = bdrv_child_cb_drained_begin,
89bd0305 1067 .drained_poll = bdrv_child_cb_drained_poll,
20018e12 1068 .drained_end = bdrv_child_cb_drained_end,
d736f119
KW
1069 .attach = bdrv_child_cb_attach,
1070 .detach = bdrv_child_cb_detach,
38701b6a 1071 .inactivate = bdrv_child_cb_inactivate,
5d231849 1072 .can_set_aio_ctx = bdrv_child_cb_can_set_aio_ctx,
53a7d041 1073 .set_aio_ctx = bdrv_child_cb_set_aio_ctx,
f3930ed0
KW
1074};
1075
db95dbba
KW
1076static void bdrv_backing_attach(BdrvChild *c)
1077{
1078 BlockDriverState *parent = c->opaque;
1079 BlockDriverState *backing_hd = c->bs;
1080
1081 assert(!parent->backing_blocker);
1082 error_setg(&parent->backing_blocker,
1083 "node is used as backing hd of '%s'",
1084 bdrv_get_device_or_node_name(parent));
1085
f30c66ba
HR
1086 bdrv_refresh_filename(backing_hd);
1087
db95dbba
KW
1088 parent->open_flags &= ~BDRV_O_NO_BACKING;
1089 pstrcpy(parent->backing_file, sizeof(parent->backing_file),
1090 backing_hd->filename);
1091 pstrcpy(parent->backing_format, sizeof(parent->backing_format),
1092 backing_hd->drv ? backing_hd->drv->format_name : "");
1093
1094 bdrv_op_block_all(backing_hd, parent->backing_blocker);
1095 /* Otherwise we won't be able to commit or stream */
1096 bdrv_op_unblock(backing_hd, BLOCK_OP_TYPE_COMMIT_TARGET,
1097 parent->backing_blocker);
1098 bdrv_op_unblock(backing_hd, BLOCK_OP_TYPE_STREAM,
1099 parent->backing_blocker);
1100 /*
1101 * We do backup in 3 ways:
1102 * 1. drive backup
1103 * The target bs is new opened, and the source is top BDS
1104 * 2. blockdev backup
1105 * Both the source and the target are top BDSes.
1106 * 3. internal backup(used for block replication)
1107 * Both the source and the target are backing file
1108 *
1109 * In case 1 and 2, neither the source nor the target is the backing file.
1110 * In case 3, we will block the top BDS, so there is only one block job
1111 * for the top BDS and its backing chain.
1112 */
1113 bdrv_op_unblock(backing_hd, BLOCK_OP_TYPE_BACKUP_SOURCE,
1114 parent->backing_blocker);
1115 bdrv_op_unblock(backing_hd, BLOCK_OP_TYPE_BACKUP_TARGET,
1116 parent->backing_blocker);
d736f119
KW
1117
1118 bdrv_child_cb_attach(c);
db95dbba
KW
1119}
1120
1121static void bdrv_backing_detach(BdrvChild *c)
1122{
1123 BlockDriverState *parent = c->opaque;
1124
1125 assert(parent->backing_blocker);
1126 bdrv_op_unblock_all(c->bs, parent->backing_blocker);
1127 error_free(parent->backing_blocker);
1128 parent->backing_blocker = NULL;
d736f119
KW
1129
1130 bdrv_child_cb_detach(c);
db95dbba
KW
1131}
1132
317fc44e 1133/*
8e2160e2
KW
1134 * Returns the options and flags that bs->backing should get, based on the
1135 * given options and flags for the parent BDS
317fc44e 1136 */
8e2160e2
KW
1137static void bdrv_backing_options(int *child_flags, QDict *child_options,
1138 int parent_flags, QDict *parent_options)
317fc44e 1139{
8e2160e2
KW
1140 int flags = parent_flags;
1141
b8816a43
KW
1142 /* The cache mode is inherited unmodified for backing files; except WCE,
1143 * which is only applied on the top level (BlockBackend) */
91a097e7
KW
1144 qdict_copy_default(child_options, parent_options, BDRV_OPT_CACHE_DIRECT);
1145 qdict_copy_default(child_options, parent_options, BDRV_OPT_CACHE_NO_FLUSH);
5a9347c6 1146 qdict_copy_default(child_options, parent_options, BDRV_OPT_FORCE_SHARE);
91a097e7 1147
317fc44e 1148 /* backing files always opened read-only */
f87a0e29 1149 qdict_set_default_str(child_options, BDRV_OPT_READ_ONLY, "on");
e35bdc12 1150 qdict_set_default_str(child_options, BDRV_OPT_AUTO_READ_ONLY, "off");
f87a0e29 1151 flags &= ~BDRV_O_COPY_ON_READ;
317fc44e
KW
1152
1153 /* snapshot=on is handled on the top layer */
8bfea15d 1154 flags &= ~(BDRV_O_SNAPSHOT | BDRV_O_TEMPORARY);
317fc44e 1155
8e2160e2 1156 *child_flags = flags;
317fc44e
KW
1157}
1158
6858eba0
KW
1159static int bdrv_backing_update_filename(BdrvChild *c, BlockDriverState *base,
1160 const char *filename, Error **errp)
1161{
1162 BlockDriverState *parent = c->opaque;
e94d3dba 1163 bool read_only = bdrv_is_read_only(parent);
6858eba0
KW
1164 int ret;
1165
e94d3dba
AG
1166 if (read_only) {
1167 ret = bdrv_reopen_set_read_only(parent, false, errp);
61f09cea
KW
1168 if (ret < 0) {
1169 return ret;
1170 }
1171 }
1172
6858eba0
KW
1173 ret = bdrv_change_backing_file(parent, filename,
1174 base->drv ? base->drv->format_name : "");
1175 if (ret < 0) {
64730694 1176 error_setg_errno(errp, -ret, "Could not update backing file link");
6858eba0
KW
1177 }
1178
e94d3dba
AG
1179 if (read_only) {
1180 bdrv_reopen_set_read_only(parent, true, NULL);
61f09cea
KW
1181 }
1182
6858eba0
KW
1183 return ret;
1184}
1185
91ef3825 1186const BdrvChildRole child_backing = {
6cd5c9d7 1187 .parent_is_bds = true,
b5411555 1188 .get_parent_desc = bdrv_child_get_parent_desc,
db95dbba
KW
1189 .attach = bdrv_backing_attach,
1190 .detach = bdrv_backing_detach,
8e2160e2 1191 .inherit_options = bdrv_backing_options,
20018e12 1192 .drained_begin = bdrv_child_cb_drained_begin,
89bd0305 1193 .drained_poll = bdrv_child_cb_drained_poll,
20018e12 1194 .drained_end = bdrv_child_cb_drained_end,
38701b6a 1195 .inactivate = bdrv_child_cb_inactivate,
6858eba0 1196 .update_filename = bdrv_backing_update_filename,
5d231849 1197 .can_set_aio_ctx = bdrv_child_cb_can_set_aio_ctx,
53a7d041 1198 .set_aio_ctx = bdrv_child_cb_set_aio_ctx,
f3930ed0
KW
1199};
1200
7b272452
KW
1201static int bdrv_open_flags(BlockDriverState *bs, int flags)
1202{
61de4c68 1203 int open_flags = flags;
7b272452
KW
1204
1205 /*
1206 * Clear flags that are internal to the block layer before opening the
1207 * image.
1208 */
20cca275 1209 open_flags &= ~(BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING | BDRV_O_PROTOCOL);
7b272452 1210
7b272452
KW
1211 return open_flags;
1212}
1213
91a097e7
KW
1214static void update_flags_from_options(int *flags, QemuOpts *opts)
1215{
2a3d4331 1216 *flags &= ~(BDRV_O_CACHE_MASK | BDRV_O_RDWR | BDRV_O_AUTO_RDONLY);
91a097e7 1217
57f9db9a 1218 if (qemu_opt_get_bool_del(opts, BDRV_OPT_CACHE_NO_FLUSH, false)) {
91a097e7
KW
1219 *flags |= BDRV_O_NO_FLUSH;
1220 }
1221
57f9db9a 1222 if (qemu_opt_get_bool_del(opts, BDRV_OPT_CACHE_DIRECT, false)) {
91a097e7
KW
1223 *flags |= BDRV_O_NOCACHE;
1224 }
f87a0e29 1225
57f9db9a 1226 if (!qemu_opt_get_bool_del(opts, BDRV_OPT_READ_ONLY, false)) {
f87a0e29
AG
1227 *flags |= BDRV_O_RDWR;
1228 }
1229
e35bdc12
KW
1230 if (qemu_opt_get_bool_del(opts, BDRV_OPT_AUTO_READ_ONLY, false)) {
1231 *flags |= BDRV_O_AUTO_RDONLY;
1232 }
91a097e7
KW
1233}
1234
1235static void update_options_from_flags(QDict *options, int flags)
1236{
91a097e7 1237 if (!qdict_haskey(options, BDRV_OPT_CACHE_DIRECT)) {
46f5ac20 1238 qdict_put_bool(options, BDRV_OPT_CACHE_DIRECT, flags & BDRV_O_NOCACHE);
91a097e7
KW
1239 }
1240 if (!qdict_haskey(options, BDRV_OPT_CACHE_NO_FLUSH)) {
46f5ac20
EB
1241 qdict_put_bool(options, BDRV_OPT_CACHE_NO_FLUSH,
1242 flags & BDRV_O_NO_FLUSH);
91a097e7 1243 }
f87a0e29 1244 if (!qdict_haskey(options, BDRV_OPT_READ_ONLY)) {
46f5ac20 1245 qdict_put_bool(options, BDRV_OPT_READ_ONLY, !(flags & BDRV_O_RDWR));
f87a0e29 1246 }
e35bdc12
KW
1247 if (!qdict_haskey(options, BDRV_OPT_AUTO_READ_ONLY)) {
1248 qdict_put_bool(options, BDRV_OPT_AUTO_READ_ONLY,
1249 flags & BDRV_O_AUTO_RDONLY);
1250 }
91a097e7
KW
1251}
1252
636ea370
KW
1253static void bdrv_assign_node_name(BlockDriverState *bs,
1254 const char *node_name,
1255 Error **errp)
6913c0c2 1256{
15489c76 1257 char *gen_node_name = NULL;
6913c0c2 1258
15489c76
JC
1259 if (!node_name) {
1260 node_name = gen_node_name = id_generate(ID_BLOCK);
1261 } else if (!id_wellformed(node_name)) {
1262 /*
1263 * Check for empty string or invalid characters, but not if it is
1264 * generated (generated names use characters not available to the user)
1265 */
9aebf3b8 1266 error_setg(errp, "Invalid node name");
636ea370 1267 return;
6913c0c2
BC
1268 }
1269
0c5e94ee 1270 /* takes care of avoiding namespaces collisions */
7f06d47e 1271 if (blk_by_name(node_name)) {
0c5e94ee
BC
1272 error_setg(errp, "node-name=%s is conflicting with a device id",
1273 node_name);
15489c76 1274 goto out;
0c5e94ee
BC
1275 }
1276
6913c0c2
BC
1277 /* takes care of avoiding duplicates node names */
1278 if (bdrv_find_node(node_name)) {
1279 error_setg(errp, "Duplicate node name");
15489c76 1280 goto out;
6913c0c2
BC
1281 }
1282
824808dd
KW
1283 /* Make sure that the node name isn't truncated */
1284 if (strlen(node_name) >= sizeof(bs->node_name)) {
1285 error_setg(errp, "Node name too long");
1286 goto out;
1287 }
1288
6913c0c2
BC
1289 /* copy node name into the bs and insert it into the graph list */
1290 pstrcpy(bs->node_name, sizeof(bs->node_name), node_name);
1291 QTAILQ_INSERT_TAIL(&graph_bdrv_states, bs, node_list);
15489c76
JC
1292out:
1293 g_free(gen_node_name);
6913c0c2
BC
1294}
1295
01a56501
KW
1296static int bdrv_open_driver(BlockDriverState *bs, BlockDriver *drv,
1297 const char *node_name, QDict *options,
1298 int open_flags, Error **errp)
1299{
1300 Error *local_err = NULL;
0f12264e 1301 int i, ret;
01a56501
KW
1302
1303 bdrv_assign_node_name(bs, node_name, &local_err);
1304 if (local_err) {
1305 error_propagate(errp, local_err);
1306 return -EINVAL;
1307 }
1308
1309 bs->drv = drv;
680c7f96 1310 bs->read_only = !(bs->open_flags & BDRV_O_RDWR);
01a56501
KW
1311 bs->opaque = g_malloc0(drv->instance_size);
1312
1313 if (drv->bdrv_file_open) {
1314 assert(!drv->bdrv_needs_filename || bs->filename[0]);
1315 ret = drv->bdrv_file_open(bs, options, open_flags, &local_err);
680c7f96 1316 } else if (drv->bdrv_open) {
01a56501 1317 ret = drv->bdrv_open(bs, options, open_flags, &local_err);
680c7f96
KW
1318 } else {
1319 ret = 0;
01a56501
KW
1320 }
1321
1322 if (ret < 0) {
1323 if (local_err) {
1324 error_propagate(errp, local_err);
1325 } else if (bs->filename[0]) {
1326 error_setg_errno(errp, -ret, "Could not open '%s'", bs->filename);
1327 } else {
1328 error_setg_errno(errp, -ret, "Could not open image");
1329 }
180ca19a 1330 goto open_failed;
01a56501
KW
1331 }
1332
1333 ret = refresh_total_sectors(bs, bs->total_sectors);
1334 if (ret < 0) {
1335 error_setg_errno(errp, -ret, "Could not refresh total sector count");
180ca19a 1336 return ret;
01a56501
KW
1337 }
1338
1339 bdrv_refresh_limits(bs, &local_err);
1340 if (local_err) {
1341 error_propagate(errp, local_err);
180ca19a 1342 return -EINVAL;
01a56501
KW
1343 }
1344
1345 assert(bdrv_opt_mem_align(bs) != 0);
1346 assert(bdrv_min_mem_align(bs) != 0);
1347 assert(is_power_of_2(bs->bl.request_alignment));
1348
0f12264e
KW
1349 for (i = 0; i < bs->quiesce_counter; i++) {
1350 if (drv->bdrv_co_drain_begin) {
1351 drv->bdrv_co_drain_begin(bs);
1352 }
1353 }
1354
01a56501 1355 return 0;
180ca19a
MP
1356open_failed:
1357 bs->drv = NULL;
1358 if (bs->file != NULL) {
1359 bdrv_unref_child(bs, bs->file);
1360 bs->file = NULL;
1361 }
01a56501
KW
1362 g_free(bs->opaque);
1363 bs->opaque = NULL;
01a56501
KW
1364 return ret;
1365}
1366
680c7f96
KW
1367BlockDriverState *bdrv_new_open_driver(BlockDriver *drv, const char *node_name,
1368 int flags, Error **errp)
1369{
1370 BlockDriverState *bs;
1371 int ret;
1372
1373 bs = bdrv_new();
1374 bs->open_flags = flags;
1375 bs->explicit_options = qdict_new();
1376 bs->options = qdict_new();
1377 bs->opaque = NULL;
1378
1379 update_options_from_flags(bs->options, flags);
1380
1381 ret = bdrv_open_driver(bs, drv, node_name, bs->options, flags, errp);
1382 if (ret < 0) {
cb3e7f08 1383 qobject_unref(bs->explicit_options);
180ca19a 1384 bs->explicit_options = NULL;
cb3e7f08 1385 qobject_unref(bs->options);
180ca19a 1386 bs->options = NULL;
680c7f96
KW
1387 bdrv_unref(bs);
1388 return NULL;
1389 }
1390
1391 return bs;
1392}
1393
c5f3014b 1394QemuOptsList bdrv_runtime_opts = {
18edf289
KW
1395 .name = "bdrv_common",
1396 .head = QTAILQ_HEAD_INITIALIZER(bdrv_runtime_opts.head),
1397 .desc = {
1398 {
1399 .name = "node-name",
1400 .type = QEMU_OPT_STRING,
1401 .help = "Node name of the block device node",
1402 },
62392ebb
KW
1403 {
1404 .name = "driver",
1405 .type = QEMU_OPT_STRING,
1406 .help = "Block driver to use for the node",
1407 },
91a097e7
KW
1408 {
1409 .name = BDRV_OPT_CACHE_DIRECT,
1410 .type = QEMU_OPT_BOOL,
1411 .help = "Bypass software writeback cache on the host",
1412 },
1413 {
1414 .name = BDRV_OPT_CACHE_NO_FLUSH,
1415 .type = QEMU_OPT_BOOL,
1416 .help = "Ignore flush requests",
1417 },
f87a0e29
AG
1418 {
1419 .name = BDRV_OPT_READ_ONLY,
1420 .type = QEMU_OPT_BOOL,
1421 .help = "Node is opened in read-only mode",
1422 },
e35bdc12
KW
1423 {
1424 .name = BDRV_OPT_AUTO_READ_ONLY,
1425 .type = QEMU_OPT_BOOL,
1426 .help = "Node can become read-only if opening read-write fails",
1427 },
692e01a2
KW
1428 {
1429 .name = "detect-zeroes",
1430 .type = QEMU_OPT_STRING,
1431 .help = "try to optimize zero writes (off, on, unmap)",
1432 },
818584a4 1433 {
415bbca8 1434 .name = BDRV_OPT_DISCARD,
818584a4
KW
1435 .type = QEMU_OPT_STRING,
1436 .help = "discard operation (ignore/off, unmap/on)",
1437 },
5a9347c6
FZ
1438 {
1439 .name = BDRV_OPT_FORCE_SHARE,
1440 .type = QEMU_OPT_BOOL,
1441 .help = "always accept other writers (default: off)",
1442 },
18edf289
KW
1443 { /* end of list */ }
1444 },
1445};
1446
57915332
KW
1447/*
1448 * Common part for opening disk images and files
b6ad491a
KW
1449 *
1450 * Removes all processed options from *options.
57915332 1451 */
5696c6e3 1452static int bdrv_open_common(BlockDriverState *bs, BlockBackend *file,
82dc8b41 1453 QDict *options, Error **errp)
57915332
KW
1454{
1455 int ret, open_flags;
035fccdf 1456 const char *filename;
62392ebb 1457 const char *driver_name = NULL;
6913c0c2 1458 const char *node_name = NULL;
818584a4 1459 const char *discard;
18edf289 1460 QemuOpts *opts;
62392ebb 1461 BlockDriver *drv;
34b5d2c6 1462 Error *local_err = NULL;
57915332 1463
6405875c 1464 assert(bs->file == NULL);
707ff828 1465 assert(options != NULL && bs->options != options);
57915332 1466
62392ebb
KW
1467 opts = qemu_opts_create(&bdrv_runtime_opts, NULL, 0, &error_abort);
1468 qemu_opts_absorb_qdict(opts, options, &local_err);
1469 if (local_err) {
1470 error_propagate(errp, local_err);
1471 ret = -EINVAL;
1472 goto fail_opts;
1473 }
1474
9b7e8691
AG
1475 update_flags_from_options(&bs->open_flags, opts);
1476
62392ebb
KW
1477 driver_name = qemu_opt_get(opts, "driver");
1478 drv = bdrv_find_format(driver_name);
1479 assert(drv != NULL);
1480
5a9347c6
FZ
1481 bs->force_share = qemu_opt_get_bool(opts, BDRV_OPT_FORCE_SHARE, false);
1482
1483 if (bs->force_share && (bs->open_flags & BDRV_O_RDWR)) {
1484 error_setg(errp,
1485 BDRV_OPT_FORCE_SHARE
1486 "=on can only be used with read-only images");
1487 ret = -EINVAL;
1488 goto fail_opts;
1489 }
1490
45673671 1491 if (file != NULL) {
f30c66ba 1492 bdrv_refresh_filename(blk_bs(file));
5696c6e3 1493 filename = blk_bs(file)->filename;
45673671 1494 } else {
129c7d1c
MA
1495 /*
1496 * Caution: while qdict_get_try_str() is fine, getting
1497 * non-string types would require more care. When @options
1498 * come from -blockdev or blockdev_add, its members are typed
1499 * according to the QAPI schema, but when they come from
1500 * -drive, they're all QString.
1501 */
45673671
KW
1502 filename = qdict_get_try_str(options, "filename");
1503 }
1504
4a008240 1505 if (drv->bdrv_needs_filename && (!filename || !filename[0])) {
765003db
KW
1506 error_setg(errp, "The '%s' block driver requires a file name",
1507 drv->format_name);
18edf289
KW
1508 ret = -EINVAL;
1509 goto fail_opts;
6913c0c2 1510 }
6913c0c2 1511
82dc8b41
KW
1512 trace_bdrv_open_common(bs, filename ?: "", bs->open_flags,
1513 drv->format_name);
62392ebb 1514
82dc8b41 1515 bs->read_only = !(bs->open_flags & BDRV_O_RDWR);
b64ec4e4
FZ
1516
1517 if (use_bdrv_whitelist && !bdrv_is_whitelisted(drv, bs->read_only)) {
8be25de6
KW
1518 if (!bs->read_only && bdrv_is_whitelisted(drv, true)) {
1519 ret = bdrv_apply_auto_read_only(bs, NULL, NULL);
1520 } else {
1521 ret = -ENOTSUP;
1522 }
1523 if (ret < 0) {
1524 error_setg(errp,
1525 !bs->read_only && bdrv_is_whitelisted(drv, true)
1526 ? "Driver '%s' can only be used for read-only devices"
1527 : "Driver '%s' is not whitelisted",
1528 drv->format_name);
1529 goto fail_opts;
1530 }
b64ec4e4 1531 }
57915332 1532
d3faa13e
PB
1533 /* bdrv_new() and bdrv_close() make it so */
1534 assert(atomic_read(&bs->copy_on_read) == 0);
1535
82dc8b41 1536 if (bs->open_flags & BDRV_O_COPY_ON_READ) {
0ebd24e0
KW
1537 if (!bs->read_only) {
1538 bdrv_enable_copy_on_read(bs);
1539 } else {
1540 error_setg(errp, "Can't use copy-on-read on read-only device");
18edf289
KW
1541 ret = -EINVAL;
1542 goto fail_opts;
0ebd24e0 1543 }
53fec9d3
SH
1544 }
1545
415bbca8 1546 discard = qemu_opt_get(opts, BDRV_OPT_DISCARD);
818584a4
KW
1547 if (discard != NULL) {
1548 if (bdrv_parse_discard_flags(discard, &bs->open_flags) != 0) {
1549 error_setg(errp, "Invalid discard option");
1550 ret = -EINVAL;
1551 goto fail_opts;
1552 }
1553 }
1554
543770bd
AG
1555 bs->detect_zeroes =
1556 bdrv_parse_detect_zeroes(opts, bs->open_flags, &local_err);
1557 if (local_err) {
1558 error_propagate(errp, local_err);
1559 ret = -EINVAL;
1560 goto fail_opts;
692e01a2
KW
1561 }
1562
c2ad1b0c
KW
1563 if (filename != NULL) {
1564 pstrcpy(bs->filename, sizeof(bs->filename), filename);
1565 } else {
1566 bs->filename[0] = '\0';
1567 }
91af7014 1568 pstrcpy(bs->exact_filename, sizeof(bs->exact_filename), bs->filename);
57915332 1569
66f82cee 1570 /* Open the image, either directly or using a protocol */
82dc8b41 1571 open_flags = bdrv_open_flags(bs, bs->open_flags);
01a56501 1572 node_name = qemu_opt_get(opts, "node-name");
57915332 1573
01a56501
KW
1574 assert(!drv->bdrv_file_open || file == NULL);
1575 ret = bdrv_open_driver(bs, drv, node_name, options, open_flags, errp);
51762288 1576 if (ret < 0) {
01a56501 1577 goto fail_opts;
3baca891
KW
1578 }
1579
18edf289 1580 qemu_opts_del(opts);
57915332
KW
1581 return 0;
1582
18edf289
KW
1583fail_opts:
1584 qemu_opts_del(opts);
57915332
KW
1585 return ret;
1586}
1587
5e5c4f63
KW
1588static QDict *parse_json_filename(const char *filename, Error **errp)
1589{
1590 QObject *options_obj;
1591 QDict *options;
1592 int ret;
1593
1594 ret = strstart(filename, "json:", &filename);
1595 assert(ret);
1596
5577fff7 1597 options_obj = qobject_from_json(filename, errp);
5e5c4f63 1598 if (!options_obj) {
5577fff7 1599 error_prepend(errp, "Could not parse the JSON options: ");
5e5c4f63
KW
1600 return NULL;
1601 }
1602
7dc847eb 1603 options = qobject_to(QDict, options_obj);
ca6b6e1e 1604 if (!options) {
cb3e7f08 1605 qobject_unref(options_obj);
5e5c4f63
KW
1606 error_setg(errp, "Invalid JSON object given");
1607 return NULL;
1608 }
1609
5e5c4f63
KW
1610 qdict_flatten(options);
1611
1612 return options;
1613}
1614
de3b53f0
KW
1615static void parse_json_protocol(QDict *options, const char **pfilename,
1616 Error **errp)
1617{
1618 QDict *json_options;
1619 Error *local_err = NULL;
1620
1621 /* Parse json: pseudo-protocol */
1622 if (!*pfilename || !g_str_has_prefix(*pfilename, "json:")) {
1623 return;
1624 }
1625
1626 json_options = parse_json_filename(*pfilename, &local_err);
1627 if (local_err) {
1628 error_propagate(errp, local_err);
1629 return;
1630 }
1631
1632 /* Options given in the filename have lower priority than options
1633 * specified directly */
1634 qdict_join(options, json_options, false);
cb3e7f08 1635 qobject_unref(json_options);
de3b53f0
KW
1636 *pfilename = NULL;
1637}
1638
b6ce07aa 1639/*
f54120ff
KW
1640 * Fills in default options for opening images and converts the legacy
1641 * filename/flags pair to option QDict entries.
53a29513
HR
1642 * The BDRV_O_PROTOCOL flag in *flags will be set or cleared accordingly if a
1643 * block driver has been specified explicitly.
b6ce07aa 1644 */
de3b53f0 1645static int bdrv_fill_options(QDict **options, const char *filename,
053e1578 1646 int *flags, Error **errp)
ea2384d3 1647{
c2ad1b0c 1648 const char *drvname;
53a29513 1649 bool protocol = *flags & BDRV_O_PROTOCOL;
e3fa4bfa 1650 bool parse_filename = false;
053e1578 1651 BlockDriver *drv = NULL;
34b5d2c6 1652 Error *local_err = NULL;
83f64091 1653
129c7d1c
MA
1654 /*
1655 * Caution: while qdict_get_try_str() is fine, getting non-string
1656 * types would require more care. When @options come from
1657 * -blockdev or blockdev_add, its members are typed according to
1658 * the QAPI schema, but when they come from -drive, they're all
1659 * QString.
1660 */
53a29513 1661 drvname = qdict_get_try_str(*options, "driver");
053e1578
HR
1662 if (drvname) {
1663 drv = bdrv_find_format(drvname);
1664 if (!drv) {
1665 error_setg(errp, "Unknown driver '%s'", drvname);
1666 return -ENOENT;
1667 }
1668 /* If the user has explicitly specified the driver, this choice should
1669 * override the BDRV_O_PROTOCOL flag */
1670 protocol = drv->bdrv_file_open;
53a29513
HR
1671 }
1672
1673 if (protocol) {
1674 *flags |= BDRV_O_PROTOCOL;
1675 } else {
1676 *flags &= ~BDRV_O_PROTOCOL;
1677 }
1678
91a097e7
KW
1679 /* Translate cache options from flags into options */
1680 update_options_from_flags(*options, *flags);
1681
035fccdf 1682 /* Fetch the file name from the options QDict if necessary */
17b005f1 1683 if (protocol && filename) {
f54120ff 1684 if (!qdict_haskey(*options, "filename")) {
46f5ac20 1685 qdict_put_str(*options, "filename", filename);
f54120ff
KW
1686 parse_filename = true;
1687 } else {
1688 error_setg(errp, "Can't specify 'file' and 'filename' options at "
1689 "the same time");
1690 return -EINVAL;
1691 }
035fccdf
KW
1692 }
1693
c2ad1b0c 1694 /* Find the right block driver */
129c7d1c 1695 /* See cautionary note on accessing @options above */
f54120ff 1696 filename = qdict_get_try_str(*options, "filename");
f54120ff 1697
053e1578
HR
1698 if (!drvname && protocol) {
1699 if (filename) {
1700 drv = bdrv_find_protocol(filename, parse_filename, errp);
17b005f1 1701 if (!drv) {
053e1578 1702 return -EINVAL;
17b005f1 1703 }
053e1578
HR
1704
1705 drvname = drv->format_name;
46f5ac20 1706 qdict_put_str(*options, "driver", drvname);
053e1578
HR
1707 } else {
1708 error_setg(errp, "Must specify either driver or file");
1709 return -EINVAL;
98289620 1710 }
c2ad1b0c
KW
1711 }
1712
17b005f1 1713 assert(drv || !protocol);
c2ad1b0c 1714
f54120ff 1715 /* Driver-specific filename parsing */
17b005f1 1716 if (drv && drv->bdrv_parse_filename && parse_filename) {
5acd9d81 1717 drv->bdrv_parse_filename(filename, *options, &local_err);
84d18f06 1718 if (local_err) {
34b5d2c6 1719 error_propagate(errp, local_err);
f54120ff 1720 return -EINVAL;
6963a30d 1721 }
cd5d031e
HR
1722
1723 if (!drv->bdrv_needs_filename) {
1724 qdict_del(*options, "filename");
cd5d031e 1725 }
6963a30d
KW
1726 }
1727
f54120ff
KW
1728 return 0;
1729}
1730
3121fb45
KW
1731static int bdrv_child_check_perm(BdrvChild *c, BlockReopenQueue *q,
1732 uint64_t perm, uint64_t shared,
9eab1544
HR
1733 GSList *ignore_children,
1734 bool *tighten_restrictions, Error **errp);
c1cef672
FZ
1735static void bdrv_child_abort_perm_update(BdrvChild *c);
1736static void bdrv_child_set_perm(BdrvChild *c, uint64_t perm, uint64_t shared);
481e0eee
HR
1737static void bdrv_get_cumulative_perm(BlockDriverState *bs, uint64_t *perm,
1738 uint64_t *shared_perm);
c1cef672 1739
148eb13c
KW
1740typedef struct BlockReopenQueueEntry {
1741 bool prepared;
69b736e7 1742 bool perms_checked;
148eb13c 1743 BDRVReopenState state;
859443b0 1744 QTAILQ_ENTRY(BlockReopenQueueEntry) entry;
148eb13c
KW
1745} BlockReopenQueueEntry;
1746
1747/*
1748 * Return the flags that @bs will have after the reopens in @q have
1749 * successfully completed. If @q is NULL (or @bs is not contained in @q),
1750 * return the current flags.
1751 */
1752static int bdrv_reopen_get_flags(BlockReopenQueue *q, BlockDriverState *bs)
1753{
1754 BlockReopenQueueEntry *entry;
1755
1756 if (q != NULL) {
859443b0 1757 QTAILQ_FOREACH(entry, q, entry) {
148eb13c
KW
1758 if (entry->state.bs == bs) {
1759 return entry->state.flags;
1760 }
1761 }
1762 }
1763
1764 return bs->open_flags;
1765}
1766
1767/* Returns whether the image file can be written to after the reopen queue @q
1768 * has been successfully applied, or right now if @q is NULL. */
cc022140
HR
1769static bool bdrv_is_writable_after_reopen(BlockDriverState *bs,
1770 BlockReopenQueue *q)
148eb13c
KW
1771{
1772 int flags = bdrv_reopen_get_flags(q, bs);
1773
1774 return (flags & (BDRV_O_RDWR | BDRV_O_INACTIVE)) == BDRV_O_RDWR;
1775}
1776
cc022140
HR
1777/*
1778 * Return whether the BDS can be written to. This is not necessarily
1779 * the same as !bdrv_is_read_only(bs), as inactivated images may not
1780 * be written to but do not count as read-only images.
1781 */
1782bool bdrv_is_writable(BlockDriverState *bs)
1783{
1784 return bdrv_is_writable_after_reopen(bs, NULL);
1785}
1786
ffd1a5a2 1787static void bdrv_child_perm(BlockDriverState *bs, BlockDriverState *child_bs,
e0995dc3
KW
1788 BdrvChild *c, const BdrvChildRole *role,
1789 BlockReopenQueue *reopen_queue,
ffd1a5a2
FZ
1790 uint64_t parent_perm, uint64_t parent_shared,
1791 uint64_t *nperm, uint64_t *nshared)
1792{
0b3ca76e
AG
1793 assert(bs->drv && bs->drv->bdrv_child_perm);
1794 bs->drv->bdrv_child_perm(bs, c, role, reopen_queue,
1795 parent_perm, parent_shared,
1796 nperm, nshared);
e0995dc3 1797 /* TODO Take force_share from reopen_queue */
ffd1a5a2
FZ
1798 if (child_bs && child_bs->force_share) {
1799 *nshared = BLK_PERM_ALL;
1800 }
1801}
1802
33a610c3
KW
1803/*
1804 * Check whether permissions on this node can be changed in a way that
1805 * @cumulative_perms and @cumulative_shared_perms are the new cumulative
1806 * permissions of all its parents. This involves checking whether all necessary
1807 * permission changes to child nodes can be performed.
1808 *
9eab1544
HR
1809 * Will set *tighten_restrictions to true if and only if new permissions have to
1810 * be taken or currently shared permissions are to be unshared. Otherwise,
1811 * errors are not fatal as long as the caller accepts that the restrictions
1812 * remain tighter than they need to be. The caller still has to abort the
1813 * transaction.
1814 * @tighten_restrictions cannot be used together with @q: When reopening, we may
1815 * encounter fatal errors even though no restrictions are to be tightened. For
1816 * example, changing a node from RW to RO will fail if the WRITE permission is
1817 * to be kept.
1818 *
33a610c3
KW
1819 * A call to this function must always be followed by a call to bdrv_set_perm()
1820 * or bdrv_abort_perm_update().
1821 */
3121fb45
KW
1822static int bdrv_check_perm(BlockDriverState *bs, BlockReopenQueue *q,
1823 uint64_t cumulative_perms,
46181129 1824 uint64_t cumulative_shared_perms,
9eab1544
HR
1825 GSList *ignore_children,
1826 bool *tighten_restrictions, Error **errp)
33a610c3
KW
1827{
1828 BlockDriver *drv = bs->drv;
1829 BdrvChild *c;
1830 int ret;
1831
9eab1544
HR
1832 assert(!q || !tighten_restrictions);
1833
1834 if (tighten_restrictions) {
1835 uint64_t current_perms, current_shared;
1836 uint64_t added_perms, removed_shared_perms;
1837
1838 bdrv_get_cumulative_perm(bs, &current_perms, &current_shared);
1839
1840 added_perms = cumulative_perms & ~current_perms;
1841 removed_shared_perms = current_shared & ~cumulative_shared_perms;
1842
1843 *tighten_restrictions = added_perms || removed_shared_perms;
1844 }
1845
33a610c3
KW
1846 /* Write permissions never work with read-only images */
1847 if ((cumulative_perms & (BLK_PERM_WRITE | BLK_PERM_WRITE_UNCHANGED)) &&
cc022140 1848 !bdrv_is_writable_after_reopen(bs, q))
33a610c3 1849 {
481e0eee
HR
1850 if (!bdrv_is_writable_after_reopen(bs, NULL)) {
1851 error_setg(errp, "Block node is read-only");
1852 } else {
1853 uint64_t current_perms, current_shared;
1854 bdrv_get_cumulative_perm(bs, &current_perms, &current_shared);
1855 if (current_perms & (BLK_PERM_WRITE | BLK_PERM_WRITE_UNCHANGED)) {
1856 error_setg(errp, "Cannot make block node read-only, there is "
1857 "a writer on it");
1858 } else {
1859 error_setg(errp, "Cannot make block node read-only and create "
1860 "a writer on it");
1861 }
1862 }
1863
33a610c3
KW
1864 return -EPERM;
1865 }
1866
1867 /* Check this node */
1868 if (!drv) {
1869 return 0;
1870 }
1871
1872 if (drv->bdrv_check_perm) {
1873 return drv->bdrv_check_perm(bs, cumulative_perms,
1874 cumulative_shared_perms, errp);
1875 }
1876
78e421c9 1877 /* Drivers that never have children can omit .bdrv_child_perm() */
33a610c3 1878 if (!drv->bdrv_child_perm) {
78e421c9 1879 assert(QLIST_EMPTY(&bs->children));
33a610c3
KW
1880 return 0;
1881 }
1882
1883 /* Check all children */
1884 QLIST_FOREACH(c, &bs->children, next) {
1885 uint64_t cur_perm, cur_shared;
9eab1544
HR
1886 bool child_tighten_restr;
1887
3121fb45 1888 bdrv_child_perm(bs, c->bs, c, c->role, q,
ffd1a5a2
FZ
1889 cumulative_perms, cumulative_shared_perms,
1890 &cur_perm, &cur_shared);
9eab1544
HR
1891 ret = bdrv_child_check_perm(c, q, cur_perm, cur_shared, ignore_children,
1892 tighten_restrictions ? &child_tighten_restr
1893 : NULL,
1894 errp);
1895 if (tighten_restrictions) {
1896 *tighten_restrictions |= child_tighten_restr;
1897 }
33a610c3
KW
1898 if (ret < 0) {
1899 return ret;
1900 }
1901 }
1902
1903 return 0;
1904}
1905
1906/*
1907 * Notifies drivers that after a previous bdrv_check_perm() call, the
1908 * permission update is not performed and any preparations made for it (e.g.
1909 * taken file locks) need to be undone.
1910 *
1911 * This function recursively notifies all child nodes.
1912 */
1913static void bdrv_abort_perm_update(BlockDriverState *bs)
1914{
1915 BlockDriver *drv = bs->drv;
1916 BdrvChild *c;
1917
1918 if (!drv) {
1919 return;
1920 }
1921
1922 if (drv->bdrv_abort_perm_update) {
1923 drv->bdrv_abort_perm_update(bs);
1924 }
1925
1926 QLIST_FOREACH(c, &bs->children, next) {
1927 bdrv_child_abort_perm_update(c);
1928 }
1929}
1930
1931static void bdrv_set_perm(BlockDriverState *bs, uint64_t cumulative_perms,
1932 uint64_t cumulative_shared_perms)
1933{
1934 BlockDriver *drv = bs->drv;
1935 BdrvChild *c;
1936
1937 if (!drv) {
1938 return;
1939 }
1940
1941 /* Update this node */
1942 if (drv->bdrv_set_perm) {
1943 drv->bdrv_set_perm(bs, cumulative_perms, cumulative_shared_perms);
1944 }
1945
78e421c9 1946 /* Drivers that never have children can omit .bdrv_child_perm() */
33a610c3 1947 if (!drv->bdrv_child_perm) {
78e421c9 1948 assert(QLIST_EMPTY(&bs->children));
33a610c3
KW
1949 return;
1950 }
1951
1952 /* Update all children */
1953 QLIST_FOREACH(c, &bs->children, next) {
1954 uint64_t cur_perm, cur_shared;
e0995dc3 1955 bdrv_child_perm(bs, c->bs, c, c->role, NULL,
ffd1a5a2
FZ
1956 cumulative_perms, cumulative_shared_perms,
1957 &cur_perm, &cur_shared);
33a610c3
KW
1958 bdrv_child_set_perm(c, cur_perm, cur_shared);
1959 }
1960}
1961
1962static void bdrv_get_cumulative_perm(BlockDriverState *bs, uint64_t *perm,
1963 uint64_t *shared_perm)
1964{
1965 BdrvChild *c;
1966 uint64_t cumulative_perms = 0;
1967 uint64_t cumulative_shared_perms = BLK_PERM_ALL;
1968
1969 QLIST_FOREACH(c, &bs->parents, next_parent) {
1970 cumulative_perms |= c->perm;
1971 cumulative_shared_perms &= c->shared_perm;
1972 }
1973
1974 *perm = cumulative_perms;
1975 *shared_perm = cumulative_shared_perms;
1976}
1977
d083319f
KW
1978static char *bdrv_child_user_desc(BdrvChild *c)
1979{
1980 if (c->role->get_parent_desc) {
1981 return c->role->get_parent_desc(c);
1982 }
1983
1984 return g_strdup("another user");
1985}
1986
5176196c 1987char *bdrv_perm_names(uint64_t perm)
d083319f
KW
1988{
1989 struct perm_name {
1990 uint64_t perm;
1991 const char *name;
1992 } permissions[] = {
1993 { BLK_PERM_CONSISTENT_READ, "consistent read" },
1994 { BLK_PERM_WRITE, "write" },
1995 { BLK_PERM_WRITE_UNCHANGED, "write unchanged" },
1996 { BLK_PERM_RESIZE, "resize" },
1997 { BLK_PERM_GRAPH_MOD, "change children" },
1998 { 0, NULL }
1999 };
2000
e2a7423a 2001 GString *result = g_string_sized_new(30);
d083319f
KW
2002 struct perm_name *p;
2003
2004 for (p = permissions; p->name; p++) {
2005 if (perm & p->perm) {
e2a7423a
AG
2006 if (result->len > 0) {
2007 g_string_append(result, ", ");
2008 }
2009 g_string_append(result, p->name);
d083319f
KW
2010 }
2011 }
2012
e2a7423a 2013 return g_string_free(result, FALSE);
d083319f
KW
2014}
2015
33a610c3
KW
2016/*
2017 * Checks whether a new reference to @bs can be added if the new user requires
46181129
KW
2018 * @new_used_perm/@new_shared_perm as its permissions. If @ignore_children is
2019 * set, the BdrvChild objects in this list are ignored in the calculations;
2020 * this allows checking permission updates for an existing reference.
33a610c3 2021 *
9eab1544
HR
2022 * See bdrv_check_perm() for the semantics of @tighten_restrictions.
2023 *
33a610c3
KW
2024 * Needs to be followed by a call to either bdrv_set_perm() or
2025 * bdrv_abort_perm_update(). */
3121fb45
KW
2026static int bdrv_check_update_perm(BlockDriverState *bs, BlockReopenQueue *q,
2027 uint64_t new_used_perm,
d5e6f437 2028 uint64_t new_shared_perm,
9eab1544
HR
2029 GSList *ignore_children,
2030 bool *tighten_restrictions,
2031 Error **errp)
d5e6f437
KW
2032{
2033 BdrvChild *c;
33a610c3
KW
2034 uint64_t cumulative_perms = new_used_perm;
2035 uint64_t cumulative_shared_perms = new_shared_perm;
d5e6f437 2036
9eab1544
HR
2037 assert(!q || !tighten_restrictions);
2038
d5e6f437
KW
2039 /* There is no reason why anyone couldn't tolerate write_unchanged */
2040 assert(new_shared_perm & BLK_PERM_WRITE_UNCHANGED);
2041
2042 QLIST_FOREACH(c, &bs->parents, next_parent) {
46181129 2043 if (g_slist_find(ignore_children, c)) {
d5e6f437
KW
2044 continue;
2045 }
2046
d083319f
KW
2047 if ((new_used_perm & c->shared_perm) != new_used_perm) {
2048 char *user = bdrv_child_user_desc(c);
2049 char *perm_names = bdrv_perm_names(new_used_perm & ~c->shared_perm);
9eab1544
HR
2050
2051 if (tighten_restrictions) {
2052 *tighten_restrictions = true;
2053 }
2054
d083319f
KW
2055 error_setg(errp, "Conflicts with use by %s as '%s', which does not "
2056 "allow '%s' on %s",
2057 user, c->name, perm_names, bdrv_get_node_name(c->bs));
2058 g_free(user);
2059 g_free(perm_names);
2060 return -EPERM;
2061 }
2062
2063 if ((c->perm & new_shared_perm) != c->perm) {
2064 char *user = bdrv_child_user_desc(c);
2065 char *perm_names = bdrv_perm_names(c->perm & ~new_shared_perm);
9eab1544
HR
2066
2067 if (tighten_restrictions) {
2068 *tighten_restrictions = true;
2069 }
2070
d083319f
KW
2071 error_setg(errp, "Conflicts with use by %s as '%s', which uses "
2072 "'%s' on %s",
2073 user, c->name, perm_names, bdrv_get_node_name(c->bs));
2074 g_free(user);
2075 g_free(perm_names);
d5e6f437
KW
2076 return -EPERM;
2077 }
33a610c3
KW
2078
2079 cumulative_perms |= c->perm;
2080 cumulative_shared_perms &= c->shared_perm;
d5e6f437
KW
2081 }
2082
3121fb45 2083 return bdrv_check_perm(bs, q, cumulative_perms, cumulative_shared_perms,
9eab1544 2084 ignore_children, tighten_restrictions, errp);
33a610c3
KW
2085}
2086
2087/* Needs to be followed by a call to either bdrv_child_set_perm() or
2088 * bdrv_child_abort_perm_update(). */
3121fb45
KW
2089static int bdrv_child_check_perm(BdrvChild *c, BlockReopenQueue *q,
2090 uint64_t perm, uint64_t shared,
9eab1544
HR
2091 GSList *ignore_children,
2092 bool *tighten_restrictions, Error **errp)
33a610c3 2093{
46181129
KW
2094 int ret;
2095
2096 ignore_children = g_slist_prepend(g_slist_copy(ignore_children), c);
9eab1544
HR
2097 ret = bdrv_check_update_perm(c->bs, q, perm, shared, ignore_children,
2098 tighten_restrictions, errp);
46181129
KW
2099 g_slist_free(ignore_children);
2100
f962e961
VSO
2101 if (ret < 0) {
2102 return ret;
2103 }
2104
2105 if (!c->has_backup_perm) {
2106 c->has_backup_perm = true;
2107 c->backup_perm = c->perm;
2108 c->backup_shared_perm = c->shared_perm;
2109 }
2110 /*
2111 * Note: it's OK if c->has_backup_perm was already set, as we can find the
2112 * same child twice during check_perm procedure
2113 */
2114
2115 c->perm = perm;
2116 c->shared_perm = shared;
2117
2118 return 0;
33a610c3
KW
2119}
2120
c1cef672 2121static void bdrv_child_set_perm(BdrvChild *c, uint64_t perm, uint64_t shared)
33a610c3
KW
2122{
2123 uint64_t cumulative_perms, cumulative_shared_perms;
2124
f962e961
VSO
2125 c->has_backup_perm = false;
2126
33a610c3
KW
2127 c->perm = perm;
2128 c->shared_perm = shared;
2129
2130 bdrv_get_cumulative_perm(c->bs, &cumulative_perms,
2131 &cumulative_shared_perms);
2132 bdrv_set_perm(c->bs, cumulative_perms, cumulative_shared_perms);
2133}
2134
c1cef672 2135static void bdrv_child_abort_perm_update(BdrvChild *c)
33a610c3 2136{
f962e961
VSO
2137 if (c->has_backup_perm) {
2138 c->perm = c->backup_perm;
2139 c->shared_perm = c->backup_shared_perm;
2140 c->has_backup_perm = false;
2141 }
2142
33a610c3
KW
2143 bdrv_abort_perm_update(c->bs);
2144}
2145
2146int bdrv_child_try_set_perm(BdrvChild *c, uint64_t perm, uint64_t shared,
2147 Error **errp)
2148{
1046779e 2149 Error *local_err = NULL;
33a610c3 2150 int ret;
1046779e 2151 bool tighten_restrictions;
33a610c3 2152
1046779e
HR
2153 ret = bdrv_child_check_perm(c, NULL, perm, shared, NULL,
2154 &tighten_restrictions, &local_err);
33a610c3
KW
2155 if (ret < 0) {
2156 bdrv_child_abort_perm_update(c);
1046779e
HR
2157 if (tighten_restrictions) {
2158 error_propagate(errp, local_err);
2159 } else {
2160 /*
2161 * Our caller may intend to only loosen restrictions and
2162 * does not expect this function to fail. Errors are not
2163 * fatal in such a case, so we can just hide them from our
2164 * caller.
2165 */
2166 error_free(local_err);
2167 ret = 0;
2168 }
33a610c3
KW
2169 return ret;
2170 }
2171
2172 bdrv_child_set_perm(c, perm, shared);
2173
d5e6f437
KW
2174 return 0;
2175}
2176
c1087f12
HR
2177int bdrv_child_refresh_perms(BlockDriverState *bs, BdrvChild *c, Error **errp)
2178{
2179 uint64_t parent_perms, parent_shared;
2180 uint64_t perms, shared;
2181
2182 bdrv_get_cumulative_perm(bs, &parent_perms, &parent_shared);
2183 bdrv_child_perm(bs, c->bs, c, c->role, NULL, parent_perms, parent_shared,
2184 &perms, &shared);
2185
2186 return bdrv_child_try_set_perm(c, perms, shared, errp);
2187}
2188
6a1b9ee1
KW
2189void bdrv_filter_default_perms(BlockDriverState *bs, BdrvChild *c,
2190 const BdrvChildRole *role,
e0995dc3 2191 BlockReopenQueue *reopen_queue,
6a1b9ee1
KW
2192 uint64_t perm, uint64_t shared,
2193 uint64_t *nperm, uint64_t *nshared)
2194{
e444fa83
KW
2195 *nperm = perm & DEFAULT_PERM_PASSTHROUGH;
2196 *nshared = (shared & DEFAULT_PERM_PASSTHROUGH) | DEFAULT_PERM_UNCHANGED;
6a1b9ee1
KW
2197}
2198
6b1a044a
KW
2199void bdrv_format_default_perms(BlockDriverState *bs, BdrvChild *c,
2200 const BdrvChildRole *role,
e0995dc3 2201 BlockReopenQueue *reopen_queue,
6b1a044a
KW
2202 uint64_t perm, uint64_t shared,
2203 uint64_t *nperm, uint64_t *nshared)
2204{
2205 bool backing = (role == &child_backing);
2206 assert(role == &child_backing || role == &child_file);
2207
2208 if (!backing) {
5fbfabd3
KW
2209 int flags = bdrv_reopen_get_flags(reopen_queue, bs);
2210
6b1a044a
KW
2211 /* Apart from the modifications below, the same permissions are
2212 * forwarded and left alone as for filters */
e0995dc3
KW
2213 bdrv_filter_default_perms(bs, c, role, reopen_queue, perm, shared,
2214 &perm, &shared);
6b1a044a
KW
2215
2216 /* Format drivers may touch metadata even if the guest doesn't write */
cc022140 2217 if (bdrv_is_writable_after_reopen(bs, reopen_queue)) {
6b1a044a
KW
2218 perm |= BLK_PERM_WRITE | BLK_PERM_RESIZE;
2219 }
2220
2221 /* bs->file always needs to be consistent because of the metadata. We
2222 * can never allow other users to resize or write to it. */
5fbfabd3
KW
2223 if (!(flags & BDRV_O_NO_IO)) {
2224 perm |= BLK_PERM_CONSISTENT_READ;
2225 }
6b1a044a
KW
2226 shared &= ~(BLK_PERM_WRITE | BLK_PERM_RESIZE);
2227 } else {
2228 /* We want consistent read from backing files if the parent needs it.
2229 * No other operations are performed on backing files. */
2230 perm &= BLK_PERM_CONSISTENT_READ;
2231
2232 /* If the parent can deal with changing data, we're okay with a
2233 * writable and resizable backing file. */
2234 /* TODO Require !(perm & BLK_PERM_CONSISTENT_READ), too? */
2235 if (shared & BLK_PERM_WRITE) {
2236 shared = BLK_PERM_WRITE | BLK_PERM_RESIZE;
2237 } else {
2238 shared = 0;
2239 }
2240
2241 shared |= BLK_PERM_CONSISTENT_READ | BLK_PERM_GRAPH_MOD |
2242 BLK_PERM_WRITE_UNCHANGED;
2243 }
2244
9c5e6594
KW
2245 if (bs->open_flags & BDRV_O_INACTIVE) {
2246 shared |= BLK_PERM_WRITE | BLK_PERM_RESIZE;
2247 }
2248
6b1a044a
KW
2249 *nperm = perm;
2250 *nshared = shared;
2251}
2252
7b1d9c4d
HR
2253uint64_t bdrv_qapi_perm_to_blk_perm(BlockPermission qapi_perm)
2254{
2255 static const uint64_t permissions[] = {
2256 [BLOCK_PERMISSION_CONSISTENT_READ] = BLK_PERM_CONSISTENT_READ,
2257 [BLOCK_PERMISSION_WRITE] = BLK_PERM_WRITE,
2258 [BLOCK_PERMISSION_WRITE_UNCHANGED] = BLK_PERM_WRITE_UNCHANGED,
2259 [BLOCK_PERMISSION_RESIZE] = BLK_PERM_RESIZE,
2260 [BLOCK_PERMISSION_GRAPH_MOD] = BLK_PERM_GRAPH_MOD,
2261 };
2262
2263 QEMU_BUILD_BUG_ON(ARRAY_SIZE(permissions) != BLOCK_PERMISSION__MAX);
2264 QEMU_BUILD_BUG_ON(1UL << ARRAY_SIZE(permissions) != BLK_PERM_ALL + 1);
2265
2266 assert(qapi_perm < BLOCK_PERMISSION__MAX);
2267
2268 return permissions[qapi_perm];
2269}
2270
8ee03995
KW
2271static void bdrv_replace_child_noperm(BdrvChild *child,
2272 BlockDriverState *new_bs)
e9740bc6
KW
2273{
2274 BlockDriverState *old_bs = child->bs;
debc2927
HR
2275 int new_bs_quiesce_counter;
2276 int drain_saldo;
e9740bc6 2277
2cad1ebe
AG
2278 assert(!child->frozen);
2279
bb2614e9
FZ
2280 if (old_bs && new_bs) {
2281 assert(bdrv_get_aio_context(old_bs) == bdrv_get_aio_context(new_bs));
2282 }
debc2927
HR
2283
2284 new_bs_quiesce_counter = (new_bs ? new_bs->quiesce_counter : 0);
2285 drain_saldo = new_bs_quiesce_counter - child->parent_quiesce_counter;
2286
2287 /*
2288 * If the new child node is drained but the old one was not, flush
2289 * all outstanding requests to the old child node.
2290 */
2291 while (drain_saldo > 0 && child->role->drained_begin) {
2292 bdrv_parent_drained_begin_single(child, true);
2293 drain_saldo--;
2294 }
2295
e9740bc6 2296 if (old_bs) {
d736f119
KW
2297 /* Detach first so that the recursive drain sections coming from @child
2298 * are already gone and we only end the drain sections that came from
2299 * elsewhere. */
2300 if (child->role->detach) {
2301 child->role->detach(child);
2302 }
e9740bc6
KW
2303 QLIST_REMOVE(child, next_parent);
2304 }
36fe1331
KW
2305
2306 child->bs = new_bs;
2307
e9740bc6
KW
2308 if (new_bs) {
2309 QLIST_INSERT_HEAD(&new_bs->parents, child, next_parent);
debc2927
HR
2310
2311 /*
2312 * Detaching the old node may have led to the new node's
2313 * quiesce_counter having been decreased. Not a problem, we
2314 * just need to recognize this here and then invoke
2315 * drained_end appropriately more often.
2316 */
2317 assert(new_bs->quiesce_counter <= new_bs_quiesce_counter);
2318 drain_saldo += new_bs->quiesce_counter - new_bs_quiesce_counter;
33a610c3 2319
d736f119
KW
2320 /* Attach only after starting new drained sections, so that recursive
2321 * drain sections coming from @child don't get an extra .drained_begin
2322 * callback. */
8ee03995
KW
2323 if (child->role->attach) {
2324 child->role->attach(child);
2325 }
2326 }
debc2927
HR
2327
2328 /*
2329 * If the old child node was drained but the new one is not, allow
2330 * requests to come in only after the new node has been attached.
2331 */
2332 while (drain_saldo < 0 && child->role->drained_end) {
2333 bdrv_parent_drained_end_single(child);
2334 drain_saldo++;
2335 }
8ee03995 2336}
33a610c3 2337
466787fb
KW
2338/*
2339 * Updates @child to change its reference to point to @new_bs, including
2340 * checking and applying the necessary permisson updates both to the old node
2341 * and to @new_bs.
2342 *
2343 * NULL is passed as @new_bs for removing the reference before freeing @child.
2344 *
2345 * If @new_bs is not NULL, bdrv_check_perm() must be called beforehand, as this
2346 * function uses bdrv_set_perm() to update the permissions according to the new
2347 * reference that @new_bs gets.
2348 */
2349static void bdrv_replace_child(BdrvChild *child, BlockDriverState *new_bs)
8ee03995
KW
2350{
2351 BlockDriverState *old_bs = child->bs;
2352 uint64_t perm, shared_perm;
2353
8aecf1d1
KW
2354 bdrv_replace_child_noperm(child, new_bs);
2355
87ace5f8
HR
2356 /*
2357 * Start with the new node's permissions. If @new_bs is a (direct
2358 * or indirect) child of @old_bs, we must complete the permission
2359 * update on @new_bs before we loosen the restrictions on @old_bs.
2360 * Otherwise, bdrv_check_perm() on @old_bs would re-initiate
2361 * updating the permissions of @new_bs, and thus not purely loosen
2362 * restrictions.
2363 */
2364 if (new_bs) {
2365 bdrv_get_cumulative_perm(new_bs, &perm, &shared_perm);
2366 bdrv_set_perm(new_bs, perm, shared_perm);
2367 }
2368
8ee03995 2369 if (old_bs) {
33a610c3
KW
2370 /* Update permissions for old node. This is guaranteed to succeed
2371 * because we're just taking a parent away, so we're loosening
2372 * restrictions. */
1046779e
HR
2373 bool tighten_restrictions;
2374 int ret;
2375
33a610c3 2376 bdrv_get_cumulative_perm(old_bs, &perm, &shared_perm);
1046779e
HR
2377 ret = bdrv_check_perm(old_bs, NULL, perm, shared_perm, NULL,
2378 &tighten_restrictions, NULL);
2379 assert(tighten_restrictions == false);
2380 if (ret < 0) {
2381 /* We only tried to loosen restrictions, so errors are not fatal */
2382 bdrv_abort_perm_update(old_bs);
2383 } else {
2384 bdrv_set_perm(old_bs, perm, shared_perm);
2385 }
ad943dcb
KW
2386
2387 /* When the parent requiring a non-default AioContext is removed, the
2388 * node moves back to the main AioContext */
2389 bdrv_try_set_aio_context(old_bs, qemu_get_aio_context(), NULL);
e9740bc6 2390 }
e9740bc6
KW
2391}
2392
b441dc71
AG
2393/*
2394 * This function steals the reference to child_bs from the caller.
2395 * That reference is later dropped by bdrv_root_unref_child().
2396 *
2397 * On failure NULL is returned, errp is set and the reference to
2398 * child_bs is also dropped.
132ada80
KW
2399 *
2400 * The caller must hold the AioContext lock @child_bs, but not that of @ctx
2401 * (unless @child_bs is already in @ctx).
b441dc71 2402 */
f21d96d0
KW
2403BdrvChild *bdrv_root_attach_child(BlockDriverState *child_bs,
2404 const char *child_name,
36fe1331 2405 const BdrvChildRole *child_role,
132ada80 2406 AioContext *ctx,
d5e6f437
KW
2407 uint64_t perm, uint64_t shared_perm,
2408 void *opaque, Error **errp)
df581792 2409{
d5e6f437 2410 BdrvChild *child;
132ada80 2411 Error *local_err = NULL;
d5e6f437
KW
2412 int ret;
2413
9eab1544
HR
2414 ret = bdrv_check_update_perm(child_bs, NULL, perm, shared_perm, NULL, NULL,
2415 errp);
d5e6f437 2416 if (ret < 0) {
33a610c3 2417 bdrv_abort_perm_update(child_bs);
b441dc71 2418 bdrv_unref(child_bs);
d5e6f437
KW
2419 return NULL;
2420 }
2421
2422 child = g_new(BdrvChild, 1);
df581792 2423 *child = (BdrvChild) {
d5e6f437
KW
2424 .bs = NULL,
2425 .name = g_strdup(child_name),
2426 .role = child_role,
2427 .perm = perm,
2428 .shared_perm = shared_perm,
2429 .opaque = opaque,
df581792
KW
2430 };
2431
132ada80
KW
2432 /* If the AioContexts don't match, first try to move the subtree of
2433 * child_bs into the AioContext of the new parent. If this doesn't work,
2434 * try moving the parent into the AioContext of child_bs instead. */
2435 if (bdrv_get_aio_context(child_bs) != ctx) {
2436 ret = bdrv_try_set_aio_context(child_bs, ctx, &local_err);
2437 if (ret < 0 && child_role->can_set_aio_ctx) {
0beab811 2438 GSList *ignore = g_slist_prepend(NULL, child);
132ada80
KW
2439 ctx = bdrv_get_aio_context(child_bs);
2440 if (child_role->can_set_aio_ctx(child, ctx, &ignore, NULL)) {
2441 error_free(local_err);
2442 ret = 0;
2443 g_slist_free(ignore);
0beab811 2444 ignore = g_slist_prepend(NULL, child);
132ada80
KW
2445 child_role->set_aio_ctx(child, ctx, &ignore);
2446 }
2447 g_slist_free(ignore);
2448 }
2449 if (ret < 0) {
2450 error_propagate(errp, local_err);
2451 g_free(child);
2452 bdrv_abort_perm_update(child_bs);
2453 return NULL;
2454 }
2455 }
2456
33a610c3 2457 /* This performs the matching bdrv_set_perm() for the above check. */
466787fb 2458 bdrv_replace_child(child, child_bs);
b4b059f6
KW
2459
2460 return child;
df581792
KW
2461}
2462
b441dc71
AG
2463/*
2464 * This function transfers the reference to child_bs from the caller
2465 * to parent_bs. That reference is later dropped by parent_bs on
2466 * bdrv_close() or if someone calls bdrv_unref_child().
2467 *
2468 * On failure NULL is returned, errp is set and the reference to
2469 * child_bs is also dropped.
132ada80
KW
2470 *
2471 * If @parent_bs and @child_bs are in different AioContexts, the caller must
2472 * hold the AioContext lock for @child_bs, but not for @parent_bs.
b441dc71 2473 */
98292c61
WC
2474BdrvChild *bdrv_attach_child(BlockDriverState *parent_bs,
2475 BlockDriverState *child_bs,
2476 const char *child_name,
8b2ff529
KW
2477 const BdrvChildRole *child_role,
2478 Error **errp)
f21d96d0 2479{
d5e6f437 2480 BdrvChild *child;
f68c598b
KW
2481 uint64_t perm, shared_perm;
2482
2483 bdrv_get_cumulative_perm(parent_bs, &perm, &shared_perm);
2484
2485 assert(parent_bs->drv);
e0995dc3 2486 bdrv_child_perm(parent_bs, child_bs, NULL, child_role, NULL,
ffd1a5a2 2487 perm, shared_perm, &perm, &shared_perm);
d5e6f437 2488
d5e6f437 2489 child = bdrv_root_attach_child(child_bs, child_name, child_role,
132ada80 2490 bdrv_get_aio_context(parent_bs),
f68c598b 2491 perm, shared_perm, parent_bs, errp);
d5e6f437
KW
2492 if (child == NULL) {
2493 return NULL;
2494 }
2495
f21d96d0
KW
2496 QLIST_INSERT_HEAD(&parent_bs->children, child, next);
2497 return child;
2498}
2499
3f09bfbc 2500static void bdrv_detach_child(BdrvChild *child)
33a60407 2501{
f21d96d0
KW
2502 if (child->next.le_prev) {
2503 QLIST_REMOVE(child, next);
2504 child->next.le_prev = NULL;
2505 }
e9740bc6 2506
466787fb 2507 bdrv_replace_child(child, NULL);
e9740bc6 2508
260fecf1 2509 g_free(child->name);
33a60407
KW
2510 g_free(child);
2511}
2512
f21d96d0 2513void bdrv_root_unref_child(BdrvChild *child)
33a60407 2514{
779020cb
KW
2515 BlockDriverState *child_bs;
2516
f21d96d0
KW
2517 child_bs = child->bs;
2518 bdrv_detach_child(child);
2519 bdrv_unref(child_bs);
2520}
2521
3cf746b3
HR
2522/**
2523 * Clear all inherits_from pointers from children and grandchildren of
2524 * @root that point to @root, where necessary.
2525 */
2526static void bdrv_unset_inherits_from(BlockDriverState *root, BdrvChild *child)
f21d96d0 2527{
3cf746b3 2528 BdrvChild *c;
4e4bf5c4 2529
3cf746b3
HR
2530 if (child->bs->inherits_from == root) {
2531 /*
2532 * Remove inherits_from only when the last reference between root and
2533 * child->bs goes away.
2534 */
2535 QLIST_FOREACH(c, &root->children, next) {
4e4bf5c4
KW
2536 if (c != child && c->bs == child->bs) {
2537 break;
2538 }
2539 }
2540 if (c == NULL) {
2541 child->bs->inherits_from = NULL;
2542 }
33a60407
KW
2543 }
2544
3cf746b3
HR
2545 QLIST_FOREACH(c, &child->bs->children, next) {
2546 bdrv_unset_inherits_from(root, c);
2547 }
2548}
2549
2550void bdrv_unref_child(BlockDriverState *parent, BdrvChild *child)
2551{
2552 if (child == NULL) {
2553 return;
2554 }
2555
2556 bdrv_unset_inherits_from(parent, child);
f21d96d0 2557 bdrv_root_unref_child(child);
33a60407
KW
2558}
2559
5c8cab48
KW
2560
2561static void bdrv_parent_cb_change_media(BlockDriverState *bs, bool load)
2562{
2563 BdrvChild *c;
2564 QLIST_FOREACH(c, &bs->parents, next_parent) {
2565 if (c->role->change_media) {
2566 c->role->change_media(c, load);
2567 }
2568 }
2569}
2570
0065c455
AG
2571/* Return true if you can reach parent going through child->inherits_from
2572 * recursively. If parent or child are NULL, return false */
2573static bool bdrv_inherits_from_recursive(BlockDriverState *child,
2574 BlockDriverState *parent)
2575{
2576 while (child && child != parent) {
2577 child = child->inherits_from;
2578 }
2579
2580 return child != NULL;
2581}
2582
5db15a57
KW
2583/*
2584 * Sets the backing file link of a BDS. A new reference is created; callers
2585 * which don't need their own reference any more must call bdrv_unref().
2586 */
12fa4af6
KW
2587void bdrv_set_backing_hd(BlockDriverState *bs, BlockDriverState *backing_hd,
2588 Error **errp)
8d24cce1 2589{
0065c455
AG
2590 bool update_inherits_from = bdrv_chain_contains(bs, backing_hd) &&
2591 bdrv_inherits_from_recursive(backing_hd, bs);
2592
2cad1ebe
AG
2593 if (bdrv_is_backing_chain_frozen(bs, backing_bs(bs), errp)) {
2594 return;
2595 }
2596
5db15a57
KW
2597 if (backing_hd) {
2598 bdrv_ref(backing_hd);
2599 }
8d24cce1 2600
760e0063 2601 if (bs->backing) {
5db15a57 2602 bdrv_unref_child(bs, bs->backing);
826b6ca0
FZ
2603 }
2604
8d24cce1 2605 if (!backing_hd) {
760e0063 2606 bs->backing = NULL;
8d24cce1
FZ
2607 goto out;
2608 }
12fa4af6 2609
8b2ff529 2610 bs->backing = bdrv_attach_child(bs, backing_hd, "backing", &child_backing,
12fa4af6 2611 errp);
0065c455
AG
2612 /* If backing_hd was already part of bs's backing chain, and
2613 * inherits_from pointed recursively to bs then let's update it to
2614 * point directly to bs (else it will become NULL). */
b441dc71 2615 if (bs->backing && update_inherits_from) {
0065c455
AG
2616 backing_hd->inherits_from = bs;
2617 }
826b6ca0 2618
8d24cce1 2619out:
3baca891 2620 bdrv_refresh_limits(bs, NULL);
8d24cce1
FZ
2621}
2622
31ca6d07
KW
2623/*
2624 * Opens the backing file for a BlockDriverState if not yet open
2625 *
d9b7b057
KW
2626 * bdref_key specifies the key for the image's BlockdevRef in the options QDict.
2627 * That QDict has to be flattened; therefore, if the BlockdevRef is a QDict
2628 * itself, all options starting with "${bdref_key}." are considered part of the
2629 * BlockdevRef.
2630 *
2631 * TODO Can this be unified with bdrv_open_image()?
31ca6d07 2632 */
d9b7b057
KW
2633int bdrv_open_backing_file(BlockDriverState *bs, QDict *parent_options,
2634 const char *bdref_key, Error **errp)
9156df12 2635{
6b6833c1 2636 char *backing_filename = NULL;
d9b7b057
KW
2637 char *bdref_key_dot;
2638 const char *reference = NULL;
317fc44e 2639 int ret = 0;
998c2019 2640 bool implicit_backing = false;
8d24cce1 2641 BlockDriverState *backing_hd;
d9b7b057
KW
2642 QDict *options;
2643 QDict *tmp_parent_options = NULL;
34b5d2c6 2644 Error *local_err = NULL;
9156df12 2645
760e0063 2646 if (bs->backing != NULL) {
1ba4b6a5 2647 goto free_exit;
9156df12
PB
2648 }
2649
31ca6d07 2650 /* NULL means an empty set of options */
d9b7b057
KW
2651 if (parent_options == NULL) {
2652 tmp_parent_options = qdict_new();
2653 parent_options = tmp_parent_options;
31ca6d07
KW
2654 }
2655
9156df12 2656 bs->open_flags &= ~BDRV_O_NO_BACKING;
d9b7b057
KW
2657
2658 bdref_key_dot = g_strdup_printf("%s.", bdref_key);
2659 qdict_extract_subqdict(parent_options, &options, bdref_key_dot);
2660 g_free(bdref_key_dot);
2661
129c7d1c
MA
2662 /*
2663 * Caution: while qdict_get_try_str() is fine, getting non-string
2664 * types would require more care. When @parent_options come from
2665 * -blockdev or blockdev_add, its members are typed according to
2666 * the QAPI schema, but when they come from -drive, they're all
2667 * QString.
2668 */
d9b7b057
KW
2669 reference = qdict_get_try_str(parent_options, bdref_key);
2670 if (reference || qdict_haskey(options, "file.filename")) {
6b6833c1 2671 /* keep backing_filename NULL */
1cb6f506 2672 } else if (bs->backing_file[0] == '\0' && qdict_size(options) == 0) {
cb3e7f08 2673 qobject_unref(options);
1ba4b6a5 2674 goto free_exit;
dbecebdd 2675 } else {
998c2019
HR
2676 if (qdict_size(options) == 0) {
2677 /* If the user specifies options that do not modify the
2678 * backing file's behavior, we might still consider it the
2679 * implicit backing file. But it's easier this way, and
2680 * just specifying some of the backing BDS's options is
2681 * only possible with -drive anyway (otherwise the QAPI
2682 * schema forces the user to specify everything). */
2683 implicit_backing = !strcmp(bs->auto_backing_file, bs->backing_file);
2684 }
2685
6b6833c1 2686 backing_filename = bdrv_get_full_backing_filename(bs, &local_err);
9f07429e
HR
2687 if (local_err) {
2688 ret = -EINVAL;
2689 error_propagate(errp, local_err);
cb3e7f08 2690 qobject_unref(options);
9f07429e
HR
2691 goto free_exit;
2692 }
9156df12
PB
2693 }
2694
8ee79e70
KW
2695 if (!bs->drv || !bs->drv->supports_backing) {
2696 ret = -EINVAL;
2697 error_setg(errp, "Driver doesn't support backing files");
cb3e7f08 2698 qobject_unref(options);
8ee79e70
KW
2699 goto free_exit;
2700 }
2701
6bff597b
PK
2702 if (!reference &&
2703 bs->backing_format[0] != '\0' && !qdict_haskey(options, "driver")) {
46f5ac20 2704 qdict_put_str(options, "driver", bs->backing_format);
9156df12
PB
2705 }
2706
6b6833c1
HR
2707 backing_hd = bdrv_open_inherit(backing_filename, reference, options, 0, bs,
2708 &child_backing, errp);
5b363937 2709 if (!backing_hd) {
9156df12 2710 bs->open_flags |= BDRV_O_NO_BACKING;
e43bfd9c 2711 error_prepend(errp, "Could not open backing file: ");
5b363937 2712 ret = -EINVAL;
1ba4b6a5 2713 goto free_exit;
9156df12 2714 }
df581792 2715
998c2019
HR
2716 if (implicit_backing) {
2717 bdrv_refresh_filename(backing_hd);
2718 pstrcpy(bs->auto_backing_file, sizeof(bs->auto_backing_file),
2719 backing_hd->filename);
2720 }
2721
5db15a57
KW
2722 /* Hook up the backing file link; drop our reference, bs owns the
2723 * backing_hd reference now */
12fa4af6 2724 bdrv_set_backing_hd(bs, backing_hd, &local_err);
5db15a57 2725 bdrv_unref(backing_hd);
12fa4af6 2726 if (local_err) {
8cd1a3e4 2727 error_propagate(errp, local_err);
12fa4af6
KW
2728 ret = -EINVAL;
2729 goto free_exit;
2730 }
d80ac658 2731
d9b7b057
KW
2732 qdict_del(parent_options, bdref_key);
2733
1ba4b6a5
BC
2734free_exit:
2735 g_free(backing_filename);
cb3e7f08 2736 qobject_unref(tmp_parent_options);
1ba4b6a5 2737 return ret;
9156df12
PB
2738}
2739
2d6b86af
KW
2740static BlockDriverState *
2741bdrv_open_child_bs(const char *filename, QDict *options, const char *bdref_key,
2742 BlockDriverState *parent, const BdrvChildRole *child_role,
2743 bool allow_none, Error **errp)
da557aac 2744{
2d6b86af 2745 BlockDriverState *bs = NULL;
da557aac 2746 QDict *image_options;
da557aac
HR
2747 char *bdref_key_dot;
2748 const char *reference;
2749
df581792 2750 assert(child_role != NULL);
f67503e5 2751
da557aac
HR
2752 bdref_key_dot = g_strdup_printf("%s.", bdref_key);
2753 qdict_extract_subqdict(options, &image_options, bdref_key_dot);
2754 g_free(bdref_key_dot);
2755
129c7d1c
MA
2756 /*
2757 * Caution: while qdict_get_try_str() is fine, getting non-string
2758 * types would require more care. When @options come from
2759 * -blockdev or blockdev_add, its members are typed according to
2760 * the QAPI schema, but when they come from -drive, they're all
2761 * QString.
2762 */
da557aac
HR
2763 reference = qdict_get_try_str(options, bdref_key);
2764 if (!filename && !reference && !qdict_size(image_options)) {
b4b059f6 2765 if (!allow_none) {
da557aac
HR
2766 error_setg(errp, "A block device must be specified for \"%s\"",
2767 bdref_key);
da557aac 2768 }
cb3e7f08 2769 qobject_unref(image_options);
da557aac
HR
2770 goto done;
2771 }
2772
5b363937
HR
2773 bs = bdrv_open_inherit(filename, reference, image_options, 0,
2774 parent, child_role, errp);
2775 if (!bs) {
df581792
KW
2776 goto done;
2777 }
2778
da557aac
HR
2779done:
2780 qdict_del(options, bdref_key);
2d6b86af
KW
2781 return bs;
2782}
2783
2784/*
2785 * Opens a disk image whose options are given as BlockdevRef in another block
2786 * device's options.
2787 *
2788 * If allow_none is true, no image will be opened if filename is false and no
2789 * BlockdevRef is given. NULL will be returned, but errp remains unset.
2790 *
2791 * bdrev_key specifies the key for the image's BlockdevRef in the options QDict.
2792 * That QDict has to be flattened; therefore, if the BlockdevRef is a QDict
2793 * itself, all options starting with "${bdref_key}." are considered part of the
2794 * BlockdevRef.
2795 *
2796 * The BlockdevRef will be removed from the options QDict.
2797 */
2798BdrvChild *bdrv_open_child(const char *filename,
2799 QDict *options, const char *bdref_key,
2800 BlockDriverState *parent,
2801 const BdrvChildRole *child_role,
2802 bool allow_none, Error **errp)
2803{
2804 BlockDriverState *bs;
2805
2806 bs = bdrv_open_child_bs(filename, options, bdref_key, parent, child_role,
2807 allow_none, errp);
2808 if (bs == NULL) {
2809 return NULL;
2810 }
2811
b441dc71 2812 return bdrv_attach_child(parent, bs, bdref_key, child_role, errp);
b4b059f6
KW
2813}
2814
e1d74bc6
KW
2815/* TODO Future callers may need to specify parent/child_role in order for
2816 * option inheritance to work. Existing callers use it for the root node. */
2817BlockDriverState *bdrv_open_blockdev_ref(BlockdevRef *ref, Error **errp)
2818{
2819 BlockDriverState *bs = NULL;
2820 Error *local_err = NULL;
2821 QObject *obj = NULL;
2822 QDict *qdict = NULL;
2823 const char *reference = NULL;
2824 Visitor *v = NULL;
2825
2826 if (ref->type == QTYPE_QSTRING) {
2827 reference = ref->u.reference;
2828 } else {
2829 BlockdevOptions *options = &ref->u.definition;
2830 assert(ref->type == QTYPE_QDICT);
2831
2832 v = qobject_output_visitor_new(&obj);
2833 visit_type_BlockdevOptions(v, NULL, &options, &local_err);
2834 if (local_err) {
2835 error_propagate(errp, local_err);
2836 goto fail;
2837 }
2838 visit_complete(v, &obj);
2839
7dc847eb 2840 qdict = qobject_to(QDict, obj);
e1d74bc6
KW
2841 qdict_flatten(qdict);
2842
2843 /* bdrv_open_inherit() defaults to the values in bdrv_flags (for
2844 * compatibility with other callers) rather than what we want as the
2845 * real defaults. Apply the defaults here instead. */
2846 qdict_set_default_str(qdict, BDRV_OPT_CACHE_DIRECT, "off");
2847 qdict_set_default_str(qdict, BDRV_OPT_CACHE_NO_FLUSH, "off");
2848 qdict_set_default_str(qdict, BDRV_OPT_READ_ONLY, "off");
e35bdc12
KW
2849 qdict_set_default_str(qdict, BDRV_OPT_AUTO_READ_ONLY, "off");
2850
e1d74bc6
KW
2851 }
2852
2853 bs = bdrv_open_inherit(NULL, reference, qdict, 0, NULL, NULL, errp);
2854 obj = NULL;
2855
2856fail:
cb3e7f08 2857 qobject_unref(obj);
e1d74bc6
KW
2858 visit_free(v);
2859 return bs;
2860}
2861
66836189
HR
2862static BlockDriverState *bdrv_append_temp_snapshot(BlockDriverState *bs,
2863 int flags,
2864 QDict *snapshot_options,
2865 Error **errp)
b998875d
KW
2866{
2867 /* TODO: extra byte is a hack to ensure MAX_PATH space on Windows. */
1ba4b6a5 2868 char *tmp_filename = g_malloc0(PATH_MAX + 1);
b998875d 2869 int64_t total_size;
83d0521a 2870 QemuOpts *opts = NULL;
ff6ed714 2871 BlockDriverState *bs_snapshot = NULL;
b2c2832c 2872 Error *local_err = NULL;
b998875d
KW
2873 int ret;
2874
2875 /* if snapshot, we create a temporary backing file and open it
2876 instead of opening 'filename' directly */
2877
2878 /* Get the required size from the image */
f187743a
KW
2879 total_size = bdrv_getlength(bs);
2880 if (total_size < 0) {
2881 error_setg_errno(errp, -total_size, "Could not get image size");
1ba4b6a5 2882 goto out;
f187743a 2883 }
b998875d
KW
2884
2885 /* Create the temporary image */
1ba4b6a5 2886 ret = get_tmp_filename(tmp_filename, PATH_MAX + 1);
b998875d
KW
2887 if (ret < 0) {
2888 error_setg_errno(errp, -ret, "Could not get temporary filename");
1ba4b6a5 2889 goto out;
b998875d
KW
2890 }
2891
ef810437 2892 opts = qemu_opts_create(bdrv_qcow2.create_opts, NULL, 0,
c282e1fd 2893 &error_abort);
39101f25 2894 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, total_size, &error_abort);
e43bfd9c 2895 ret = bdrv_create(&bdrv_qcow2, tmp_filename, opts, errp);
83d0521a 2896 qemu_opts_del(opts);
b998875d 2897 if (ret < 0) {
e43bfd9c
MA
2898 error_prepend(errp, "Could not create temporary overlay '%s': ",
2899 tmp_filename);
1ba4b6a5 2900 goto out;
b998875d
KW
2901 }
2902
73176bee 2903 /* Prepare options QDict for the temporary file */
46f5ac20
EB
2904 qdict_put_str(snapshot_options, "file.driver", "file");
2905 qdict_put_str(snapshot_options, "file.filename", tmp_filename);
2906 qdict_put_str(snapshot_options, "driver", "qcow2");
b998875d 2907
5b363937 2908 bs_snapshot = bdrv_open(NULL, NULL, snapshot_options, flags, errp);
73176bee 2909 snapshot_options = NULL;
5b363937 2910 if (!bs_snapshot) {
1ba4b6a5 2911 goto out;
b998875d
KW
2912 }
2913
ff6ed714
EB
2914 /* bdrv_append() consumes a strong reference to bs_snapshot
2915 * (i.e. it will call bdrv_unref() on it) even on error, so in
2916 * order to be able to return one, we have to increase
2917 * bs_snapshot's refcount here */
66836189 2918 bdrv_ref(bs_snapshot);
b2c2832c
KW
2919 bdrv_append(bs_snapshot, bs, &local_err);
2920 if (local_err) {
2921 error_propagate(errp, local_err);
ff6ed714 2922 bs_snapshot = NULL;
b2c2832c
KW
2923 goto out;
2924 }
1ba4b6a5
BC
2925
2926out:
cb3e7f08 2927 qobject_unref(snapshot_options);
1ba4b6a5 2928 g_free(tmp_filename);
ff6ed714 2929 return bs_snapshot;
b998875d
KW
2930}
2931
b6ce07aa
KW
2932/*
2933 * Opens a disk image (raw, qcow2, vmdk, ...)
de9c0cec
KW
2934 *
2935 * options is a QDict of options to pass to the block drivers, or NULL for an
2936 * empty set of options. The reference to the QDict belongs to the block layer
2937 * after the call (even on failure), so if the caller intends to reuse the
cb3e7f08 2938 * dictionary, it needs to use qobject_ref() before calling bdrv_open.
f67503e5
HR
2939 *
2940 * If *pbs is NULL, a new BDS will be created with a pointer to it stored there.
2941 * If it is not NULL, the referenced BDS will be reused.
ddf5636d
HR
2942 *
2943 * The reference parameter may be used to specify an existing block device which
2944 * should be opened. If specified, neither options nor a filename may be given,
2945 * nor can an existing BDS be reused (that is, *pbs has to be NULL).
b6ce07aa 2946 */
5b363937
HR
2947static BlockDriverState *bdrv_open_inherit(const char *filename,
2948 const char *reference,
2949 QDict *options, int flags,
2950 BlockDriverState *parent,
2951 const BdrvChildRole *child_role,
2952 Error **errp)
ea2384d3 2953{
b6ce07aa 2954 int ret;
5696c6e3 2955 BlockBackend *file = NULL;
9a4f4c31 2956 BlockDriverState *bs;
ce343771 2957 BlockDriver *drv = NULL;
2f624b80 2958 BdrvChild *child;
74fe54f2 2959 const char *drvname;
3e8c2e57 2960 const char *backing;
34b5d2c6 2961 Error *local_err = NULL;
73176bee 2962 QDict *snapshot_options = NULL;
b1e6fc08 2963 int snapshot_flags = 0;
712e7874 2964
f3930ed0
KW
2965 assert(!child_role || !flags);
2966 assert(!child_role == !parent);
f67503e5 2967
ddf5636d
HR
2968 if (reference) {
2969 bool options_non_empty = options ? qdict_size(options) : false;
cb3e7f08 2970 qobject_unref(options);
ddf5636d 2971
ddf5636d
HR
2972 if (filename || options_non_empty) {
2973 error_setg(errp, "Cannot reference an existing block device with "
2974 "additional options or a new filename");
5b363937 2975 return NULL;
ddf5636d
HR
2976 }
2977
2978 bs = bdrv_lookup_bs(reference, reference, errp);
2979 if (!bs) {
5b363937 2980 return NULL;
ddf5636d 2981 }
76b22320 2982
ddf5636d 2983 bdrv_ref(bs);
5b363937 2984 return bs;
ddf5636d
HR
2985 }
2986
5b363937 2987 bs = bdrv_new();
f67503e5 2988
de9c0cec
KW
2989 /* NULL means an empty set of options */
2990 if (options == NULL) {
2991 options = qdict_new();
2992 }
2993
145f598e 2994 /* json: syntax counts as explicit options, as if in the QDict */
de3b53f0
KW
2995 parse_json_protocol(options, &filename, &local_err);
2996 if (local_err) {
de3b53f0
KW
2997 goto fail;
2998 }
2999
145f598e
KW
3000 bs->explicit_options = qdict_clone_shallow(options);
3001
f3930ed0 3002 if (child_role) {
bddcec37 3003 bs->inherits_from = parent;
8e2160e2
KW
3004 child_role->inherit_options(&flags, options,
3005 parent->open_flags, parent->options);
f3930ed0
KW
3006 }
3007
de3b53f0 3008 ret = bdrv_fill_options(&options, filename, &flags, &local_err);
462f5bcf
KW
3009 if (local_err) {
3010 goto fail;
3011 }
3012
129c7d1c
MA
3013 /*
3014 * Set the BDRV_O_RDWR and BDRV_O_ALLOW_RDWR flags.
3015 * Caution: getting a boolean member of @options requires care.
3016 * When @options come from -blockdev or blockdev_add, members are
3017 * typed according to the QAPI schema, but when they come from
3018 * -drive, they're all QString.
3019 */
f87a0e29
AG
3020 if (g_strcmp0(qdict_get_try_str(options, BDRV_OPT_READ_ONLY), "on") &&
3021 !qdict_get_try_bool(options, BDRV_OPT_READ_ONLY, false)) {
3022 flags |= (BDRV_O_RDWR | BDRV_O_ALLOW_RDWR);
3023 } else {
3024 flags &= ~BDRV_O_RDWR;
14499ea5
AG
3025 }
3026
3027 if (flags & BDRV_O_SNAPSHOT) {
3028 snapshot_options = qdict_new();
3029 bdrv_temp_snapshot_options(&snapshot_flags, snapshot_options,
3030 flags, options);
f87a0e29
AG
3031 /* Let bdrv_backing_options() override "read-only" */
3032 qdict_del(options, BDRV_OPT_READ_ONLY);
14499ea5
AG
3033 bdrv_backing_options(&flags, options, flags, options);
3034 }
3035
62392ebb
KW
3036 bs->open_flags = flags;
3037 bs->options = options;
3038 options = qdict_clone_shallow(options);
3039
76c591b0 3040 /* Find the right image format driver */
129c7d1c 3041 /* See cautionary note on accessing @options above */
76c591b0
KW
3042 drvname = qdict_get_try_str(options, "driver");
3043 if (drvname) {
3044 drv = bdrv_find_format(drvname);
76c591b0
KW
3045 if (!drv) {
3046 error_setg(errp, "Unknown driver: '%s'", drvname);
76c591b0
KW
3047 goto fail;
3048 }
3049 }
3050
3051 assert(drvname || !(flags & BDRV_O_PROTOCOL));
76c591b0 3052
129c7d1c 3053 /* See cautionary note on accessing @options above */
3e8c2e57 3054 backing = qdict_get_try_str(options, "backing");
e59a0cf1
HR
3055 if (qobject_to(QNull, qdict_get(options, "backing")) != NULL ||
3056 (backing && *backing == '\0'))
3057 {
4f7be280
HR
3058 if (backing) {
3059 warn_report("Use of \"backing\": \"\" is deprecated; "
3060 "use \"backing\": null instead");
3061 }
3e8c2e57 3062 flags |= BDRV_O_NO_BACKING;
ae0f57f0
KW
3063 qdict_del(bs->explicit_options, "backing");
3064 qdict_del(bs->options, "backing");
3e8c2e57
AG
3065 qdict_del(options, "backing");
3066 }
3067
5696c6e3 3068 /* Open image file without format layer. This BlockBackend is only used for
4e4bf5c4
KW
3069 * probing, the block drivers will do their own bdrv_open_child() for the
3070 * same BDS, which is why we put the node name back into options. */
f4788adc 3071 if ((flags & BDRV_O_PROTOCOL) == 0) {
5696c6e3
KW
3072 BlockDriverState *file_bs;
3073
3074 file_bs = bdrv_open_child_bs(filename, options, "file", bs,
3075 &child_file, true, &local_err);
1fdd6933 3076 if (local_err) {
f4788adc
KW
3077 goto fail;
3078 }
5696c6e3 3079 if (file_bs != NULL) {
dacaa162
KW
3080 /* Not requesting BLK_PERM_CONSISTENT_READ because we're only
3081 * looking at the header to guess the image format. This works even
3082 * in cases where a guest would not see a consistent state. */
d861ab3a 3083 file = blk_new(bdrv_get_aio_context(file_bs), 0, BLK_PERM_ALL);
d7086422 3084 blk_insert_bs(file, file_bs, &local_err);
5696c6e3 3085 bdrv_unref(file_bs);
d7086422
KW
3086 if (local_err) {
3087 goto fail;
3088 }
5696c6e3 3089
46f5ac20 3090 qdict_put_str(options, "file", bdrv_get_node_name(file_bs));
4e4bf5c4 3091 }
f500a6d3
KW
3092 }
3093
76c591b0 3094 /* Image format probing */
38f3ef57 3095 bs->probed = !drv;
76c591b0 3096 if (!drv && file) {
cf2ab8fc 3097 ret = find_image_format(file, filename, &drv, &local_err);
17b005f1 3098 if (ret < 0) {
8bfea15d 3099 goto fail;
2a05cbe4 3100 }
62392ebb
KW
3101 /*
3102 * This option update would logically belong in bdrv_fill_options(),
3103 * but we first need to open bs->file for the probing to work, while
3104 * opening bs->file already requires the (mostly) final set of options
3105 * so that cache mode etc. can be inherited.
3106 *
3107 * Adding the driver later is somewhat ugly, but it's not an option
3108 * that would ever be inherited, so it's correct. We just need to make
3109 * sure to update both bs->options (which has the full effective
3110 * options for bs) and options (which has file.* already removed).
3111 */
46f5ac20
EB
3112 qdict_put_str(bs->options, "driver", drv->format_name);
3113 qdict_put_str(options, "driver", drv->format_name);
76c591b0 3114 } else if (!drv) {
17b005f1 3115 error_setg(errp, "Must specify either driver or file");
8bfea15d 3116 goto fail;
ea2384d3 3117 }
b6ce07aa 3118
53a29513
HR
3119 /* BDRV_O_PROTOCOL must be set iff a protocol BDS is about to be created */
3120 assert(!!(flags & BDRV_O_PROTOCOL) == !!drv->bdrv_file_open);
3121 /* file must be NULL if a protocol BDS is about to be created
3122 * (the inverse results in an error message from bdrv_open_common()) */
3123 assert(!(flags & BDRV_O_PROTOCOL) || !file);
3124
b6ce07aa 3125 /* Open the image */
82dc8b41 3126 ret = bdrv_open_common(bs, file, options, &local_err);
b6ce07aa 3127 if (ret < 0) {
8bfea15d 3128 goto fail;
6987307c
CH
3129 }
3130
4e4bf5c4 3131 if (file) {
5696c6e3 3132 blk_unref(file);
f500a6d3
KW
3133 file = NULL;
3134 }
3135
b6ce07aa 3136 /* If there is a backing file, use it */
9156df12 3137 if ((flags & BDRV_O_NO_BACKING) == 0) {
d9b7b057 3138 ret = bdrv_open_backing_file(bs, options, "backing", &local_err);
b6ce07aa 3139 if (ret < 0) {
b6ad491a 3140 goto close_and_fail;
b6ce07aa 3141 }
b6ce07aa
KW
3142 }
3143
50196d7a
AG
3144 /* Remove all children options and references
3145 * from bs->options and bs->explicit_options */
2f624b80
AG
3146 QLIST_FOREACH(child, &bs->children, next) {
3147 char *child_key_dot;
3148 child_key_dot = g_strdup_printf("%s.", child->name);
3149 qdict_extract_subqdict(bs->explicit_options, NULL, child_key_dot);
3150 qdict_extract_subqdict(bs->options, NULL, child_key_dot);
50196d7a
AG
3151 qdict_del(bs->explicit_options, child->name);
3152 qdict_del(bs->options, child->name);
2f624b80
AG
3153 g_free(child_key_dot);
3154 }
3155
b6ad491a 3156 /* Check if any unknown options were used */
7ad2757f 3157 if (qdict_size(options) != 0) {
b6ad491a 3158 const QDictEntry *entry = qdict_first(options);
5acd9d81
HR
3159 if (flags & BDRV_O_PROTOCOL) {
3160 error_setg(errp, "Block protocol '%s' doesn't support the option "
3161 "'%s'", drv->format_name, entry->key);
3162 } else {
d0e46a55
HR
3163 error_setg(errp,
3164 "Block format '%s' does not support the option '%s'",
3165 drv->format_name, entry->key);
5acd9d81 3166 }
b6ad491a 3167
b6ad491a
KW
3168 goto close_and_fail;
3169 }
b6ad491a 3170
c01c214b 3171 bdrv_parent_cb_change_media(bs, true);
b6ce07aa 3172
cb3e7f08 3173 qobject_unref(options);
8961be33 3174 options = NULL;
dd62f1ca
KW
3175
3176 /* For snapshot=on, create a temporary qcow2 overlay. bs points to the
3177 * temporary snapshot afterwards. */
3178 if (snapshot_flags) {
66836189
HR
3179 BlockDriverState *snapshot_bs;
3180 snapshot_bs = bdrv_append_temp_snapshot(bs, snapshot_flags,
3181 snapshot_options, &local_err);
73176bee 3182 snapshot_options = NULL;
dd62f1ca
KW
3183 if (local_err) {
3184 goto close_and_fail;
3185 }
5b363937
HR
3186 /* We are not going to return bs but the overlay on top of it
3187 * (snapshot_bs); thus, we have to drop the strong reference to bs
3188 * (which we obtained by calling bdrv_new()). bs will not be deleted,
3189 * though, because the overlay still has a reference to it. */
3190 bdrv_unref(bs);
3191 bs = snapshot_bs;
dd62f1ca
KW
3192 }
3193
5b363937 3194 return bs;
b6ce07aa 3195
8bfea15d 3196fail:
5696c6e3 3197 blk_unref(file);
cb3e7f08
MAL
3198 qobject_unref(snapshot_options);
3199 qobject_unref(bs->explicit_options);
3200 qobject_unref(bs->options);
3201 qobject_unref(options);
de9c0cec 3202 bs->options = NULL;
998cbd6a 3203 bs->explicit_options = NULL;
5b363937 3204 bdrv_unref(bs);
621ff94d 3205 error_propagate(errp, local_err);
5b363937 3206 return NULL;
de9c0cec 3207
b6ad491a 3208close_and_fail:
5b363937 3209 bdrv_unref(bs);
cb3e7f08
MAL
3210 qobject_unref(snapshot_options);
3211 qobject_unref(options);
621ff94d 3212 error_propagate(errp, local_err);
5b363937 3213 return NULL;
b6ce07aa
KW
3214}
3215
5b363937
HR
3216BlockDriverState *bdrv_open(const char *filename, const char *reference,
3217 QDict *options, int flags, Error **errp)
f3930ed0 3218{
5b363937 3219 return bdrv_open_inherit(filename, reference, options, flags, NULL,
ce343771 3220 NULL, errp);
f3930ed0
KW
3221}
3222
faf116b4
AG
3223/* Return true if the NULL-terminated @list contains @str */
3224static bool is_str_in_list(const char *str, const char *const *list)
3225{
3226 if (str && list) {
3227 int i;
3228 for (i = 0; list[i] != NULL; i++) {
3229 if (!strcmp(str, list[i])) {
3230 return true;
3231 }
3232 }
3233 }
3234 return false;
3235}
3236
3237/*
3238 * Check that every option set in @bs->options is also set in
3239 * @new_opts.
3240 *
3241 * Options listed in the common_options list and in
3242 * @bs->drv->mutable_opts are skipped.
3243 *
3244 * Return 0 on success, otherwise return -EINVAL and set @errp.
3245 */
3246static int bdrv_reset_options_allowed(BlockDriverState *bs,
3247 const QDict *new_opts, Error **errp)
3248{
3249 const QDictEntry *e;
3250 /* These options are common to all block drivers and are handled
3251 * in bdrv_reopen_prepare() so they can be left out of @new_opts */
3252 const char *const common_options[] = {
3253 "node-name", "discard", "cache.direct", "cache.no-flush",
3254 "read-only", "auto-read-only", "detect-zeroes", NULL
3255 };
3256
3257 for (e = qdict_first(bs->options); e; e = qdict_next(bs->options, e)) {
3258 if (!qdict_haskey(new_opts, e->key) &&
3259 !is_str_in_list(e->key, common_options) &&
3260 !is_str_in_list(e->key, bs->drv->mutable_opts)) {
3261 error_setg(errp, "Option '%s' cannot be reset "
3262 "to its default value", e->key);
3263 return -EINVAL;
3264 }
3265 }
3266
3267 return 0;
3268}
3269
cb828c31
AG
3270/*
3271 * Returns true if @child can be reached recursively from @bs
3272 */
3273static bool bdrv_recurse_has_child(BlockDriverState *bs,
3274 BlockDriverState *child)
3275{
3276 BdrvChild *c;
3277
3278 if (bs == child) {
3279 return true;
3280 }
3281
3282 QLIST_FOREACH(c, &bs->children, next) {
3283 if (bdrv_recurse_has_child(c->bs, child)) {
3284 return true;
3285 }
3286 }
3287
3288 return false;
3289}
3290
e971aa12
JC
3291/*
3292 * Adds a BlockDriverState to a simple queue for an atomic, transactional
3293 * reopen of multiple devices.
3294 *
859443b0 3295 * bs_queue can either be an existing BlockReopenQueue that has had QTAILQ_INIT
e971aa12
JC
3296 * already performed, or alternatively may be NULL a new BlockReopenQueue will
3297 * be created and initialized. This newly created BlockReopenQueue should be
3298 * passed back in for subsequent calls that are intended to be of the same
3299 * atomic 'set'.
3300 *
3301 * bs is the BlockDriverState to add to the reopen queue.
3302 *
4d2cb092
KW
3303 * options contains the changed options for the associated bs
3304 * (the BlockReopenQueue takes ownership)
3305 *
e971aa12
JC
3306 * flags contains the open flags for the associated bs
3307 *
3308 * returns a pointer to bs_queue, which is either the newly allocated
3309 * bs_queue, or the existing bs_queue being used.
3310 *
1a63a907 3311 * bs must be drained between bdrv_reopen_queue() and bdrv_reopen_multiple().
e971aa12 3312 */
28518102
KW
3313static BlockReopenQueue *bdrv_reopen_queue_child(BlockReopenQueue *bs_queue,
3314 BlockDriverState *bs,
3315 QDict *options,
28518102
KW
3316 const BdrvChildRole *role,
3317 QDict *parent_options,
077e8e20
AG
3318 int parent_flags,
3319 bool keep_old_opts)
e971aa12
JC
3320{
3321 assert(bs != NULL);
3322
3323 BlockReopenQueueEntry *bs_entry;
67251a31 3324 BdrvChild *child;
9aa09ddd
AG
3325 QDict *old_options, *explicit_options, *options_copy;
3326 int flags;
3327 QemuOpts *opts;
67251a31 3328
1a63a907
KW
3329 /* Make sure that the caller remembered to use a drained section. This is
3330 * important to avoid graph changes between the recursive queuing here and
3331 * bdrv_reopen_multiple(). */
3332 assert(bs->quiesce_counter > 0);
3333
e971aa12
JC
3334 if (bs_queue == NULL) {
3335 bs_queue = g_new0(BlockReopenQueue, 1);
859443b0 3336 QTAILQ_INIT(bs_queue);
e971aa12
JC
3337 }
3338
4d2cb092
KW
3339 if (!options) {
3340 options = qdict_new();
3341 }
3342
5b7ba05f 3343 /* Check if this BlockDriverState is already in the queue */
859443b0 3344 QTAILQ_FOREACH(bs_entry, bs_queue, entry) {
5b7ba05f
AG
3345 if (bs == bs_entry->state.bs) {
3346 break;
3347 }
3348 }
3349
28518102
KW
3350 /*
3351 * Precedence of options:
3352 * 1. Explicitly passed in options (highest)
9aa09ddd
AG
3353 * 2. Retained from explicitly set options of bs
3354 * 3. Inherited from parent node
3355 * 4. Retained from effective options of bs
28518102
KW
3356 */
3357
145f598e 3358 /* Old explicitly set values (don't overwrite by inherited value) */
077e8e20
AG
3359 if (bs_entry || keep_old_opts) {
3360 old_options = qdict_clone_shallow(bs_entry ?
3361 bs_entry->state.explicit_options :
3362 bs->explicit_options);
3363 bdrv_join_options(bs, options, old_options);
3364 qobject_unref(old_options);
5b7ba05f 3365 }
145f598e
KW
3366
3367 explicit_options = qdict_clone_shallow(options);
3368
28518102
KW
3369 /* Inherit from parent node */
3370 if (parent_options) {
9aa09ddd 3371 flags = 0;
8e2160e2 3372 role->inherit_options(&flags, options, parent_flags, parent_options);
9aa09ddd
AG
3373 } else {
3374 flags = bdrv_get_flags(bs);
28518102
KW
3375 }
3376
077e8e20
AG
3377 if (keep_old_opts) {
3378 /* Old values are used for options that aren't set yet */
3379 old_options = qdict_clone_shallow(bs->options);
3380 bdrv_join_options(bs, options, old_options);
3381 qobject_unref(old_options);
3382 }
4d2cb092 3383
9aa09ddd
AG
3384 /* We have the final set of options so let's update the flags */
3385 options_copy = qdict_clone_shallow(options);
3386 opts = qemu_opts_create(&bdrv_runtime_opts, NULL, 0, &error_abort);
3387 qemu_opts_absorb_qdict(opts, options_copy, NULL);
3388 update_flags_from_options(&flags, opts);
3389 qemu_opts_del(opts);
3390 qobject_unref(options_copy);
3391
fd452021 3392 /* bdrv_open_inherit() sets and clears some additional flags internally */
f1f25a2e 3393 flags &= ~BDRV_O_PROTOCOL;
fd452021
KW
3394 if (flags & BDRV_O_RDWR) {
3395 flags |= BDRV_O_ALLOW_RDWR;
3396 }
f1f25a2e 3397
1857c97b
KW
3398 if (!bs_entry) {
3399 bs_entry = g_new0(BlockReopenQueueEntry, 1);
859443b0 3400 QTAILQ_INSERT_TAIL(bs_queue, bs_entry, entry);
1857c97b 3401 } else {
cb3e7f08
MAL
3402 qobject_unref(bs_entry->state.options);
3403 qobject_unref(bs_entry->state.explicit_options);
1857c97b
KW
3404 }
3405
3406 bs_entry->state.bs = bs;
3407 bs_entry->state.options = options;
3408 bs_entry->state.explicit_options = explicit_options;
3409 bs_entry->state.flags = flags;
3410
30450259
KW
3411 /* This needs to be overwritten in bdrv_reopen_prepare() */
3412 bs_entry->state.perm = UINT64_MAX;
3413 bs_entry->state.shared_perm = 0;
3414
8546632e
AG
3415 /*
3416 * If keep_old_opts is false then it means that unspecified
3417 * options must be reset to their original value. We don't allow
3418 * resetting 'backing' but we need to know if the option is
3419 * missing in order to decide if we have to return an error.
3420 */
3421 if (!keep_old_opts) {
3422 bs_entry->state.backing_missing =
3423 !qdict_haskey(options, "backing") &&
3424 !qdict_haskey(options, "backing.driver");
3425 }
3426
67251a31 3427 QLIST_FOREACH(child, &bs->children, next) {
8546632e
AG
3428 QDict *new_child_options = NULL;
3429 bool child_keep_old = keep_old_opts;
67251a31 3430
4c9dfe5d
KW
3431 /* reopen can only change the options of block devices that were
3432 * implicitly created and inherited options. For other (referenced)
3433 * block devices, a syntax like "backing.foo" results in an error. */
67251a31
KW
3434 if (child->bs->inherits_from != bs) {
3435 continue;
3436 }
3437
8546632e
AG
3438 /* Check if the options contain a child reference */
3439 if (qdict_haskey(options, child->name)) {
3440 const char *childref = qdict_get_try_str(options, child->name);
3441 /*
3442 * The current child must not be reopened if the child
3443 * reference is null or points to a different node.
3444 */
3445 if (g_strcmp0(childref, child->bs->node_name)) {
3446 continue;
3447 }
3448 /*
3449 * If the child reference points to the current child then
3450 * reopen it with its existing set of options (note that
3451 * it can still inherit new options from the parent).
3452 */
3453 child_keep_old = true;
3454 } else {
3455 /* Extract child options ("child-name.*") */
3456 char *child_key_dot = g_strdup_printf("%s.", child->name);
3457 qdict_extract_subqdict(explicit_options, NULL, child_key_dot);
3458 qdict_extract_subqdict(options, &new_child_options, child_key_dot);
3459 g_free(child_key_dot);
3460 }
4c9dfe5d 3461
9aa09ddd 3462 bdrv_reopen_queue_child(bs_queue, child->bs, new_child_options,
8546632e 3463 child->role, options, flags, child_keep_old);
e971aa12
JC
3464 }
3465
e971aa12
JC
3466 return bs_queue;
3467}
3468
28518102
KW
3469BlockReopenQueue *bdrv_reopen_queue(BlockReopenQueue *bs_queue,
3470 BlockDriverState *bs,
077e8e20 3471 QDict *options, bool keep_old_opts)
28518102 3472{
077e8e20
AG
3473 return bdrv_reopen_queue_child(bs_queue, bs, options, NULL, NULL, 0,
3474 keep_old_opts);
28518102
KW
3475}
3476
e971aa12
JC
3477/*
3478 * Reopen multiple BlockDriverStates atomically & transactionally.
3479 *
3480 * The queue passed in (bs_queue) must have been built up previous
3481 * via bdrv_reopen_queue().
3482 *
3483 * Reopens all BDS specified in the queue, with the appropriate
3484 * flags. All devices are prepared for reopen, and failure of any
50d6a8a3 3485 * device will cause all device changes to be abandoned, and intermediate
e971aa12
JC
3486 * data cleaned up.
3487 *
3488 * If all devices prepare successfully, then the changes are committed
3489 * to all devices.
3490 *
1a63a907
KW
3491 * All affected nodes must be drained between bdrv_reopen_queue() and
3492 * bdrv_reopen_multiple().
e971aa12 3493 */
5019aece 3494int bdrv_reopen_multiple(BlockReopenQueue *bs_queue, Error **errp)
e971aa12
JC
3495{
3496 int ret = -1;
3497 BlockReopenQueueEntry *bs_entry, *next;
e971aa12
JC
3498
3499 assert(bs_queue != NULL);
3500
859443b0 3501 QTAILQ_FOREACH(bs_entry, bs_queue, entry) {
1a63a907 3502 assert(bs_entry->state.bs->quiesce_counter > 0);
a4615ab3 3503 if (bdrv_reopen_prepare(&bs_entry->state, bs_queue, errp)) {
e971aa12
JC
3504 goto cleanup;
3505 }
3506 bs_entry->prepared = true;
3507 }
3508
859443b0 3509 QTAILQ_FOREACH(bs_entry, bs_queue, entry) {
69b736e7
KW
3510 BDRVReopenState *state = &bs_entry->state;
3511 ret = bdrv_check_perm(state->bs, bs_queue, state->perm,
9eab1544 3512 state->shared_perm, NULL, NULL, errp);
69b736e7
KW
3513 if (ret < 0) {
3514 goto cleanup_perm;
3515 }
cb828c31
AG
3516 /* Check if new_backing_bs would accept the new permissions */
3517 if (state->replace_backing_bs && state->new_backing_bs) {
3518 uint64_t nperm, nshared;
3519 bdrv_child_perm(state->bs, state->new_backing_bs,
3520 NULL, &child_backing, bs_queue,
3521 state->perm, state->shared_perm,
3522 &nperm, &nshared);
3523 ret = bdrv_check_update_perm(state->new_backing_bs, NULL,
9eab1544 3524 nperm, nshared, NULL, NULL, errp);
cb828c31
AG
3525 if (ret < 0) {
3526 goto cleanup_perm;
3527 }
3528 }
69b736e7
KW
3529 bs_entry->perms_checked = true;
3530 }
3531
fcd6a4f4
VSO
3532 /*
3533 * If we reach this point, we have success and just need to apply the
3534 * changes.
3535 *
3536 * Reverse order is used to comfort qcow2 driver: on commit it need to write
3537 * IN_USE flag to the image, to mark bitmaps in the image as invalid. But
3538 * children are usually goes after parents in reopen-queue, so go from last
3539 * to first element.
e971aa12 3540 */
fcd6a4f4 3541 QTAILQ_FOREACH_REVERSE(bs_entry, bs_queue, entry) {
e971aa12
JC
3542 bdrv_reopen_commit(&bs_entry->state);
3543 }
3544
3545 ret = 0;
69b736e7 3546cleanup_perm:
859443b0 3547 QTAILQ_FOREACH_SAFE(bs_entry, bs_queue, entry, next) {
69b736e7
KW
3548 BDRVReopenState *state = &bs_entry->state;
3549
3550 if (!bs_entry->perms_checked) {
3551 continue;
3552 }
e971aa12 3553
69b736e7
KW
3554 if (ret == 0) {
3555 bdrv_set_perm(state->bs, state->perm, state->shared_perm);
3556 } else {
3557 bdrv_abort_perm_update(state->bs);
cb828c31
AG
3558 if (state->replace_backing_bs && state->new_backing_bs) {
3559 bdrv_abort_perm_update(state->new_backing_bs);
3560 }
69b736e7
KW
3561 }
3562 }
e971aa12 3563cleanup:
859443b0 3564 QTAILQ_FOREACH_SAFE(bs_entry, bs_queue, entry, next) {
1bab38e7
AG
3565 if (ret) {
3566 if (bs_entry->prepared) {
3567 bdrv_reopen_abort(&bs_entry->state);
3568 }
cb3e7f08 3569 qobject_unref(bs_entry->state.explicit_options);
4c8350fe 3570 qobject_unref(bs_entry->state.options);
e971aa12 3571 }
cb828c31
AG
3572 if (bs_entry->state.new_backing_bs) {
3573 bdrv_unref(bs_entry->state.new_backing_bs);
3574 }
e971aa12
JC
3575 g_free(bs_entry);
3576 }
3577 g_free(bs_queue);
40840e41 3578
e971aa12
JC
3579 return ret;
3580}
3581
6e1000a8
AG
3582int bdrv_reopen_set_read_only(BlockDriverState *bs, bool read_only,
3583 Error **errp)
3584{
3585 int ret;
3586 BlockReopenQueue *queue;
3587 QDict *opts = qdict_new();
3588
3589 qdict_put_bool(opts, BDRV_OPT_READ_ONLY, read_only);
3590
3591 bdrv_subtree_drained_begin(bs);
077e8e20 3592 queue = bdrv_reopen_queue(NULL, bs, opts, true);
5019aece 3593 ret = bdrv_reopen_multiple(queue, errp);
6e1000a8
AG
3594 bdrv_subtree_drained_end(bs);
3595
3596 return ret;
3597}
3598
30450259
KW
3599static BlockReopenQueueEntry *find_parent_in_reopen_queue(BlockReopenQueue *q,
3600 BdrvChild *c)
3601{
3602 BlockReopenQueueEntry *entry;
3603
859443b0 3604 QTAILQ_FOREACH(entry, q, entry) {
30450259
KW
3605 BlockDriverState *bs = entry->state.bs;
3606 BdrvChild *child;
3607
3608 QLIST_FOREACH(child, &bs->children, next) {
3609 if (child == c) {
3610 return entry;
3611 }
3612 }
3613 }
3614
3615 return NULL;
3616}
3617
3618static void bdrv_reopen_perm(BlockReopenQueue *q, BlockDriverState *bs,
3619 uint64_t *perm, uint64_t *shared)
3620{
3621 BdrvChild *c;
3622 BlockReopenQueueEntry *parent;
3623 uint64_t cumulative_perms = 0;
3624 uint64_t cumulative_shared_perms = BLK_PERM_ALL;
3625
3626 QLIST_FOREACH(c, &bs->parents, next_parent) {
3627 parent = find_parent_in_reopen_queue(q, c);
3628 if (!parent) {
3629 cumulative_perms |= c->perm;
3630 cumulative_shared_perms &= c->shared_perm;
3631 } else {
3632 uint64_t nperm, nshared;
3633
3634 bdrv_child_perm(parent->state.bs, bs, c, c->role, q,
3635 parent->state.perm, parent->state.shared_perm,
3636 &nperm, &nshared);
3637
3638 cumulative_perms |= nperm;
3639 cumulative_shared_perms &= nshared;
3640 }
3641 }
3642 *perm = cumulative_perms;
3643 *shared = cumulative_shared_perms;
3644}
e971aa12 3645
cb828c31
AG
3646/*
3647 * Take a BDRVReopenState and check if the value of 'backing' in the
3648 * reopen_state->options QDict is valid or not.
3649 *
3650 * If 'backing' is missing from the QDict then return 0.
3651 *
3652 * If 'backing' contains the node name of the backing file of
3653 * reopen_state->bs then return 0.
3654 *
3655 * If 'backing' contains a different node name (or is null) then check
3656 * whether the current backing file can be replaced with the new one.
3657 * If that's the case then reopen_state->replace_backing_bs is set to
3658 * true and reopen_state->new_backing_bs contains a pointer to the new
3659 * backing BlockDriverState (or NULL).
3660 *
3661 * Return 0 on success, otherwise return < 0 and set @errp.
3662 */
3663static int bdrv_reopen_parse_backing(BDRVReopenState *reopen_state,
3664 Error **errp)
3665{
3666 BlockDriverState *bs = reopen_state->bs;
3667 BlockDriverState *overlay_bs, *new_backing_bs;
3668 QObject *value;
3669 const char *str;
3670
3671 value = qdict_get(reopen_state->options, "backing");
3672 if (value == NULL) {
3673 return 0;
3674 }
3675
3676 switch (qobject_type(value)) {
3677 case QTYPE_QNULL:
3678 new_backing_bs = NULL;
3679 break;
3680 case QTYPE_QSTRING:
3681 str = qobject_get_try_str(value);
3682 new_backing_bs = bdrv_lookup_bs(NULL, str, errp);
3683 if (new_backing_bs == NULL) {
3684 return -EINVAL;
3685 } else if (bdrv_recurse_has_child(new_backing_bs, bs)) {
3686 error_setg(errp, "Making '%s' a backing file of '%s' "
3687 "would create a cycle", str, bs->node_name);
3688 return -EINVAL;
3689 }
3690 break;
3691 default:
3692 /* 'backing' does not allow any other data type */
3693 g_assert_not_reached();
3694 }
3695
3696 /*
3697 * TODO: before removing the x- prefix from x-blockdev-reopen we
3698 * should move the new backing file into the right AioContext
3699 * instead of returning an error.
3700 */
3701 if (new_backing_bs) {
3702 if (bdrv_get_aio_context(new_backing_bs) != bdrv_get_aio_context(bs)) {
3703 error_setg(errp, "Cannot use a new backing file "
3704 "with a different AioContext");
3705 return -EINVAL;
3706 }
3707 }
3708
3709 /*
3710 * Find the "actual" backing file by skipping all links that point
3711 * to an implicit node, if any (e.g. a commit filter node).
3712 */
3713 overlay_bs = bs;
3714 while (backing_bs(overlay_bs) && backing_bs(overlay_bs)->implicit) {
3715 overlay_bs = backing_bs(overlay_bs);
3716 }
3717
3718 /* If we want to replace the backing file we need some extra checks */
3719 if (new_backing_bs != backing_bs(overlay_bs)) {
3720 /* Check for implicit nodes between bs and its backing file */
3721 if (bs != overlay_bs) {
3722 error_setg(errp, "Cannot change backing link if '%s' has "
3723 "an implicit backing file", bs->node_name);
3724 return -EPERM;
3725 }
3726 /* Check if the backing link that we want to replace is frozen */
3727 if (bdrv_is_backing_chain_frozen(overlay_bs, backing_bs(overlay_bs),
3728 errp)) {
3729 return -EPERM;
3730 }
3731 reopen_state->replace_backing_bs = true;
3732 if (new_backing_bs) {
3733 bdrv_ref(new_backing_bs);
3734 reopen_state->new_backing_bs = new_backing_bs;
3735 }
3736 }
3737
3738 return 0;
3739}
3740
e971aa12
JC
3741/*
3742 * Prepares a BlockDriverState for reopen. All changes are staged in the
3743 * 'opaque' field of the BDRVReopenState, which is used and allocated by
3744 * the block driver layer .bdrv_reopen_prepare()
3745 *
3746 * bs is the BlockDriverState to reopen
3747 * flags are the new open flags
3748 * queue is the reopen queue
3749 *
3750 * Returns 0 on success, non-zero on error. On error errp will be set
3751 * as well.
3752 *
3753 * On failure, bdrv_reopen_abort() will be called to clean up any data.
3754 * It is the responsibility of the caller to then call the abort() or
3755 * commit() for any other BDS that have been left in a prepare() state
3756 *
3757 */
3758int bdrv_reopen_prepare(BDRVReopenState *reopen_state, BlockReopenQueue *queue,
3759 Error **errp)
3760{
3761 int ret = -1;
e6d79c41 3762 int old_flags;
e971aa12
JC
3763 Error *local_err = NULL;
3764 BlockDriver *drv;
ccf9dc07 3765 QemuOpts *opts;
4c8350fe 3766 QDict *orig_reopen_opts;
593b3071 3767 char *discard = NULL;
3d8ce171 3768 bool read_only;
9ad08c44 3769 bool drv_prepared = false;
e971aa12
JC
3770
3771 assert(reopen_state != NULL);
3772 assert(reopen_state->bs->drv != NULL);
3773 drv = reopen_state->bs->drv;
3774
4c8350fe
AG
3775 /* This function and each driver's bdrv_reopen_prepare() remove
3776 * entries from reopen_state->options as they are processed, so
3777 * we need to make a copy of the original QDict. */
3778 orig_reopen_opts = qdict_clone_shallow(reopen_state->options);
3779
ccf9dc07
KW
3780 /* Process generic block layer options */
3781 opts = qemu_opts_create(&bdrv_runtime_opts, NULL, 0, &error_abort);
3782 qemu_opts_absorb_qdict(opts, reopen_state->options, &local_err);
3783 if (local_err) {
3784 error_propagate(errp, local_err);
3785 ret = -EINVAL;
3786 goto error;
3787 }
3788
e6d79c41
AG
3789 /* This was already called in bdrv_reopen_queue_child() so the flags
3790 * are up-to-date. This time we simply want to remove the options from
3791 * QemuOpts in order to indicate that they have been processed. */
3792 old_flags = reopen_state->flags;
91a097e7 3793 update_flags_from_options(&reopen_state->flags, opts);
e6d79c41 3794 assert(old_flags == reopen_state->flags);
91a097e7 3795
415bbca8 3796 discard = qemu_opt_get_del(opts, BDRV_OPT_DISCARD);
593b3071
AG
3797 if (discard != NULL) {
3798 if (bdrv_parse_discard_flags(discard, &reopen_state->flags) != 0) {
3799 error_setg(errp, "Invalid discard option");
3800 ret = -EINVAL;
3801 goto error;
3802 }
3803 }
3804
543770bd
AG
3805 reopen_state->detect_zeroes =
3806 bdrv_parse_detect_zeroes(opts, reopen_state->flags, &local_err);
3807 if (local_err) {
3808 error_propagate(errp, local_err);
3809 ret = -EINVAL;
3810 goto error;
3811 }
3812
57f9db9a
AG
3813 /* All other options (including node-name and driver) must be unchanged.
3814 * Put them back into the QDict, so that they are checked at the end
3815 * of this function. */
3816 qemu_opts_to_qdict(opts, reopen_state->options);
ccf9dc07 3817
3d8ce171
JC
3818 /* If we are to stay read-only, do not allow permission change
3819 * to r/w. Attempting to set to r/w may fail if either BDRV_O_ALLOW_RDWR is
3820 * not set, or if the BDS still has copy_on_read enabled */
3821 read_only = !(reopen_state->flags & BDRV_O_RDWR);
54a32bfe 3822 ret = bdrv_can_set_read_only(reopen_state->bs, read_only, true, &local_err);
3d8ce171
JC
3823 if (local_err) {
3824 error_propagate(errp, local_err);
e971aa12
JC
3825 goto error;
3826 }
3827
30450259
KW
3828 /* Calculate required permissions after reopening */
3829 bdrv_reopen_perm(queue, reopen_state->bs,
3830 &reopen_state->perm, &reopen_state->shared_perm);
e971aa12
JC
3831
3832 ret = bdrv_flush(reopen_state->bs);
3833 if (ret) {
455b0fde 3834 error_setg_errno(errp, -ret, "Error flushing drive");
e971aa12
JC
3835 goto error;
3836 }
3837
3838 if (drv->bdrv_reopen_prepare) {
faf116b4
AG
3839 /*
3840 * If a driver-specific option is missing, it means that we
3841 * should reset it to its default value.
3842 * But not all options allow that, so we need to check it first.
3843 */
3844 ret = bdrv_reset_options_allowed(reopen_state->bs,
3845 reopen_state->options, errp);
3846 if (ret) {
3847 goto error;
3848 }
3849
e971aa12
JC
3850 ret = drv->bdrv_reopen_prepare(reopen_state, queue, &local_err);
3851 if (ret) {
3852 if (local_err != NULL) {
3853 error_propagate(errp, local_err);
3854 } else {
f30c66ba 3855 bdrv_refresh_filename(reopen_state->bs);
d8b6895f
LC
3856 error_setg(errp, "failed while preparing to reopen image '%s'",
3857 reopen_state->bs->filename);
e971aa12
JC
3858 }
3859 goto error;
3860 }
3861 } else {
3862 /* It is currently mandatory to have a bdrv_reopen_prepare()
3863 * handler for each supported drv. */
81e5f78a
AG
3864 error_setg(errp, "Block format '%s' used by node '%s' "
3865 "does not support reopening files", drv->format_name,
3866 bdrv_get_device_or_node_name(reopen_state->bs));
e971aa12
JC
3867 ret = -1;
3868 goto error;
3869 }
3870
9ad08c44
HR
3871 drv_prepared = true;
3872
bacd9b87
AG
3873 /*
3874 * We must provide the 'backing' option if the BDS has a backing
3875 * file or if the image file has a backing file name as part of
3876 * its metadata. Otherwise the 'backing' option can be omitted.
3877 */
3878 if (drv->supports_backing && reopen_state->backing_missing &&
3879 (backing_bs(reopen_state->bs) || reopen_state->bs->backing_file[0])) {
8546632e
AG
3880 error_setg(errp, "backing is missing for '%s'",
3881 reopen_state->bs->node_name);
3882 ret = -EINVAL;
3883 goto error;
3884 }
3885
cb828c31
AG
3886 /*
3887 * Allow changing the 'backing' option. The new value can be
3888 * either a reference to an existing node (using its node name)
3889 * or NULL to simply detach the current backing file.
3890 */
3891 ret = bdrv_reopen_parse_backing(reopen_state, errp);
3892 if (ret < 0) {
3893 goto error;
3894 }
3895 qdict_del(reopen_state->options, "backing");
3896
4d2cb092
KW
3897 /* Options that are not handled are only okay if they are unchanged
3898 * compared to the old state. It is expected that some options are only
3899 * used for the initial open, but not reopen (e.g. filename) */
3900 if (qdict_size(reopen_state->options)) {
3901 const QDictEntry *entry = qdict_first(reopen_state->options);
3902
3903 do {
54fd1b0d
HR
3904 QObject *new = entry->value;
3905 QObject *old = qdict_get(reopen_state->bs->options, entry->key);
3906
db905283
AG
3907 /* Allow child references (child_name=node_name) as long as they
3908 * point to the current child (i.e. everything stays the same). */
3909 if (qobject_type(new) == QTYPE_QSTRING) {
3910 BdrvChild *child;
3911 QLIST_FOREACH(child, &reopen_state->bs->children, next) {
3912 if (!strcmp(child->name, entry->key)) {
3913 break;
3914 }
3915 }
3916
3917 if (child) {
3918 const char *str = qobject_get_try_str(new);
3919 if (!strcmp(child->bs->node_name, str)) {
3920 continue; /* Found child with this name, skip option */
3921 }
3922 }
3923 }
3924
129c7d1c 3925 /*
54fd1b0d
HR
3926 * TODO: When using -drive to specify blockdev options, all values
3927 * will be strings; however, when using -blockdev, blockdev-add or
3928 * filenames using the json:{} pseudo-protocol, they will be
3929 * correctly typed.
3930 * In contrast, reopening options are (currently) always strings
3931 * (because you can only specify them through qemu-io; all other
3932 * callers do not specify any options).
3933 * Therefore, when using anything other than -drive to create a BDS,
3934 * this cannot detect non-string options as unchanged, because
3935 * qobject_is_equal() always returns false for objects of different
3936 * type. In the future, this should be remedied by correctly typing
3937 * all options. For now, this is not too big of an issue because
3938 * the user can simply omit options which cannot be changed anyway,
3939 * so they will stay unchanged.
129c7d1c 3940 */
54fd1b0d 3941 if (!qobject_is_equal(new, old)) {
4d2cb092
KW
3942 error_setg(errp, "Cannot change the option '%s'", entry->key);
3943 ret = -EINVAL;
3944 goto error;
3945 }
3946 } while ((entry = qdict_next(reopen_state->options, entry)));
3947 }
3948
e971aa12
JC
3949 ret = 0;
3950
4c8350fe
AG
3951 /* Restore the original reopen_state->options QDict */
3952 qobject_unref(reopen_state->options);
3953 reopen_state->options = qobject_ref(orig_reopen_opts);
3954
e971aa12 3955error:
9ad08c44
HR
3956 if (ret < 0 && drv_prepared) {
3957 /* drv->bdrv_reopen_prepare() has succeeded, so we need to
3958 * call drv->bdrv_reopen_abort() before signaling an error
3959 * (bdrv_reopen_multiple() will not call bdrv_reopen_abort()
3960 * when the respective bdrv_reopen_prepare() has failed) */
3961 if (drv->bdrv_reopen_abort) {
3962 drv->bdrv_reopen_abort(reopen_state);
3963 }
3964 }
ccf9dc07 3965 qemu_opts_del(opts);
4c8350fe 3966 qobject_unref(orig_reopen_opts);
593b3071 3967 g_free(discard);
e971aa12
JC
3968 return ret;
3969}
3970
3971/*
3972 * Takes the staged changes for the reopen from bdrv_reopen_prepare(), and
3973 * makes them final by swapping the staging BlockDriverState contents into
3974 * the active BlockDriverState contents.
3975 */
3976void bdrv_reopen_commit(BDRVReopenState *reopen_state)
3977{
3978 BlockDriver *drv;
50bf65ba 3979 BlockDriverState *bs;
50196d7a 3980 BdrvChild *child;
e971aa12
JC
3981
3982 assert(reopen_state != NULL);
50bf65ba
VSO
3983 bs = reopen_state->bs;
3984 drv = bs->drv;
e971aa12
JC
3985 assert(drv != NULL);
3986
3987 /* If there are any driver level actions to take */
3988 if (drv->bdrv_reopen_commit) {
3989 drv->bdrv_reopen_commit(reopen_state);
3990 }
3991
3992 /* set BDS specific flags now */
cb3e7f08 3993 qobject_unref(bs->explicit_options);
4c8350fe 3994 qobject_unref(bs->options);
145f598e 3995
50bf65ba 3996 bs->explicit_options = reopen_state->explicit_options;
4c8350fe 3997 bs->options = reopen_state->options;
50bf65ba
VSO
3998 bs->open_flags = reopen_state->flags;
3999 bs->read_only = !(reopen_state->flags & BDRV_O_RDWR);
543770bd 4000 bs->detect_zeroes = reopen_state->detect_zeroes;
355ef4ac 4001
cb828c31
AG
4002 if (reopen_state->replace_backing_bs) {
4003 qdict_del(bs->explicit_options, "backing");
4004 qdict_del(bs->options, "backing");
4005 }
4006
50196d7a
AG
4007 /* Remove child references from bs->options and bs->explicit_options.
4008 * Child options were already removed in bdrv_reopen_queue_child() */
4009 QLIST_FOREACH(child, &bs->children, next) {
4010 qdict_del(bs->explicit_options, child->name);
4011 qdict_del(bs->options, child->name);
4012 }
4013
cb828c31
AG
4014 /*
4015 * Change the backing file if a new one was specified. We do this
4016 * after updating bs->options, so bdrv_refresh_filename() (called
4017 * from bdrv_set_backing_hd()) has the new values.
4018 */
4019 if (reopen_state->replace_backing_bs) {
4020 BlockDriverState *old_backing_bs = backing_bs(bs);
4021 assert(!old_backing_bs || !old_backing_bs->implicit);
4022 /* Abort the permission update on the backing bs we're detaching */
4023 if (old_backing_bs) {
4024 bdrv_abort_perm_update(old_backing_bs);
4025 }
4026 bdrv_set_backing_hd(bs, reopen_state->new_backing_bs, &error_abort);
4027 }
4028
50bf65ba 4029 bdrv_refresh_limits(bs, NULL);
e971aa12
JC
4030}
4031
4032/*
4033 * Abort the reopen, and delete and free the staged changes in
4034 * reopen_state
4035 */
4036void bdrv_reopen_abort(BDRVReopenState *reopen_state)
4037{
4038 BlockDriver *drv;
4039
4040 assert(reopen_state != NULL);
4041 drv = reopen_state->bs->drv;
4042 assert(drv != NULL);
4043
4044 if (drv->bdrv_reopen_abort) {
4045 drv->bdrv_reopen_abort(reopen_state);
4046 }
4047}
4048
4049
64dff520 4050static void bdrv_close(BlockDriverState *bs)
fc01f7e7 4051{
33384421 4052 BdrvAioNotifier *ban, *ban_next;
50a3efb0 4053 BdrvChild *child, *next;
33384421 4054
30f55fb8 4055 assert(!bs->refcnt);
99b7e775 4056
fc27291d 4057 bdrv_drained_begin(bs); /* complete I/O */
58fda173 4058 bdrv_flush(bs);
53ec73e2 4059 bdrv_drain(bs); /* in case flush left pending I/O */
fc27291d 4060
3cbc002c 4061 if (bs->drv) {
3c005293
VSO
4062 if (bs->drv->bdrv_close) {
4063 bs->drv->bdrv_close(bs);
4064 }
9a4f4c31 4065 bs->drv = NULL;
50a3efb0 4066 }
9a7dedbc 4067
50a3efb0 4068 QLIST_FOREACH_SAFE(child, &bs->children, next, next) {
dd4118c7 4069 bdrv_unref_child(bs, child);
b338082b 4070 }
98f90dba 4071
dd4118c7
AG
4072 bs->backing = NULL;
4073 bs->file = NULL;
50a3efb0
AG
4074 g_free(bs->opaque);
4075 bs->opaque = NULL;
4076 atomic_set(&bs->copy_on_read, 0);
4077 bs->backing_file[0] = '\0';
4078 bs->backing_format[0] = '\0';
4079 bs->total_sectors = 0;
4080 bs->encrypted = false;
4081 bs->sg = false;
cb3e7f08
MAL
4082 qobject_unref(bs->options);
4083 qobject_unref(bs->explicit_options);
50a3efb0
AG
4084 bs->options = NULL;
4085 bs->explicit_options = NULL;
cb3e7f08 4086 qobject_unref(bs->full_open_options);
50a3efb0
AG
4087 bs->full_open_options = NULL;
4088
cca43ae1
VSO
4089 bdrv_release_named_dirty_bitmaps(bs);
4090 assert(QLIST_EMPTY(&bs->dirty_bitmaps));
4091
33384421
HR
4092 QLIST_FOREACH_SAFE(ban, &bs->aio_notifiers, list, ban_next) {
4093 g_free(ban);
4094 }
4095 QLIST_INIT(&bs->aio_notifiers);
fc27291d 4096 bdrv_drained_end(bs);
b338082b
FB
4097}
4098
2bc93fed
MK
4099void bdrv_close_all(void)
4100{
b3b5299d 4101 assert(job_next(NULL) == NULL);
cd7fca95 4102 nbd_export_close_all();
ca9bd24c
HR
4103
4104 /* Drop references from requests still in flight, such as canceled block
4105 * jobs whose AIO context has not been polled yet */
4106 bdrv_drain_all();
2bc93fed 4107
ca9bd24c
HR
4108 blk_remove_all_bs();
4109 blockdev_close_all_bdrv_states();
ed78cda3 4110
a1a2af07 4111 assert(QTAILQ_EMPTY(&all_bdrv_states));
2bc93fed
MK
4112}
4113
d0ac0380
KW
4114static bool should_update_child(BdrvChild *c, BlockDriverState *to)
4115{
2f30b7c3
VSO
4116 GQueue *queue;
4117 GHashTable *found;
4118 bool ret;
d0ac0380
KW
4119
4120 if (c->role->stay_at_node) {
4121 return false;
4122 }
4123
ec9f10fe
HR
4124 /* If the child @c belongs to the BDS @to, replacing the current
4125 * c->bs by @to would mean to create a loop.
4126 *
4127 * Such a case occurs when appending a BDS to a backing chain.
4128 * For instance, imagine the following chain:
4129 *
4130 * guest device -> node A -> further backing chain...
4131 *
4132 * Now we create a new BDS B which we want to put on top of this
4133 * chain, so we first attach A as its backing node:
4134 *
4135 * node B
4136 * |
4137 * v
4138 * guest device -> node A -> further backing chain...
4139 *
4140 * Finally we want to replace A by B. When doing that, we want to
4141 * replace all pointers to A by pointers to B -- except for the
4142 * pointer from B because (1) that would create a loop, and (2)
4143 * that pointer should simply stay intact:
4144 *
4145 * guest device -> node B
4146 * |
4147 * v
4148 * node A -> further backing chain...
4149 *
4150 * In general, when replacing a node A (c->bs) by a node B (@to),
4151 * if A is a child of B, that means we cannot replace A by B there
4152 * because that would create a loop. Silently detaching A from B
4153 * is also not really an option. So overall just leaving A in
2f30b7c3
VSO
4154 * place there is the most sensible choice.
4155 *
4156 * We would also create a loop in any cases where @c is only
4157 * indirectly referenced by @to. Prevent this by returning false
4158 * if @c is found (by breadth-first search) anywhere in the whole
4159 * subtree of @to.
4160 */
4161
4162 ret = true;
4163 found = g_hash_table_new(NULL, NULL);
4164 g_hash_table_add(found, to);
4165 queue = g_queue_new();
4166 g_queue_push_tail(queue, to);
4167
4168 while (!g_queue_is_empty(queue)) {
4169 BlockDriverState *v = g_queue_pop_head(queue);
4170 BdrvChild *c2;
4171
4172 QLIST_FOREACH(c2, &v->children, next) {
4173 if (c2 == c) {
4174 ret = false;
4175 break;
4176 }
4177
4178 if (g_hash_table_contains(found, c2->bs)) {
4179 continue;
4180 }
4181
4182 g_queue_push_tail(queue, c2->bs);
4183 g_hash_table_add(found, c2->bs);
d0ac0380
KW
4184 }
4185 }
4186
2f30b7c3
VSO
4187 g_queue_free(queue);
4188 g_hash_table_destroy(found);
4189
4190 return ret;
d0ac0380
KW
4191}
4192
5fe31c25
KW
4193void bdrv_replace_node(BlockDriverState *from, BlockDriverState *to,
4194 Error **errp)
dd62f1ca 4195{
d0ac0380 4196 BdrvChild *c, *next;
234ac1a9 4197 GSList *list = NULL, *p;
234ac1a9
KW
4198 uint64_t perm = 0, shared = BLK_PERM_ALL;
4199 int ret;
4200
4201 /* Make sure that @from doesn't go away until we have successfully attached
4202 * all of its parents to @to. */
4203 bdrv_ref(from);
dd62f1ca 4204
f871abd6
KW
4205 assert(qemu_get_current_aio_context() == qemu_get_aio_context());
4206 bdrv_drained_begin(from);
4207
234ac1a9 4208 /* Put all parents into @list and calculate their cumulative permissions */
dd62f1ca 4209 QLIST_FOREACH_SAFE(c, &from->parents, next_parent, next) {
ec9f10fe 4210 assert(c->bs == from);
d0ac0380 4211 if (!should_update_child(c, to)) {
26de9438
KW
4212 continue;
4213 }
2cad1ebe
AG
4214 if (c->frozen) {
4215 error_setg(errp, "Cannot change '%s' link to '%s'",
4216 c->name, from->node_name);
4217 goto out;
4218 }
234ac1a9
KW
4219 list = g_slist_prepend(list, c);
4220 perm |= c->perm;
4221 shared &= c->shared_perm;
4222 }
4223
4224 /* Check whether the required permissions can be granted on @to, ignoring
4225 * all BdrvChild in @list so that they can't block themselves. */
9eab1544 4226 ret = bdrv_check_update_perm(to, NULL, perm, shared, list, NULL, errp);
234ac1a9
KW
4227 if (ret < 0) {
4228 bdrv_abort_perm_update(to);
4229 goto out;
4230 }
4231
4232 /* Now actually perform the change. We performed the permission check for
4233 * all elements of @list at once, so set the permissions all at once at the
4234 * very end. */
4235 for (p = list; p != NULL; p = p->next) {
4236 c = p->data;
9bd910e2 4237
dd62f1ca 4238 bdrv_ref(to);
234ac1a9 4239 bdrv_replace_child_noperm(c, to);
dd62f1ca
KW
4240 bdrv_unref(from);
4241 }
234ac1a9 4242
b503de61
VSO
4243 bdrv_get_cumulative_perm(to, &perm, &shared);
4244 bdrv_set_perm(to, perm, shared);
234ac1a9
KW
4245
4246out:
4247 g_slist_free(list);
f871abd6 4248 bdrv_drained_end(from);
234ac1a9 4249 bdrv_unref(from);
dd62f1ca
KW
4250}
4251
4ddc07ca
PB
4252/*
4253 * Add new bs contents at the top of an image chain while the chain is
4254 * live, while keeping required fields on the top layer.
4255 *
4256 * This will modify the BlockDriverState fields, and swap contents
4257 * between bs_new and bs_top. Both bs_new and bs_top are modified.
4258 *
bfb197e0 4259 * bs_new must not be attached to a BlockBackend.
4ddc07ca
PB
4260 *
4261 * This function does not create any image files.
dd62f1ca
KW
4262 *
4263 * bdrv_append() takes ownership of a bs_new reference and unrefs it because
4264 * that's what the callers commonly need. bs_new will be referenced by the old
4265 * parents of bs_top after bdrv_append() returns. If the caller needs to keep a
4266 * reference of its own, it must call bdrv_ref().
4ddc07ca 4267 */
b2c2832c
KW
4268void bdrv_append(BlockDriverState *bs_new, BlockDriverState *bs_top,
4269 Error **errp)
4ddc07ca 4270{
b2c2832c
KW
4271 Error *local_err = NULL;
4272
b2c2832c
KW
4273 bdrv_set_backing_hd(bs_new, bs_top, &local_err);
4274 if (local_err) {
4275 error_propagate(errp, local_err);
4276 goto out;
4277 }
dd62f1ca 4278
5fe31c25 4279 bdrv_replace_node(bs_top, bs_new, &local_err);
234ac1a9
KW
4280 if (local_err) {
4281 error_propagate(errp, local_err);
4282 bdrv_set_backing_hd(bs_new, NULL, &error_abort);
4283 goto out;
4284 }
4ddc07ca 4285
dd62f1ca
KW
4286 /* bs_new is now referenced by its new parents, we don't need the
4287 * additional reference any more. */
b2c2832c 4288out:
dd62f1ca 4289 bdrv_unref(bs_new);
8802d1fd
JC
4290}
4291
4f6fd349 4292static void bdrv_delete(BlockDriverState *bs)
b338082b 4293{
3718d8ab 4294 assert(bdrv_op_blocker_is_empty(bs));
4f6fd349 4295 assert(!bs->refcnt);
18846dee 4296
1b7bdbc1 4297 /* remove from list, if necessary */
63eaaae0
KW
4298 if (bs->node_name[0] != '\0') {
4299 QTAILQ_REMOVE(&graph_bdrv_states, bs, node_list);
4300 }
2c1d04e0
HR
4301 QTAILQ_REMOVE(&all_bdrv_states, bs, bs_list);
4302
30c321f9
AK
4303 bdrv_close(bs);
4304
7267c094 4305 g_free(bs);
fc01f7e7
FB
4306}
4307
e97fc193
AL
4308/*
4309 * Run consistency checks on an image
4310 *
e076f338 4311 * Returns 0 if the check could be completed (it doesn't mean that the image is
a1c7273b 4312 * free of errors) or -errno when an internal error occurred. The results of the
e076f338 4313 * check are stored in res.
e97fc193 4314 */
2fd61638
PB
4315static int coroutine_fn bdrv_co_check(BlockDriverState *bs,
4316 BdrvCheckResult *res, BdrvCheckMode fix)
e97fc193 4317{
908bcd54
HR
4318 if (bs->drv == NULL) {
4319 return -ENOMEDIUM;
4320 }
2fd61638 4321 if (bs->drv->bdrv_co_check == NULL) {
e97fc193
AL
4322 return -ENOTSUP;
4323 }
4324
e076f338 4325 memset(res, 0, sizeof(*res));
2fd61638
PB
4326 return bs->drv->bdrv_co_check(bs, res, fix);
4327}
4328
4329typedef struct CheckCo {
4330 BlockDriverState *bs;
4331 BdrvCheckResult *res;
4332 BdrvCheckMode fix;
4333 int ret;
4334} CheckCo;
4335
66a5bdf3 4336static void coroutine_fn bdrv_check_co_entry(void *opaque)
2fd61638
PB
4337{
4338 CheckCo *cco = opaque;
4339 cco->ret = bdrv_co_check(cco->bs, cco->res, cco->fix);
4720cbee 4340 aio_wait_kick();
2fd61638
PB
4341}
4342
4343int bdrv_check(BlockDriverState *bs,
4344 BdrvCheckResult *res, BdrvCheckMode fix)
4345{
4346 Coroutine *co;
4347 CheckCo cco = {
4348 .bs = bs,
4349 .res = res,
4350 .ret = -EINPROGRESS,
4351 .fix = fix,
4352 };
4353
4354 if (qemu_in_coroutine()) {
4355 /* Fast-path if already in coroutine context */
4356 bdrv_check_co_entry(&cco);
4357 } else {
4358 co = qemu_coroutine_create(bdrv_check_co_entry, &cco);
4720cbee 4359 bdrv_coroutine_enter(bs, co);
2fd61638
PB
4360 BDRV_POLL_WHILE(bs, cco.ret == -EINPROGRESS);
4361 }
4362
4363 return cco.ret;
e97fc193
AL
4364}
4365
756e6736
KW
4366/*
4367 * Return values:
4368 * 0 - success
4369 * -EINVAL - backing format specified, but no file
4370 * -ENOSPC - can't update the backing file because no space is left in the
4371 * image file header
4372 * -ENOTSUP - format driver doesn't support changing the backing file
4373 */
4374int bdrv_change_backing_file(BlockDriverState *bs,
4375 const char *backing_file, const char *backing_fmt)
4376{
4377 BlockDriver *drv = bs->drv;
469ef350 4378 int ret;
756e6736 4379
d470ad42
HR
4380 if (!drv) {
4381 return -ENOMEDIUM;
4382 }
4383
5f377794
PB
4384 /* Backing file format doesn't make sense without a backing file */
4385 if (backing_fmt && !backing_file) {
4386 return -EINVAL;
4387 }
4388
756e6736 4389 if (drv->bdrv_change_backing_file != NULL) {
469ef350 4390 ret = drv->bdrv_change_backing_file(bs, backing_file, backing_fmt);
756e6736 4391 } else {
469ef350 4392 ret = -ENOTSUP;
756e6736 4393 }
469ef350
PB
4394
4395 if (ret == 0) {
4396 pstrcpy(bs->backing_file, sizeof(bs->backing_file), backing_file ?: "");
4397 pstrcpy(bs->backing_format, sizeof(bs->backing_format), backing_fmt ?: "");
998c2019
HR
4398 pstrcpy(bs->auto_backing_file, sizeof(bs->auto_backing_file),
4399 backing_file ?: "");
469ef350
PB
4400 }
4401 return ret;
756e6736
KW
4402}
4403
6ebdcee2
JC
4404/*
4405 * Finds the image layer in the chain that has 'bs' as its backing file.
4406 *
4407 * active is the current topmost image.
4408 *
4409 * Returns NULL if bs is not found in active's image chain,
4410 * or if active == bs.
4caf0fcd
JC
4411 *
4412 * Returns the bottommost base image if bs == NULL.
6ebdcee2
JC
4413 */
4414BlockDriverState *bdrv_find_overlay(BlockDriverState *active,
4415 BlockDriverState *bs)
4416{
760e0063
KW
4417 while (active && bs != backing_bs(active)) {
4418 active = backing_bs(active);
6ebdcee2
JC
4419 }
4420
4caf0fcd
JC
4421 return active;
4422}
6ebdcee2 4423
4caf0fcd
JC
4424/* Given a BDS, searches for the base layer. */
4425BlockDriverState *bdrv_find_base(BlockDriverState *bs)
4426{
4427 return bdrv_find_overlay(bs, NULL);
6ebdcee2
JC
4428}
4429
2cad1ebe
AG
4430/*
4431 * Return true if at least one of the backing links between @bs and
4432 * @base is frozen. @errp is set if that's the case.
0f0998f6 4433 * @base must be reachable from @bs, or NULL.
2cad1ebe
AG
4434 */
4435bool bdrv_is_backing_chain_frozen(BlockDriverState *bs, BlockDriverState *base,
4436 Error **errp)
4437{
4438 BlockDriverState *i;
4439
0f0998f6
AG
4440 for (i = bs; i != base; i = backing_bs(i)) {
4441 if (i->backing && i->backing->frozen) {
2cad1ebe
AG
4442 error_setg(errp, "Cannot change '%s' link from '%s' to '%s'",
4443 i->backing->name, i->node_name,
4444 backing_bs(i)->node_name);
4445 return true;
4446 }
4447 }
4448
4449 return false;
4450}
4451
4452/*
4453 * Freeze all backing links between @bs and @base.
4454 * If any of the links is already frozen the operation is aborted and
4455 * none of the links are modified.
0f0998f6 4456 * @base must be reachable from @bs, or NULL.
2cad1ebe
AG
4457 * Returns 0 on success. On failure returns < 0 and sets @errp.
4458 */
4459int bdrv_freeze_backing_chain(BlockDriverState *bs, BlockDriverState *base,
4460 Error **errp)
4461{
4462 BlockDriverState *i;
4463
4464 if (bdrv_is_backing_chain_frozen(bs, base, errp)) {
4465 return -EPERM;
4466 }
4467
e5182c1c
HR
4468 for (i = bs; i != base; i = backing_bs(i)) {
4469 if (i->backing && backing_bs(i)->never_freeze) {
4470 error_setg(errp, "Cannot freeze '%s' link to '%s'",
4471 i->backing->name, backing_bs(i)->node_name);
4472 return -EPERM;
4473 }
4474 }
4475
0f0998f6
AG
4476 for (i = bs; i != base; i = backing_bs(i)) {
4477 if (i->backing) {
4478 i->backing->frozen = true;
4479 }
2cad1ebe
AG
4480 }
4481
4482 return 0;
4483}
4484
4485/*
4486 * Unfreeze all backing links between @bs and @base. The caller must
4487 * ensure that all links are frozen before using this function.
0f0998f6 4488 * @base must be reachable from @bs, or NULL.
2cad1ebe
AG
4489 */
4490void bdrv_unfreeze_backing_chain(BlockDriverState *bs, BlockDriverState *base)
4491{
4492 BlockDriverState *i;
4493
0f0998f6
AG
4494 for (i = bs; i != base; i = backing_bs(i)) {
4495 if (i->backing) {
4496 assert(i->backing->frozen);
4497 i->backing->frozen = false;
4498 }
2cad1ebe
AG
4499 }
4500}
4501
6ebdcee2
JC
4502/*
4503 * Drops images above 'base' up to and including 'top', and sets the image
4504 * above 'top' to have base as its backing file.
4505 *
4506 * Requires that the overlay to 'top' is opened r/w, so that the backing file
4507 * information in 'bs' can be properly updated.
4508 *
4509 * E.g., this will convert the following chain:
4510 * bottom <- base <- intermediate <- top <- active
4511 *
4512 * to
4513 *
4514 * bottom <- base <- active
4515 *
4516 * It is allowed for bottom==base, in which case it converts:
4517 *
4518 * base <- intermediate <- top <- active
4519 *
4520 * to
4521 *
4522 * base <- active
4523 *
54e26900
JC
4524 * If backing_file_str is non-NULL, it will be used when modifying top's
4525 * overlay image metadata.
4526 *
6ebdcee2
JC
4527 * Error conditions:
4528 * if active == top, that is considered an error
4529 *
4530 */
bde70715
KW
4531int bdrv_drop_intermediate(BlockDriverState *top, BlockDriverState *base,
4532 const char *backing_file_str)
6ebdcee2 4533{
6bd858b3
AG
4534 BlockDriverState *explicit_top = top;
4535 bool update_inherits_from;
61f09cea 4536 BdrvChild *c, *next;
12fa4af6 4537 Error *local_err = NULL;
6ebdcee2
JC
4538 int ret = -EIO;
4539
6858eba0 4540 bdrv_ref(top);
637d54a5 4541 bdrv_subtree_drained_begin(top);
6858eba0 4542
6ebdcee2
JC
4543 if (!top->drv || !base->drv) {
4544 goto exit;
4545 }
4546
5db15a57
KW
4547 /* Make sure that base is in the backing chain of top */
4548 if (!bdrv_chain_contains(top, base)) {
6ebdcee2
JC
4549 goto exit;
4550 }
4551
2cad1ebe
AG
4552 /* This function changes all links that point to top and makes
4553 * them point to base. Check that none of them is frozen. */
4554 QLIST_FOREACH(c, &top->parents, next_parent) {
4555 if (c->frozen) {
4556 goto exit;
4557 }
4558 }
4559
6bd858b3
AG
4560 /* If 'base' recursively inherits from 'top' then we should set
4561 * base->inherits_from to top->inherits_from after 'top' and all
4562 * other intermediate nodes have been dropped.
4563 * If 'top' is an implicit node (e.g. "commit_top") we should skip
4564 * it because no one inherits from it. We use explicit_top for that. */
4565 while (explicit_top && explicit_top->implicit) {
4566 explicit_top = backing_bs(explicit_top);
4567 }
4568 update_inherits_from = bdrv_inherits_from_recursive(base, explicit_top);
4569
6ebdcee2 4570 /* success - we can delete the intermediate states, and link top->base */
bde70715
KW
4571 /* TODO Check graph modification op blockers (BLK_PERM_GRAPH_MOD) once
4572 * we've figured out how they should work. */
f30c66ba
HR
4573 if (!backing_file_str) {
4574 bdrv_refresh_filename(base);
4575 backing_file_str = base->filename;
4576 }
61f09cea
KW
4577
4578 QLIST_FOREACH_SAFE(c, &top->parents, next_parent, next) {
4579 /* Check whether we are allowed to switch c from top to base */
4580 GSList *ignore_children = g_slist_prepend(NULL, c);
2345bde6 4581 ret = bdrv_check_update_perm(base, NULL, c->perm, c->shared_perm,
9eab1544 4582 ignore_children, NULL, &local_err);
2c860e79 4583 g_slist_free(ignore_children);
2345bde6 4584 if (ret < 0) {
61f09cea 4585 error_report_err(local_err);
6858eba0
KW
4586 goto exit;
4587 }
12fa4af6 4588
61f09cea
KW
4589 /* If so, update the backing file path in the image file */
4590 if (c->role->update_filename) {
4591 ret = c->role->update_filename(c, base, backing_file_str,
4592 &local_err);
4593 if (ret < 0) {
4594 bdrv_abort_perm_update(base);
4595 error_report_err(local_err);
4596 goto exit;
4597 }
4598 }
4599
4600 /* Do the actual switch in the in-memory graph.
4601 * Completes bdrv_check_update_perm() transaction internally. */
4602 bdrv_ref(base);
4603 bdrv_replace_child(c, base);
4604 bdrv_unref(top);
12fa4af6 4605 }
6ebdcee2 4606
6bd858b3
AG
4607 if (update_inherits_from) {
4608 base->inherits_from = explicit_top->inherits_from;
4609 }
4610
6ebdcee2 4611 ret = 0;
6ebdcee2 4612exit:
637d54a5 4613 bdrv_subtree_drained_end(top);
6858eba0 4614 bdrv_unref(top);
6ebdcee2
JC
4615 return ret;
4616}
4617
61007b31
SH
4618/**
4619 * Length of a allocated file in bytes. Sparse files are counted by actual
4620 * allocated space. Return < 0 if error or unknown.
4621 */
4622int64_t bdrv_get_allocated_file_size(BlockDriverState *bs)
71d0770c 4623{
61007b31
SH
4624 BlockDriver *drv = bs->drv;
4625 if (!drv) {
4626 return -ENOMEDIUM;
8f4754ed 4627 }
61007b31
SH
4628 if (drv->bdrv_get_allocated_file_size) {
4629 return drv->bdrv_get_allocated_file_size(bs);
4630 }
4631 if (bs->file) {
9a4f4c31 4632 return bdrv_get_allocated_file_size(bs->file->bs);
1c9805a3 4633 }
61007b31 4634 return -ENOTSUP;
1c9805a3 4635}
e7a8a783 4636
90880ff1
SH
4637/*
4638 * bdrv_measure:
4639 * @drv: Format driver
4640 * @opts: Creation options for new image
4641 * @in_bs: Existing image containing data for new image (may be NULL)
4642 * @errp: Error object
4643 * Returns: A #BlockMeasureInfo (free using qapi_free_BlockMeasureInfo())
4644 * or NULL on error
4645 *
4646 * Calculate file size required to create a new image.
4647 *
4648 * If @in_bs is given then space for allocated clusters and zero clusters
4649 * from that image are included in the calculation. If @opts contains a
4650 * backing file that is shared by @in_bs then backing clusters may be omitted
4651 * from the calculation.
4652 *
4653 * If @in_bs is NULL then the calculation includes no allocated clusters
4654 * unless a preallocation option is given in @opts.
4655 *
4656 * Note that @in_bs may use a different BlockDriver from @drv.
4657 *
4658 * If an error occurs the @errp pointer is set.
4659 */
4660BlockMeasureInfo *bdrv_measure(BlockDriver *drv, QemuOpts *opts,
4661 BlockDriverState *in_bs, Error **errp)
4662{
4663 if (!drv->bdrv_measure) {
4664 error_setg(errp, "Block driver '%s' does not support size measurement",
4665 drv->format_name);
4666 return NULL;
4667 }
4668
4669 return drv->bdrv_measure(opts, in_bs, errp);
4670}
4671
61007b31
SH
4672/**
4673 * Return number of sectors on success, -errno on error.
1c9805a3 4674 */
61007b31 4675int64_t bdrv_nb_sectors(BlockDriverState *bs)
1c9805a3 4676{
61007b31 4677 BlockDriver *drv = bs->drv;
498e386c 4678
61007b31
SH
4679 if (!drv)
4680 return -ENOMEDIUM;
2572b37a 4681
61007b31
SH
4682 if (drv->has_variable_length) {
4683 int ret = refresh_total_sectors(bs, bs->total_sectors);
4684 if (ret < 0) {
4685 return ret;
1c9805a3
SH
4686 }
4687 }
61007b31 4688 return bs->total_sectors;
1c9805a3 4689}
b338082b 4690
61007b31
SH
4691/**
4692 * Return length in bytes on success, -errno on error.
4693 * The length is always a multiple of BDRV_SECTOR_SIZE.
8d3b1a2d 4694 */
61007b31 4695int64_t bdrv_getlength(BlockDriverState *bs)
8d3b1a2d 4696{
61007b31 4697 int64_t ret = bdrv_nb_sectors(bs);
8d3b1a2d 4698
4a9c9ea0 4699 ret = ret > INT64_MAX / BDRV_SECTOR_SIZE ? -EFBIG : ret;
61007b31 4700 return ret < 0 ? ret : ret * BDRV_SECTOR_SIZE;
fc01f7e7
FB
4701}
4702
61007b31
SH
4703/* return 0 as number of sectors if no device present or error */
4704void bdrv_get_geometry(BlockDriverState *bs, uint64_t *nb_sectors_ptr)
07d27a44 4705{
61007b31 4706 int64_t nb_sectors = bdrv_nb_sectors(bs);
07d27a44 4707
61007b31 4708 *nb_sectors_ptr = nb_sectors < 0 ? 0 : nb_sectors;
07d27a44
MA
4709}
4710
54115412 4711bool bdrv_is_sg(BlockDriverState *bs)
f08145fe 4712{
61007b31 4713 return bs->sg;
f08145fe
KW
4714}
4715
54115412 4716bool bdrv_is_encrypted(BlockDriverState *bs)
fc3959e4 4717{
760e0063 4718 if (bs->backing && bs->backing->bs->encrypted) {
54115412 4719 return true;
760e0063 4720 }
61007b31 4721 return bs->encrypted;
fc3959e4
FZ
4722}
4723
61007b31 4724const char *bdrv_get_format_name(BlockDriverState *bs)
40b4f539 4725{
61007b31 4726 return bs->drv ? bs->drv->format_name : NULL;
40b4f539
KW
4727}
4728
61007b31 4729static int qsort_strcmp(const void *a, const void *b)
40b4f539 4730{
ceff5bd7 4731 return strcmp(*(char *const *)a, *(char *const *)b);
40b4f539
KW
4732}
4733
61007b31 4734void bdrv_iterate_format(void (*it)(void *opaque, const char *name),
9ac404c5 4735 void *opaque, bool read_only)
40b4f539 4736{
61007b31
SH
4737 BlockDriver *drv;
4738 int count = 0;
4739 int i;
4740 const char **formats = NULL;
40b4f539 4741
61007b31
SH
4742 QLIST_FOREACH(drv, &bdrv_drivers, list) {
4743 if (drv->format_name) {
4744 bool found = false;
4745 int i = count;
9ac404c5
AS
4746
4747 if (use_bdrv_whitelist && !bdrv_is_whitelisted(drv, read_only)) {
4748 continue;
4749 }
4750
61007b31
SH
4751 while (formats && i && !found) {
4752 found = !strcmp(formats[--i], drv->format_name);
4753 }
e2a305fb 4754
61007b31
SH
4755 if (!found) {
4756 formats = g_renew(const char *, formats, count + 1);
4757 formats[count++] = drv->format_name;
4758 }
6c5a42ac 4759 }
61007b31 4760 }
6c5a42ac 4761
eb0df69f
HR
4762 for (i = 0; i < (int)ARRAY_SIZE(block_driver_modules); i++) {
4763 const char *format_name = block_driver_modules[i].format_name;
4764
4765 if (format_name) {
4766 bool found = false;
4767 int j = count;
4768
9ac404c5
AS
4769 if (use_bdrv_whitelist &&
4770 !bdrv_format_is_whitelisted(format_name, read_only)) {
4771 continue;
4772 }
4773
eb0df69f
HR
4774 while (formats && j && !found) {
4775 found = !strcmp(formats[--j], format_name);
4776 }
4777
4778 if (!found) {
4779 formats = g_renew(const char *, formats, count + 1);
4780 formats[count++] = format_name;
4781 }
4782 }
4783 }
4784
61007b31 4785 qsort(formats, count, sizeof(formats[0]), qsort_strcmp);
40b4f539 4786
61007b31
SH
4787 for (i = 0; i < count; i++) {
4788 it(opaque, formats[i]);
4789 }
40b4f539 4790
61007b31
SH
4791 g_free(formats);
4792}
40b4f539 4793
61007b31
SH
4794/* This function is to find a node in the bs graph */
4795BlockDriverState *bdrv_find_node(const char *node_name)
4796{
4797 BlockDriverState *bs;
391827eb 4798
61007b31 4799 assert(node_name);
40b4f539 4800
61007b31
SH
4801 QTAILQ_FOREACH(bs, &graph_bdrv_states, node_list) {
4802 if (!strcmp(node_name, bs->node_name)) {
4803 return bs;
40b4f539
KW
4804 }
4805 }
61007b31 4806 return NULL;
40b4f539
KW
4807}
4808
61007b31
SH
4809/* Put this QMP function here so it can access the static graph_bdrv_states. */
4810BlockDeviceInfoList *bdrv_named_nodes_list(Error **errp)
40b4f539 4811{
61007b31
SH
4812 BlockDeviceInfoList *list, *entry;
4813 BlockDriverState *bs;
40b4f539 4814
61007b31
SH
4815 list = NULL;
4816 QTAILQ_FOREACH(bs, &graph_bdrv_states, node_list) {
c83f9fba 4817 BlockDeviceInfo *info = bdrv_block_device_info(NULL, bs, errp);
61007b31
SH
4818 if (!info) {
4819 qapi_free_BlockDeviceInfoList(list);
4820 return NULL;
301db7c2 4821 }
61007b31
SH
4822 entry = g_malloc0(sizeof(*entry));
4823 entry->value = info;
4824 entry->next = list;
4825 list = entry;
301db7c2
RH
4826 }
4827
61007b31
SH
4828 return list;
4829}
40b4f539 4830
5d3b4e99
VSO
4831#define QAPI_LIST_ADD(list, element) do { \
4832 typeof(list) _tmp = g_new(typeof(*(list)), 1); \
4833 _tmp->value = (element); \
4834 _tmp->next = (list); \
4835 (list) = _tmp; \
4836} while (0)
4837
4838typedef struct XDbgBlockGraphConstructor {
4839 XDbgBlockGraph *graph;
4840 GHashTable *graph_nodes;
4841} XDbgBlockGraphConstructor;
4842
4843static XDbgBlockGraphConstructor *xdbg_graph_new(void)
4844{
4845 XDbgBlockGraphConstructor *gr = g_new(XDbgBlockGraphConstructor, 1);
4846
4847 gr->graph = g_new0(XDbgBlockGraph, 1);
4848 gr->graph_nodes = g_hash_table_new(NULL, NULL);
4849
4850 return gr;
4851}
4852
4853static XDbgBlockGraph *xdbg_graph_finalize(XDbgBlockGraphConstructor *gr)
4854{
4855 XDbgBlockGraph *graph = gr->graph;
4856
4857 g_hash_table_destroy(gr->graph_nodes);
4858 g_free(gr);
4859
4860 return graph;
4861}
4862
4863static uintptr_t xdbg_graph_node_num(XDbgBlockGraphConstructor *gr, void *node)
4864{
4865 uintptr_t ret = (uintptr_t)g_hash_table_lookup(gr->graph_nodes, node);
4866
4867 if (ret != 0) {
4868 return ret;
4869 }
4870
4871 /*
4872 * Start counting from 1, not 0, because 0 interferes with not-found (NULL)
4873 * answer of g_hash_table_lookup.
4874 */
4875 ret = g_hash_table_size(gr->graph_nodes) + 1;
4876 g_hash_table_insert(gr->graph_nodes, node, (void *)ret);
4877
4878 return ret;
4879}
4880
4881static void xdbg_graph_add_node(XDbgBlockGraphConstructor *gr, void *node,
4882 XDbgBlockGraphNodeType type, const char *name)
4883{
4884 XDbgBlockGraphNode *n;
4885
4886 n = g_new0(XDbgBlockGraphNode, 1);
4887
4888 n->id = xdbg_graph_node_num(gr, node);
4889 n->type = type;
4890 n->name = g_strdup(name);
4891
4892 QAPI_LIST_ADD(gr->graph->nodes, n);
4893}
4894
4895static void xdbg_graph_add_edge(XDbgBlockGraphConstructor *gr, void *parent,
4896 const BdrvChild *child)
4897{
cdb1cec8 4898 BlockPermission qapi_perm;
5d3b4e99
VSO
4899 XDbgBlockGraphEdge *edge;
4900
5d3b4e99
VSO
4901 edge = g_new0(XDbgBlockGraphEdge, 1);
4902
4903 edge->parent = xdbg_graph_node_num(gr, parent);
4904 edge->child = xdbg_graph_node_num(gr, child->bs);
4905 edge->name = g_strdup(child->name);
4906
cdb1cec8
HR
4907 for (qapi_perm = 0; qapi_perm < BLOCK_PERMISSION__MAX; qapi_perm++) {
4908 uint64_t flag = bdrv_qapi_perm_to_blk_perm(qapi_perm);
4909
4910 if (flag & child->perm) {
4911 QAPI_LIST_ADD(edge->perm, qapi_perm);
5d3b4e99 4912 }
cdb1cec8
HR
4913 if (flag & child->shared_perm) {
4914 QAPI_LIST_ADD(edge->shared_perm, qapi_perm);
5d3b4e99
VSO
4915 }
4916 }
4917
4918 QAPI_LIST_ADD(gr->graph->edges, edge);
4919}
4920
4921
4922XDbgBlockGraph *bdrv_get_xdbg_block_graph(Error **errp)
4923{
4924 BlockBackend *blk;
4925 BlockJob *job;
4926 BlockDriverState *bs;
4927 BdrvChild *child;
4928 XDbgBlockGraphConstructor *gr = xdbg_graph_new();
4929
4930 for (blk = blk_all_next(NULL); blk; blk = blk_all_next(blk)) {
4931 char *allocated_name = NULL;
4932 const char *name = blk_name(blk);
4933
4934 if (!*name) {
4935 name = allocated_name = blk_get_attached_dev_id(blk);
4936 }
4937 xdbg_graph_add_node(gr, blk, X_DBG_BLOCK_GRAPH_NODE_TYPE_BLOCK_BACKEND,
4938 name);
4939 g_free(allocated_name);
4940 if (blk_root(blk)) {
4941 xdbg_graph_add_edge(gr, blk, blk_root(blk));
4942 }
4943 }
4944
4945 for (job = block_job_next(NULL); job; job = block_job_next(job)) {
4946 GSList *el;
4947
4948 xdbg_graph_add_node(gr, job, X_DBG_BLOCK_GRAPH_NODE_TYPE_BLOCK_JOB,
4949 job->job.id);
4950 for (el = job->nodes; el; el = el->next) {
4951 xdbg_graph_add_edge(gr, job, (BdrvChild *)el->data);
4952 }
4953 }
4954
4955 QTAILQ_FOREACH(bs, &graph_bdrv_states, node_list) {
4956 xdbg_graph_add_node(gr, bs, X_DBG_BLOCK_GRAPH_NODE_TYPE_BLOCK_DRIVER,
4957 bs->node_name);
4958 QLIST_FOREACH(child, &bs->children, next) {
4959 xdbg_graph_add_edge(gr, bs, child);
4960 }
4961 }
4962
4963 return xdbg_graph_finalize(gr);
4964}
4965
61007b31
SH
4966BlockDriverState *bdrv_lookup_bs(const char *device,
4967 const char *node_name,
4968 Error **errp)
4969{
4970 BlockBackend *blk;
4971 BlockDriverState *bs;
40b4f539 4972
61007b31
SH
4973 if (device) {
4974 blk = blk_by_name(device);
40b4f539 4975
61007b31 4976 if (blk) {
9f4ed6fb
AG
4977 bs = blk_bs(blk);
4978 if (!bs) {
5433c24f 4979 error_setg(errp, "Device '%s' has no medium", device);
5433c24f
HR
4980 }
4981
9f4ed6fb 4982 return bs;
61007b31
SH
4983 }
4984 }
40b4f539 4985
61007b31
SH
4986 if (node_name) {
4987 bs = bdrv_find_node(node_name);
6d519a5f 4988
61007b31
SH
4989 if (bs) {
4990 return bs;
4991 }
40b4f539
KW
4992 }
4993
61007b31
SH
4994 error_setg(errp, "Cannot find device=%s nor node_name=%s",
4995 device ? device : "",
4996 node_name ? node_name : "");
4997 return NULL;
40b4f539
KW
4998}
4999
61007b31
SH
5000/* If 'base' is in the same chain as 'top', return true. Otherwise,
5001 * return false. If either argument is NULL, return false. */
5002bool bdrv_chain_contains(BlockDriverState *top, BlockDriverState *base)
83f64091 5003{
61007b31 5004 while (top && top != base) {
760e0063 5005 top = backing_bs(top);
02c50efe 5006 }
61007b31
SH
5007
5008 return top != NULL;
02c50efe
FZ
5009}
5010
61007b31 5011BlockDriverState *bdrv_next_node(BlockDriverState *bs)
02c50efe 5012{
61007b31
SH
5013 if (!bs) {
5014 return QTAILQ_FIRST(&graph_bdrv_states);
02c50efe 5015 }
61007b31 5016 return QTAILQ_NEXT(bs, node_list);
83f64091
FB
5017}
5018
0f12264e
KW
5019BlockDriverState *bdrv_next_all_states(BlockDriverState *bs)
5020{
5021 if (!bs) {
5022 return QTAILQ_FIRST(&all_bdrv_states);
5023 }
5024 return QTAILQ_NEXT(bs, bs_list);
5025}
5026
61007b31 5027const char *bdrv_get_node_name(const BlockDriverState *bs)
83f64091 5028{
61007b31 5029 return bs->node_name;
beac80cd
FB
5030}
5031
1f0c461b 5032const char *bdrv_get_parent_name(const BlockDriverState *bs)
4c265bf9
KW
5033{
5034 BdrvChild *c;
5035 const char *name;
5036
5037 /* If multiple parents have a name, just pick the first one. */
5038 QLIST_FOREACH(c, &bs->parents, next_parent) {
5039 if (c->role->get_name) {
5040 name = c->role->get_name(c);
5041 if (name && *name) {
5042 return name;
5043 }
5044 }
5045 }
5046
5047 return NULL;
5048}
5049
61007b31
SH
5050/* TODO check what callers really want: bs->node_name or blk_name() */
5051const char *bdrv_get_device_name(const BlockDriverState *bs)
beac80cd 5052{
4c265bf9 5053 return bdrv_get_parent_name(bs) ?: "";
f141eafe 5054}
83f64091 5055
61007b31
SH
5056/* This can be used to identify nodes that might not have a device
5057 * name associated. Since node and device names live in the same
5058 * namespace, the result is unambiguous. The exception is if both are
5059 * absent, then this returns an empty (non-null) string. */
5060const char *bdrv_get_device_or_node_name(const BlockDriverState *bs)
f141eafe 5061{
4c265bf9 5062 return bdrv_get_parent_name(bs) ?: bs->node_name;
beac80cd 5063}
beac80cd 5064
61007b31 5065int bdrv_get_flags(BlockDriverState *bs)
0b5a2445 5066{
61007b31 5067 return bs->open_flags;
0b5a2445
PB
5068}
5069
61007b31 5070int bdrv_has_zero_init_1(BlockDriverState *bs)
68485420 5071{
61007b31 5072 return 1;
0b5a2445
PB
5073}
5074
61007b31 5075int bdrv_has_zero_init(BlockDriverState *bs)
0b5a2445 5076{
d470ad42
HR
5077 if (!bs->drv) {
5078 return 0;
5079 }
0b5a2445 5080
61007b31
SH
5081 /* If BS is a copy on write image, it is initialized to
5082 the contents of the base image, which may not be zeroes. */
760e0063 5083 if (bs->backing) {
61007b31
SH
5084 return 0;
5085 }
5086 if (bs->drv->bdrv_has_zero_init) {
5087 return bs->drv->bdrv_has_zero_init(bs);
0b5a2445 5088 }
5a612c00
MP
5089 if (bs->file && bs->drv->is_filter) {
5090 return bdrv_has_zero_init(bs->file->bs);
5091 }
61007b31
SH
5092
5093 /* safe default */
5094 return 0;
68485420
KW
5095}
5096
ceaca56f
HR
5097int bdrv_has_zero_init_truncate(BlockDriverState *bs)
5098{
5099 if (!bs->drv) {
5100 return 0;
5101 }
5102
5103 if (bs->backing) {
5104 /* Depends on the backing image length, but better safe than sorry */
5105 return 0;
5106 }
5107 if (bs->drv->bdrv_has_zero_init_truncate) {
5108 return bs->drv->bdrv_has_zero_init_truncate(bs);
5109 }
5110 if (bs->file && bs->drv->is_filter) {
5111 return bdrv_has_zero_init_truncate(bs->file->bs);
5112 }
5113
5114 /* safe default */
5115 return 0;
5116}
5117
61007b31 5118bool bdrv_unallocated_blocks_are_zero(BlockDriverState *bs)
b2a61371 5119{
61007b31 5120 BlockDriverInfo bdi;
b2a61371 5121
760e0063 5122 if (bs->backing) {
61007b31
SH
5123 return false;
5124 }
5125
5126 if (bdrv_get_info(bs, &bdi) == 0) {
5127 return bdi.unallocated_blocks_are_zero;
b2a61371
SH
5128 }
5129
61007b31 5130 return false;
b2a61371
SH
5131}
5132
61007b31 5133bool bdrv_can_write_zeroes_with_unmap(BlockDriverState *bs)
68485420 5134{
2f0342ef 5135 if (!(bs->open_flags & BDRV_O_UNMAP)) {
61007b31
SH
5136 return false;
5137 }
68485420 5138
e24d813b 5139 return bs->supported_zero_flags & BDRV_REQ_MAY_UNMAP;
68485420
KW
5140}
5141
61007b31
SH
5142void bdrv_get_backing_filename(BlockDriverState *bs,
5143 char *filename, int filename_size)
016f5cf6 5144{
61007b31
SH
5145 pstrcpy(filename, filename_size, bs->backing_file);
5146}
d318aea9 5147
61007b31
SH
5148int bdrv_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
5149{
5150 BlockDriver *drv = bs->drv;
5a612c00
MP
5151 /* if bs->drv == NULL, bs is closed, so there's nothing to do here */
5152 if (!drv) {
61007b31 5153 return -ENOMEDIUM;
5a612c00
MP
5154 }
5155 if (!drv->bdrv_get_info) {
5156 if (bs->file && drv->is_filter) {
5157 return bdrv_get_info(bs->file->bs, bdi);
5158 }
61007b31 5159 return -ENOTSUP;
5a612c00 5160 }
61007b31
SH
5161 memset(bdi, 0, sizeof(*bdi));
5162 return drv->bdrv_get_info(bs, bdi);
5163}
016f5cf6 5164
1bf6e9ca
AS
5165ImageInfoSpecific *bdrv_get_specific_info(BlockDriverState *bs,
5166 Error **errp)
61007b31
SH
5167{
5168 BlockDriver *drv = bs->drv;
5169 if (drv && drv->bdrv_get_specific_info) {
1bf6e9ca 5170 return drv->bdrv_get_specific_info(bs, errp);
61007b31
SH
5171 }
5172 return NULL;
016f5cf6
AG
5173}
5174
d9245599
AN
5175BlockStatsSpecific *bdrv_get_specific_stats(BlockDriverState *bs)
5176{
5177 BlockDriver *drv = bs->drv;
5178 if (!drv || !drv->bdrv_get_specific_stats) {
5179 return NULL;
5180 }
5181 return drv->bdrv_get_specific_stats(bs);
5182}
5183
a31939e6 5184void bdrv_debug_event(BlockDriverState *bs, BlkdebugEvent event)
4265d620 5185{
61007b31
SH
5186 if (!bs || !bs->drv || !bs->drv->bdrv_debug_event) {
5187 return;
5188 }
4265d620 5189
61007b31 5190 bs->drv->bdrv_debug_event(bs, event);
4265d620
PB
5191}
5192
d10529a2 5193static BlockDriverState *bdrv_find_debug_node(BlockDriverState *bs)
4265d620 5194{
61007b31 5195 while (bs && bs->drv && !bs->drv->bdrv_debug_breakpoint) {
d10529a2
VSO
5196 if (bs->file) {
5197 bs = bs->file->bs;
5198 continue;
5199 }
5200
5201 if (bs->drv->is_filter && bs->backing) {
5202 bs = bs->backing->bs;
5203 continue;
5204 }
5205
5206 break;
61007b31 5207 }
4265d620 5208
61007b31 5209 if (bs && bs->drv && bs->drv->bdrv_debug_breakpoint) {
d10529a2
VSO
5210 assert(bs->drv->bdrv_debug_remove_breakpoint);
5211 return bs;
5212 }
5213
5214 return NULL;
5215}
5216
5217int bdrv_debug_breakpoint(BlockDriverState *bs, const char *event,
5218 const char *tag)
5219{
5220 bs = bdrv_find_debug_node(bs);
5221 if (bs) {
61007b31
SH
5222 return bs->drv->bdrv_debug_breakpoint(bs, event, tag);
5223 }
4265d620 5224
61007b31 5225 return -ENOTSUP;
4265d620
PB
5226}
5227
61007b31 5228int bdrv_debug_remove_breakpoint(BlockDriverState *bs, const char *tag)
ea2384d3 5229{
d10529a2
VSO
5230 bs = bdrv_find_debug_node(bs);
5231 if (bs) {
61007b31
SH
5232 return bs->drv->bdrv_debug_remove_breakpoint(bs, tag);
5233 }
5234
5235 return -ENOTSUP;
eb852011
MA
5236}
5237
61007b31 5238int bdrv_debug_resume(BlockDriverState *bs, const char *tag)
ce1a14dc 5239{
61007b31 5240 while (bs && (!bs->drv || !bs->drv->bdrv_debug_resume)) {
9a4f4c31 5241 bs = bs->file ? bs->file->bs : NULL;
61007b31 5242 }
ce1a14dc 5243
61007b31
SH
5244 if (bs && bs->drv && bs->drv->bdrv_debug_resume) {
5245 return bs->drv->bdrv_debug_resume(bs, tag);
5246 }
ce1a14dc 5247
61007b31 5248 return -ENOTSUP;
f197fe2b
FZ
5249}
5250
61007b31 5251bool bdrv_debug_is_suspended(BlockDriverState *bs, const char *tag)
ce1a14dc 5252{
61007b31 5253 while (bs && bs->drv && !bs->drv->bdrv_debug_is_suspended) {
9a4f4c31 5254 bs = bs->file ? bs->file->bs : NULL;
f197fe2b 5255 }
19cb3738 5256
61007b31
SH
5257 if (bs && bs->drv && bs->drv->bdrv_debug_is_suspended) {
5258 return bs->drv->bdrv_debug_is_suspended(bs, tag);
5259 }
f9f05dc5 5260
61007b31
SH
5261 return false;
5262}
f9f05dc5 5263
61007b31
SH
5264/* backing_file can either be relative, or absolute, or a protocol. If it is
5265 * relative, it must be relative to the chain. So, passing in bs->filename
5266 * from a BDS as backing_file should not be done, as that may be relative to
5267 * the CWD rather than the chain. */
5268BlockDriverState *bdrv_find_backing_image(BlockDriverState *bs,
5269 const char *backing_file)
f9f05dc5 5270{
61007b31
SH
5271 char *filename_full = NULL;
5272 char *backing_file_full = NULL;
5273 char *filename_tmp = NULL;
5274 int is_protocol = 0;
5275 BlockDriverState *curr_bs = NULL;
5276 BlockDriverState *retval = NULL;
f9f05dc5 5277
61007b31
SH
5278 if (!bs || !bs->drv || !backing_file) {
5279 return NULL;
f9f05dc5
KW
5280 }
5281
61007b31
SH
5282 filename_full = g_malloc(PATH_MAX);
5283 backing_file_full = g_malloc(PATH_MAX);
f9f05dc5 5284
61007b31 5285 is_protocol = path_has_protocol(backing_file);
f9f05dc5 5286
760e0063 5287 for (curr_bs = bs; curr_bs->backing; curr_bs = curr_bs->backing->bs) {
f9f05dc5 5288
61007b31
SH
5289 /* If either of the filename paths is actually a protocol, then
5290 * compare unmodified paths; otherwise make paths relative */
5291 if (is_protocol || path_has_protocol(curr_bs->backing_file)) {
6b6833c1
HR
5292 char *backing_file_full_ret;
5293
61007b31 5294 if (strcmp(backing_file, curr_bs->backing_file) == 0) {
760e0063 5295 retval = curr_bs->backing->bs;
61007b31
SH
5296 break;
5297 }
418661e0 5298 /* Also check against the full backing filename for the image */
6b6833c1
HR
5299 backing_file_full_ret = bdrv_get_full_backing_filename(curr_bs,
5300 NULL);
5301 if (backing_file_full_ret) {
5302 bool equal = strcmp(backing_file, backing_file_full_ret) == 0;
5303 g_free(backing_file_full_ret);
5304 if (equal) {
418661e0
JC
5305 retval = curr_bs->backing->bs;
5306 break;
5307 }
418661e0 5308 }
61007b31
SH
5309 } else {
5310 /* If not an absolute filename path, make it relative to the current
5311 * image's filename path */
2d9158ce
HR
5312 filename_tmp = bdrv_make_absolute_filename(curr_bs, backing_file,
5313 NULL);
5314 /* We are going to compare canonicalized absolute pathnames */
5315 if (!filename_tmp || !realpath(filename_tmp, filename_full)) {
5316 g_free(filename_tmp);
61007b31
SH
5317 continue;
5318 }
2d9158ce 5319 g_free(filename_tmp);
07f07615 5320
61007b31
SH
5321 /* We need to make sure the backing filename we are comparing against
5322 * is relative to the current image filename (or absolute) */
2d9158ce
HR
5323 filename_tmp = bdrv_get_full_backing_filename(curr_bs, NULL);
5324 if (!filename_tmp || !realpath(filename_tmp, backing_file_full)) {
5325 g_free(filename_tmp);
61007b31
SH
5326 continue;
5327 }
2d9158ce 5328 g_free(filename_tmp);
eb489bb1 5329
61007b31 5330 if (strcmp(backing_file_full, filename_full) == 0) {
760e0063 5331 retval = curr_bs->backing->bs;
61007b31
SH
5332 break;
5333 }
5334 }
eb489bb1
KW
5335 }
5336
61007b31
SH
5337 g_free(filename_full);
5338 g_free(backing_file_full);
61007b31
SH
5339 return retval;
5340}
5341
61007b31
SH
5342void bdrv_init(void)
5343{
5344 module_call_init(MODULE_INIT_BLOCK);
5345}
29cdb251 5346
61007b31
SH
5347void bdrv_init_with_whitelist(void)
5348{
5349 use_bdrv_whitelist = 1;
5350 bdrv_init();
07f07615
PB
5351}
5352
2b148f39
PB
5353static void coroutine_fn bdrv_co_invalidate_cache(BlockDriverState *bs,
5354 Error **errp)
0f15423c 5355{
4417ab7a 5356 BdrvChild *child, *parent;
9c5e6594 5357 uint64_t perm, shared_perm;
5a8a30db
KW
5358 Error *local_err = NULL;
5359 int ret;
9c98f145 5360 BdrvDirtyBitmap *bm;
5a8a30db 5361
3456a8d1
KW
5362 if (!bs->drv) {
5363 return;
5364 }
5365
16e977d5 5366 QLIST_FOREACH(child, &bs->children, next) {
2b148f39 5367 bdrv_co_invalidate_cache(child->bs, &local_err);
0d1c5c91 5368 if (local_err) {
0d1c5c91
FZ
5369 error_propagate(errp, local_err);
5370 return;
5371 }
5a8a30db 5372 }
0d1c5c91 5373
dafe0960
KW
5374 /*
5375 * Update permissions, they may differ for inactive nodes.
5376 *
5377 * Note that the required permissions of inactive images are always a
5378 * subset of the permissions required after activating the image. This
5379 * allows us to just get the permissions upfront without restricting
5380 * drv->bdrv_invalidate_cache().
5381 *
5382 * It also means that in error cases, we don't have to try and revert to
5383 * the old permissions (which is an operation that could fail, too). We can
5384 * just keep the extended permissions for the next time that an activation
5385 * of the image is tried.
5386 */
7bb4941a
KW
5387 if (bs->open_flags & BDRV_O_INACTIVE) {
5388 bs->open_flags &= ~BDRV_O_INACTIVE;
5389 bdrv_get_cumulative_perm(bs, &perm, &shared_perm);
5390 ret = bdrv_check_perm(bs, NULL, perm, shared_perm, NULL, NULL, &local_err);
5391 if (ret < 0) {
0d1c5c91
FZ
5392 bs->open_flags |= BDRV_O_INACTIVE;
5393 error_propagate(errp, local_err);
5394 return;
5395 }
7bb4941a 5396 bdrv_set_perm(bs, perm, shared_perm);
3456a8d1 5397
7bb4941a
KW
5398 if (bs->drv->bdrv_co_invalidate_cache) {
5399 bs->drv->bdrv_co_invalidate_cache(bs, &local_err);
5400 if (local_err) {
5401 bs->open_flags |= BDRV_O_INACTIVE;
5402 error_propagate(errp, local_err);
5403 return;
5404 }
5405 }
9c98f145 5406
7bb4941a
KW
5407 FOR_EACH_DIRTY_BITMAP(bs, bm) {
5408 bdrv_dirty_bitmap_skip_store(bm, false);
5409 }
5410
5411 ret = refresh_total_sectors(bs, bs->total_sectors);
5412 if (ret < 0) {
5413 bs->open_flags |= BDRV_O_INACTIVE;
5414 error_setg_errno(errp, -ret, "Could not refresh total sector count");
5415 return;
5416 }
5a8a30db 5417 }
4417ab7a
KW
5418
5419 QLIST_FOREACH(parent, &bs->parents, next_parent) {
5420 if (parent->role->activate) {
5421 parent->role->activate(parent, &local_err);
5422 if (local_err) {
78fc3b3a 5423 bs->open_flags |= BDRV_O_INACTIVE;
4417ab7a
KW
5424 error_propagate(errp, local_err);
5425 return;
5426 }
5427 }
5428 }
0f15423c
AL
5429}
5430
2b148f39
PB
5431typedef struct InvalidateCacheCo {
5432 BlockDriverState *bs;
5433 Error **errp;
5434 bool done;
5435} InvalidateCacheCo;
5436
5437static void coroutine_fn bdrv_invalidate_cache_co_entry(void *opaque)
5438{
5439 InvalidateCacheCo *ico = opaque;
5440 bdrv_co_invalidate_cache(ico->bs, ico->errp);
5441 ico->done = true;
4720cbee 5442 aio_wait_kick();
2b148f39
PB
5443}
5444
5445void bdrv_invalidate_cache(BlockDriverState *bs, Error **errp)
5446{
5447 Coroutine *co;
5448 InvalidateCacheCo ico = {
5449 .bs = bs,
5450 .done = false,
5451 .errp = errp
5452 };
5453
5454 if (qemu_in_coroutine()) {
5455 /* Fast-path if already in coroutine context */
5456 bdrv_invalidate_cache_co_entry(&ico);
5457 } else {
5458 co = qemu_coroutine_create(bdrv_invalidate_cache_co_entry, &ico);
4720cbee 5459 bdrv_coroutine_enter(bs, co);
2b148f39
PB
5460 BDRV_POLL_WHILE(bs, !ico.done);
5461 }
5462}
5463
5a8a30db 5464void bdrv_invalidate_cache_all(Error **errp)
0f15423c 5465{
7c8eece4 5466 BlockDriverState *bs;
5a8a30db 5467 Error *local_err = NULL;
88be7b4b 5468 BdrvNextIterator it;
0f15423c 5469
88be7b4b 5470 for (bs = bdrv_first(&it); bs; bs = bdrv_next(&it)) {
ed78cda3
SH
5471 AioContext *aio_context = bdrv_get_aio_context(bs);
5472
5473 aio_context_acquire(aio_context);
5a8a30db 5474 bdrv_invalidate_cache(bs, &local_err);
ed78cda3 5475 aio_context_release(aio_context);
5a8a30db
KW
5476 if (local_err) {
5477 error_propagate(errp, local_err);
5e003f17 5478 bdrv_next_cleanup(&it);
5a8a30db
KW
5479 return;
5480 }
0f15423c
AL
5481 }
5482}
5483
9e37271f
KW
5484static bool bdrv_has_bds_parent(BlockDriverState *bs, bool only_active)
5485{
5486 BdrvChild *parent;
5487
5488 QLIST_FOREACH(parent, &bs->parents, next_parent) {
5489 if (parent->role->parent_is_bds) {
5490 BlockDriverState *parent_bs = parent->opaque;
5491 if (!only_active || !(parent_bs->open_flags & BDRV_O_INACTIVE)) {
5492 return true;
5493 }
5494 }
5495 }
5496
5497 return false;
5498}
5499
5500static int bdrv_inactivate_recurse(BlockDriverState *bs)
76b1c7fe 5501{
cfa1a572 5502 BdrvChild *child, *parent;
1046779e 5503 bool tighten_restrictions;
9e37271f 5504 uint64_t perm, shared_perm;
76b1c7fe
KW
5505 int ret;
5506
d470ad42
HR
5507 if (!bs->drv) {
5508 return -ENOMEDIUM;
5509 }
5510
9e37271f
KW
5511 /* Make sure that we don't inactivate a child before its parent.
5512 * It will be covered by recursion from the yet active parent. */
5513 if (bdrv_has_bds_parent(bs, true)) {
5514 return 0;
5515 }
5516
5517 assert(!(bs->open_flags & BDRV_O_INACTIVE));
5518
5519 /* Inactivate this node */
5520 if (bs->drv->bdrv_inactivate) {
76b1c7fe
KW
5521 ret = bs->drv->bdrv_inactivate(bs);
5522 if (ret < 0) {
5523 return ret;
5524 }
5525 }
5526
9e37271f
KW
5527 QLIST_FOREACH(parent, &bs->parents, next_parent) {
5528 if (parent->role->inactivate) {
5529 ret = parent->role->inactivate(parent);
5530 if (ret < 0) {
5531 return ret;
cfa1a572
KW
5532 }
5533 }
9e37271f 5534 }
9c5e6594 5535
9e37271f 5536 bs->open_flags |= BDRV_O_INACTIVE;
7d5b5261 5537
9e37271f
KW
5538 /* Update permissions, they may differ for inactive nodes */
5539 bdrv_get_cumulative_perm(bs, &perm, &shared_perm);
1046779e
HR
5540 ret = bdrv_check_perm(bs, NULL, perm, shared_perm, NULL,
5541 &tighten_restrictions, NULL);
5542 assert(tighten_restrictions == false);
5543 if (ret < 0) {
5544 /* We only tried to loosen restrictions, so errors are not fatal */
5545 bdrv_abort_perm_update(bs);
5546 } else {
5547 bdrv_set_perm(bs, perm, shared_perm);
5548 }
38701b6a 5549
9e37271f
KW
5550
5551 /* Recursively inactivate children */
38701b6a 5552 QLIST_FOREACH(child, &bs->children, next) {
9e37271f 5553 ret = bdrv_inactivate_recurse(child->bs);
38701b6a
KW
5554 if (ret < 0) {
5555 return ret;
5556 }
5557 }
5558
76b1c7fe
KW
5559 return 0;
5560}
5561
5562int bdrv_inactivate_all(void)
5563{
79720af6 5564 BlockDriverState *bs = NULL;
88be7b4b 5565 BdrvNextIterator it;
aad0b7a0 5566 int ret = 0;
bd6458e4 5567 GSList *aio_ctxs = NULL, *ctx;
76b1c7fe 5568
88be7b4b 5569 for (bs = bdrv_first(&it); bs; bs = bdrv_next(&it)) {
bd6458e4
PB
5570 AioContext *aio_context = bdrv_get_aio_context(bs);
5571
5572 if (!g_slist_find(aio_ctxs, aio_context)) {
5573 aio_ctxs = g_slist_prepend(aio_ctxs, aio_context);
5574 aio_context_acquire(aio_context);
5575 }
aad0b7a0 5576 }
76b1c7fe 5577
9e37271f
KW
5578 for (bs = bdrv_first(&it); bs; bs = bdrv_next(&it)) {
5579 /* Nodes with BDS parents are covered by recursion from the last
5580 * parent that gets inactivated. Don't inactivate them a second
5581 * time if that has already happened. */
5582 if (bdrv_has_bds_parent(bs, false)) {
5583 continue;
5584 }
5585 ret = bdrv_inactivate_recurse(bs);
5586 if (ret < 0) {
5587 bdrv_next_cleanup(&it);
5588 goto out;
76b1c7fe
KW
5589 }
5590 }
5591
aad0b7a0 5592out:
bd6458e4
PB
5593 for (ctx = aio_ctxs; ctx != NULL; ctx = ctx->next) {
5594 AioContext *aio_context = ctx->data;
5595 aio_context_release(aio_context);
aad0b7a0 5596 }
bd6458e4 5597 g_slist_free(aio_ctxs);
aad0b7a0
FZ
5598
5599 return ret;
76b1c7fe
KW
5600}
5601
19cb3738
FB
5602/**************************************************************/
5603/* removable device support */
5604
5605/**
5606 * Return TRUE if the media is present
5607 */
e031f750 5608bool bdrv_is_inserted(BlockDriverState *bs)
19cb3738
FB
5609{
5610 BlockDriver *drv = bs->drv;
28d7a789 5611 BdrvChild *child;
a1aff5bf 5612
e031f750
HR
5613 if (!drv) {
5614 return false;
5615 }
28d7a789
HR
5616 if (drv->bdrv_is_inserted) {
5617 return drv->bdrv_is_inserted(bs);
5618 }
5619 QLIST_FOREACH(child, &bs->children, next) {
5620 if (!bdrv_is_inserted(child->bs)) {
5621 return false;
5622 }
e031f750 5623 }
28d7a789 5624 return true;
19cb3738
FB
5625}
5626
19cb3738
FB
5627/**
5628 * If eject_flag is TRUE, eject the media. Otherwise, close the tray
5629 */
f36f3949 5630void bdrv_eject(BlockDriverState *bs, bool eject_flag)
19cb3738
FB
5631{
5632 BlockDriver *drv = bs->drv;
19cb3738 5633
822e1cd1
MA
5634 if (drv && drv->bdrv_eject) {
5635 drv->bdrv_eject(bs, eject_flag);
19cb3738
FB
5636 }
5637}
5638
19cb3738
FB
5639/**
5640 * Lock or unlock the media (if it is locked, the user won't be able
5641 * to eject it manually).
5642 */
025e849a 5643void bdrv_lock_medium(BlockDriverState *bs, bool locked)
19cb3738
FB
5644{
5645 BlockDriver *drv = bs->drv;
5646
025e849a 5647 trace_bdrv_lock_medium(bs, locked);
b8c6d095 5648
025e849a
MA
5649 if (drv && drv->bdrv_lock_medium) {
5650 drv->bdrv_lock_medium(bs, locked);
19cb3738
FB
5651 }
5652}
985a03b0 5653
9fcb0251
FZ
5654/* Get a reference to bs */
5655void bdrv_ref(BlockDriverState *bs)
5656{
5657 bs->refcnt++;
5658}
5659
5660/* Release a previously grabbed reference to bs.
5661 * If after releasing, reference count is zero, the BlockDriverState is
5662 * deleted. */
5663void bdrv_unref(BlockDriverState *bs)
5664{
9a4d5ca6
JC
5665 if (!bs) {
5666 return;
5667 }
9fcb0251
FZ
5668 assert(bs->refcnt > 0);
5669 if (--bs->refcnt == 0) {
5670 bdrv_delete(bs);
5671 }
5672}
5673
fbe40ff7
FZ
5674struct BdrvOpBlocker {
5675 Error *reason;
5676 QLIST_ENTRY(BdrvOpBlocker) list;
5677};
5678
5679bool bdrv_op_is_blocked(BlockDriverState *bs, BlockOpType op, Error **errp)
5680{
5681 BdrvOpBlocker *blocker;
5682 assert((int) op >= 0 && op < BLOCK_OP_TYPE_MAX);
5683 if (!QLIST_EMPTY(&bs->op_blockers[op])) {
5684 blocker = QLIST_FIRST(&bs->op_blockers[op]);
4b576648
MA
5685 error_propagate_prepend(errp, error_copy(blocker->reason),
5686 "Node '%s' is busy: ",
5687 bdrv_get_device_or_node_name(bs));
fbe40ff7
FZ
5688 return true;
5689 }
5690 return false;
5691}
5692
5693void bdrv_op_block(BlockDriverState *bs, BlockOpType op, Error *reason)
5694{
5695 BdrvOpBlocker *blocker;
5696 assert((int) op >= 0 && op < BLOCK_OP_TYPE_MAX);
5697
5839e53b 5698 blocker = g_new0(BdrvOpBlocker, 1);
fbe40ff7
FZ
5699 blocker->reason = reason;
5700 QLIST_INSERT_HEAD(&bs->op_blockers[op], blocker, list);
5701}
5702
5703void bdrv_op_unblock(BlockDriverState *bs, BlockOpType op, Error *reason)
5704{
5705 BdrvOpBlocker *blocker, *next;
5706 assert((int) op >= 0 && op < BLOCK_OP_TYPE_MAX);
5707 QLIST_FOREACH_SAFE(blocker, &bs->op_blockers[op], list, next) {
5708 if (blocker->reason == reason) {
5709 QLIST_REMOVE(blocker, list);
5710 g_free(blocker);
5711 }
5712 }
5713}
5714
5715void bdrv_op_block_all(BlockDriverState *bs, Error *reason)
5716{
5717 int i;
5718 for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
5719 bdrv_op_block(bs, i, reason);
5720 }
5721}
5722
5723void bdrv_op_unblock_all(BlockDriverState *bs, Error *reason)
5724{
5725 int i;
5726 for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
5727 bdrv_op_unblock(bs, i, reason);
5728 }
5729}
5730
5731bool bdrv_op_blocker_is_empty(BlockDriverState *bs)
5732{
5733 int i;
5734
5735 for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
5736 if (!QLIST_EMPTY(&bs->op_blockers[i])) {
5737 return false;
5738 }
5739 }
5740 return true;
5741}
5742
d92ada22
LC
5743void bdrv_img_create(const char *filename, const char *fmt,
5744 const char *base_filename, const char *base_fmt,
9217283d
FZ
5745 char *options, uint64_t img_size, int flags, bool quiet,
5746 Error **errp)
f88e1a42 5747{
83d0521a
CL
5748 QemuOptsList *create_opts = NULL;
5749 QemuOpts *opts = NULL;
5750 const char *backing_fmt, *backing_file;
5751 int64_t size;
f88e1a42 5752 BlockDriver *drv, *proto_drv;
cc84d90f 5753 Error *local_err = NULL;
f88e1a42
JS
5754 int ret = 0;
5755
5756 /* Find driver and parse its options */
5757 drv = bdrv_find_format(fmt);
5758 if (!drv) {
71c79813 5759 error_setg(errp, "Unknown file format '%s'", fmt);
d92ada22 5760 return;
f88e1a42
JS
5761 }
5762
b65a5e12 5763 proto_drv = bdrv_find_protocol(filename, true, errp);
f88e1a42 5764 if (!proto_drv) {
d92ada22 5765 return;
f88e1a42
JS
5766 }
5767
c6149724
HR
5768 if (!drv->create_opts) {
5769 error_setg(errp, "Format driver '%s' does not support image creation",
5770 drv->format_name);
5771 return;
5772 }
5773
5774 if (!proto_drv->create_opts) {
5775 error_setg(errp, "Protocol driver '%s' does not support image creation",
5776 proto_drv->format_name);
5777 return;
5778 }
5779
f6dc1c31 5780 /* Create parameter list */
c282e1fd
CL
5781 create_opts = qemu_opts_append(create_opts, drv->create_opts);
5782 create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
f88e1a42 5783
83d0521a 5784 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
f88e1a42
JS
5785
5786 /* Parse -o options */
5787 if (options) {
dc523cd3
MA
5788 qemu_opts_do_parse(opts, options, NULL, &local_err);
5789 if (local_err) {
f88e1a42
JS
5790 goto out;
5791 }
5792 }
5793
f6dc1c31
KW
5794 if (!qemu_opt_get(opts, BLOCK_OPT_SIZE)) {
5795 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, img_size, &error_abort);
5796 } else if (img_size != UINT64_C(-1)) {
5797 error_setg(errp, "The image size must be specified only once");
5798 goto out;
5799 }
5800
f88e1a42 5801 if (base_filename) {
f43e47db 5802 qemu_opt_set(opts, BLOCK_OPT_BACKING_FILE, base_filename, &local_err);
6be4194b 5803 if (local_err) {
71c79813
LC
5804 error_setg(errp, "Backing file not supported for file format '%s'",
5805 fmt);
f88e1a42
JS
5806 goto out;
5807 }
5808 }
5809
5810 if (base_fmt) {
f43e47db 5811 qemu_opt_set(opts, BLOCK_OPT_BACKING_FMT, base_fmt, &local_err);
6be4194b 5812 if (local_err) {
71c79813
LC
5813 error_setg(errp, "Backing file format not supported for file "
5814 "format '%s'", fmt);
f88e1a42
JS
5815 goto out;
5816 }
5817 }
5818
83d0521a
CL
5819 backing_file = qemu_opt_get(opts, BLOCK_OPT_BACKING_FILE);
5820 if (backing_file) {
5821 if (!strcmp(filename, backing_file)) {
71c79813
LC
5822 error_setg(errp, "Error: Trying to create an image with the "
5823 "same filename as the backing file");
792da93a
JS
5824 goto out;
5825 }
5826 }
5827
83d0521a 5828 backing_fmt = qemu_opt_get(opts, BLOCK_OPT_BACKING_FMT);
f88e1a42 5829
6e6e55f5
JS
5830 /* The size for the image must always be specified, unless we have a backing
5831 * file and we have not been forbidden from opening it. */
a8b42a1c 5832 size = qemu_opt_get_size(opts, BLOCK_OPT_SIZE, img_size);
6e6e55f5
JS
5833 if (backing_file && !(flags & BDRV_O_NO_BACKING)) {
5834 BlockDriverState *bs;
645ae7d8 5835 char *full_backing;
6e6e55f5
JS
5836 int back_flags;
5837 QDict *backing_options = NULL;
5838
645ae7d8
HR
5839 full_backing =
5840 bdrv_get_full_backing_filename_from_filename(filename, backing_file,
5841 &local_err);
6e6e55f5 5842 if (local_err) {
6e6e55f5
JS
5843 goto out;
5844 }
645ae7d8 5845 assert(full_backing);
29168018 5846
6e6e55f5
JS
5847 /* backing files always opened read-only */
5848 back_flags = flags;
5849 back_flags &= ~(BDRV_O_RDWR | BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING);
f88e1a42 5850
cc954f01 5851 backing_options = qdict_new();
6e6e55f5 5852 if (backing_fmt) {
6e6e55f5
JS
5853 qdict_put_str(backing_options, "driver", backing_fmt);
5854 }
cc954f01 5855 qdict_put_bool(backing_options, BDRV_OPT_FORCE_SHARE, true);
e6641719 5856
6e6e55f5
JS
5857 bs = bdrv_open(full_backing, NULL, backing_options, back_flags,
5858 &local_err);
5859 g_free(full_backing);
5860 if (!bs && size != -1) {
5861 /* Couldn't open BS, but we have a size, so it's nonfatal */
5862 warn_reportf_err(local_err,
5863 "Could not verify backing image. "
5864 "This may become an error in future versions.\n");
5865 local_err = NULL;
5866 } else if (!bs) {
5867 /* Couldn't open bs, do not have size */
5868 error_append_hint(&local_err,
5869 "Could not open backing image to determine size.\n");
5870 goto out;
5871 } else {
5872 if (size == -1) {
5873 /* Opened BS, have no size */
5874 size = bdrv_getlength(bs);
5875 if (size < 0) {
5876 error_setg_errno(errp, -size, "Could not get size of '%s'",
5877 backing_file);
5878 bdrv_unref(bs);
5879 goto out;
5880 }
5881 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, size, &error_abort);
52bf1e72 5882 }
66f6b814 5883 bdrv_unref(bs);
f88e1a42 5884 }
6e6e55f5
JS
5885 } /* (backing_file && !(flags & BDRV_O_NO_BACKING)) */
5886
5887 if (size == -1) {
5888 error_setg(errp, "Image creation needs a size parameter");
5889 goto out;
f88e1a42
JS
5890 }
5891
f382d43a 5892 if (!quiet) {
fe646693 5893 printf("Formatting '%s', fmt=%s ", filename, fmt);
43c5d8f8 5894 qemu_opts_print(opts, " ");
f382d43a
MR
5895 puts("");
5896 }
83d0521a 5897
c282e1fd 5898 ret = bdrv_create(drv, filename, opts, &local_err);
83d0521a 5899
cc84d90f
HR
5900 if (ret == -EFBIG) {
5901 /* This is generally a better message than whatever the driver would
5902 * deliver (especially because of the cluster_size_hint), since that
5903 * is most probably not much different from "image too large". */
5904 const char *cluster_size_hint = "";
83d0521a 5905 if (qemu_opt_get_size(opts, BLOCK_OPT_CLUSTER_SIZE, 0)) {
cc84d90f 5906 cluster_size_hint = " (try using a larger cluster size)";
f88e1a42 5907 }
cc84d90f
HR
5908 error_setg(errp, "The image size is too large for file format '%s'"
5909 "%s", fmt, cluster_size_hint);
5910 error_free(local_err);
5911 local_err = NULL;
f88e1a42
JS
5912 }
5913
5914out:
83d0521a
CL
5915 qemu_opts_del(opts);
5916 qemu_opts_free(create_opts);
621ff94d 5917 error_propagate(errp, local_err);
f88e1a42 5918}
85d126f3
SH
5919
5920AioContext *bdrv_get_aio_context(BlockDriverState *bs)
5921{
33f2a757 5922 return bs ? bs->aio_context : qemu_get_aio_context();
dcd04228
SH
5923}
5924
052a7572
FZ
5925void bdrv_coroutine_enter(BlockDriverState *bs, Coroutine *co)
5926{
5927 aio_co_enter(bdrv_get_aio_context(bs), co);
5928}
5929
e8a095da
SH
5930static void bdrv_do_remove_aio_context_notifier(BdrvAioNotifier *ban)
5931{
5932 QLIST_REMOVE(ban, list);
5933 g_free(ban);
5934}
5935
a3a683c3 5936static void bdrv_detach_aio_context(BlockDriverState *bs)
dcd04228 5937{
e8a095da 5938 BdrvAioNotifier *baf, *baf_tmp;
33384421 5939
e8a095da
SH
5940 assert(!bs->walking_aio_notifiers);
5941 bs->walking_aio_notifiers = true;
5942 QLIST_FOREACH_SAFE(baf, &bs->aio_notifiers, list, baf_tmp) {
5943 if (baf->deleted) {
5944 bdrv_do_remove_aio_context_notifier(baf);
5945 } else {
5946 baf->detach_aio_context(baf->opaque);
5947 }
33384421 5948 }
e8a095da
SH
5949 /* Never mind iterating again to check for ->deleted. bdrv_close() will
5950 * remove remaining aio notifiers if we aren't called again.
5951 */
5952 bs->walking_aio_notifiers = false;
33384421 5953
1bffe1ae 5954 if (bs->drv && bs->drv->bdrv_detach_aio_context) {
dcd04228
SH
5955 bs->drv->bdrv_detach_aio_context(bs);
5956 }
dcd04228 5957
e64f25f3
KW
5958 if (bs->quiesce_counter) {
5959 aio_enable_external(bs->aio_context);
5960 }
dcd04228
SH
5961 bs->aio_context = NULL;
5962}
5963
a3a683c3
KW
5964static void bdrv_attach_aio_context(BlockDriverState *bs,
5965 AioContext *new_context)
dcd04228 5966{
e8a095da 5967 BdrvAioNotifier *ban, *ban_tmp;
33384421 5968
e64f25f3
KW
5969 if (bs->quiesce_counter) {
5970 aio_disable_external(new_context);
5971 }
5972
dcd04228
SH
5973 bs->aio_context = new_context;
5974
1bffe1ae 5975 if (bs->drv && bs->drv->bdrv_attach_aio_context) {
dcd04228
SH
5976 bs->drv->bdrv_attach_aio_context(bs, new_context);
5977 }
33384421 5978
e8a095da
SH
5979 assert(!bs->walking_aio_notifiers);
5980 bs->walking_aio_notifiers = true;
5981 QLIST_FOREACH_SAFE(ban, &bs->aio_notifiers, list, ban_tmp) {
5982 if (ban->deleted) {
5983 bdrv_do_remove_aio_context_notifier(ban);
5984 } else {
5985 ban->attached_aio_context(new_context, ban->opaque);
5986 }
33384421 5987 }
e8a095da 5988 bs->walking_aio_notifiers = false;
dcd04228
SH
5989}
5990
42a65f02
KW
5991/*
5992 * Changes the AioContext used for fd handlers, timers, and BHs by this
5993 * BlockDriverState and all its children and parents.
5994 *
43eaaaef
HR
5995 * Must be called from the main AioContext.
5996 *
42a65f02
KW
5997 * The caller must own the AioContext lock for the old AioContext of bs, but it
5998 * must not own the AioContext lock for new_context (unless new_context is the
5999 * same as the current context of bs).
6000 *
6001 * @ignore will accumulate all visited BdrvChild object. The caller is
6002 * responsible for freeing the list afterwards.
6003 */
53a7d041
KW
6004void bdrv_set_aio_context_ignore(BlockDriverState *bs,
6005 AioContext *new_context, GSList **ignore)
dcd04228 6006{
e037c09c 6007 AioContext *old_context = bdrv_get_aio_context(bs);
0d83708a
KW
6008 BdrvChild *child;
6009
43eaaaef
HR
6010 g_assert(qemu_get_current_aio_context() == qemu_get_aio_context());
6011
e037c09c 6012 if (old_context == new_context) {
57830a49
DP
6013 return;
6014 }
6015
d70d5954 6016 bdrv_drained_begin(bs);
0d83708a
KW
6017
6018 QLIST_FOREACH(child, &bs->children, next) {
53a7d041
KW
6019 if (g_slist_find(*ignore, child)) {
6020 continue;
6021 }
6022 *ignore = g_slist_prepend(*ignore, child);
6023 bdrv_set_aio_context_ignore(child->bs, new_context, ignore);
6024 }
6025 QLIST_FOREACH(child, &bs->parents, next_parent) {
6026 if (g_slist_find(*ignore, child)) {
6027 continue;
6028 }
42a65f02
KW
6029 assert(child->role->set_aio_ctx);
6030 *ignore = g_slist_prepend(*ignore, child);
6031 child->role->set_aio_ctx(child, new_context, ignore);
0d83708a
KW
6032 }
6033
dcd04228
SH
6034 bdrv_detach_aio_context(bs);
6035
e037c09c 6036 /* Acquire the new context, if necessary */
43eaaaef 6037 if (qemu_get_aio_context() != new_context) {
e037c09c
HR
6038 aio_context_acquire(new_context);
6039 }
6040
dcd04228 6041 bdrv_attach_aio_context(bs, new_context);
e037c09c
HR
6042
6043 /*
6044 * If this function was recursively called from
6045 * bdrv_set_aio_context_ignore(), there may be nodes in the
6046 * subtree that have not yet been moved to the new AioContext.
6047 * Release the old one so bdrv_drained_end() can poll them.
6048 */
43eaaaef 6049 if (qemu_get_aio_context() != old_context) {
e037c09c
HR
6050 aio_context_release(old_context);
6051 }
6052
d70d5954 6053 bdrv_drained_end(bs);
e037c09c 6054
43eaaaef 6055 if (qemu_get_aio_context() != old_context) {
e037c09c
HR
6056 aio_context_acquire(old_context);
6057 }
43eaaaef 6058 if (qemu_get_aio_context() != new_context) {
e037c09c
HR
6059 aio_context_release(new_context);
6060 }
85d126f3 6061}
d616b224 6062
5d231849
KW
6063static bool bdrv_parent_can_set_aio_context(BdrvChild *c, AioContext *ctx,
6064 GSList **ignore, Error **errp)
6065{
6066 if (g_slist_find(*ignore, c)) {
6067 return true;
6068 }
6069 *ignore = g_slist_prepend(*ignore, c);
6070
6071 /* A BdrvChildRole that doesn't handle AioContext changes cannot
6072 * tolerate any AioContext changes */
6073 if (!c->role->can_set_aio_ctx) {
6074 char *user = bdrv_child_user_desc(c);
6075 error_setg(errp, "Changing iothreads is not supported by %s", user);
6076 g_free(user);
6077 return false;
6078 }
6079 if (!c->role->can_set_aio_ctx(c, ctx, ignore, errp)) {
6080 assert(!errp || *errp);
6081 return false;
6082 }
6083 return true;
6084}
6085
6086bool bdrv_child_can_set_aio_context(BdrvChild *c, AioContext *ctx,
6087 GSList **ignore, Error **errp)
6088{
6089 if (g_slist_find(*ignore, c)) {
6090 return true;
6091 }
6092 *ignore = g_slist_prepend(*ignore, c);
6093 return bdrv_can_set_aio_context(c->bs, ctx, ignore, errp);
6094}
6095
6096/* @ignore will accumulate all visited BdrvChild object. The caller is
6097 * responsible for freeing the list afterwards. */
6098bool bdrv_can_set_aio_context(BlockDriverState *bs, AioContext *ctx,
6099 GSList **ignore, Error **errp)
6100{
6101 BdrvChild *c;
6102
6103 if (bdrv_get_aio_context(bs) == ctx) {
6104 return true;
6105 }
6106
6107 QLIST_FOREACH(c, &bs->parents, next_parent) {
6108 if (!bdrv_parent_can_set_aio_context(c, ctx, ignore, errp)) {
6109 return false;
6110 }
6111 }
6112 QLIST_FOREACH(c, &bs->children, next) {
6113 if (!bdrv_child_can_set_aio_context(c, ctx, ignore, errp)) {
6114 return false;
6115 }
6116 }
6117
6118 return true;
6119}
6120
6121int bdrv_child_try_set_aio_context(BlockDriverState *bs, AioContext *ctx,
6122 BdrvChild *ignore_child, Error **errp)
6123{
6124 GSList *ignore;
6125 bool ret;
6126
6127 ignore = ignore_child ? g_slist_prepend(NULL, ignore_child) : NULL;
6128 ret = bdrv_can_set_aio_context(bs, ctx, &ignore, errp);
6129 g_slist_free(ignore);
6130
6131 if (!ret) {
6132 return -EPERM;
6133 }
6134
53a7d041
KW
6135 ignore = ignore_child ? g_slist_prepend(NULL, ignore_child) : NULL;
6136 bdrv_set_aio_context_ignore(bs, ctx, &ignore);
6137 g_slist_free(ignore);
6138
5d231849
KW
6139 return 0;
6140}
6141
6142int bdrv_try_set_aio_context(BlockDriverState *bs, AioContext *ctx,
6143 Error **errp)
6144{
6145 return bdrv_child_try_set_aio_context(bs, ctx, NULL, errp);
6146}
6147
33384421
HR
6148void bdrv_add_aio_context_notifier(BlockDriverState *bs,
6149 void (*attached_aio_context)(AioContext *new_context, void *opaque),
6150 void (*detach_aio_context)(void *opaque), void *opaque)
6151{
6152 BdrvAioNotifier *ban = g_new(BdrvAioNotifier, 1);
6153 *ban = (BdrvAioNotifier){
6154 .attached_aio_context = attached_aio_context,
6155 .detach_aio_context = detach_aio_context,
6156 .opaque = opaque
6157 };
6158
6159 QLIST_INSERT_HEAD(&bs->aio_notifiers, ban, list);
6160}
6161
6162void bdrv_remove_aio_context_notifier(BlockDriverState *bs,
6163 void (*attached_aio_context)(AioContext *,
6164 void *),
6165 void (*detach_aio_context)(void *),
6166 void *opaque)
6167{
6168 BdrvAioNotifier *ban, *ban_next;
6169
6170 QLIST_FOREACH_SAFE(ban, &bs->aio_notifiers, list, ban_next) {
6171 if (ban->attached_aio_context == attached_aio_context &&
6172 ban->detach_aio_context == detach_aio_context &&
e8a095da
SH
6173 ban->opaque == opaque &&
6174 ban->deleted == false)
33384421 6175 {
e8a095da
SH
6176 if (bs->walking_aio_notifiers) {
6177 ban->deleted = true;
6178 } else {
6179 bdrv_do_remove_aio_context_notifier(ban);
6180 }
33384421
HR
6181 return;
6182 }
6183 }
6184
6185 abort();
6186}
6187
77485434 6188int bdrv_amend_options(BlockDriverState *bs, QemuOpts *opts,
d1402b50
HR
6189 BlockDriverAmendStatusCB *status_cb, void *cb_opaque,
6190 Error **errp)
6f176b48 6191{
d470ad42 6192 if (!bs->drv) {
d1402b50 6193 error_setg(errp, "Node is ejected");
d470ad42
HR
6194 return -ENOMEDIUM;
6195 }
c282e1fd 6196 if (!bs->drv->bdrv_amend_options) {
d1402b50
HR
6197 error_setg(errp, "Block driver '%s' does not support option amendment",
6198 bs->drv->format_name);
6f176b48
HR
6199 return -ENOTSUP;
6200 }
d1402b50 6201 return bs->drv->bdrv_amend_options(bs, opts, status_cb, cb_opaque, errp);
6f176b48 6202}
f6186f49 6203
b5042a36
BC
6204/* This function will be called by the bdrv_recurse_is_first_non_filter method
6205 * of block filter and by bdrv_is_first_non_filter.
6206 * It is used to test if the given bs is the candidate or recurse more in the
6207 * node graph.
212a5a8f 6208 */
b5042a36 6209bool bdrv_recurse_is_first_non_filter(BlockDriverState *bs,
212a5a8f 6210 BlockDriverState *candidate)
f6186f49 6211{
b5042a36
BC
6212 /* return false if basic checks fails */
6213 if (!bs || !bs->drv) {
212a5a8f 6214 return false;
f6186f49
BC
6215 }
6216
b5042a36
BC
6217 /* the code reached a non block filter driver -> check if the bs is
6218 * the same as the candidate. It's the recursion termination condition.
6219 */
6220 if (!bs->drv->is_filter) {
6221 return bs == candidate;
212a5a8f 6222 }
b5042a36 6223 /* Down this path the driver is a block filter driver */
212a5a8f 6224
b5042a36
BC
6225 /* If the block filter recursion method is defined use it to recurse down
6226 * the node graph.
6227 */
6228 if (bs->drv->bdrv_recurse_is_first_non_filter) {
212a5a8f 6229 return bs->drv->bdrv_recurse_is_first_non_filter(bs, candidate);
f6186f49
BC
6230 }
6231
b5042a36
BC
6232 /* the driver is a block filter but don't allow to recurse -> return false
6233 */
6234 return false;
f6186f49
BC
6235}
6236
5d69b5ab
HR
6237/*
6238 * This function checks whether the given @to_replace is allowed to be
6239 * replaced by a node that always shows the same data as @bs. This is
6240 * used for example to verify whether the mirror job can replace
6241 * @to_replace by the target mirrored from @bs.
6242 * To be replaceable, @bs and @to_replace may either be guaranteed to
6243 * always show the same data (because they are only connected through
6244 * filters), or some driver may allow replacing one of its children
6245 * because it can guarantee that this child's data is not visible at
6246 * all (for example, for dissenting quorum children that have no other
6247 * parents).
6248 */
6249bool bdrv_recurse_can_replace(BlockDriverState *bs,
6250 BlockDriverState *to_replace)
6251{
6252 if (!bs || !bs->drv) {
6253 return false;
6254 }
6255
6256 if (bs == to_replace) {
6257 return true;
6258 }
6259
6260 /* See what the driver can do */
6261 if (bs->drv->bdrv_recurse_can_replace) {
6262 return bs->drv->bdrv_recurse_can_replace(bs, to_replace);
6263 }
6264
6265 /* For filters without an own implementation, we can recurse on our own */
6266 if (bs->drv->is_filter) {
6267 BdrvChild *child = bs->file ?: bs->backing;
6268 return bdrv_recurse_can_replace(child->bs, to_replace);
6269 }
6270
6271 /* Safe default */
6272 return false;
6273}
6274
e12f3784
WC
6275BlockDriverState *check_to_replace_node(BlockDriverState *parent_bs,
6276 const char *node_name, Error **errp)
09158f00
BC
6277{
6278 BlockDriverState *to_replace_bs = bdrv_find_node(node_name);
5a7e7a0b
SH
6279 AioContext *aio_context;
6280
09158f00
BC
6281 if (!to_replace_bs) {
6282 error_setg(errp, "Node name '%s' not found", node_name);
6283 return NULL;
6284 }
6285
5a7e7a0b
SH
6286 aio_context = bdrv_get_aio_context(to_replace_bs);
6287 aio_context_acquire(aio_context);
6288
09158f00 6289 if (bdrv_op_is_blocked(to_replace_bs, BLOCK_OP_TYPE_REPLACE, errp)) {
5a7e7a0b
SH
6290 to_replace_bs = NULL;
6291 goto out;
09158f00
BC
6292 }
6293
6294 /* We don't want arbitrary node of the BDS chain to be replaced only the top
6295 * most non filter in order to prevent data corruption.
6296 * Another benefit is that this tests exclude backing files which are
6297 * blocked by the backing blockers.
6298 */
e12f3784 6299 if (!bdrv_recurse_is_first_non_filter(parent_bs, to_replace_bs)) {
09158f00 6300 error_setg(errp, "Only top most non filter can be replaced");
5a7e7a0b
SH
6301 to_replace_bs = NULL;
6302 goto out;
09158f00
BC
6303 }
6304
5a7e7a0b
SH
6305out:
6306 aio_context_release(aio_context);
09158f00
BC
6307 return to_replace_bs;
6308}
448ad91d 6309
97e2f021
HR
6310/**
6311 * Iterates through the list of runtime option keys that are said to
6312 * be "strong" for a BDS. An option is called "strong" if it changes
6313 * a BDS's data. For example, the null block driver's "size" and
6314 * "read-zeroes" options are strong, but its "latency-ns" option is
6315 * not.
6316 *
6317 * If a key returned by this function ends with a dot, all options
6318 * starting with that prefix are strong.
6319 */
6320static const char *const *strong_options(BlockDriverState *bs,
6321 const char *const *curopt)
6322{
6323 static const char *const global_options[] = {
6324 "driver", "filename", NULL
6325 };
6326
6327 if (!curopt) {
6328 return &global_options[0];
6329 }
6330
6331 curopt++;
6332 if (curopt == &global_options[ARRAY_SIZE(global_options) - 1] && bs->drv) {
6333 curopt = bs->drv->strong_runtime_opts;
6334 }
6335
6336 return (curopt && *curopt) ? curopt : NULL;
6337}
6338
6339/**
6340 * Copies all strong runtime options from bs->options to the given
6341 * QDict. The set of strong option keys is determined by invoking
6342 * strong_options().
6343 *
6344 * Returns true iff any strong option was present in bs->options (and
6345 * thus copied to the target QDict) with the exception of "filename"
6346 * and "driver". The caller is expected to use this value to decide
6347 * whether the existence of strong options prevents the generation of
6348 * a plain filename.
6349 */
6350static bool append_strong_runtime_options(QDict *d, BlockDriverState *bs)
6351{
6352 bool found_any = false;
6353 const char *const *option_name = NULL;
6354
6355 if (!bs->drv) {
6356 return false;
6357 }
6358
6359 while ((option_name = strong_options(bs, option_name))) {
6360 bool option_given = false;
6361
6362 assert(strlen(*option_name) > 0);
6363 if ((*option_name)[strlen(*option_name) - 1] != '.') {
6364 QObject *entry = qdict_get(bs->options, *option_name);
6365 if (!entry) {
6366 continue;
6367 }
6368
6369 qdict_put_obj(d, *option_name, qobject_ref(entry));
6370 option_given = true;
6371 } else {
6372 const QDictEntry *entry;
6373 for (entry = qdict_first(bs->options); entry;
6374 entry = qdict_next(bs->options, entry))
6375 {
6376 if (strstart(qdict_entry_key(entry), *option_name, NULL)) {
6377 qdict_put_obj(d, qdict_entry_key(entry),
6378 qobject_ref(qdict_entry_value(entry)));
6379 option_given = true;
6380 }
6381 }
6382 }
6383
6384 /* While "driver" and "filename" need to be included in a JSON filename,
6385 * their existence does not prohibit generation of a plain filename. */
6386 if (!found_any && option_given &&
6387 strcmp(*option_name, "driver") && strcmp(*option_name, "filename"))
6388 {
6389 found_any = true;
6390 }
6391 }
6392
62a01a27
HR
6393 if (!qdict_haskey(d, "driver")) {
6394 /* Drivers created with bdrv_new_open_driver() may not have a
6395 * @driver option. Add it here. */
6396 qdict_put_str(d, "driver", bs->drv->format_name);
6397 }
6398
97e2f021
HR
6399 return found_any;
6400}
6401
90993623
HR
6402/* Note: This function may return false positives; it may return true
6403 * even if opening the backing file specified by bs's image header
6404 * would result in exactly bs->backing. */
6405static bool bdrv_backing_overridden(BlockDriverState *bs)
6406{
6407 if (bs->backing) {
6408 return strcmp(bs->auto_backing_file,
6409 bs->backing->bs->filename);
6410 } else {
6411 /* No backing BDS, so if the image header reports any backing
6412 * file, it must have been suppressed */
6413 return bs->auto_backing_file[0] != '\0';
6414 }
6415}
6416
91af7014
HR
6417/* Updates the following BDS fields:
6418 * - exact_filename: A filename which may be used for opening a block device
6419 * which (mostly) equals the given BDS (even without any
6420 * other options; so reading and writing must return the same
6421 * results, but caching etc. may be different)
6422 * - full_open_options: Options which, when given when opening a block device
6423 * (without a filename), result in a BDS (mostly)
6424 * equalling the given one
6425 * - filename: If exact_filename is set, it is copied here. Otherwise,
6426 * full_open_options is converted to a JSON object, prefixed with
6427 * "json:" (for use through the JSON pseudo protocol) and put here.
6428 */
6429void bdrv_refresh_filename(BlockDriverState *bs)
6430{
6431 BlockDriver *drv = bs->drv;
e24518e3 6432 BdrvChild *child;
91af7014 6433 QDict *opts;
90993623 6434 bool backing_overridden;
998b3a1e
HR
6435 bool generate_json_filename; /* Whether our default implementation should
6436 fill exact_filename (false) or not (true) */
91af7014
HR
6437
6438 if (!drv) {
6439 return;
6440 }
6441
e24518e3
HR
6442 /* This BDS's file name may depend on any of its children's file names, so
6443 * refresh those first */
6444 QLIST_FOREACH(child, &bs->children, next) {
6445 bdrv_refresh_filename(child->bs);
91af7014
HR
6446 }
6447
bb808d5f
HR
6448 if (bs->implicit) {
6449 /* For implicit nodes, just copy everything from the single child */
6450 child = QLIST_FIRST(&bs->children);
6451 assert(QLIST_NEXT(child, next) == NULL);
6452
6453 pstrcpy(bs->exact_filename, sizeof(bs->exact_filename),
6454 child->bs->exact_filename);
6455 pstrcpy(bs->filename, sizeof(bs->filename), child->bs->filename);
6456
cb895614 6457 qobject_unref(bs->full_open_options);
bb808d5f
HR
6458 bs->full_open_options = qobject_ref(child->bs->full_open_options);
6459
6460 return;
6461 }
6462
90993623
HR
6463 backing_overridden = bdrv_backing_overridden(bs);
6464
6465 if (bs->open_flags & BDRV_O_NO_IO) {
6466 /* Without I/O, the backing file does not change anything.
6467 * Therefore, in such a case (primarily qemu-img), we can
6468 * pretend the backing file has not been overridden even if
6469 * it technically has been. */
6470 backing_overridden = false;
6471 }
6472
97e2f021
HR
6473 /* Gather the options QDict */
6474 opts = qdict_new();
998b3a1e
HR
6475 generate_json_filename = append_strong_runtime_options(opts, bs);
6476 generate_json_filename |= backing_overridden;
97e2f021
HR
6477
6478 if (drv->bdrv_gather_child_options) {
6479 /* Some block drivers may not want to present all of their children's
6480 * options, or name them differently from BdrvChild.name */
6481 drv->bdrv_gather_child_options(bs, opts, backing_overridden);
6482 } else {
6483 QLIST_FOREACH(child, &bs->children, next) {
6484 if (child->role == &child_backing && !backing_overridden) {
6485 /* We can skip the backing BDS if it has not been overridden */
6486 continue;
6487 }
6488
6489 qdict_put(opts, child->name,
6490 qobject_ref(child->bs->full_open_options));
6491 }
6492
6493 if (backing_overridden && !bs->backing) {
6494 /* Force no backing file */
6495 qdict_put_null(opts, "backing");
6496 }
6497 }
6498
6499 qobject_unref(bs->full_open_options);
6500 bs->full_open_options = opts;
6501
998b3a1e
HR
6502 if (drv->bdrv_refresh_filename) {
6503 /* Obsolete information is of no use here, so drop the old file name
6504 * information before refreshing it */
6505 bs->exact_filename[0] = '\0';
6506
6507 drv->bdrv_refresh_filename(bs);
6508 } else if (bs->file) {
6509 /* Try to reconstruct valid information from the underlying file */
6510
6511 bs->exact_filename[0] = '\0';
6512
fb695c74
HR
6513 /*
6514 * We can use the underlying file's filename if:
6515 * - it has a filename,
6516 * - the file is a protocol BDS, and
6517 * - opening that file (as this BDS's format) will automatically create
6518 * the BDS tree we have right now, that is:
6519 * - the user did not significantly change this BDS's behavior with
6520 * some explicit (strong) options
6521 * - no non-file child of this BDS has been overridden by the user
6522 * Both of these conditions are represented by generate_json_filename.
6523 */
6524 if (bs->file->bs->exact_filename[0] &&
6525 bs->file->bs->drv->bdrv_file_open &&
6526 !generate_json_filename)
6527 {
998b3a1e
HR
6528 strcpy(bs->exact_filename, bs->file->bs->exact_filename);
6529 }
6530 }
6531
91af7014
HR
6532 if (bs->exact_filename[0]) {
6533 pstrcpy(bs->filename, sizeof(bs->filename), bs->exact_filename);
97e2f021 6534 } else {
91af7014
HR
6535 QString *json = qobject_to_json(QOBJECT(bs->full_open_options));
6536 snprintf(bs->filename, sizeof(bs->filename), "json:%s",
6537 qstring_get_str(json));
cb3e7f08 6538 qobject_unref(json);
91af7014
HR
6539 }
6540}
e06018ad 6541
1e89d0f9
HR
6542char *bdrv_dirname(BlockDriverState *bs, Error **errp)
6543{
6544 BlockDriver *drv = bs->drv;
6545
6546 if (!drv) {
6547 error_setg(errp, "Node '%s' is ejected", bs->node_name);
6548 return NULL;
6549 }
6550
6551 if (drv->bdrv_dirname) {
6552 return drv->bdrv_dirname(bs, errp);
6553 }
6554
6555 if (bs->file) {
6556 return bdrv_dirname(bs->file->bs, errp);
6557 }
6558
6559 bdrv_refresh_filename(bs);
6560 if (bs->exact_filename[0] != '\0') {
6561 return path_combine(bs->exact_filename, "");
6562 }
6563
6564 error_setg(errp, "Cannot generate a base directory for %s nodes",
6565 drv->format_name);
6566 return NULL;
6567}
6568
e06018ad
WC
6569/*
6570 * Hot add/remove a BDS's child. So the user can take a child offline when
6571 * it is broken and take a new child online
6572 */
6573void bdrv_add_child(BlockDriverState *parent_bs, BlockDriverState *child_bs,
6574 Error **errp)
6575{
6576
6577 if (!parent_bs->drv || !parent_bs->drv->bdrv_add_child) {
6578 error_setg(errp, "The node %s does not support adding a child",
6579 bdrv_get_device_or_node_name(parent_bs));
6580 return;
6581 }
6582
6583 if (!QLIST_EMPTY(&child_bs->parents)) {
6584 error_setg(errp, "The node %s already has a parent",
6585 child_bs->node_name);
6586 return;
6587 }
6588
6589 parent_bs->drv->bdrv_add_child(parent_bs, child_bs, errp);
6590}
6591
6592void bdrv_del_child(BlockDriverState *parent_bs, BdrvChild *child, Error **errp)
6593{
6594 BdrvChild *tmp;
6595
6596 if (!parent_bs->drv || !parent_bs->drv->bdrv_del_child) {
6597 error_setg(errp, "The node %s does not support removing a child",
6598 bdrv_get_device_or_node_name(parent_bs));
6599 return;
6600 }
6601
6602 QLIST_FOREACH(tmp, &parent_bs->children, next) {
6603 if (tmp == child) {
6604 break;
6605 }
6606 }
6607
6608 if (!tmp) {
6609 error_setg(errp, "The node %s does not have a child named %s",
6610 bdrv_get_device_or_node_name(parent_bs),
6611 bdrv_get_device_or_node_name(child->bs));
6612 return;
6613 }
6614
6615 parent_bs->drv->bdrv_del_child(parent_bs, child, errp);
6616}