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