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