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