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