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