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