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