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