]> git.proxmox.com Git - mirror_qemu.git/blame - block.c
block: Update flags in bdrv_set_read_only()
[mirror_qemu.git] / block.c
CommitLineData
fc01f7e7
FB
1/*
2 * QEMU System Emulator block driver
5fafdf24 3 *
fc01f7e7 4 * Copyright (c) 2003 Fabrice Bellard
5fafdf24 5 *
fc01f7e7
FB
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
12 *
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
15 *
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22 * THE SOFTWARE.
23 */
e688df6b 24
d38ea87a 25#include "qemu/osdep.h"
0ab8ed18 26#include "block/trace.h"
737e150e
PB
27#include "block/block_int.h"
28#include "block/blockjob.h"
cd7fca95 29#include "block/nbd.h"
609f45ea 30#include "block/qdict.h"
d49b6836 31#include "qemu/error-report.h"
88d88798 32#include "module_block.h"
1de7afc9 33#include "qemu/module.h"
e688df6b 34#include "qapi/error.h"
452fcdbc 35#include "qapi/qmp/qdict.h"
7b1b5d19 36#include "qapi/qmp/qjson.h"
e59a0cf1 37#include "qapi/qmp/qnull.h"
fc81fa1e 38#include "qapi/qmp/qstring.h"
e1d74bc6
KW
39#include "qapi/qobject-output-visitor.h"
40#include "qapi/qapi-visit-block-core.h"
bfb197e0 41#include "sysemu/block-backend.h"
9c17d615 42#include "sysemu/sysemu.h"
1de7afc9 43#include "qemu/notify.h"
922a01a0 44#include "qemu/option.h"
10817bf0 45#include "qemu/coroutine.h"
c13163fb 46#include "block/qapi.h"
1de7afc9 47#include "qemu/timer.h"
f348b6d1
VB
48#include "qemu/cutils.h"
49#include "qemu/id.h"
fc01f7e7 50
71e72a19 51#ifdef CONFIG_BSD
7674e7bf 52#include <sys/ioctl.h>
72cf2d4f 53#include <sys/queue.h>
c5e97233 54#ifndef __DragonFly__
7674e7bf
FB
55#include <sys/disk.h>
56#endif
c5e97233 57#endif
7674e7bf 58
49dc768d
AL
59#ifdef _WIN32
60#include <windows.h>
61#endif
62
1c9805a3
SH
63#define NOT_DONE 0x7fffffff /* used while emulated sync operation in progress */
64
dc364f4c
BC
65static QTAILQ_HEAD(, BlockDriverState) graph_bdrv_states =
66 QTAILQ_HEAD_INITIALIZER(graph_bdrv_states);
67
2c1d04e0
HR
68static QTAILQ_HEAD(, BlockDriverState) all_bdrv_states =
69 QTAILQ_HEAD_INITIALIZER(all_bdrv_states);
70
8a22f02a
SH
71static QLIST_HEAD(, BlockDriver) bdrv_drivers =
72 QLIST_HEAD_INITIALIZER(bdrv_drivers);
ea2384d3 73
5b363937
HR
74static BlockDriverState *bdrv_open_inherit(const char *filename,
75 const char *reference,
76 QDict *options, int flags,
77 BlockDriverState *parent,
78 const BdrvChildRole *child_role,
79 Error **errp);
f3930ed0 80
eb852011
MA
81/* If non-zero, use only whitelisted block drivers */
82static int use_bdrv_whitelist;
83
9e0b22f4
SH
84#ifdef _WIN32
85static int is_windows_drive_prefix(const char *filename)
86{
87 return (((filename[0] >= 'a' && filename[0] <= 'z') ||
88 (filename[0] >= 'A' && filename[0] <= 'Z')) &&
89 filename[1] == ':');
90}
91
92int is_windows_drive(const char *filename)
93{
94 if (is_windows_drive_prefix(filename) &&
95 filename[2] == '\0')
96 return 1;
97 if (strstart(filename, "\\\\.\\", NULL) ||
98 strstart(filename, "//./", NULL))
99 return 1;
100 return 0;
101}
102#endif
103
339064d5
KW
104size_t bdrv_opt_mem_align(BlockDriverState *bs)
105{
106 if (!bs || !bs->drv) {
459b4e66
DL
107 /* page size or 4k (hdd sector size) should be on the safe side */
108 return MAX(4096, getpagesize());
339064d5
KW
109 }
110
111 return bs->bl.opt_mem_alignment;
112}
113
4196d2f0
DL
114size_t bdrv_min_mem_align(BlockDriverState *bs)
115{
116 if (!bs || !bs->drv) {
459b4e66
DL
117 /* page size or 4k (hdd sector size) should be on the safe side */
118 return MAX(4096, getpagesize());
4196d2f0
DL
119 }
120
121 return bs->bl.min_mem_alignment;
122}
123
9e0b22f4 124/* check if the path starts with "<protocol>:" */
5c98415b 125int path_has_protocol(const char *path)
9e0b22f4 126{
947995c0
PB
127 const char *p;
128
9e0b22f4
SH
129#ifdef _WIN32
130 if (is_windows_drive(path) ||
131 is_windows_drive_prefix(path)) {
132 return 0;
133 }
947995c0
PB
134 p = path + strcspn(path, ":/\\");
135#else
136 p = path + strcspn(path, ":/");
9e0b22f4
SH
137#endif
138
947995c0 139 return *p == ':';
9e0b22f4
SH
140}
141
83f64091 142int path_is_absolute(const char *path)
3b0d4f61 143{
21664424
FB
144#ifdef _WIN32
145 /* specific case for names like: "\\.\d:" */
f53f4da9 146 if (is_windows_drive(path) || is_windows_drive_prefix(path)) {
21664424 147 return 1;
f53f4da9
PB
148 }
149 return (*path == '/' || *path == '\\');
3b9f94e1 150#else
f53f4da9 151 return (*path == '/');
3b9f94e1 152#endif
3b0d4f61
FB
153}
154
83f64091
FB
155/* if filename is absolute, just copy it to dest. Otherwise, build a
156 path to it by considering it is relative to base_path. URL are
157 supported. */
158void path_combine(char *dest, int dest_size,
159 const char *base_path,
160 const char *filename)
3b0d4f61 161{
83f64091
FB
162 const char *p, *p1;
163 int len;
164
165 if (dest_size <= 0)
166 return;
167 if (path_is_absolute(filename)) {
168 pstrcpy(dest, dest_size, filename);
169 } else {
0d54a6fe
HR
170 const char *protocol_stripped = NULL;
171
172 if (path_has_protocol(base_path)) {
173 protocol_stripped = strchr(base_path, ':');
174 if (protocol_stripped) {
175 protocol_stripped++;
176 }
177 }
178 p = protocol_stripped ?: base_path;
179
3b9f94e1
FB
180 p1 = strrchr(base_path, '/');
181#ifdef _WIN32
182 {
183 const char *p2;
184 p2 = strrchr(base_path, '\\');
185 if (!p1 || p2 > p1)
186 p1 = p2;
187 }
188#endif
83f64091
FB
189 if (p1)
190 p1++;
191 else
192 p1 = base_path;
193 if (p1 > p)
194 p = p1;
195 len = p - base_path;
196 if (len > dest_size - 1)
197 len = dest_size - 1;
198 memcpy(dest, base_path, len);
199 dest[len] = '\0';
200 pstrcat(dest, dest_size, filename);
3b0d4f61 201 }
3b0d4f61
FB
202}
203
03c320d8
HR
204/*
205 * Helper function for bdrv_parse_filename() implementations to remove optional
206 * protocol prefixes (especially "file:") from a filename and for putting the
207 * stripped filename into the options QDict if there is such a prefix.
208 */
209void bdrv_parse_filename_strip_prefix(const char *filename, const char *prefix,
210 QDict *options)
211{
212 if (strstart(filename, prefix, &filename)) {
213 /* Stripping the explicit protocol prefix may result in a protocol
214 * prefix being (wrongly) detected (if the filename contains a colon) */
215 if (path_has_protocol(filename)) {
216 QString *fat_filename;
217
218 /* This means there is some colon before the first slash; therefore,
219 * this cannot be an absolute path */
220 assert(!path_is_absolute(filename));
221
222 /* And we can thus fix the protocol detection issue by prefixing it
223 * by "./" */
224 fat_filename = qstring_from_str("./");
225 qstring_append(fat_filename, filename);
226
227 assert(!path_has_protocol(qstring_get_str(fat_filename)));
228
229 qdict_put(options, "filename", fat_filename);
230 } else {
231 /* If no protocol prefix was detected, we can use the shortened
232 * filename as-is */
233 qdict_put_str(options, "filename", filename);
234 }
235 }
236}
237
238
9c5e6594
KW
239/* Returns whether the image file is opened as read-only. Note that this can
240 * return false and writing to the image file is still not possible because the
241 * image is inactivated. */
93ed524e
JC
242bool bdrv_is_read_only(BlockDriverState *bs)
243{
244 return bs->read_only;
245}
246
54a32bfe
KW
247int bdrv_can_set_read_only(BlockDriverState *bs, bool read_only,
248 bool ignore_allow_rdw, Error **errp)
fe5241bf 249{
e2b8247a
JC
250 /* Do not set read_only if copy_on_read is enabled */
251 if (bs->copy_on_read && read_only) {
252 error_setg(errp, "Can't set node '%s' to r/o with copy-on-read enabled",
253 bdrv_get_device_or_node_name(bs));
254 return -EINVAL;
255 }
256
d6fcdf06 257 /* Do not clear read_only if it is prohibited */
54a32bfe
KW
258 if (!read_only && !(bs->open_flags & BDRV_O_ALLOW_RDWR) &&
259 !ignore_allow_rdw)
260 {
d6fcdf06
JC
261 error_setg(errp, "Node '%s' is read only",
262 bdrv_get_device_or_node_name(bs));
263 return -EPERM;
264 }
265
45803a03
JC
266 return 0;
267}
268
398e6ad0
KW
269/* TODO Remove (deprecated since 2.11)
270 * Block drivers are not supposed to automatically change bs->read_only.
271 * Instead, they should just check whether they can provide what the user
272 * explicitly requested and error out if read-write is requested, but they can
273 * only provide read-only access. */
45803a03
JC
274int bdrv_set_read_only(BlockDriverState *bs, bool read_only, Error **errp)
275{
276 int ret = 0;
277
54a32bfe 278 ret = bdrv_can_set_read_only(bs, read_only, false, errp);
45803a03
JC
279 if (ret < 0) {
280 return ret;
281 }
282
fe5241bf 283 bs->read_only = read_only;
eeae6a59
KW
284
285 if (read_only) {
286 bs->open_flags &= ~BDRV_O_RDWR;
287 } else {
288 bs->open_flags |= BDRV_O_RDWR;
289 }
290
e2b8247a 291 return 0;
fe5241bf
JC
292}
293
0a82855a
HR
294void bdrv_get_full_backing_filename_from_filename(const char *backed,
295 const char *backing,
9f07429e
HR
296 char *dest, size_t sz,
297 Error **errp)
dc5a1371 298{
9f07429e
HR
299 if (backing[0] == '\0' || path_has_protocol(backing) ||
300 path_is_absolute(backing))
301 {
0a82855a 302 pstrcpy(dest, sz, backing);
9f07429e
HR
303 } else if (backed[0] == '\0' || strstart(backed, "json:", NULL)) {
304 error_setg(errp, "Cannot use relative backing file names for '%s'",
305 backed);
dc5a1371 306 } else {
0a82855a 307 path_combine(dest, sz, backed, backing);
dc5a1371
PB
308 }
309}
310
9f07429e
HR
311void bdrv_get_full_backing_filename(BlockDriverState *bs, char *dest, size_t sz,
312 Error **errp)
0a82855a 313{
9f07429e
HR
314 char *backed = bs->exact_filename[0] ? bs->exact_filename : bs->filename;
315
316 bdrv_get_full_backing_filename_from_filename(backed, bs->backing_file,
317 dest, sz, errp);
0a82855a
HR
318}
319
0eb7217e
SH
320void bdrv_register(BlockDriver *bdrv)
321{
8a22f02a 322 QLIST_INSERT_HEAD(&bdrv_drivers, bdrv, list);
ea2384d3 323}
b338082b 324
e4e9986b
MA
325BlockDriverState *bdrv_new(void)
326{
327 BlockDriverState *bs;
328 int i;
329
5839e53b 330 bs = g_new0(BlockDriverState, 1);
e4654d2d 331 QLIST_INIT(&bs->dirty_bitmaps);
fbe40ff7
FZ
332 for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
333 QLIST_INIT(&bs->op_blockers[i]);
334 }
d616b224 335 notifier_with_return_list_init(&bs->before_write_notifiers);
3783fa3d 336 qemu_co_mutex_init(&bs->reqs_lock);
2119882c 337 qemu_mutex_init(&bs->dirty_bitmap_mutex);
9fcb0251 338 bs->refcnt = 1;
dcd04228 339 bs->aio_context = qemu_get_aio_context();
d7d512f6 340
3ff2f67a
EY
341 qemu_co_queue_init(&bs->flush_queue);
342
0f12264e
KW
343 for (i = 0; i < bdrv_drain_all_count; i++) {
344 bdrv_drained_begin(bs);
345 }
346
2c1d04e0
HR
347 QTAILQ_INSERT_TAIL(&all_bdrv_states, bs, bs_list);
348
b338082b
FB
349 return bs;
350}
351
88d88798 352static BlockDriver *bdrv_do_find_format(const char *format_name)
ea2384d3
FB
353{
354 BlockDriver *drv1;
88d88798 355
8a22f02a
SH
356 QLIST_FOREACH(drv1, &bdrv_drivers, list) {
357 if (!strcmp(drv1->format_name, format_name)) {
ea2384d3 358 return drv1;
8a22f02a 359 }
ea2384d3 360 }
88d88798 361
ea2384d3
FB
362 return NULL;
363}
364
88d88798
MM
365BlockDriver *bdrv_find_format(const char *format_name)
366{
367 BlockDriver *drv1;
368 int i;
369
370 drv1 = bdrv_do_find_format(format_name);
371 if (drv1) {
372 return drv1;
373 }
374
375 /* The driver isn't registered, maybe we need to load a module */
376 for (i = 0; i < (int)ARRAY_SIZE(block_driver_modules); ++i) {
377 if (!strcmp(block_driver_modules[i].format_name, format_name)) {
378 block_module_load_one(block_driver_modules[i].library_name);
379 break;
380 }
381 }
382
383 return bdrv_do_find_format(format_name);
384}
385
e8eb8637 386int bdrv_is_whitelisted(BlockDriver *drv, bool read_only)
eb852011 387{
b64ec4e4
FZ
388 static const char *whitelist_rw[] = {
389 CONFIG_BDRV_RW_WHITELIST
390 };
391 static const char *whitelist_ro[] = {
392 CONFIG_BDRV_RO_WHITELIST
eb852011
MA
393 };
394 const char **p;
395
b64ec4e4 396 if (!whitelist_rw[0] && !whitelist_ro[0]) {
eb852011 397 return 1; /* no whitelist, anything goes */
b64ec4e4 398 }
eb852011 399
b64ec4e4 400 for (p = whitelist_rw; *p; p++) {
eb852011
MA
401 if (!strcmp(drv->format_name, *p)) {
402 return 1;
403 }
404 }
b64ec4e4
FZ
405 if (read_only) {
406 for (p = whitelist_ro; *p; p++) {
407 if (!strcmp(drv->format_name, *p)) {
408 return 1;
409 }
410 }
411 }
eb852011
MA
412 return 0;
413}
414
e6ff69bf
DB
415bool bdrv_uses_whitelist(void)
416{
417 return use_bdrv_whitelist;
418}
419
5b7e1542
ZYW
420typedef struct CreateCo {
421 BlockDriver *drv;
422 char *filename;
83d0521a 423 QemuOpts *opts;
5b7e1542 424 int ret;
cc84d90f 425 Error *err;
5b7e1542
ZYW
426} CreateCo;
427
428static void coroutine_fn bdrv_create_co_entry(void *opaque)
429{
cc84d90f
HR
430 Error *local_err = NULL;
431 int ret;
432
5b7e1542
ZYW
433 CreateCo *cco = opaque;
434 assert(cco->drv);
435
efc75e2a 436 ret = cco->drv->bdrv_co_create_opts(cco->filename, cco->opts, &local_err);
621ff94d 437 error_propagate(&cco->err, local_err);
cc84d90f 438 cco->ret = ret;
5b7e1542
ZYW
439}
440
0e7e1989 441int bdrv_create(BlockDriver *drv, const char* filename,
83d0521a 442 QemuOpts *opts, Error **errp)
ea2384d3 443{
5b7e1542
ZYW
444 int ret;
445
446 Coroutine *co;
447 CreateCo cco = {
448 .drv = drv,
449 .filename = g_strdup(filename),
83d0521a 450 .opts = opts,
5b7e1542 451 .ret = NOT_DONE,
cc84d90f 452 .err = NULL,
5b7e1542
ZYW
453 };
454
efc75e2a 455 if (!drv->bdrv_co_create_opts) {
cc84d90f 456 error_setg(errp, "Driver '%s' does not support image creation", drv->format_name);
80168bff
LC
457 ret = -ENOTSUP;
458 goto out;
5b7e1542
ZYW
459 }
460
461 if (qemu_in_coroutine()) {
462 /* Fast-path if already in coroutine context */
463 bdrv_create_co_entry(&cco);
464 } else {
0b8b8753
PB
465 co = qemu_coroutine_create(bdrv_create_co_entry, &cco);
466 qemu_coroutine_enter(co);
5b7e1542 467 while (cco.ret == NOT_DONE) {
b47ec2c4 468 aio_poll(qemu_get_aio_context(), true);
5b7e1542
ZYW
469 }
470 }
471
472 ret = cco.ret;
cc84d90f 473 if (ret < 0) {
84d18f06 474 if (cco.err) {
cc84d90f
HR
475 error_propagate(errp, cco.err);
476 } else {
477 error_setg_errno(errp, -ret, "Could not create image");
478 }
479 }
0e7e1989 480
80168bff
LC
481out:
482 g_free(cco.filename);
5b7e1542 483 return ret;
ea2384d3
FB
484}
485
c282e1fd 486int bdrv_create_file(const char *filename, QemuOpts *opts, Error **errp)
84a12e66
CH
487{
488 BlockDriver *drv;
cc84d90f
HR
489 Error *local_err = NULL;
490 int ret;
84a12e66 491
b65a5e12 492 drv = bdrv_find_protocol(filename, true, errp);
84a12e66 493 if (drv == NULL) {
16905d71 494 return -ENOENT;
84a12e66
CH
495 }
496
c282e1fd 497 ret = bdrv_create(drv, filename, opts, &local_err);
621ff94d 498 error_propagate(errp, local_err);
cc84d90f 499 return ret;
84a12e66
CH
500}
501
892b7de8
ET
502/**
503 * Try to get @bs's logical and physical block size.
504 * On success, store them in @bsz struct and return 0.
505 * On failure return -errno.
506 * @bs must not be empty.
507 */
508int bdrv_probe_blocksizes(BlockDriverState *bs, BlockSizes *bsz)
509{
510 BlockDriver *drv = bs->drv;
511
512 if (drv && drv->bdrv_probe_blocksizes) {
513 return drv->bdrv_probe_blocksizes(bs, bsz);
5a612c00
MP
514 } else if (drv && drv->is_filter && bs->file) {
515 return bdrv_probe_blocksizes(bs->file->bs, bsz);
892b7de8
ET
516 }
517
518 return -ENOTSUP;
519}
520
521/**
522 * Try to get @bs's geometry (cyls, heads, sectors).
523 * On success, store them in @geo struct and return 0.
524 * On failure return -errno.
525 * @bs must not be empty.
526 */
527int bdrv_probe_geometry(BlockDriverState *bs, HDGeometry *geo)
528{
529 BlockDriver *drv = bs->drv;
530
531 if (drv && drv->bdrv_probe_geometry) {
532 return drv->bdrv_probe_geometry(bs, geo);
5a612c00
MP
533 } else if (drv && drv->is_filter && bs->file) {
534 return bdrv_probe_geometry(bs->file->bs, geo);
892b7de8
ET
535 }
536
537 return -ENOTSUP;
538}
539
eba25057
JM
540/*
541 * Create a uniquely-named empty temporary file.
542 * Return 0 upon success, otherwise a negative errno value.
543 */
544int get_tmp_filename(char *filename, int size)
d5249393 545{
eba25057 546#ifdef _WIN32
3b9f94e1 547 char temp_dir[MAX_PATH];
eba25057
JM
548 /* GetTempFileName requires that its output buffer (4th param)
549 have length MAX_PATH or greater. */
550 assert(size >= MAX_PATH);
551 return (GetTempPath(MAX_PATH, temp_dir)
552 && GetTempFileName(temp_dir, "qem", 0, filename)
553 ? 0 : -GetLastError());
d5249393 554#else
67b915a5 555 int fd;
7ccfb2eb 556 const char *tmpdir;
0badc1ee 557 tmpdir = getenv("TMPDIR");
69bef793
AS
558 if (!tmpdir) {
559 tmpdir = "/var/tmp";
560 }
eba25057
JM
561 if (snprintf(filename, size, "%s/vl.XXXXXX", tmpdir) >= size) {
562 return -EOVERFLOW;
563 }
ea2384d3 564 fd = mkstemp(filename);
fe235a06
DH
565 if (fd < 0) {
566 return -errno;
567 }
568 if (close(fd) != 0) {
569 unlink(filename);
eba25057
JM
570 return -errno;
571 }
572 return 0;
d5249393 573#endif
eba25057 574}
fc01f7e7 575
84a12e66
CH
576/*
577 * Detect host devices. By convention, /dev/cdrom[N] is always
578 * recognized as a host CDROM.
579 */
580static BlockDriver *find_hdev_driver(const char *filename)
581{
582 int score_max = 0, score;
583 BlockDriver *drv = NULL, *d;
584
585 QLIST_FOREACH(d, &bdrv_drivers, list) {
586 if (d->bdrv_probe_device) {
587 score = d->bdrv_probe_device(filename);
588 if (score > score_max) {
589 score_max = score;
590 drv = d;
591 }
592 }
593 }
594
595 return drv;
596}
597
88d88798
MM
598static BlockDriver *bdrv_do_find_protocol(const char *protocol)
599{
600 BlockDriver *drv1;
601
602 QLIST_FOREACH(drv1, &bdrv_drivers, list) {
603 if (drv1->protocol_name && !strcmp(drv1->protocol_name, protocol)) {
604 return drv1;
605 }
606 }
607
608 return NULL;
609}
610
98289620 611BlockDriver *bdrv_find_protocol(const char *filename,
b65a5e12
HR
612 bool allow_protocol_prefix,
613 Error **errp)
83f64091
FB
614{
615 BlockDriver *drv1;
616 char protocol[128];
1cec71e3 617 int len;
83f64091 618 const char *p;
88d88798 619 int i;
19cb3738 620
66f82cee
KW
621 /* TODO Drivers without bdrv_file_open must be specified explicitly */
622
39508e7a
CH
623 /*
624 * XXX(hch): we really should not let host device detection
625 * override an explicit protocol specification, but moving this
626 * later breaks access to device names with colons in them.
627 * Thanks to the brain-dead persistent naming schemes on udev-
628 * based Linux systems those actually are quite common.
629 */
630 drv1 = find_hdev_driver(filename);
631 if (drv1) {
632 return drv1;
633 }
634
98289620 635 if (!path_has_protocol(filename) || !allow_protocol_prefix) {
ef810437 636 return &bdrv_file;
84a12e66 637 }
98289620 638
9e0b22f4
SH
639 p = strchr(filename, ':');
640 assert(p != NULL);
1cec71e3
AL
641 len = p - filename;
642 if (len > sizeof(protocol) - 1)
643 len = sizeof(protocol) - 1;
644 memcpy(protocol, filename, len);
645 protocol[len] = '\0';
88d88798
MM
646
647 drv1 = bdrv_do_find_protocol(protocol);
648 if (drv1) {
649 return drv1;
650 }
651
652 for (i = 0; i < (int)ARRAY_SIZE(block_driver_modules); ++i) {
653 if (block_driver_modules[i].protocol_name &&
654 !strcmp(block_driver_modules[i].protocol_name, protocol)) {
655 block_module_load_one(block_driver_modules[i].library_name);
656 break;
8a22f02a 657 }
83f64091 658 }
b65a5e12 659
88d88798
MM
660 drv1 = bdrv_do_find_protocol(protocol);
661 if (!drv1) {
662 error_setg(errp, "Unknown protocol '%s'", protocol);
663 }
664 return drv1;
83f64091
FB
665}
666
c6684249
MA
667/*
668 * Guess image format by probing its contents.
669 * This is not a good idea when your image is raw (CVE-2008-2004), but
670 * we do it anyway for backward compatibility.
671 *
672 * @buf contains the image's first @buf_size bytes.
7cddd372
KW
673 * @buf_size is the buffer size in bytes (generally BLOCK_PROBE_BUF_SIZE,
674 * but can be smaller if the image file is smaller)
c6684249
MA
675 * @filename is its filename.
676 *
677 * For all block drivers, call the bdrv_probe() method to get its
678 * probing score.
679 * Return the first block driver with the highest probing score.
680 */
38f3ef57
KW
681BlockDriver *bdrv_probe_all(const uint8_t *buf, int buf_size,
682 const char *filename)
c6684249
MA
683{
684 int score_max = 0, score;
685 BlockDriver *drv = NULL, *d;
686
687 QLIST_FOREACH(d, &bdrv_drivers, list) {
688 if (d->bdrv_probe) {
689 score = d->bdrv_probe(buf, buf_size, filename);
690 if (score > score_max) {
691 score_max = score;
692 drv = d;
693 }
694 }
695 }
696
697 return drv;
698}
699
5696c6e3 700static int find_image_format(BlockBackend *file, const char *filename,
34b5d2c6 701 BlockDriver **pdrv, Error **errp)
f3a5d3f8 702{
c6684249 703 BlockDriver *drv;
7cddd372 704 uint8_t buf[BLOCK_PROBE_BUF_SIZE];
f500a6d3 705 int ret = 0;
f8ea0b00 706
08a00559 707 /* Return the raw BlockDriver * to scsi-generic devices or empty drives */
5696c6e3 708 if (blk_is_sg(file) || !blk_is_inserted(file) || blk_getlength(file) == 0) {
ef810437 709 *pdrv = &bdrv_raw;
c98ac35d 710 return ret;
1a396859 711 }
f8ea0b00 712
5696c6e3 713 ret = blk_pread(file, 0, buf, sizeof(buf));
83f64091 714 if (ret < 0) {
34b5d2c6
HR
715 error_setg_errno(errp, -ret, "Could not read image for determining its "
716 "format");
c98ac35d
SW
717 *pdrv = NULL;
718 return ret;
83f64091
FB
719 }
720
c6684249 721 drv = bdrv_probe_all(buf, ret, filename);
c98ac35d 722 if (!drv) {
34b5d2c6
HR
723 error_setg(errp, "Could not determine image format: No compatible "
724 "driver found");
c98ac35d
SW
725 ret = -ENOENT;
726 }
727 *pdrv = drv;
728 return ret;
ea2384d3
FB
729}
730
51762288
SH
731/**
732 * Set the current 'total_sectors' value
65a9bb25 733 * Return 0 on success, -errno on error.
51762288 734 */
3d9f2d2a 735int refresh_total_sectors(BlockDriverState *bs, int64_t hint)
51762288
SH
736{
737 BlockDriver *drv = bs->drv;
738
d470ad42
HR
739 if (!drv) {
740 return -ENOMEDIUM;
741 }
742
396759ad 743 /* Do not attempt drv->bdrv_getlength() on scsi-generic devices */
b192af8a 744 if (bdrv_is_sg(bs))
396759ad
NB
745 return 0;
746
51762288
SH
747 /* query actual device if possible, otherwise just trust the hint */
748 if (drv->bdrv_getlength) {
749 int64_t length = drv->bdrv_getlength(bs);
750 if (length < 0) {
751 return length;
752 }
7e382003 753 hint = DIV_ROUND_UP(length, BDRV_SECTOR_SIZE);
51762288
SH
754 }
755
756 bs->total_sectors = hint;
757 return 0;
758}
759
cddff5ba
KW
760/**
761 * Combines a QDict of new block driver @options with any missing options taken
762 * from @old_options, so that leaving out an option defaults to its old value.
763 */
764static void bdrv_join_options(BlockDriverState *bs, QDict *options,
765 QDict *old_options)
766{
767 if (bs->drv && bs->drv->bdrv_join_options) {
768 bs->drv->bdrv_join_options(options, old_options);
769 } else {
770 qdict_join(options, old_options, false);
771 }
772}
773
543770bd
AG
774static BlockdevDetectZeroesOptions bdrv_parse_detect_zeroes(QemuOpts *opts,
775 int open_flags,
776 Error **errp)
777{
778 Error *local_err = NULL;
779 char *value = qemu_opt_get_del(opts, "detect-zeroes");
780 BlockdevDetectZeroesOptions detect_zeroes =
781 qapi_enum_parse(&BlockdevDetectZeroesOptions_lookup, value,
782 BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF, &local_err);
783 g_free(value);
784 if (local_err) {
785 error_propagate(errp, local_err);
786 return detect_zeroes;
787 }
788
789 if (detect_zeroes == BLOCKDEV_DETECT_ZEROES_OPTIONS_UNMAP &&
790 !(open_flags & BDRV_O_UNMAP))
791 {
792 error_setg(errp, "setting detect-zeroes to unmap is not allowed "
793 "without setting discard operation to unmap");
794 }
795
796 return detect_zeroes;
797}
798
9e8f1835
PB
799/**
800 * Set open flags for a given discard mode
801 *
802 * Return 0 on success, -1 if the discard mode was invalid.
803 */
804int bdrv_parse_discard_flags(const char *mode, int *flags)
805{
806 *flags &= ~BDRV_O_UNMAP;
807
808 if (!strcmp(mode, "off") || !strcmp(mode, "ignore")) {
809 /* do nothing */
810 } else if (!strcmp(mode, "on") || !strcmp(mode, "unmap")) {
811 *flags |= BDRV_O_UNMAP;
812 } else {
813 return -1;
814 }
815
816 return 0;
817}
818
c3993cdc
SH
819/**
820 * Set open flags for a given cache mode
821 *
822 * Return 0 on success, -1 if the cache mode was invalid.
823 */
53e8ae01 824int bdrv_parse_cache_mode(const char *mode, int *flags, bool *writethrough)
c3993cdc
SH
825{
826 *flags &= ~BDRV_O_CACHE_MASK;
827
828 if (!strcmp(mode, "off") || !strcmp(mode, "none")) {
53e8ae01
KW
829 *writethrough = false;
830 *flags |= BDRV_O_NOCACHE;
92196b2f 831 } else if (!strcmp(mode, "directsync")) {
53e8ae01 832 *writethrough = true;
92196b2f 833 *flags |= BDRV_O_NOCACHE;
c3993cdc 834 } else if (!strcmp(mode, "writeback")) {
53e8ae01 835 *writethrough = false;
c3993cdc 836 } else if (!strcmp(mode, "unsafe")) {
53e8ae01 837 *writethrough = false;
c3993cdc
SH
838 *flags |= BDRV_O_NO_FLUSH;
839 } else if (!strcmp(mode, "writethrough")) {
53e8ae01 840 *writethrough = true;
c3993cdc
SH
841 } else {
842 return -1;
843 }
844
845 return 0;
846}
847
b5411555
KW
848static char *bdrv_child_get_parent_desc(BdrvChild *c)
849{
850 BlockDriverState *parent = c->opaque;
851 return g_strdup(bdrv_get_device_or_node_name(parent));
852}
853
20018e12
KW
854static void bdrv_child_cb_drained_begin(BdrvChild *child)
855{
856 BlockDriverState *bs = child->opaque;
6cd5c9d7 857 bdrv_do_drained_begin_quiesce(bs, NULL, false);
20018e12
KW
858}
859
89bd0305
KW
860static bool bdrv_child_cb_drained_poll(BdrvChild *child)
861{
862 BlockDriverState *bs = child->opaque;
6cd5c9d7 863 return bdrv_drain_poll(bs, false, NULL, false);
89bd0305
KW
864}
865
20018e12
KW
866static void bdrv_child_cb_drained_end(BdrvChild *child)
867{
868 BlockDriverState *bs = child->opaque;
869 bdrv_drained_end(bs);
870}
871
d736f119
KW
872static void bdrv_child_cb_attach(BdrvChild *child)
873{
874 BlockDriverState *bs = child->opaque;
875 bdrv_apply_subtree_drain(child, bs);
876}
877
878static void bdrv_child_cb_detach(BdrvChild *child)
879{
880 BlockDriverState *bs = child->opaque;
881 bdrv_unapply_subtree_drain(child, bs);
882}
883
38701b6a
KW
884static int bdrv_child_cb_inactivate(BdrvChild *child)
885{
886 BlockDriverState *bs = child->opaque;
887 assert(bs->open_flags & BDRV_O_INACTIVE);
888 return 0;
889}
890
b1e6fc08 891/*
73176bee
KW
892 * Returns the options and flags that a temporary snapshot should get, based on
893 * the originally requested flags (the originally requested image will have
894 * flags like a backing file)
b1e6fc08 895 */
73176bee
KW
896static void bdrv_temp_snapshot_options(int *child_flags, QDict *child_options,
897 int parent_flags, QDict *parent_options)
b1e6fc08 898{
73176bee
KW
899 *child_flags = (parent_flags & ~BDRV_O_SNAPSHOT) | BDRV_O_TEMPORARY;
900
901 /* For temporary files, unconditional cache=unsafe is fine */
73176bee
KW
902 qdict_set_default_str(child_options, BDRV_OPT_CACHE_DIRECT, "off");
903 qdict_set_default_str(child_options, BDRV_OPT_CACHE_NO_FLUSH, "on");
41869044 904
f87a0e29
AG
905 /* Copy the read-only option from the parent */
906 qdict_copy_default(child_options, parent_options, BDRV_OPT_READ_ONLY);
907
41869044
KW
908 /* aio=native doesn't work for cache.direct=off, so disable it for the
909 * temporary snapshot */
910 *child_flags &= ~BDRV_O_NATIVE_AIO;
b1e6fc08
KW
911}
912
0b50cc88 913/*
8e2160e2
KW
914 * Returns the options and flags that bs->file should get if a protocol driver
915 * is expected, based on the given options and flags for the parent BDS
0b50cc88 916 */
8e2160e2
KW
917static void bdrv_inherited_options(int *child_flags, QDict *child_options,
918 int parent_flags, QDict *parent_options)
0b50cc88 919{
8e2160e2
KW
920 int flags = parent_flags;
921
0b50cc88
KW
922 /* Enable protocol handling, disable format probing for bs->file */
923 flags |= BDRV_O_PROTOCOL;
924
91a097e7
KW
925 /* If the cache mode isn't explicitly set, inherit direct and no-flush from
926 * the parent. */
927 qdict_copy_default(child_options, parent_options, BDRV_OPT_CACHE_DIRECT);
928 qdict_copy_default(child_options, parent_options, BDRV_OPT_CACHE_NO_FLUSH);
5a9347c6 929 qdict_copy_default(child_options, parent_options, BDRV_OPT_FORCE_SHARE);
91a097e7 930
f87a0e29
AG
931 /* Inherit the read-only option from the parent if it's not set */
932 qdict_copy_default(child_options, parent_options, BDRV_OPT_READ_ONLY);
933
0b50cc88 934 /* Our block drivers take care to send flushes and respect unmap policy,
91a097e7
KW
935 * so we can default to enable both on lower layers regardless of the
936 * corresponding parent options. */
818584a4 937 qdict_set_default_str(child_options, BDRV_OPT_DISCARD, "unmap");
0b50cc88 938
0b50cc88 939 /* Clear flags that only apply to the top layer */
abb06c5a
DB
940 flags &= ~(BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING | BDRV_O_COPY_ON_READ |
941 BDRV_O_NO_IO);
0b50cc88 942
8e2160e2 943 *child_flags = flags;
0b50cc88
KW
944}
945
f3930ed0 946const BdrvChildRole child_file = {
6cd5c9d7 947 .parent_is_bds = true,
b5411555 948 .get_parent_desc = bdrv_child_get_parent_desc,
8e2160e2 949 .inherit_options = bdrv_inherited_options,
20018e12 950 .drained_begin = bdrv_child_cb_drained_begin,
89bd0305 951 .drained_poll = bdrv_child_cb_drained_poll,
20018e12 952 .drained_end = bdrv_child_cb_drained_end,
d736f119
KW
953 .attach = bdrv_child_cb_attach,
954 .detach = bdrv_child_cb_detach,
38701b6a 955 .inactivate = bdrv_child_cb_inactivate,
f3930ed0
KW
956};
957
958/*
8e2160e2
KW
959 * Returns the options and flags that bs->file should get if the use of formats
960 * (and not only protocols) is permitted for it, based on the given options and
961 * flags for the parent BDS
f3930ed0 962 */
8e2160e2
KW
963static void bdrv_inherited_fmt_options(int *child_flags, QDict *child_options,
964 int parent_flags, QDict *parent_options)
f3930ed0 965{
8e2160e2
KW
966 child_file.inherit_options(child_flags, child_options,
967 parent_flags, parent_options);
968
abb06c5a 969 *child_flags &= ~(BDRV_O_PROTOCOL | BDRV_O_NO_IO);
f3930ed0
KW
970}
971
972const BdrvChildRole child_format = {
6cd5c9d7 973 .parent_is_bds = true,
b5411555 974 .get_parent_desc = bdrv_child_get_parent_desc,
8e2160e2 975 .inherit_options = bdrv_inherited_fmt_options,
20018e12 976 .drained_begin = bdrv_child_cb_drained_begin,
89bd0305 977 .drained_poll = bdrv_child_cb_drained_poll,
20018e12 978 .drained_end = bdrv_child_cb_drained_end,
d736f119
KW
979 .attach = bdrv_child_cb_attach,
980 .detach = bdrv_child_cb_detach,
38701b6a 981 .inactivate = bdrv_child_cb_inactivate,
f3930ed0
KW
982};
983
db95dbba
KW
984static void bdrv_backing_attach(BdrvChild *c)
985{
986 BlockDriverState *parent = c->opaque;
987 BlockDriverState *backing_hd = c->bs;
988
989 assert(!parent->backing_blocker);
990 error_setg(&parent->backing_blocker,
991 "node is used as backing hd of '%s'",
992 bdrv_get_device_or_node_name(parent));
993
994 parent->open_flags &= ~BDRV_O_NO_BACKING;
995 pstrcpy(parent->backing_file, sizeof(parent->backing_file),
996 backing_hd->filename);
997 pstrcpy(parent->backing_format, sizeof(parent->backing_format),
998 backing_hd->drv ? backing_hd->drv->format_name : "");
999
1000 bdrv_op_block_all(backing_hd, parent->backing_blocker);
1001 /* Otherwise we won't be able to commit or stream */
1002 bdrv_op_unblock(backing_hd, BLOCK_OP_TYPE_COMMIT_TARGET,
1003 parent->backing_blocker);
1004 bdrv_op_unblock(backing_hd, BLOCK_OP_TYPE_STREAM,
1005 parent->backing_blocker);
1006 /*
1007 * We do backup in 3 ways:
1008 * 1. drive backup
1009 * The target bs is new opened, and the source is top BDS
1010 * 2. blockdev backup
1011 * Both the source and the target are top BDSes.
1012 * 3. internal backup(used for block replication)
1013 * Both the source and the target are backing file
1014 *
1015 * In case 1 and 2, neither the source nor the target is the backing file.
1016 * In case 3, we will block the top BDS, so there is only one block job
1017 * for the top BDS and its backing chain.
1018 */
1019 bdrv_op_unblock(backing_hd, BLOCK_OP_TYPE_BACKUP_SOURCE,
1020 parent->backing_blocker);
1021 bdrv_op_unblock(backing_hd, BLOCK_OP_TYPE_BACKUP_TARGET,
1022 parent->backing_blocker);
d736f119
KW
1023
1024 bdrv_child_cb_attach(c);
db95dbba
KW
1025}
1026
1027static void bdrv_backing_detach(BdrvChild *c)
1028{
1029 BlockDriverState *parent = c->opaque;
1030
1031 assert(parent->backing_blocker);
1032 bdrv_op_unblock_all(c->bs, parent->backing_blocker);
1033 error_free(parent->backing_blocker);
1034 parent->backing_blocker = NULL;
d736f119
KW
1035
1036 bdrv_child_cb_detach(c);
db95dbba
KW
1037}
1038
317fc44e 1039/*
8e2160e2
KW
1040 * Returns the options and flags that bs->backing should get, based on the
1041 * given options and flags for the parent BDS
317fc44e 1042 */
8e2160e2
KW
1043static void bdrv_backing_options(int *child_flags, QDict *child_options,
1044 int parent_flags, QDict *parent_options)
317fc44e 1045{
8e2160e2
KW
1046 int flags = parent_flags;
1047
b8816a43
KW
1048 /* The cache mode is inherited unmodified for backing files; except WCE,
1049 * which is only applied on the top level (BlockBackend) */
91a097e7
KW
1050 qdict_copy_default(child_options, parent_options, BDRV_OPT_CACHE_DIRECT);
1051 qdict_copy_default(child_options, parent_options, BDRV_OPT_CACHE_NO_FLUSH);
5a9347c6 1052 qdict_copy_default(child_options, parent_options, BDRV_OPT_FORCE_SHARE);
91a097e7 1053
317fc44e 1054 /* backing files always opened read-only */
f87a0e29
AG
1055 qdict_set_default_str(child_options, BDRV_OPT_READ_ONLY, "on");
1056 flags &= ~BDRV_O_COPY_ON_READ;
317fc44e
KW
1057
1058 /* snapshot=on is handled on the top layer */
8bfea15d 1059 flags &= ~(BDRV_O_SNAPSHOT | BDRV_O_TEMPORARY);
317fc44e 1060
8e2160e2 1061 *child_flags = flags;
317fc44e
KW
1062}
1063
6858eba0
KW
1064static int bdrv_backing_update_filename(BdrvChild *c, BlockDriverState *base,
1065 const char *filename, Error **errp)
1066{
1067 BlockDriverState *parent = c->opaque;
61f09cea 1068 int orig_flags = bdrv_get_flags(parent);
6858eba0
KW
1069 int ret;
1070
61f09cea
KW
1071 if (!(orig_flags & BDRV_O_RDWR)) {
1072 ret = bdrv_reopen(parent, orig_flags | BDRV_O_RDWR, errp);
1073 if (ret < 0) {
1074 return ret;
1075 }
1076 }
1077
6858eba0
KW
1078 ret = bdrv_change_backing_file(parent, filename,
1079 base->drv ? base->drv->format_name : "");
1080 if (ret < 0) {
64730694 1081 error_setg_errno(errp, -ret, "Could not update backing file link");
6858eba0
KW
1082 }
1083
61f09cea
KW
1084 if (!(orig_flags & BDRV_O_RDWR)) {
1085 bdrv_reopen(parent, orig_flags, NULL);
1086 }
1087
6858eba0
KW
1088 return ret;
1089}
1090
91ef3825 1091const BdrvChildRole child_backing = {
6cd5c9d7 1092 .parent_is_bds = true,
b5411555 1093 .get_parent_desc = bdrv_child_get_parent_desc,
db95dbba
KW
1094 .attach = bdrv_backing_attach,
1095 .detach = bdrv_backing_detach,
8e2160e2 1096 .inherit_options = bdrv_backing_options,
20018e12 1097 .drained_begin = bdrv_child_cb_drained_begin,
89bd0305 1098 .drained_poll = bdrv_child_cb_drained_poll,
20018e12 1099 .drained_end = bdrv_child_cb_drained_end,
38701b6a 1100 .inactivate = bdrv_child_cb_inactivate,
6858eba0 1101 .update_filename = bdrv_backing_update_filename,
f3930ed0
KW
1102};
1103
7b272452
KW
1104static int bdrv_open_flags(BlockDriverState *bs, int flags)
1105{
61de4c68 1106 int open_flags = flags;
7b272452
KW
1107
1108 /*
1109 * Clear flags that are internal to the block layer before opening the
1110 * image.
1111 */
20cca275 1112 open_flags &= ~(BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING | BDRV_O_PROTOCOL);
7b272452
KW
1113
1114 /*
1115 * Snapshots should be writable.
1116 */
8bfea15d 1117 if (flags & BDRV_O_TEMPORARY) {
7b272452
KW
1118 open_flags |= BDRV_O_RDWR;
1119 }
1120
1121 return open_flags;
1122}
1123
91a097e7
KW
1124static void update_flags_from_options(int *flags, QemuOpts *opts)
1125{
1126 *flags &= ~BDRV_O_CACHE_MASK;
1127
91a097e7 1128 assert(qemu_opt_find(opts, BDRV_OPT_CACHE_NO_FLUSH));
57f9db9a 1129 if (qemu_opt_get_bool_del(opts, BDRV_OPT_CACHE_NO_FLUSH, false)) {
91a097e7
KW
1130 *flags |= BDRV_O_NO_FLUSH;
1131 }
1132
1133 assert(qemu_opt_find(opts, BDRV_OPT_CACHE_DIRECT));
57f9db9a 1134 if (qemu_opt_get_bool_del(opts, BDRV_OPT_CACHE_DIRECT, false)) {
91a097e7
KW
1135 *flags |= BDRV_O_NOCACHE;
1136 }
f87a0e29
AG
1137
1138 *flags &= ~BDRV_O_RDWR;
1139
1140 assert(qemu_opt_find(opts, BDRV_OPT_READ_ONLY));
57f9db9a 1141 if (!qemu_opt_get_bool_del(opts, BDRV_OPT_READ_ONLY, false)) {
f87a0e29
AG
1142 *flags |= BDRV_O_RDWR;
1143 }
1144
91a097e7
KW
1145}
1146
1147static void update_options_from_flags(QDict *options, int flags)
1148{
91a097e7 1149 if (!qdict_haskey(options, BDRV_OPT_CACHE_DIRECT)) {
46f5ac20 1150 qdict_put_bool(options, BDRV_OPT_CACHE_DIRECT, flags & BDRV_O_NOCACHE);
91a097e7
KW
1151 }
1152 if (!qdict_haskey(options, BDRV_OPT_CACHE_NO_FLUSH)) {
46f5ac20
EB
1153 qdict_put_bool(options, BDRV_OPT_CACHE_NO_FLUSH,
1154 flags & BDRV_O_NO_FLUSH);
91a097e7 1155 }
f87a0e29 1156 if (!qdict_haskey(options, BDRV_OPT_READ_ONLY)) {
46f5ac20 1157 qdict_put_bool(options, BDRV_OPT_READ_ONLY, !(flags & BDRV_O_RDWR));
f87a0e29 1158 }
91a097e7
KW
1159}
1160
636ea370
KW
1161static void bdrv_assign_node_name(BlockDriverState *bs,
1162 const char *node_name,
1163 Error **errp)
6913c0c2 1164{
15489c76 1165 char *gen_node_name = NULL;
6913c0c2 1166
15489c76
JC
1167 if (!node_name) {
1168 node_name = gen_node_name = id_generate(ID_BLOCK);
1169 } else if (!id_wellformed(node_name)) {
1170 /*
1171 * Check for empty string or invalid characters, but not if it is
1172 * generated (generated names use characters not available to the user)
1173 */
9aebf3b8 1174 error_setg(errp, "Invalid node name");
636ea370 1175 return;
6913c0c2
BC
1176 }
1177
0c5e94ee 1178 /* takes care of avoiding namespaces collisions */
7f06d47e 1179 if (blk_by_name(node_name)) {
0c5e94ee
BC
1180 error_setg(errp, "node-name=%s is conflicting with a device id",
1181 node_name);
15489c76 1182 goto out;
0c5e94ee
BC
1183 }
1184
6913c0c2
BC
1185 /* takes care of avoiding duplicates node names */
1186 if (bdrv_find_node(node_name)) {
1187 error_setg(errp, "Duplicate node name");
15489c76 1188 goto out;
6913c0c2
BC
1189 }
1190
824808dd
KW
1191 /* Make sure that the node name isn't truncated */
1192 if (strlen(node_name) >= sizeof(bs->node_name)) {
1193 error_setg(errp, "Node name too long");
1194 goto out;
1195 }
1196
6913c0c2
BC
1197 /* copy node name into the bs and insert it into the graph list */
1198 pstrcpy(bs->node_name, sizeof(bs->node_name), node_name);
1199 QTAILQ_INSERT_TAIL(&graph_bdrv_states, bs, node_list);
15489c76
JC
1200out:
1201 g_free(gen_node_name);
6913c0c2
BC
1202}
1203
01a56501
KW
1204static int bdrv_open_driver(BlockDriverState *bs, BlockDriver *drv,
1205 const char *node_name, QDict *options,
1206 int open_flags, Error **errp)
1207{
1208 Error *local_err = NULL;
0f12264e 1209 int i, ret;
01a56501
KW
1210
1211 bdrv_assign_node_name(bs, node_name, &local_err);
1212 if (local_err) {
1213 error_propagate(errp, local_err);
1214 return -EINVAL;
1215 }
1216
1217 bs->drv = drv;
680c7f96 1218 bs->read_only = !(bs->open_flags & BDRV_O_RDWR);
01a56501
KW
1219 bs->opaque = g_malloc0(drv->instance_size);
1220
1221 if (drv->bdrv_file_open) {
1222 assert(!drv->bdrv_needs_filename || bs->filename[0]);
1223 ret = drv->bdrv_file_open(bs, options, open_flags, &local_err);
680c7f96 1224 } else if (drv->bdrv_open) {
01a56501 1225 ret = drv->bdrv_open(bs, options, open_flags, &local_err);
680c7f96
KW
1226 } else {
1227 ret = 0;
01a56501
KW
1228 }
1229
1230 if (ret < 0) {
1231 if (local_err) {
1232 error_propagate(errp, local_err);
1233 } else if (bs->filename[0]) {
1234 error_setg_errno(errp, -ret, "Could not open '%s'", bs->filename);
1235 } else {
1236 error_setg_errno(errp, -ret, "Could not open image");
1237 }
180ca19a 1238 goto open_failed;
01a56501
KW
1239 }
1240
1241 ret = refresh_total_sectors(bs, bs->total_sectors);
1242 if (ret < 0) {
1243 error_setg_errno(errp, -ret, "Could not refresh total sector count");
180ca19a 1244 return ret;
01a56501
KW
1245 }
1246
1247 bdrv_refresh_limits(bs, &local_err);
1248 if (local_err) {
1249 error_propagate(errp, local_err);
180ca19a 1250 return -EINVAL;
01a56501
KW
1251 }
1252
1253 assert(bdrv_opt_mem_align(bs) != 0);
1254 assert(bdrv_min_mem_align(bs) != 0);
1255 assert(is_power_of_2(bs->bl.request_alignment));
1256
0f12264e
KW
1257 for (i = 0; i < bs->quiesce_counter; i++) {
1258 if (drv->bdrv_co_drain_begin) {
1259 drv->bdrv_co_drain_begin(bs);
1260 }
1261 }
1262
01a56501 1263 return 0;
180ca19a
MP
1264open_failed:
1265 bs->drv = NULL;
1266 if (bs->file != NULL) {
1267 bdrv_unref_child(bs, bs->file);
1268 bs->file = NULL;
1269 }
01a56501
KW
1270 g_free(bs->opaque);
1271 bs->opaque = NULL;
01a56501
KW
1272 return ret;
1273}
1274
680c7f96
KW
1275BlockDriverState *bdrv_new_open_driver(BlockDriver *drv, const char *node_name,
1276 int flags, Error **errp)
1277{
1278 BlockDriverState *bs;
1279 int ret;
1280
1281 bs = bdrv_new();
1282 bs->open_flags = flags;
1283 bs->explicit_options = qdict_new();
1284 bs->options = qdict_new();
1285 bs->opaque = NULL;
1286
1287 update_options_from_flags(bs->options, flags);
1288
1289 ret = bdrv_open_driver(bs, drv, node_name, bs->options, flags, errp);
1290 if (ret < 0) {
cb3e7f08 1291 qobject_unref(bs->explicit_options);
180ca19a 1292 bs->explicit_options = NULL;
cb3e7f08 1293 qobject_unref(bs->options);
180ca19a 1294 bs->options = NULL;
680c7f96
KW
1295 bdrv_unref(bs);
1296 return NULL;
1297 }
1298
1299 return bs;
1300}
1301
c5f3014b 1302QemuOptsList bdrv_runtime_opts = {
18edf289
KW
1303 .name = "bdrv_common",
1304 .head = QTAILQ_HEAD_INITIALIZER(bdrv_runtime_opts.head),
1305 .desc = {
1306 {
1307 .name = "node-name",
1308 .type = QEMU_OPT_STRING,
1309 .help = "Node name of the block device node",
1310 },
62392ebb
KW
1311 {
1312 .name = "driver",
1313 .type = QEMU_OPT_STRING,
1314 .help = "Block driver to use for the node",
1315 },
91a097e7
KW
1316 {
1317 .name = BDRV_OPT_CACHE_DIRECT,
1318 .type = QEMU_OPT_BOOL,
1319 .help = "Bypass software writeback cache on the host",
1320 },
1321 {
1322 .name = BDRV_OPT_CACHE_NO_FLUSH,
1323 .type = QEMU_OPT_BOOL,
1324 .help = "Ignore flush requests",
1325 },
f87a0e29
AG
1326 {
1327 .name = BDRV_OPT_READ_ONLY,
1328 .type = QEMU_OPT_BOOL,
1329 .help = "Node is opened in read-only mode",
1330 },
692e01a2
KW
1331 {
1332 .name = "detect-zeroes",
1333 .type = QEMU_OPT_STRING,
1334 .help = "try to optimize zero writes (off, on, unmap)",
1335 },
818584a4 1336 {
415bbca8 1337 .name = BDRV_OPT_DISCARD,
818584a4
KW
1338 .type = QEMU_OPT_STRING,
1339 .help = "discard operation (ignore/off, unmap/on)",
1340 },
5a9347c6
FZ
1341 {
1342 .name = BDRV_OPT_FORCE_SHARE,
1343 .type = QEMU_OPT_BOOL,
1344 .help = "always accept other writers (default: off)",
1345 },
18edf289
KW
1346 { /* end of list */ }
1347 },
1348};
1349
57915332
KW
1350/*
1351 * Common part for opening disk images and files
b6ad491a
KW
1352 *
1353 * Removes all processed options from *options.
57915332 1354 */
5696c6e3 1355static int bdrv_open_common(BlockDriverState *bs, BlockBackend *file,
82dc8b41 1356 QDict *options, Error **errp)
57915332
KW
1357{
1358 int ret, open_flags;
035fccdf 1359 const char *filename;
62392ebb 1360 const char *driver_name = NULL;
6913c0c2 1361 const char *node_name = NULL;
818584a4 1362 const char *discard;
18edf289 1363 QemuOpts *opts;
62392ebb 1364 BlockDriver *drv;
34b5d2c6 1365 Error *local_err = NULL;
57915332 1366
6405875c 1367 assert(bs->file == NULL);
707ff828 1368 assert(options != NULL && bs->options != options);
57915332 1369
62392ebb
KW
1370 opts = qemu_opts_create(&bdrv_runtime_opts, NULL, 0, &error_abort);
1371 qemu_opts_absorb_qdict(opts, options, &local_err);
1372 if (local_err) {
1373 error_propagate(errp, local_err);
1374 ret = -EINVAL;
1375 goto fail_opts;
1376 }
1377
9b7e8691
AG
1378 update_flags_from_options(&bs->open_flags, opts);
1379
62392ebb
KW
1380 driver_name = qemu_opt_get(opts, "driver");
1381 drv = bdrv_find_format(driver_name);
1382 assert(drv != NULL);
1383
5a9347c6
FZ
1384 bs->force_share = qemu_opt_get_bool(opts, BDRV_OPT_FORCE_SHARE, false);
1385
1386 if (bs->force_share && (bs->open_flags & BDRV_O_RDWR)) {
1387 error_setg(errp,
1388 BDRV_OPT_FORCE_SHARE
1389 "=on can only be used with read-only images");
1390 ret = -EINVAL;
1391 goto fail_opts;
1392 }
1393
45673671 1394 if (file != NULL) {
5696c6e3 1395 filename = blk_bs(file)->filename;
45673671 1396 } else {
129c7d1c
MA
1397 /*
1398 * Caution: while qdict_get_try_str() is fine, getting
1399 * non-string types would require more care. When @options
1400 * come from -blockdev or blockdev_add, its members are typed
1401 * according to the QAPI schema, but when they come from
1402 * -drive, they're all QString.
1403 */
45673671
KW
1404 filename = qdict_get_try_str(options, "filename");
1405 }
1406
4a008240 1407 if (drv->bdrv_needs_filename && (!filename || !filename[0])) {
765003db
KW
1408 error_setg(errp, "The '%s' block driver requires a file name",
1409 drv->format_name);
18edf289
KW
1410 ret = -EINVAL;
1411 goto fail_opts;
6913c0c2 1412 }
6913c0c2 1413
82dc8b41
KW
1414 trace_bdrv_open_common(bs, filename ?: "", bs->open_flags,
1415 drv->format_name);
62392ebb 1416
82dc8b41 1417 bs->read_only = !(bs->open_flags & BDRV_O_RDWR);
b64ec4e4
FZ
1418
1419 if (use_bdrv_whitelist && !bdrv_is_whitelisted(drv, bs->read_only)) {
8f94a6e4
KW
1420 error_setg(errp,
1421 !bs->read_only && bdrv_is_whitelisted(drv, true)
1422 ? "Driver '%s' can only be used for read-only devices"
1423 : "Driver '%s' is not whitelisted",
1424 drv->format_name);
18edf289
KW
1425 ret = -ENOTSUP;
1426 goto fail_opts;
b64ec4e4 1427 }
57915332 1428
d3faa13e
PB
1429 /* bdrv_new() and bdrv_close() make it so */
1430 assert(atomic_read(&bs->copy_on_read) == 0);
1431
82dc8b41 1432 if (bs->open_flags & BDRV_O_COPY_ON_READ) {
0ebd24e0
KW
1433 if (!bs->read_only) {
1434 bdrv_enable_copy_on_read(bs);
1435 } else {
1436 error_setg(errp, "Can't use copy-on-read on read-only device");
18edf289
KW
1437 ret = -EINVAL;
1438 goto fail_opts;
0ebd24e0 1439 }
53fec9d3
SH
1440 }
1441
415bbca8 1442 discard = qemu_opt_get(opts, BDRV_OPT_DISCARD);
818584a4
KW
1443 if (discard != NULL) {
1444 if (bdrv_parse_discard_flags(discard, &bs->open_flags) != 0) {
1445 error_setg(errp, "Invalid discard option");
1446 ret = -EINVAL;
1447 goto fail_opts;
1448 }
1449 }
1450
543770bd
AG
1451 bs->detect_zeroes =
1452 bdrv_parse_detect_zeroes(opts, bs->open_flags, &local_err);
1453 if (local_err) {
1454 error_propagate(errp, local_err);
1455 ret = -EINVAL;
1456 goto fail_opts;
692e01a2
KW
1457 }
1458
c2ad1b0c
KW
1459 if (filename != NULL) {
1460 pstrcpy(bs->filename, sizeof(bs->filename), filename);
1461 } else {
1462 bs->filename[0] = '\0';
1463 }
91af7014 1464 pstrcpy(bs->exact_filename, sizeof(bs->exact_filename), bs->filename);
57915332 1465
66f82cee 1466 /* Open the image, either directly or using a protocol */
82dc8b41 1467 open_flags = bdrv_open_flags(bs, bs->open_flags);
01a56501 1468 node_name = qemu_opt_get(opts, "node-name");
57915332 1469
01a56501
KW
1470 assert(!drv->bdrv_file_open || file == NULL);
1471 ret = bdrv_open_driver(bs, drv, node_name, options, open_flags, errp);
51762288 1472 if (ret < 0) {
01a56501 1473 goto fail_opts;
3baca891
KW
1474 }
1475
18edf289 1476 qemu_opts_del(opts);
57915332
KW
1477 return 0;
1478
18edf289
KW
1479fail_opts:
1480 qemu_opts_del(opts);
57915332
KW
1481 return ret;
1482}
1483
5e5c4f63
KW
1484static QDict *parse_json_filename(const char *filename, Error **errp)
1485{
1486 QObject *options_obj;
1487 QDict *options;
1488 int ret;
1489
1490 ret = strstart(filename, "json:", &filename);
1491 assert(ret);
1492
5577fff7 1493 options_obj = qobject_from_json(filename, errp);
5e5c4f63 1494 if (!options_obj) {
5577fff7 1495 error_prepend(errp, "Could not parse the JSON options: ");
5e5c4f63
KW
1496 return NULL;
1497 }
1498
7dc847eb 1499 options = qobject_to(QDict, options_obj);
ca6b6e1e 1500 if (!options) {
cb3e7f08 1501 qobject_unref(options_obj);
5e5c4f63
KW
1502 error_setg(errp, "Invalid JSON object given");
1503 return NULL;
1504 }
1505
5e5c4f63
KW
1506 qdict_flatten(options);
1507
1508 return options;
1509}
1510
de3b53f0
KW
1511static void parse_json_protocol(QDict *options, const char **pfilename,
1512 Error **errp)
1513{
1514 QDict *json_options;
1515 Error *local_err = NULL;
1516
1517 /* Parse json: pseudo-protocol */
1518 if (!*pfilename || !g_str_has_prefix(*pfilename, "json:")) {
1519 return;
1520 }
1521
1522 json_options = parse_json_filename(*pfilename, &local_err);
1523 if (local_err) {
1524 error_propagate(errp, local_err);
1525 return;
1526 }
1527
1528 /* Options given in the filename have lower priority than options
1529 * specified directly */
1530 qdict_join(options, json_options, false);
cb3e7f08 1531 qobject_unref(json_options);
de3b53f0
KW
1532 *pfilename = NULL;
1533}
1534
b6ce07aa 1535/*
f54120ff
KW
1536 * Fills in default options for opening images and converts the legacy
1537 * filename/flags pair to option QDict entries.
53a29513
HR
1538 * The BDRV_O_PROTOCOL flag in *flags will be set or cleared accordingly if a
1539 * block driver has been specified explicitly.
b6ce07aa 1540 */
de3b53f0 1541static int bdrv_fill_options(QDict **options, const char *filename,
053e1578 1542 int *flags, Error **errp)
ea2384d3 1543{
c2ad1b0c 1544 const char *drvname;
53a29513 1545 bool protocol = *flags & BDRV_O_PROTOCOL;
e3fa4bfa 1546 bool parse_filename = false;
053e1578 1547 BlockDriver *drv = NULL;
34b5d2c6 1548 Error *local_err = NULL;
83f64091 1549
129c7d1c
MA
1550 /*
1551 * Caution: while qdict_get_try_str() is fine, getting non-string
1552 * types would require more care. When @options come from
1553 * -blockdev or blockdev_add, its members are typed according to
1554 * the QAPI schema, but when they come from -drive, they're all
1555 * QString.
1556 */
53a29513 1557 drvname = qdict_get_try_str(*options, "driver");
053e1578
HR
1558 if (drvname) {
1559 drv = bdrv_find_format(drvname);
1560 if (!drv) {
1561 error_setg(errp, "Unknown driver '%s'", drvname);
1562 return -ENOENT;
1563 }
1564 /* If the user has explicitly specified the driver, this choice should
1565 * override the BDRV_O_PROTOCOL flag */
1566 protocol = drv->bdrv_file_open;
53a29513
HR
1567 }
1568
1569 if (protocol) {
1570 *flags |= BDRV_O_PROTOCOL;
1571 } else {
1572 *flags &= ~BDRV_O_PROTOCOL;
1573 }
1574
91a097e7
KW
1575 /* Translate cache options from flags into options */
1576 update_options_from_flags(*options, *flags);
1577
035fccdf 1578 /* Fetch the file name from the options QDict if necessary */
17b005f1 1579 if (protocol && filename) {
f54120ff 1580 if (!qdict_haskey(*options, "filename")) {
46f5ac20 1581 qdict_put_str(*options, "filename", filename);
f54120ff
KW
1582 parse_filename = true;
1583 } else {
1584 error_setg(errp, "Can't specify 'file' and 'filename' options at "
1585 "the same time");
1586 return -EINVAL;
1587 }
035fccdf
KW
1588 }
1589
c2ad1b0c 1590 /* Find the right block driver */
129c7d1c 1591 /* See cautionary note on accessing @options above */
f54120ff 1592 filename = qdict_get_try_str(*options, "filename");
f54120ff 1593
053e1578
HR
1594 if (!drvname && protocol) {
1595 if (filename) {
1596 drv = bdrv_find_protocol(filename, parse_filename, errp);
17b005f1 1597 if (!drv) {
053e1578 1598 return -EINVAL;
17b005f1 1599 }
053e1578
HR
1600
1601 drvname = drv->format_name;
46f5ac20 1602 qdict_put_str(*options, "driver", drvname);
053e1578
HR
1603 } else {
1604 error_setg(errp, "Must specify either driver or file");
1605 return -EINVAL;
98289620 1606 }
c2ad1b0c
KW
1607 }
1608
17b005f1 1609 assert(drv || !protocol);
c2ad1b0c 1610
f54120ff 1611 /* Driver-specific filename parsing */
17b005f1 1612 if (drv && drv->bdrv_parse_filename && parse_filename) {
5acd9d81 1613 drv->bdrv_parse_filename(filename, *options, &local_err);
84d18f06 1614 if (local_err) {
34b5d2c6 1615 error_propagate(errp, local_err);
f54120ff 1616 return -EINVAL;
6963a30d 1617 }
cd5d031e
HR
1618
1619 if (!drv->bdrv_needs_filename) {
1620 qdict_del(*options, "filename");
cd5d031e 1621 }
6963a30d
KW
1622 }
1623
f54120ff
KW
1624 return 0;
1625}
1626
3121fb45
KW
1627static int bdrv_child_check_perm(BdrvChild *c, BlockReopenQueue *q,
1628 uint64_t perm, uint64_t shared,
c1cef672
FZ
1629 GSList *ignore_children, Error **errp);
1630static void bdrv_child_abort_perm_update(BdrvChild *c);
1631static void bdrv_child_set_perm(BdrvChild *c, uint64_t perm, uint64_t shared);
1632
148eb13c
KW
1633typedef struct BlockReopenQueueEntry {
1634 bool prepared;
1635 BDRVReopenState state;
1636 QSIMPLEQ_ENTRY(BlockReopenQueueEntry) entry;
1637} BlockReopenQueueEntry;
1638
1639/*
1640 * Return the flags that @bs will have after the reopens in @q have
1641 * successfully completed. If @q is NULL (or @bs is not contained in @q),
1642 * return the current flags.
1643 */
1644static int bdrv_reopen_get_flags(BlockReopenQueue *q, BlockDriverState *bs)
1645{
1646 BlockReopenQueueEntry *entry;
1647
1648 if (q != NULL) {
1649 QSIMPLEQ_FOREACH(entry, q, entry) {
1650 if (entry->state.bs == bs) {
1651 return entry->state.flags;
1652 }
1653 }
1654 }
1655
1656 return bs->open_flags;
1657}
1658
1659/* Returns whether the image file can be written to after the reopen queue @q
1660 * has been successfully applied, or right now if @q is NULL. */
cc022140
HR
1661static bool bdrv_is_writable_after_reopen(BlockDriverState *bs,
1662 BlockReopenQueue *q)
148eb13c
KW
1663{
1664 int flags = bdrv_reopen_get_flags(q, bs);
1665
1666 return (flags & (BDRV_O_RDWR | BDRV_O_INACTIVE)) == BDRV_O_RDWR;
1667}
1668
cc022140
HR
1669/*
1670 * Return whether the BDS can be written to. This is not necessarily
1671 * the same as !bdrv_is_read_only(bs), as inactivated images may not
1672 * be written to but do not count as read-only images.
1673 */
1674bool bdrv_is_writable(BlockDriverState *bs)
1675{
1676 return bdrv_is_writable_after_reopen(bs, NULL);
1677}
1678
ffd1a5a2 1679static void bdrv_child_perm(BlockDriverState *bs, BlockDriverState *child_bs,
e0995dc3
KW
1680 BdrvChild *c, const BdrvChildRole *role,
1681 BlockReopenQueue *reopen_queue,
ffd1a5a2
FZ
1682 uint64_t parent_perm, uint64_t parent_shared,
1683 uint64_t *nperm, uint64_t *nshared)
1684{
1685 if (bs->drv && bs->drv->bdrv_child_perm) {
e0995dc3 1686 bs->drv->bdrv_child_perm(bs, c, role, reopen_queue,
ffd1a5a2
FZ
1687 parent_perm, parent_shared,
1688 nperm, nshared);
1689 }
e0995dc3 1690 /* TODO Take force_share from reopen_queue */
ffd1a5a2
FZ
1691 if (child_bs && child_bs->force_share) {
1692 *nshared = BLK_PERM_ALL;
1693 }
1694}
1695
33a610c3
KW
1696/*
1697 * Check whether permissions on this node can be changed in a way that
1698 * @cumulative_perms and @cumulative_shared_perms are the new cumulative
1699 * permissions of all its parents. This involves checking whether all necessary
1700 * permission changes to child nodes can be performed.
1701 *
1702 * A call to this function must always be followed by a call to bdrv_set_perm()
1703 * or bdrv_abort_perm_update().
1704 */
3121fb45
KW
1705static int bdrv_check_perm(BlockDriverState *bs, BlockReopenQueue *q,
1706 uint64_t cumulative_perms,
46181129
KW
1707 uint64_t cumulative_shared_perms,
1708 GSList *ignore_children, Error **errp)
33a610c3
KW
1709{
1710 BlockDriver *drv = bs->drv;
1711 BdrvChild *c;
1712 int ret;
1713
1714 /* Write permissions never work with read-only images */
1715 if ((cumulative_perms & (BLK_PERM_WRITE | BLK_PERM_WRITE_UNCHANGED)) &&
cc022140 1716 !bdrv_is_writable_after_reopen(bs, q))
33a610c3
KW
1717 {
1718 error_setg(errp, "Block node is read-only");
1719 return -EPERM;
1720 }
1721
1722 /* Check this node */
1723 if (!drv) {
1724 return 0;
1725 }
1726
1727 if (drv->bdrv_check_perm) {
1728 return drv->bdrv_check_perm(bs, cumulative_perms,
1729 cumulative_shared_perms, errp);
1730 }
1731
78e421c9 1732 /* Drivers that never have children can omit .bdrv_child_perm() */
33a610c3 1733 if (!drv->bdrv_child_perm) {
78e421c9 1734 assert(QLIST_EMPTY(&bs->children));
33a610c3
KW
1735 return 0;
1736 }
1737
1738 /* Check all children */
1739 QLIST_FOREACH(c, &bs->children, next) {
1740 uint64_t cur_perm, cur_shared;
3121fb45 1741 bdrv_child_perm(bs, c->bs, c, c->role, q,
ffd1a5a2
FZ
1742 cumulative_perms, cumulative_shared_perms,
1743 &cur_perm, &cur_shared);
3121fb45
KW
1744 ret = bdrv_child_check_perm(c, q, cur_perm, cur_shared,
1745 ignore_children, errp);
33a610c3
KW
1746 if (ret < 0) {
1747 return ret;
1748 }
1749 }
1750
1751 return 0;
1752}
1753
1754/*
1755 * Notifies drivers that after a previous bdrv_check_perm() call, the
1756 * permission update is not performed and any preparations made for it (e.g.
1757 * taken file locks) need to be undone.
1758 *
1759 * This function recursively notifies all child nodes.
1760 */
1761static void bdrv_abort_perm_update(BlockDriverState *bs)
1762{
1763 BlockDriver *drv = bs->drv;
1764 BdrvChild *c;
1765
1766 if (!drv) {
1767 return;
1768 }
1769
1770 if (drv->bdrv_abort_perm_update) {
1771 drv->bdrv_abort_perm_update(bs);
1772 }
1773
1774 QLIST_FOREACH(c, &bs->children, next) {
1775 bdrv_child_abort_perm_update(c);
1776 }
1777}
1778
1779static void bdrv_set_perm(BlockDriverState *bs, uint64_t cumulative_perms,
1780 uint64_t cumulative_shared_perms)
1781{
1782 BlockDriver *drv = bs->drv;
1783 BdrvChild *c;
1784
1785 if (!drv) {
1786 return;
1787 }
1788
1789 /* Update this node */
1790 if (drv->bdrv_set_perm) {
1791 drv->bdrv_set_perm(bs, cumulative_perms, cumulative_shared_perms);
1792 }
1793
78e421c9 1794 /* Drivers that never have children can omit .bdrv_child_perm() */
33a610c3 1795 if (!drv->bdrv_child_perm) {
78e421c9 1796 assert(QLIST_EMPTY(&bs->children));
33a610c3
KW
1797 return;
1798 }
1799
1800 /* Update all children */
1801 QLIST_FOREACH(c, &bs->children, next) {
1802 uint64_t cur_perm, cur_shared;
e0995dc3 1803 bdrv_child_perm(bs, c->bs, c, c->role, NULL,
ffd1a5a2
FZ
1804 cumulative_perms, cumulative_shared_perms,
1805 &cur_perm, &cur_shared);
33a610c3
KW
1806 bdrv_child_set_perm(c, cur_perm, cur_shared);
1807 }
1808}
1809
1810static void bdrv_get_cumulative_perm(BlockDriverState *bs, uint64_t *perm,
1811 uint64_t *shared_perm)
1812{
1813 BdrvChild *c;
1814 uint64_t cumulative_perms = 0;
1815 uint64_t cumulative_shared_perms = BLK_PERM_ALL;
1816
1817 QLIST_FOREACH(c, &bs->parents, next_parent) {
1818 cumulative_perms |= c->perm;
1819 cumulative_shared_perms &= c->shared_perm;
1820 }
1821
1822 *perm = cumulative_perms;
1823 *shared_perm = cumulative_shared_perms;
1824}
1825
d083319f
KW
1826static char *bdrv_child_user_desc(BdrvChild *c)
1827{
1828 if (c->role->get_parent_desc) {
1829 return c->role->get_parent_desc(c);
1830 }
1831
1832 return g_strdup("another user");
1833}
1834
5176196c 1835char *bdrv_perm_names(uint64_t perm)
d083319f
KW
1836{
1837 struct perm_name {
1838 uint64_t perm;
1839 const char *name;
1840 } permissions[] = {
1841 { BLK_PERM_CONSISTENT_READ, "consistent read" },
1842 { BLK_PERM_WRITE, "write" },
1843 { BLK_PERM_WRITE_UNCHANGED, "write unchanged" },
1844 { BLK_PERM_RESIZE, "resize" },
1845 { BLK_PERM_GRAPH_MOD, "change children" },
1846 { 0, NULL }
1847 };
1848
1849 char *result = g_strdup("");
1850 struct perm_name *p;
1851
1852 for (p = permissions; p->name; p++) {
1853 if (perm & p->perm) {
1854 char *old = result;
1855 result = g_strdup_printf("%s%s%s", old, *old ? ", " : "", p->name);
1856 g_free(old);
1857 }
1858 }
1859
1860 return result;
1861}
1862
33a610c3
KW
1863/*
1864 * Checks whether a new reference to @bs can be added if the new user requires
46181129
KW
1865 * @new_used_perm/@new_shared_perm as its permissions. If @ignore_children is
1866 * set, the BdrvChild objects in this list are ignored in the calculations;
1867 * this allows checking permission updates for an existing reference.
33a610c3
KW
1868 *
1869 * Needs to be followed by a call to either bdrv_set_perm() or
1870 * bdrv_abort_perm_update(). */
3121fb45
KW
1871static int bdrv_check_update_perm(BlockDriverState *bs, BlockReopenQueue *q,
1872 uint64_t new_used_perm,
d5e6f437 1873 uint64_t new_shared_perm,
46181129 1874 GSList *ignore_children, Error **errp)
d5e6f437
KW
1875{
1876 BdrvChild *c;
33a610c3
KW
1877 uint64_t cumulative_perms = new_used_perm;
1878 uint64_t cumulative_shared_perms = new_shared_perm;
d5e6f437
KW
1879
1880 /* There is no reason why anyone couldn't tolerate write_unchanged */
1881 assert(new_shared_perm & BLK_PERM_WRITE_UNCHANGED);
1882
1883 QLIST_FOREACH(c, &bs->parents, next_parent) {
46181129 1884 if (g_slist_find(ignore_children, c)) {
d5e6f437
KW
1885 continue;
1886 }
1887
d083319f
KW
1888 if ((new_used_perm & c->shared_perm) != new_used_perm) {
1889 char *user = bdrv_child_user_desc(c);
1890 char *perm_names = bdrv_perm_names(new_used_perm & ~c->shared_perm);
1891 error_setg(errp, "Conflicts with use by %s as '%s', which does not "
1892 "allow '%s' on %s",
1893 user, c->name, perm_names, bdrv_get_node_name(c->bs));
1894 g_free(user);
1895 g_free(perm_names);
1896 return -EPERM;
1897 }
1898
1899 if ((c->perm & new_shared_perm) != c->perm) {
1900 char *user = bdrv_child_user_desc(c);
1901 char *perm_names = bdrv_perm_names(c->perm & ~new_shared_perm);
1902 error_setg(errp, "Conflicts with use by %s as '%s', which uses "
1903 "'%s' on %s",
1904 user, c->name, perm_names, bdrv_get_node_name(c->bs));
1905 g_free(user);
1906 g_free(perm_names);
d5e6f437
KW
1907 return -EPERM;
1908 }
33a610c3
KW
1909
1910 cumulative_perms |= c->perm;
1911 cumulative_shared_perms &= c->shared_perm;
d5e6f437
KW
1912 }
1913
3121fb45 1914 return bdrv_check_perm(bs, q, cumulative_perms, cumulative_shared_perms,
46181129 1915 ignore_children, errp);
33a610c3
KW
1916}
1917
1918/* Needs to be followed by a call to either bdrv_child_set_perm() or
1919 * bdrv_child_abort_perm_update(). */
3121fb45
KW
1920static int bdrv_child_check_perm(BdrvChild *c, BlockReopenQueue *q,
1921 uint64_t perm, uint64_t shared,
c1cef672 1922 GSList *ignore_children, Error **errp)
33a610c3 1923{
46181129
KW
1924 int ret;
1925
1926 ignore_children = g_slist_prepend(g_slist_copy(ignore_children), c);
3121fb45 1927 ret = bdrv_check_update_perm(c->bs, q, perm, shared, ignore_children, errp);
46181129
KW
1928 g_slist_free(ignore_children);
1929
1930 return ret;
33a610c3
KW
1931}
1932
c1cef672 1933static void bdrv_child_set_perm(BdrvChild *c, uint64_t perm, uint64_t shared)
33a610c3
KW
1934{
1935 uint64_t cumulative_perms, cumulative_shared_perms;
1936
1937 c->perm = perm;
1938 c->shared_perm = shared;
1939
1940 bdrv_get_cumulative_perm(c->bs, &cumulative_perms,
1941 &cumulative_shared_perms);
1942 bdrv_set_perm(c->bs, cumulative_perms, cumulative_shared_perms);
1943}
1944
c1cef672 1945static void bdrv_child_abort_perm_update(BdrvChild *c)
33a610c3
KW
1946{
1947 bdrv_abort_perm_update(c->bs);
1948}
1949
1950int bdrv_child_try_set_perm(BdrvChild *c, uint64_t perm, uint64_t shared,
1951 Error **errp)
1952{
1953 int ret;
1954
3121fb45 1955 ret = bdrv_child_check_perm(c, NULL, perm, shared, NULL, errp);
33a610c3
KW
1956 if (ret < 0) {
1957 bdrv_child_abort_perm_update(c);
1958 return ret;
1959 }
1960
1961 bdrv_child_set_perm(c, perm, shared);
1962
d5e6f437
KW
1963 return 0;
1964}
1965
6a1b9ee1
KW
1966void bdrv_filter_default_perms(BlockDriverState *bs, BdrvChild *c,
1967 const BdrvChildRole *role,
e0995dc3 1968 BlockReopenQueue *reopen_queue,
6a1b9ee1
KW
1969 uint64_t perm, uint64_t shared,
1970 uint64_t *nperm, uint64_t *nshared)
1971{
1972 if (c == NULL) {
1973 *nperm = perm & DEFAULT_PERM_PASSTHROUGH;
1974 *nshared = (shared & DEFAULT_PERM_PASSTHROUGH) | DEFAULT_PERM_UNCHANGED;
1975 return;
1976 }
1977
1978 *nperm = (perm & DEFAULT_PERM_PASSTHROUGH) |
1979 (c->perm & DEFAULT_PERM_UNCHANGED);
1980 *nshared = (shared & DEFAULT_PERM_PASSTHROUGH) |
1981 (c->shared_perm & DEFAULT_PERM_UNCHANGED);
1982}
1983
6b1a044a
KW
1984void bdrv_format_default_perms(BlockDriverState *bs, BdrvChild *c,
1985 const BdrvChildRole *role,
e0995dc3 1986 BlockReopenQueue *reopen_queue,
6b1a044a
KW
1987 uint64_t perm, uint64_t shared,
1988 uint64_t *nperm, uint64_t *nshared)
1989{
1990 bool backing = (role == &child_backing);
1991 assert(role == &child_backing || role == &child_file);
1992
1993 if (!backing) {
5fbfabd3
KW
1994 int flags = bdrv_reopen_get_flags(reopen_queue, bs);
1995
6b1a044a
KW
1996 /* Apart from the modifications below, the same permissions are
1997 * forwarded and left alone as for filters */
e0995dc3
KW
1998 bdrv_filter_default_perms(bs, c, role, reopen_queue, perm, shared,
1999 &perm, &shared);
6b1a044a
KW
2000
2001 /* Format drivers may touch metadata even if the guest doesn't write */
cc022140 2002 if (bdrv_is_writable_after_reopen(bs, reopen_queue)) {
6b1a044a
KW
2003 perm |= BLK_PERM_WRITE | BLK_PERM_RESIZE;
2004 }
2005
2006 /* bs->file always needs to be consistent because of the metadata. We
2007 * can never allow other users to resize or write to it. */
5fbfabd3
KW
2008 if (!(flags & BDRV_O_NO_IO)) {
2009 perm |= BLK_PERM_CONSISTENT_READ;
2010 }
6b1a044a
KW
2011 shared &= ~(BLK_PERM_WRITE | BLK_PERM_RESIZE);
2012 } else {
2013 /* We want consistent read from backing files if the parent needs it.
2014 * No other operations are performed on backing files. */
2015 perm &= BLK_PERM_CONSISTENT_READ;
2016
2017 /* If the parent can deal with changing data, we're okay with a
2018 * writable and resizable backing file. */
2019 /* TODO Require !(perm & BLK_PERM_CONSISTENT_READ), too? */
2020 if (shared & BLK_PERM_WRITE) {
2021 shared = BLK_PERM_WRITE | BLK_PERM_RESIZE;
2022 } else {
2023 shared = 0;
2024 }
2025
2026 shared |= BLK_PERM_CONSISTENT_READ | BLK_PERM_GRAPH_MOD |
2027 BLK_PERM_WRITE_UNCHANGED;
2028 }
2029
9c5e6594
KW
2030 if (bs->open_flags & BDRV_O_INACTIVE) {
2031 shared |= BLK_PERM_WRITE | BLK_PERM_RESIZE;
2032 }
2033
6b1a044a
KW
2034 *nperm = perm;
2035 *nshared = shared;
2036}
2037
8ee03995
KW
2038static void bdrv_replace_child_noperm(BdrvChild *child,
2039 BlockDriverState *new_bs)
e9740bc6
KW
2040{
2041 BlockDriverState *old_bs = child->bs;
0152bf40 2042 int i;
e9740bc6 2043
bb2614e9
FZ
2044 if (old_bs && new_bs) {
2045 assert(bdrv_get_aio_context(old_bs) == bdrv_get_aio_context(new_bs));
2046 }
e9740bc6 2047 if (old_bs) {
d736f119
KW
2048 /* Detach first so that the recursive drain sections coming from @child
2049 * are already gone and we only end the drain sections that came from
2050 * elsewhere. */
2051 if (child->role->detach) {
2052 child->role->detach(child);
2053 }
36fe1331 2054 if (old_bs->quiesce_counter && child->role->drained_end) {
0f12264e
KW
2055 int num = old_bs->quiesce_counter;
2056 if (child->role->parent_is_bds) {
2057 num -= bdrv_drain_all_count;
2058 }
2059 assert(num >= 0);
2060 for (i = 0; i < num; i++) {
0152bf40
KW
2061 child->role->drained_end(child);
2062 }
36fe1331 2063 }
e9740bc6
KW
2064 QLIST_REMOVE(child, next_parent);
2065 }
36fe1331
KW
2066
2067 child->bs = new_bs;
2068
e9740bc6
KW
2069 if (new_bs) {
2070 QLIST_INSERT_HEAD(&new_bs->parents, child, next_parent);
36fe1331 2071 if (new_bs->quiesce_counter && child->role->drained_begin) {
0f12264e
KW
2072 int num = new_bs->quiesce_counter;
2073 if (child->role->parent_is_bds) {
2074 num -= bdrv_drain_all_count;
2075 }
2076 assert(num >= 0);
2077 for (i = 0; i < num; i++) {
4be6a6d1 2078 bdrv_parent_drained_begin_single(child, true);
0152bf40 2079 }
36fe1331 2080 }
33a610c3 2081
d736f119
KW
2082 /* Attach only after starting new drained sections, so that recursive
2083 * drain sections coming from @child don't get an extra .drained_begin
2084 * callback. */
8ee03995
KW
2085 if (child->role->attach) {
2086 child->role->attach(child);
2087 }
2088 }
2089}
33a610c3 2090
466787fb
KW
2091/*
2092 * Updates @child to change its reference to point to @new_bs, including
2093 * checking and applying the necessary permisson updates both to the old node
2094 * and to @new_bs.
2095 *
2096 * NULL is passed as @new_bs for removing the reference before freeing @child.
2097 *
2098 * If @new_bs is not NULL, bdrv_check_perm() must be called beforehand, as this
2099 * function uses bdrv_set_perm() to update the permissions according to the new
2100 * reference that @new_bs gets.
2101 */
2102static void bdrv_replace_child(BdrvChild *child, BlockDriverState *new_bs)
8ee03995
KW
2103{
2104 BlockDriverState *old_bs = child->bs;
2105 uint64_t perm, shared_perm;
2106
8aecf1d1
KW
2107 bdrv_replace_child_noperm(child, new_bs);
2108
8ee03995 2109 if (old_bs) {
33a610c3
KW
2110 /* Update permissions for old node. This is guaranteed to succeed
2111 * because we're just taking a parent away, so we're loosening
2112 * restrictions. */
2113 bdrv_get_cumulative_perm(old_bs, &perm, &shared_perm);
3121fb45 2114 bdrv_check_perm(old_bs, NULL, perm, shared_perm, NULL, &error_abort);
33a610c3 2115 bdrv_set_perm(old_bs, perm, shared_perm);
e9740bc6 2116 }
36fe1331 2117
e9740bc6 2118 if (new_bs) {
33a610c3 2119 bdrv_get_cumulative_perm(new_bs, &perm, &shared_perm);
33a610c3 2120 bdrv_set_perm(new_bs, perm, shared_perm);
e9740bc6 2121 }
e9740bc6
KW
2122}
2123
f21d96d0
KW
2124BdrvChild *bdrv_root_attach_child(BlockDriverState *child_bs,
2125 const char *child_name,
36fe1331 2126 const BdrvChildRole *child_role,
d5e6f437
KW
2127 uint64_t perm, uint64_t shared_perm,
2128 void *opaque, Error **errp)
df581792 2129{
d5e6f437
KW
2130 BdrvChild *child;
2131 int ret;
2132
3121fb45 2133 ret = bdrv_check_update_perm(child_bs, NULL, perm, shared_perm, NULL, errp);
d5e6f437 2134 if (ret < 0) {
33a610c3 2135 bdrv_abort_perm_update(child_bs);
d5e6f437
KW
2136 return NULL;
2137 }
2138
2139 child = g_new(BdrvChild, 1);
df581792 2140 *child = (BdrvChild) {
d5e6f437
KW
2141 .bs = NULL,
2142 .name = g_strdup(child_name),
2143 .role = child_role,
2144 .perm = perm,
2145 .shared_perm = shared_perm,
2146 .opaque = opaque,
df581792
KW
2147 };
2148
33a610c3 2149 /* This performs the matching bdrv_set_perm() for the above check. */
466787fb 2150 bdrv_replace_child(child, child_bs);
b4b059f6
KW
2151
2152 return child;
df581792
KW
2153}
2154
98292c61
WC
2155BdrvChild *bdrv_attach_child(BlockDriverState *parent_bs,
2156 BlockDriverState *child_bs,
2157 const char *child_name,
8b2ff529
KW
2158 const BdrvChildRole *child_role,
2159 Error **errp)
f21d96d0 2160{
d5e6f437 2161 BdrvChild *child;
f68c598b
KW
2162 uint64_t perm, shared_perm;
2163
2164 bdrv_get_cumulative_perm(parent_bs, &perm, &shared_perm);
2165
2166 assert(parent_bs->drv);
bb2614e9 2167 assert(bdrv_get_aio_context(parent_bs) == bdrv_get_aio_context(child_bs));
e0995dc3 2168 bdrv_child_perm(parent_bs, child_bs, NULL, child_role, NULL,
ffd1a5a2 2169 perm, shared_perm, &perm, &shared_perm);
d5e6f437 2170
d5e6f437 2171 child = bdrv_root_attach_child(child_bs, child_name, child_role,
f68c598b 2172 perm, shared_perm, parent_bs, errp);
d5e6f437
KW
2173 if (child == NULL) {
2174 return NULL;
2175 }
2176
f21d96d0
KW
2177 QLIST_INSERT_HEAD(&parent_bs->children, child, next);
2178 return child;
2179}
2180
3f09bfbc 2181static void bdrv_detach_child(BdrvChild *child)
33a60407 2182{
f21d96d0
KW
2183 if (child->next.le_prev) {
2184 QLIST_REMOVE(child, next);
2185 child->next.le_prev = NULL;
2186 }
e9740bc6 2187
466787fb 2188 bdrv_replace_child(child, NULL);
e9740bc6 2189
260fecf1 2190 g_free(child->name);
33a60407
KW
2191 g_free(child);
2192}
2193
f21d96d0 2194void bdrv_root_unref_child(BdrvChild *child)
33a60407 2195{
779020cb
KW
2196 BlockDriverState *child_bs;
2197
f21d96d0
KW
2198 child_bs = child->bs;
2199 bdrv_detach_child(child);
2200 bdrv_unref(child_bs);
2201}
2202
2203void bdrv_unref_child(BlockDriverState *parent, BdrvChild *child)
2204{
779020cb
KW
2205 if (child == NULL) {
2206 return;
2207 }
33a60407
KW
2208
2209 if (child->bs->inherits_from == parent) {
4e4bf5c4
KW
2210 BdrvChild *c;
2211
2212 /* Remove inherits_from only when the last reference between parent and
2213 * child->bs goes away. */
2214 QLIST_FOREACH(c, &parent->children, next) {
2215 if (c != child && c->bs == child->bs) {
2216 break;
2217 }
2218 }
2219 if (c == NULL) {
2220 child->bs->inherits_from = NULL;
2221 }
33a60407
KW
2222 }
2223
f21d96d0 2224 bdrv_root_unref_child(child);
33a60407
KW
2225}
2226
5c8cab48
KW
2227
2228static void bdrv_parent_cb_change_media(BlockDriverState *bs, bool load)
2229{
2230 BdrvChild *c;
2231 QLIST_FOREACH(c, &bs->parents, next_parent) {
2232 if (c->role->change_media) {
2233 c->role->change_media(c, load);
2234 }
2235 }
2236}
2237
5db15a57
KW
2238/*
2239 * Sets the backing file link of a BDS. A new reference is created; callers
2240 * which don't need their own reference any more must call bdrv_unref().
2241 */
12fa4af6
KW
2242void bdrv_set_backing_hd(BlockDriverState *bs, BlockDriverState *backing_hd,
2243 Error **errp)
8d24cce1 2244{
5db15a57
KW
2245 if (backing_hd) {
2246 bdrv_ref(backing_hd);
2247 }
8d24cce1 2248
760e0063 2249 if (bs->backing) {
5db15a57 2250 bdrv_unref_child(bs, bs->backing);
826b6ca0
FZ
2251 }
2252
8d24cce1 2253 if (!backing_hd) {
760e0063 2254 bs->backing = NULL;
8d24cce1
FZ
2255 goto out;
2256 }
12fa4af6 2257
8b2ff529 2258 bs->backing = bdrv_attach_child(bs, backing_hd, "backing", &child_backing,
12fa4af6
KW
2259 errp);
2260 if (!bs->backing) {
2261 bdrv_unref(backing_hd);
2262 }
826b6ca0 2263
9e7e940c
KW
2264 bdrv_refresh_filename(bs);
2265
8d24cce1 2266out:
3baca891 2267 bdrv_refresh_limits(bs, NULL);
8d24cce1
FZ
2268}
2269
31ca6d07
KW
2270/*
2271 * Opens the backing file for a BlockDriverState if not yet open
2272 *
d9b7b057
KW
2273 * bdref_key specifies the key for the image's BlockdevRef in the options QDict.
2274 * That QDict has to be flattened; therefore, if the BlockdevRef is a QDict
2275 * itself, all options starting with "${bdref_key}." are considered part of the
2276 * BlockdevRef.
2277 *
2278 * TODO Can this be unified with bdrv_open_image()?
31ca6d07 2279 */
d9b7b057
KW
2280int bdrv_open_backing_file(BlockDriverState *bs, QDict *parent_options,
2281 const char *bdref_key, Error **errp)
9156df12 2282{
1ba4b6a5 2283 char *backing_filename = g_malloc0(PATH_MAX);
d9b7b057
KW
2284 char *bdref_key_dot;
2285 const char *reference = NULL;
317fc44e 2286 int ret = 0;
8d24cce1 2287 BlockDriverState *backing_hd;
d9b7b057
KW
2288 QDict *options;
2289 QDict *tmp_parent_options = NULL;
34b5d2c6 2290 Error *local_err = NULL;
9156df12 2291
760e0063 2292 if (bs->backing != NULL) {
1ba4b6a5 2293 goto free_exit;
9156df12
PB
2294 }
2295
31ca6d07 2296 /* NULL means an empty set of options */
d9b7b057
KW
2297 if (parent_options == NULL) {
2298 tmp_parent_options = qdict_new();
2299 parent_options = tmp_parent_options;
31ca6d07
KW
2300 }
2301
9156df12 2302 bs->open_flags &= ~BDRV_O_NO_BACKING;
d9b7b057
KW
2303
2304 bdref_key_dot = g_strdup_printf("%s.", bdref_key);
2305 qdict_extract_subqdict(parent_options, &options, bdref_key_dot);
2306 g_free(bdref_key_dot);
2307
129c7d1c
MA
2308 /*
2309 * Caution: while qdict_get_try_str() is fine, getting non-string
2310 * types would require more care. When @parent_options come from
2311 * -blockdev or blockdev_add, its members are typed according to
2312 * the QAPI schema, but when they come from -drive, they're all
2313 * QString.
2314 */
d9b7b057
KW
2315 reference = qdict_get_try_str(parent_options, bdref_key);
2316 if (reference || qdict_haskey(options, "file.filename")) {
1cb6f506
KW
2317 backing_filename[0] = '\0';
2318 } else if (bs->backing_file[0] == '\0' && qdict_size(options) == 0) {
cb3e7f08 2319 qobject_unref(options);
1ba4b6a5 2320 goto free_exit;
dbecebdd 2321 } else {
9f07429e
HR
2322 bdrv_get_full_backing_filename(bs, backing_filename, PATH_MAX,
2323 &local_err);
2324 if (local_err) {
2325 ret = -EINVAL;
2326 error_propagate(errp, local_err);
cb3e7f08 2327 qobject_unref(options);
9f07429e
HR
2328 goto free_exit;
2329 }
9156df12
PB
2330 }
2331
8ee79e70
KW
2332 if (!bs->drv || !bs->drv->supports_backing) {
2333 ret = -EINVAL;
2334 error_setg(errp, "Driver doesn't support backing files");
cb3e7f08 2335 qobject_unref(options);
8ee79e70
KW
2336 goto free_exit;
2337 }
2338
6bff597b
PK
2339 if (!reference &&
2340 bs->backing_format[0] != '\0' && !qdict_haskey(options, "driver")) {
46f5ac20 2341 qdict_put_str(options, "driver", bs->backing_format);
9156df12
PB
2342 }
2343
5b363937
HR
2344 backing_hd = bdrv_open_inherit(*backing_filename ? backing_filename : NULL,
2345 reference, options, 0, bs, &child_backing,
2346 errp);
2347 if (!backing_hd) {
9156df12 2348 bs->open_flags |= BDRV_O_NO_BACKING;
e43bfd9c 2349 error_prepend(errp, "Could not open backing file: ");
5b363937 2350 ret = -EINVAL;
1ba4b6a5 2351 goto free_exit;
9156df12 2352 }
5ce6bfe2 2353 bdrv_set_aio_context(backing_hd, bdrv_get_aio_context(bs));
df581792 2354
5db15a57
KW
2355 /* Hook up the backing file link; drop our reference, bs owns the
2356 * backing_hd reference now */
12fa4af6 2357 bdrv_set_backing_hd(bs, backing_hd, &local_err);
5db15a57 2358 bdrv_unref(backing_hd);
12fa4af6 2359 if (local_err) {
8cd1a3e4 2360 error_propagate(errp, local_err);
12fa4af6
KW
2361 ret = -EINVAL;
2362 goto free_exit;
2363 }
d80ac658 2364
d9b7b057
KW
2365 qdict_del(parent_options, bdref_key);
2366
1ba4b6a5
BC
2367free_exit:
2368 g_free(backing_filename);
cb3e7f08 2369 qobject_unref(tmp_parent_options);
1ba4b6a5 2370 return ret;
9156df12
PB
2371}
2372
2d6b86af
KW
2373static BlockDriverState *
2374bdrv_open_child_bs(const char *filename, QDict *options, const char *bdref_key,
2375 BlockDriverState *parent, const BdrvChildRole *child_role,
2376 bool allow_none, Error **errp)
da557aac 2377{
2d6b86af 2378 BlockDriverState *bs = NULL;
da557aac 2379 QDict *image_options;
da557aac
HR
2380 char *bdref_key_dot;
2381 const char *reference;
2382
df581792 2383 assert(child_role != NULL);
f67503e5 2384
da557aac
HR
2385 bdref_key_dot = g_strdup_printf("%s.", bdref_key);
2386 qdict_extract_subqdict(options, &image_options, bdref_key_dot);
2387 g_free(bdref_key_dot);
2388
129c7d1c
MA
2389 /*
2390 * Caution: while qdict_get_try_str() is fine, getting non-string
2391 * types would require more care. When @options come from
2392 * -blockdev or blockdev_add, its members are typed according to
2393 * the QAPI schema, but when they come from -drive, they're all
2394 * QString.
2395 */
da557aac
HR
2396 reference = qdict_get_try_str(options, bdref_key);
2397 if (!filename && !reference && !qdict_size(image_options)) {
b4b059f6 2398 if (!allow_none) {
da557aac
HR
2399 error_setg(errp, "A block device must be specified for \"%s\"",
2400 bdref_key);
da557aac 2401 }
cb3e7f08 2402 qobject_unref(image_options);
da557aac
HR
2403 goto done;
2404 }
2405
5b363937
HR
2406 bs = bdrv_open_inherit(filename, reference, image_options, 0,
2407 parent, child_role, errp);
2408 if (!bs) {
df581792
KW
2409 goto done;
2410 }
2411
da557aac
HR
2412done:
2413 qdict_del(options, bdref_key);
2d6b86af
KW
2414 return bs;
2415}
2416
2417/*
2418 * Opens a disk image whose options are given as BlockdevRef in another block
2419 * device's options.
2420 *
2421 * If allow_none is true, no image will be opened if filename is false and no
2422 * BlockdevRef is given. NULL will be returned, but errp remains unset.
2423 *
2424 * bdrev_key specifies the key for the image's BlockdevRef in the options QDict.
2425 * That QDict has to be flattened; therefore, if the BlockdevRef is a QDict
2426 * itself, all options starting with "${bdref_key}." are considered part of the
2427 * BlockdevRef.
2428 *
2429 * The BlockdevRef will be removed from the options QDict.
2430 */
2431BdrvChild *bdrv_open_child(const char *filename,
2432 QDict *options, const char *bdref_key,
2433 BlockDriverState *parent,
2434 const BdrvChildRole *child_role,
2435 bool allow_none, Error **errp)
2436{
8b2ff529 2437 BdrvChild *c;
2d6b86af
KW
2438 BlockDriverState *bs;
2439
2440 bs = bdrv_open_child_bs(filename, options, bdref_key, parent, child_role,
2441 allow_none, errp);
2442 if (bs == NULL) {
2443 return NULL;
2444 }
2445
8b2ff529
KW
2446 c = bdrv_attach_child(parent, bs, bdref_key, child_role, errp);
2447 if (!c) {
2448 bdrv_unref(bs);
2449 return NULL;
2450 }
2451
2452 return c;
b4b059f6
KW
2453}
2454
e1d74bc6
KW
2455/* TODO Future callers may need to specify parent/child_role in order for
2456 * option inheritance to work. Existing callers use it for the root node. */
2457BlockDriverState *bdrv_open_blockdev_ref(BlockdevRef *ref, Error **errp)
2458{
2459 BlockDriverState *bs = NULL;
2460 Error *local_err = NULL;
2461 QObject *obj = NULL;
2462 QDict *qdict = NULL;
2463 const char *reference = NULL;
2464 Visitor *v = NULL;
2465
2466 if (ref->type == QTYPE_QSTRING) {
2467 reference = ref->u.reference;
2468 } else {
2469 BlockdevOptions *options = &ref->u.definition;
2470 assert(ref->type == QTYPE_QDICT);
2471
2472 v = qobject_output_visitor_new(&obj);
2473 visit_type_BlockdevOptions(v, NULL, &options, &local_err);
2474 if (local_err) {
2475 error_propagate(errp, local_err);
2476 goto fail;
2477 }
2478 visit_complete(v, &obj);
2479
7dc847eb 2480 qdict = qobject_to(QDict, obj);
e1d74bc6
KW
2481 qdict_flatten(qdict);
2482
2483 /* bdrv_open_inherit() defaults to the values in bdrv_flags (for
2484 * compatibility with other callers) rather than what we want as the
2485 * real defaults. Apply the defaults here instead. */
2486 qdict_set_default_str(qdict, BDRV_OPT_CACHE_DIRECT, "off");
2487 qdict_set_default_str(qdict, BDRV_OPT_CACHE_NO_FLUSH, "off");
2488 qdict_set_default_str(qdict, BDRV_OPT_READ_ONLY, "off");
2489 }
2490
2491 bs = bdrv_open_inherit(NULL, reference, qdict, 0, NULL, NULL, errp);
2492 obj = NULL;
2493
2494fail:
cb3e7f08 2495 qobject_unref(obj);
e1d74bc6
KW
2496 visit_free(v);
2497 return bs;
2498}
2499
66836189
HR
2500static BlockDriverState *bdrv_append_temp_snapshot(BlockDriverState *bs,
2501 int flags,
2502 QDict *snapshot_options,
2503 Error **errp)
b998875d
KW
2504{
2505 /* TODO: extra byte is a hack to ensure MAX_PATH space on Windows. */
1ba4b6a5 2506 char *tmp_filename = g_malloc0(PATH_MAX + 1);
b998875d 2507 int64_t total_size;
83d0521a 2508 QemuOpts *opts = NULL;
ff6ed714 2509 BlockDriverState *bs_snapshot = NULL;
b2c2832c 2510 Error *local_err = NULL;
b998875d
KW
2511 int ret;
2512
2513 /* if snapshot, we create a temporary backing file and open it
2514 instead of opening 'filename' directly */
2515
2516 /* Get the required size from the image */
f187743a
KW
2517 total_size = bdrv_getlength(bs);
2518 if (total_size < 0) {
2519 error_setg_errno(errp, -total_size, "Could not get image size");
1ba4b6a5 2520 goto out;
f187743a 2521 }
b998875d
KW
2522
2523 /* Create the temporary image */
1ba4b6a5 2524 ret = get_tmp_filename(tmp_filename, PATH_MAX + 1);
b998875d
KW
2525 if (ret < 0) {
2526 error_setg_errno(errp, -ret, "Could not get temporary filename");
1ba4b6a5 2527 goto out;
b998875d
KW
2528 }
2529
ef810437 2530 opts = qemu_opts_create(bdrv_qcow2.create_opts, NULL, 0,
c282e1fd 2531 &error_abort);
39101f25 2532 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, total_size, &error_abort);
e43bfd9c 2533 ret = bdrv_create(&bdrv_qcow2, tmp_filename, opts, errp);
83d0521a 2534 qemu_opts_del(opts);
b998875d 2535 if (ret < 0) {
e43bfd9c
MA
2536 error_prepend(errp, "Could not create temporary overlay '%s': ",
2537 tmp_filename);
1ba4b6a5 2538 goto out;
b998875d
KW
2539 }
2540
73176bee 2541 /* Prepare options QDict for the temporary file */
46f5ac20
EB
2542 qdict_put_str(snapshot_options, "file.driver", "file");
2543 qdict_put_str(snapshot_options, "file.filename", tmp_filename);
2544 qdict_put_str(snapshot_options, "driver", "qcow2");
b998875d 2545
5b363937 2546 bs_snapshot = bdrv_open(NULL, NULL, snapshot_options, flags, errp);
73176bee 2547 snapshot_options = NULL;
5b363937 2548 if (!bs_snapshot) {
1ba4b6a5 2549 goto out;
b998875d
KW
2550 }
2551
ff6ed714
EB
2552 /* bdrv_append() consumes a strong reference to bs_snapshot
2553 * (i.e. it will call bdrv_unref() on it) even on error, so in
2554 * order to be able to return one, we have to increase
2555 * bs_snapshot's refcount here */
66836189 2556 bdrv_ref(bs_snapshot);
b2c2832c
KW
2557 bdrv_append(bs_snapshot, bs, &local_err);
2558 if (local_err) {
2559 error_propagate(errp, local_err);
ff6ed714 2560 bs_snapshot = NULL;
b2c2832c
KW
2561 goto out;
2562 }
1ba4b6a5
BC
2563
2564out:
cb3e7f08 2565 qobject_unref(snapshot_options);
1ba4b6a5 2566 g_free(tmp_filename);
ff6ed714 2567 return bs_snapshot;
b998875d
KW
2568}
2569
b6ce07aa
KW
2570/*
2571 * Opens a disk image (raw, qcow2, vmdk, ...)
de9c0cec
KW
2572 *
2573 * options is a QDict of options to pass to the block drivers, or NULL for an
2574 * empty set of options. The reference to the QDict belongs to the block layer
2575 * after the call (even on failure), so if the caller intends to reuse the
cb3e7f08 2576 * dictionary, it needs to use qobject_ref() before calling bdrv_open.
f67503e5
HR
2577 *
2578 * If *pbs is NULL, a new BDS will be created with a pointer to it stored there.
2579 * If it is not NULL, the referenced BDS will be reused.
ddf5636d
HR
2580 *
2581 * The reference parameter may be used to specify an existing block device which
2582 * should be opened. If specified, neither options nor a filename may be given,
2583 * nor can an existing BDS be reused (that is, *pbs has to be NULL).
b6ce07aa 2584 */
5b363937
HR
2585static BlockDriverState *bdrv_open_inherit(const char *filename,
2586 const char *reference,
2587 QDict *options, int flags,
2588 BlockDriverState *parent,
2589 const BdrvChildRole *child_role,
2590 Error **errp)
ea2384d3 2591{
b6ce07aa 2592 int ret;
5696c6e3 2593 BlockBackend *file = NULL;
9a4f4c31 2594 BlockDriverState *bs;
ce343771 2595 BlockDriver *drv = NULL;
2f624b80 2596 BdrvChild *child;
74fe54f2 2597 const char *drvname;
3e8c2e57 2598 const char *backing;
34b5d2c6 2599 Error *local_err = NULL;
73176bee 2600 QDict *snapshot_options = NULL;
b1e6fc08 2601 int snapshot_flags = 0;
712e7874 2602
f3930ed0
KW
2603 assert(!child_role || !flags);
2604 assert(!child_role == !parent);
f67503e5 2605
ddf5636d
HR
2606 if (reference) {
2607 bool options_non_empty = options ? qdict_size(options) : false;
cb3e7f08 2608 qobject_unref(options);
ddf5636d 2609
ddf5636d
HR
2610 if (filename || options_non_empty) {
2611 error_setg(errp, "Cannot reference an existing block device with "
2612 "additional options or a new filename");
5b363937 2613 return NULL;
ddf5636d
HR
2614 }
2615
2616 bs = bdrv_lookup_bs(reference, reference, errp);
2617 if (!bs) {
5b363937 2618 return NULL;
ddf5636d 2619 }
76b22320 2620
ddf5636d 2621 bdrv_ref(bs);
5b363937 2622 return bs;
ddf5636d
HR
2623 }
2624
5b363937 2625 bs = bdrv_new();
f67503e5 2626
de9c0cec
KW
2627 /* NULL means an empty set of options */
2628 if (options == NULL) {
2629 options = qdict_new();
2630 }
2631
145f598e 2632 /* json: syntax counts as explicit options, as if in the QDict */
de3b53f0
KW
2633 parse_json_protocol(options, &filename, &local_err);
2634 if (local_err) {
de3b53f0
KW
2635 goto fail;
2636 }
2637
145f598e
KW
2638 bs->explicit_options = qdict_clone_shallow(options);
2639
f3930ed0 2640 if (child_role) {
bddcec37 2641 bs->inherits_from = parent;
8e2160e2
KW
2642 child_role->inherit_options(&flags, options,
2643 parent->open_flags, parent->options);
f3930ed0
KW
2644 }
2645
de3b53f0 2646 ret = bdrv_fill_options(&options, filename, &flags, &local_err);
462f5bcf
KW
2647 if (local_err) {
2648 goto fail;
2649 }
2650
129c7d1c
MA
2651 /*
2652 * Set the BDRV_O_RDWR and BDRV_O_ALLOW_RDWR flags.
2653 * Caution: getting a boolean member of @options requires care.
2654 * When @options come from -blockdev or blockdev_add, members are
2655 * typed according to the QAPI schema, but when they come from
2656 * -drive, they're all QString.
2657 */
f87a0e29
AG
2658 if (g_strcmp0(qdict_get_try_str(options, BDRV_OPT_READ_ONLY), "on") &&
2659 !qdict_get_try_bool(options, BDRV_OPT_READ_ONLY, false)) {
2660 flags |= (BDRV_O_RDWR | BDRV_O_ALLOW_RDWR);
2661 } else {
2662 flags &= ~BDRV_O_RDWR;
14499ea5
AG
2663 }
2664
2665 if (flags & BDRV_O_SNAPSHOT) {
2666 snapshot_options = qdict_new();
2667 bdrv_temp_snapshot_options(&snapshot_flags, snapshot_options,
2668 flags, options);
f87a0e29
AG
2669 /* Let bdrv_backing_options() override "read-only" */
2670 qdict_del(options, BDRV_OPT_READ_ONLY);
14499ea5
AG
2671 bdrv_backing_options(&flags, options, flags, options);
2672 }
2673
62392ebb
KW
2674 bs->open_flags = flags;
2675 bs->options = options;
2676 options = qdict_clone_shallow(options);
2677
76c591b0 2678 /* Find the right image format driver */
129c7d1c 2679 /* See cautionary note on accessing @options above */
76c591b0
KW
2680 drvname = qdict_get_try_str(options, "driver");
2681 if (drvname) {
2682 drv = bdrv_find_format(drvname);
76c591b0
KW
2683 if (!drv) {
2684 error_setg(errp, "Unknown driver: '%s'", drvname);
76c591b0
KW
2685 goto fail;
2686 }
2687 }
2688
2689 assert(drvname || !(flags & BDRV_O_PROTOCOL));
76c591b0 2690
129c7d1c 2691 /* See cautionary note on accessing @options above */
3e8c2e57 2692 backing = qdict_get_try_str(options, "backing");
e59a0cf1
HR
2693 if (qobject_to(QNull, qdict_get(options, "backing")) != NULL ||
2694 (backing && *backing == '\0'))
2695 {
4f7be280
HR
2696 if (backing) {
2697 warn_report("Use of \"backing\": \"\" is deprecated; "
2698 "use \"backing\": null instead");
2699 }
3e8c2e57
AG
2700 flags |= BDRV_O_NO_BACKING;
2701 qdict_del(options, "backing");
2702 }
2703
5696c6e3 2704 /* Open image file without format layer. This BlockBackend is only used for
4e4bf5c4
KW
2705 * probing, the block drivers will do their own bdrv_open_child() for the
2706 * same BDS, which is why we put the node name back into options. */
f4788adc 2707 if ((flags & BDRV_O_PROTOCOL) == 0) {
5696c6e3
KW
2708 BlockDriverState *file_bs;
2709
2710 file_bs = bdrv_open_child_bs(filename, options, "file", bs,
2711 &child_file, true, &local_err);
1fdd6933 2712 if (local_err) {
f4788adc
KW
2713 goto fail;
2714 }
5696c6e3 2715 if (file_bs != NULL) {
dacaa162
KW
2716 /* Not requesting BLK_PERM_CONSISTENT_READ because we're only
2717 * looking at the header to guess the image format. This works even
2718 * in cases where a guest would not see a consistent state. */
2719 file = blk_new(0, BLK_PERM_ALL);
d7086422 2720 blk_insert_bs(file, file_bs, &local_err);
5696c6e3 2721 bdrv_unref(file_bs);
d7086422
KW
2722 if (local_err) {
2723 goto fail;
2724 }
5696c6e3 2725
46f5ac20 2726 qdict_put_str(options, "file", bdrv_get_node_name(file_bs));
4e4bf5c4 2727 }
f500a6d3
KW
2728 }
2729
76c591b0 2730 /* Image format probing */
38f3ef57 2731 bs->probed = !drv;
76c591b0 2732 if (!drv && file) {
cf2ab8fc 2733 ret = find_image_format(file, filename, &drv, &local_err);
17b005f1 2734 if (ret < 0) {
8bfea15d 2735 goto fail;
2a05cbe4 2736 }
62392ebb
KW
2737 /*
2738 * This option update would logically belong in bdrv_fill_options(),
2739 * but we first need to open bs->file for the probing to work, while
2740 * opening bs->file already requires the (mostly) final set of options
2741 * so that cache mode etc. can be inherited.
2742 *
2743 * Adding the driver later is somewhat ugly, but it's not an option
2744 * that would ever be inherited, so it's correct. We just need to make
2745 * sure to update both bs->options (which has the full effective
2746 * options for bs) and options (which has file.* already removed).
2747 */
46f5ac20
EB
2748 qdict_put_str(bs->options, "driver", drv->format_name);
2749 qdict_put_str(options, "driver", drv->format_name);
76c591b0 2750 } else if (!drv) {
17b005f1 2751 error_setg(errp, "Must specify either driver or file");
8bfea15d 2752 goto fail;
ea2384d3 2753 }
b6ce07aa 2754
53a29513
HR
2755 /* BDRV_O_PROTOCOL must be set iff a protocol BDS is about to be created */
2756 assert(!!(flags & BDRV_O_PROTOCOL) == !!drv->bdrv_file_open);
2757 /* file must be NULL if a protocol BDS is about to be created
2758 * (the inverse results in an error message from bdrv_open_common()) */
2759 assert(!(flags & BDRV_O_PROTOCOL) || !file);
2760
b6ce07aa 2761 /* Open the image */
82dc8b41 2762 ret = bdrv_open_common(bs, file, options, &local_err);
b6ce07aa 2763 if (ret < 0) {
8bfea15d 2764 goto fail;
6987307c
CH
2765 }
2766
4e4bf5c4 2767 if (file) {
5696c6e3 2768 blk_unref(file);
f500a6d3
KW
2769 file = NULL;
2770 }
2771
b6ce07aa 2772 /* If there is a backing file, use it */
9156df12 2773 if ((flags & BDRV_O_NO_BACKING) == 0) {
d9b7b057 2774 ret = bdrv_open_backing_file(bs, options, "backing", &local_err);
b6ce07aa 2775 if (ret < 0) {
b6ad491a 2776 goto close_and_fail;
b6ce07aa 2777 }
b6ce07aa
KW
2778 }
2779
50196d7a
AG
2780 /* Remove all children options and references
2781 * from bs->options and bs->explicit_options */
2f624b80
AG
2782 QLIST_FOREACH(child, &bs->children, next) {
2783 char *child_key_dot;
2784 child_key_dot = g_strdup_printf("%s.", child->name);
2785 qdict_extract_subqdict(bs->explicit_options, NULL, child_key_dot);
2786 qdict_extract_subqdict(bs->options, NULL, child_key_dot);
50196d7a
AG
2787 qdict_del(bs->explicit_options, child->name);
2788 qdict_del(bs->options, child->name);
2f624b80
AG
2789 g_free(child_key_dot);
2790 }
2791
91af7014
HR
2792 bdrv_refresh_filename(bs);
2793
b6ad491a 2794 /* Check if any unknown options were used */
7ad2757f 2795 if (qdict_size(options) != 0) {
b6ad491a 2796 const QDictEntry *entry = qdict_first(options);
5acd9d81
HR
2797 if (flags & BDRV_O_PROTOCOL) {
2798 error_setg(errp, "Block protocol '%s' doesn't support the option "
2799 "'%s'", drv->format_name, entry->key);
2800 } else {
d0e46a55
HR
2801 error_setg(errp,
2802 "Block format '%s' does not support the option '%s'",
2803 drv->format_name, entry->key);
5acd9d81 2804 }
b6ad491a 2805
b6ad491a
KW
2806 goto close_and_fail;
2807 }
b6ad491a 2808
c01c214b 2809 bdrv_parent_cb_change_media(bs, true);
b6ce07aa 2810
cb3e7f08 2811 qobject_unref(options);
8961be33 2812 options = NULL;
dd62f1ca
KW
2813
2814 /* For snapshot=on, create a temporary qcow2 overlay. bs points to the
2815 * temporary snapshot afterwards. */
2816 if (snapshot_flags) {
66836189
HR
2817 BlockDriverState *snapshot_bs;
2818 snapshot_bs = bdrv_append_temp_snapshot(bs, snapshot_flags,
2819 snapshot_options, &local_err);
73176bee 2820 snapshot_options = NULL;
dd62f1ca
KW
2821 if (local_err) {
2822 goto close_and_fail;
2823 }
5b363937
HR
2824 /* We are not going to return bs but the overlay on top of it
2825 * (snapshot_bs); thus, we have to drop the strong reference to bs
2826 * (which we obtained by calling bdrv_new()). bs will not be deleted,
2827 * though, because the overlay still has a reference to it. */
2828 bdrv_unref(bs);
2829 bs = snapshot_bs;
dd62f1ca
KW
2830 }
2831
5b363937 2832 return bs;
b6ce07aa 2833
8bfea15d 2834fail:
5696c6e3 2835 blk_unref(file);
cb3e7f08
MAL
2836 qobject_unref(snapshot_options);
2837 qobject_unref(bs->explicit_options);
2838 qobject_unref(bs->options);
2839 qobject_unref(options);
de9c0cec 2840 bs->options = NULL;
998cbd6a 2841 bs->explicit_options = NULL;
5b363937 2842 bdrv_unref(bs);
621ff94d 2843 error_propagate(errp, local_err);
5b363937 2844 return NULL;
de9c0cec 2845
b6ad491a 2846close_and_fail:
5b363937 2847 bdrv_unref(bs);
cb3e7f08
MAL
2848 qobject_unref(snapshot_options);
2849 qobject_unref(options);
621ff94d 2850 error_propagate(errp, local_err);
5b363937 2851 return NULL;
b6ce07aa
KW
2852}
2853
5b363937
HR
2854BlockDriverState *bdrv_open(const char *filename, const char *reference,
2855 QDict *options, int flags, Error **errp)
f3930ed0 2856{
5b363937 2857 return bdrv_open_inherit(filename, reference, options, flags, NULL,
ce343771 2858 NULL, errp);
f3930ed0
KW
2859}
2860
e971aa12
JC
2861/*
2862 * Adds a BlockDriverState to a simple queue for an atomic, transactional
2863 * reopen of multiple devices.
2864 *
2865 * bs_queue can either be an existing BlockReopenQueue that has had QSIMPLE_INIT
2866 * already performed, or alternatively may be NULL a new BlockReopenQueue will
2867 * be created and initialized. This newly created BlockReopenQueue should be
2868 * passed back in for subsequent calls that are intended to be of the same
2869 * atomic 'set'.
2870 *
2871 * bs is the BlockDriverState to add to the reopen queue.
2872 *
4d2cb092
KW
2873 * options contains the changed options for the associated bs
2874 * (the BlockReopenQueue takes ownership)
2875 *
e971aa12
JC
2876 * flags contains the open flags for the associated bs
2877 *
2878 * returns a pointer to bs_queue, which is either the newly allocated
2879 * bs_queue, or the existing bs_queue being used.
2880 *
1a63a907 2881 * bs must be drained between bdrv_reopen_queue() and bdrv_reopen_multiple().
e971aa12 2882 */
28518102
KW
2883static BlockReopenQueue *bdrv_reopen_queue_child(BlockReopenQueue *bs_queue,
2884 BlockDriverState *bs,
2885 QDict *options,
2886 int flags,
2887 const BdrvChildRole *role,
2888 QDict *parent_options,
2889 int parent_flags)
e971aa12
JC
2890{
2891 assert(bs != NULL);
2892
2893 BlockReopenQueueEntry *bs_entry;
67251a31 2894 BdrvChild *child;
145f598e 2895 QDict *old_options, *explicit_options;
67251a31 2896
1a63a907
KW
2897 /* Make sure that the caller remembered to use a drained section. This is
2898 * important to avoid graph changes between the recursive queuing here and
2899 * bdrv_reopen_multiple(). */
2900 assert(bs->quiesce_counter > 0);
2901
e971aa12
JC
2902 if (bs_queue == NULL) {
2903 bs_queue = g_new0(BlockReopenQueue, 1);
2904 QSIMPLEQ_INIT(bs_queue);
2905 }
2906
4d2cb092
KW
2907 if (!options) {
2908 options = qdict_new();
2909 }
2910
5b7ba05f
AG
2911 /* Check if this BlockDriverState is already in the queue */
2912 QSIMPLEQ_FOREACH(bs_entry, bs_queue, entry) {
2913 if (bs == bs_entry->state.bs) {
2914 break;
2915 }
2916 }
2917
28518102
KW
2918 /*
2919 * Precedence of options:
2920 * 1. Explicitly passed in options (highest)
91a097e7 2921 * 2. Set in flags (only for top level)
145f598e 2922 * 3. Retained from explicitly set options of bs
8e2160e2 2923 * 4. Inherited from parent node
28518102
KW
2924 * 5. Retained from effective options of bs
2925 */
2926
91a097e7
KW
2927 if (!parent_options) {
2928 /*
2929 * Any setting represented by flags is always updated. If the
2930 * corresponding QDict option is set, it takes precedence. Otherwise
2931 * the flag is translated into a QDict option. The old setting of bs is
2932 * not considered.
2933 */
2934 update_options_from_flags(options, flags);
2935 }
2936
145f598e 2937 /* Old explicitly set values (don't overwrite by inherited value) */
5b7ba05f
AG
2938 if (bs_entry) {
2939 old_options = qdict_clone_shallow(bs_entry->state.explicit_options);
2940 } else {
2941 old_options = qdict_clone_shallow(bs->explicit_options);
2942 }
145f598e 2943 bdrv_join_options(bs, options, old_options);
cb3e7f08 2944 qobject_unref(old_options);
145f598e
KW
2945
2946 explicit_options = qdict_clone_shallow(options);
2947
28518102
KW
2948 /* Inherit from parent node */
2949 if (parent_options) {
1a529736
FZ
2950 QemuOpts *opts;
2951 QDict *options_copy;
28518102 2952 assert(!flags);
8e2160e2 2953 role->inherit_options(&flags, options, parent_flags, parent_options);
1a529736
FZ
2954 options_copy = qdict_clone_shallow(options);
2955 opts = qemu_opts_create(&bdrv_runtime_opts, NULL, 0, &error_abort);
2956 qemu_opts_absorb_qdict(opts, options_copy, NULL);
2957 update_flags_from_options(&flags, opts);
2958 qemu_opts_del(opts);
cb3e7f08 2959 qobject_unref(options_copy);
28518102
KW
2960 }
2961
2962 /* Old values are used for options that aren't set yet */
4d2cb092 2963 old_options = qdict_clone_shallow(bs->options);
cddff5ba 2964 bdrv_join_options(bs, options, old_options);
cb3e7f08 2965 qobject_unref(old_options);
4d2cb092 2966
fd452021 2967 /* bdrv_open_inherit() sets and clears some additional flags internally */
f1f25a2e 2968 flags &= ~BDRV_O_PROTOCOL;
fd452021
KW
2969 if (flags & BDRV_O_RDWR) {
2970 flags |= BDRV_O_ALLOW_RDWR;
2971 }
f1f25a2e 2972
1857c97b
KW
2973 if (!bs_entry) {
2974 bs_entry = g_new0(BlockReopenQueueEntry, 1);
2975 QSIMPLEQ_INSERT_TAIL(bs_queue, bs_entry, entry);
2976 } else {
cb3e7f08
MAL
2977 qobject_unref(bs_entry->state.options);
2978 qobject_unref(bs_entry->state.explicit_options);
1857c97b
KW
2979 }
2980
2981 bs_entry->state.bs = bs;
2982 bs_entry->state.options = options;
2983 bs_entry->state.explicit_options = explicit_options;
2984 bs_entry->state.flags = flags;
2985
30450259
KW
2986 /* This needs to be overwritten in bdrv_reopen_prepare() */
2987 bs_entry->state.perm = UINT64_MAX;
2988 bs_entry->state.shared_perm = 0;
2989
67251a31 2990 QLIST_FOREACH(child, &bs->children, next) {
4c9dfe5d
KW
2991 QDict *new_child_options;
2992 char *child_key_dot;
67251a31 2993
4c9dfe5d
KW
2994 /* reopen can only change the options of block devices that were
2995 * implicitly created and inherited options. For other (referenced)
2996 * block devices, a syntax like "backing.foo" results in an error. */
67251a31
KW
2997 if (child->bs->inherits_from != bs) {
2998 continue;
2999 }
3000
4c9dfe5d 3001 child_key_dot = g_strdup_printf("%s.", child->name);
2f624b80 3002 qdict_extract_subqdict(explicit_options, NULL, child_key_dot);
4c9dfe5d
KW
3003 qdict_extract_subqdict(options, &new_child_options, child_key_dot);
3004 g_free(child_key_dot);
3005
28518102
KW
3006 bdrv_reopen_queue_child(bs_queue, child->bs, new_child_options, 0,
3007 child->role, options, flags);
e971aa12
JC
3008 }
3009
e971aa12
JC
3010 return bs_queue;
3011}
3012
28518102
KW
3013BlockReopenQueue *bdrv_reopen_queue(BlockReopenQueue *bs_queue,
3014 BlockDriverState *bs,
3015 QDict *options, int flags)
3016{
3017 return bdrv_reopen_queue_child(bs_queue, bs, options, flags,
3018 NULL, NULL, 0);
3019}
3020
e971aa12
JC
3021/*
3022 * Reopen multiple BlockDriverStates atomically & transactionally.
3023 *
3024 * The queue passed in (bs_queue) must have been built up previous
3025 * via bdrv_reopen_queue().
3026 *
3027 * Reopens all BDS specified in the queue, with the appropriate
3028 * flags. All devices are prepared for reopen, and failure of any
50d6a8a3 3029 * device will cause all device changes to be abandoned, and intermediate
e971aa12
JC
3030 * data cleaned up.
3031 *
3032 * If all devices prepare successfully, then the changes are committed
3033 * to all devices.
3034 *
1a63a907
KW
3035 * All affected nodes must be drained between bdrv_reopen_queue() and
3036 * bdrv_reopen_multiple().
e971aa12 3037 */
720150f3 3038int bdrv_reopen_multiple(AioContext *ctx, BlockReopenQueue *bs_queue, Error **errp)
e971aa12
JC
3039{
3040 int ret = -1;
3041 BlockReopenQueueEntry *bs_entry, *next;
3042 Error *local_err = NULL;
3043
3044 assert(bs_queue != NULL);
3045
e971aa12 3046 QSIMPLEQ_FOREACH(bs_entry, bs_queue, entry) {
1a63a907 3047 assert(bs_entry->state.bs->quiesce_counter > 0);
e971aa12
JC
3048 if (bdrv_reopen_prepare(&bs_entry->state, bs_queue, &local_err)) {
3049 error_propagate(errp, local_err);
3050 goto cleanup;
3051 }
3052 bs_entry->prepared = true;
3053 }
3054
3055 /* If we reach this point, we have success and just need to apply the
3056 * changes
3057 */
3058 QSIMPLEQ_FOREACH(bs_entry, bs_queue, entry) {
3059 bdrv_reopen_commit(&bs_entry->state);
3060 }
3061
3062 ret = 0;
3063
3064cleanup:
3065 QSIMPLEQ_FOREACH_SAFE(bs_entry, bs_queue, entry, next) {
1bab38e7
AG
3066 if (ret) {
3067 if (bs_entry->prepared) {
3068 bdrv_reopen_abort(&bs_entry->state);
3069 }
cb3e7f08 3070 qobject_unref(bs_entry->state.explicit_options);
4c8350fe 3071 qobject_unref(bs_entry->state.options);
e971aa12
JC
3072 }
3073 g_free(bs_entry);
3074 }
3075 g_free(bs_queue);
40840e41 3076
e971aa12
JC
3077 return ret;
3078}
3079
3080
3081/* Reopen a single BlockDriverState with the specified flags. */
3082int bdrv_reopen(BlockDriverState *bs, int bdrv_flags, Error **errp)
3083{
3084 int ret = -1;
3085 Error *local_err = NULL;
1a63a907 3086 BlockReopenQueue *queue;
e971aa12 3087
1a63a907
KW
3088 bdrv_subtree_drained_begin(bs);
3089
3090 queue = bdrv_reopen_queue(NULL, bs, NULL, bdrv_flags);
720150f3 3091 ret = bdrv_reopen_multiple(bdrv_get_aio_context(bs), queue, &local_err);
e971aa12
JC
3092 if (local_err != NULL) {
3093 error_propagate(errp, local_err);
3094 }
1a63a907
KW
3095
3096 bdrv_subtree_drained_end(bs);
3097
e971aa12
JC
3098 return ret;
3099}
3100
30450259
KW
3101static BlockReopenQueueEntry *find_parent_in_reopen_queue(BlockReopenQueue *q,
3102 BdrvChild *c)
3103{
3104 BlockReopenQueueEntry *entry;
3105
3106 QSIMPLEQ_FOREACH(entry, q, entry) {
3107 BlockDriverState *bs = entry->state.bs;
3108 BdrvChild *child;
3109
3110 QLIST_FOREACH(child, &bs->children, next) {
3111 if (child == c) {
3112 return entry;
3113 }
3114 }
3115 }
3116
3117 return NULL;
3118}
3119
3120static void bdrv_reopen_perm(BlockReopenQueue *q, BlockDriverState *bs,
3121 uint64_t *perm, uint64_t *shared)
3122{
3123 BdrvChild *c;
3124 BlockReopenQueueEntry *parent;
3125 uint64_t cumulative_perms = 0;
3126 uint64_t cumulative_shared_perms = BLK_PERM_ALL;
3127
3128 QLIST_FOREACH(c, &bs->parents, next_parent) {
3129 parent = find_parent_in_reopen_queue(q, c);
3130 if (!parent) {
3131 cumulative_perms |= c->perm;
3132 cumulative_shared_perms &= c->shared_perm;
3133 } else {
3134 uint64_t nperm, nshared;
3135
3136 bdrv_child_perm(parent->state.bs, bs, c, c->role, q,
3137 parent->state.perm, parent->state.shared_perm,
3138 &nperm, &nshared);
3139
3140 cumulative_perms |= nperm;
3141 cumulative_shared_perms &= nshared;
3142 }
3143 }
3144 *perm = cumulative_perms;
3145 *shared = cumulative_shared_perms;
3146}
e971aa12
JC
3147
3148/*
3149 * Prepares a BlockDriverState for reopen. All changes are staged in the
3150 * 'opaque' field of the BDRVReopenState, which is used and allocated by
3151 * the block driver layer .bdrv_reopen_prepare()
3152 *
3153 * bs is the BlockDriverState to reopen
3154 * flags are the new open flags
3155 * queue is the reopen queue
3156 *
3157 * Returns 0 on success, non-zero on error. On error errp will be set
3158 * as well.
3159 *
3160 * On failure, bdrv_reopen_abort() will be called to clean up any data.
3161 * It is the responsibility of the caller to then call the abort() or
3162 * commit() for any other BDS that have been left in a prepare() state
3163 *
3164 */
3165int bdrv_reopen_prepare(BDRVReopenState *reopen_state, BlockReopenQueue *queue,
3166 Error **errp)
3167{
3168 int ret = -1;
3169 Error *local_err = NULL;
3170 BlockDriver *drv;
ccf9dc07 3171 QemuOpts *opts;
4c8350fe 3172 QDict *orig_reopen_opts;
593b3071 3173 char *discard = NULL;
3d8ce171 3174 bool read_only;
e971aa12
JC
3175
3176 assert(reopen_state != NULL);
3177 assert(reopen_state->bs->drv != NULL);
3178 drv = reopen_state->bs->drv;
3179
4c8350fe
AG
3180 /* This function and each driver's bdrv_reopen_prepare() remove
3181 * entries from reopen_state->options as they are processed, so
3182 * we need to make a copy of the original QDict. */
3183 orig_reopen_opts = qdict_clone_shallow(reopen_state->options);
3184
ccf9dc07
KW
3185 /* Process generic block layer options */
3186 opts = qemu_opts_create(&bdrv_runtime_opts, NULL, 0, &error_abort);
3187 qemu_opts_absorb_qdict(opts, reopen_state->options, &local_err);
3188 if (local_err) {
3189 error_propagate(errp, local_err);
3190 ret = -EINVAL;
3191 goto error;
3192 }
3193
91a097e7
KW
3194 update_flags_from_options(&reopen_state->flags, opts);
3195
415bbca8 3196 discard = qemu_opt_get_del(opts, BDRV_OPT_DISCARD);
593b3071
AG
3197 if (discard != NULL) {
3198 if (bdrv_parse_discard_flags(discard, &reopen_state->flags) != 0) {
3199 error_setg(errp, "Invalid discard option");
3200 ret = -EINVAL;
3201 goto error;
3202 }
3203 }
3204
543770bd
AG
3205 reopen_state->detect_zeroes =
3206 bdrv_parse_detect_zeroes(opts, reopen_state->flags, &local_err);
3207 if (local_err) {
3208 error_propagate(errp, local_err);
3209 ret = -EINVAL;
3210 goto error;
3211 }
3212
57f9db9a
AG
3213 /* All other options (including node-name and driver) must be unchanged.
3214 * Put them back into the QDict, so that they are checked at the end
3215 * of this function. */
3216 qemu_opts_to_qdict(opts, reopen_state->options);
ccf9dc07 3217
3d8ce171
JC
3218 /* If we are to stay read-only, do not allow permission change
3219 * to r/w. Attempting to set to r/w may fail if either BDRV_O_ALLOW_RDWR is
3220 * not set, or if the BDS still has copy_on_read enabled */
3221 read_only = !(reopen_state->flags & BDRV_O_RDWR);
54a32bfe 3222 ret = bdrv_can_set_read_only(reopen_state->bs, read_only, true, &local_err);
3d8ce171
JC
3223 if (local_err) {
3224 error_propagate(errp, local_err);
e971aa12
JC
3225 goto error;
3226 }
3227
30450259
KW
3228 /* Calculate required permissions after reopening */
3229 bdrv_reopen_perm(queue, reopen_state->bs,
3230 &reopen_state->perm, &reopen_state->shared_perm);
e971aa12
JC
3231
3232 ret = bdrv_flush(reopen_state->bs);
3233 if (ret) {
455b0fde 3234 error_setg_errno(errp, -ret, "Error flushing drive");
e971aa12
JC
3235 goto error;
3236 }
3237
3238 if (drv->bdrv_reopen_prepare) {
3239 ret = drv->bdrv_reopen_prepare(reopen_state, queue, &local_err);
3240 if (ret) {
3241 if (local_err != NULL) {
3242 error_propagate(errp, local_err);
3243 } else {
d8b6895f
LC
3244 error_setg(errp, "failed while preparing to reopen image '%s'",
3245 reopen_state->bs->filename);
e971aa12
JC
3246 }
3247 goto error;
3248 }
3249 } else {
3250 /* It is currently mandatory to have a bdrv_reopen_prepare()
3251 * handler for each supported drv. */
81e5f78a
AG
3252 error_setg(errp, "Block format '%s' used by node '%s' "
3253 "does not support reopening files", drv->format_name,
3254 bdrv_get_device_or_node_name(reopen_state->bs));
e971aa12
JC
3255 ret = -1;
3256 goto error;
3257 }
3258
4d2cb092
KW
3259 /* Options that are not handled are only okay if they are unchanged
3260 * compared to the old state. It is expected that some options are only
3261 * used for the initial open, but not reopen (e.g. filename) */
3262 if (qdict_size(reopen_state->options)) {
3263 const QDictEntry *entry = qdict_first(reopen_state->options);
3264
3265 do {
54fd1b0d
HR
3266 QObject *new = entry->value;
3267 QObject *old = qdict_get(reopen_state->bs->options, entry->key);
3268
db905283
AG
3269 /* Allow child references (child_name=node_name) as long as they
3270 * point to the current child (i.e. everything stays the same). */
3271 if (qobject_type(new) == QTYPE_QSTRING) {
3272 BdrvChild *child;
3273 QLIST_FOREACH(child, &reopen_state->bs->children, next) {
3274 if (!strcmp(child->name, entry->key)) {
3275 break;
3276 }
3277 }
3278
3279 if (child) {
3280 const char *str = qobject_get_try_str(new);
3281 if (!strcmp(child->bs->node_name, str)) {
3282 continue; /* Found child with this name, skip option */
3283 }
3284 }
3285 }
3286
129c7d1c 3287 /*
54fd1b0d
HR
3288 * TODO: When using -drive to specify blockdev options, all values
3289 * will be strings; however, when using -blockdev, blockdev-add or
3290 * filenames using the json:{} pseudo-protocol, they will be
3291 * correctly typed.
3292 * In contrast, reopening options are (currently) always strings
3293 * (because you can only specify them through qemu-io; all other
3294 * callers do not specify any options).
3295 * Therefore, when using anything other than -drive to create a BDS,
3296 * this cannot detect non-string options as unchanged, because
3297 * qobject_is_equal() always returns false for objects of different
3298 * type. In the future, this should be remedied by correctly typing
3299 * all options. For now, this is not too big of an issue because
3300 * the user can simply omit options which cannot be changed anyway,
3301 * so they will stay unchanged.
129c7d1c 3302 */
54fd1b0d 3303 if (!qobject_is_equal(new, old)) {
4d2cb092
KW
3304 error_setg(errp, "Cannot change the option '%s'", entry->key);
3305 ret = -EINVAL;
3306 goto error;
3307 }
3308 } while ((entry = qdict_next(reopen_state->options, entry)));
3309 }
3310
30450259
KW
3311 ret = bdrv_check_perm(reopen_state->bs, queue, reopen_state->perm,
3312 reopen_state->shared_perm, NULL, errp);
3313 if (ret < 0) {
3314 goto error;
3315 }
3316
e971aa12
JC
3317 ret = 0;
3318
4c8350fe
AG
3319 /* Restore the original reopen_state->options QDict */
3320 qobject_unref(reopen_state->options);
3321 reopen_state->options = qobject_ref(orig_reopen_opts);
3322
e971aa12 3323error:
ccf9dc07 3324 qemu_opts_del(opts);
4c8350fe 3325 qobject_unref(orig_reopen_opts);
593b3071 3326 g_free(discard);
e971aa12
JC
3327 return ret;
3328}
3329
3330/*
3331 * Takes the staged changes for the reopen from bdrv_reopen_prepare(), and
3332 * makes them final by swapping the staging BlockDriverState contents into
3333 * the active BlockDriverState contents.
3334 */
3335void bdrv_reopen_commit(BDRVReopenState *reopen_state)
3336{
3337 BlockDriver *drv;
50bf65ba 3338 BlockDriverState *bs;
50196d7a 3339 BdrvChild *child;
cb9ff6c2 3340 bool old_can_write, new_can_write;
e971aa12
JC
3341
3342 assert(reopen_state != NULL);
50bf65ba
VSO
3343 bs = reopen_state->bs;
3344 drv = bs->drv;
e971aa12
JC
3345 assert(drv != NULL);
3346
cb9ff6c2
VSO
3347 old_can_write =
3348 !bdrv_is_read_only(bs) && !(bdrv_get_flags(bs) & BDRV_O_INACTIVE);
3349
e971aa12
JC
3350 /* If there are any driver level actions to take */
3351 if (drv->bdrv_reopen_commit) {
3352 drv->bdrv_reopen_commit(reopen_state);
3353 }
3354
3355 /* set BDS specific flags now */
cb3e7f08 3356 qobject_unref(bs->explicit_options);
4c8350fe 3357 qobject_unref(bs->options);
145f598e 3358
50bf65ba 3359 bs->explicit_options = reopen_state->explicit_options;
4c8350fe 3360 bs->options = reopen_state->options;
50bf65ba
VSO
3361 bs->open_flags = reopen_state->flags;
3362 bs->read_only = !(reopen_state->flags & BDRV_O_RDWR);
543770bd 3363 bs->detect_zeroes = reopen_state->detect_zeroes;
355ef4ac 3364
50196d7a
AG
3365 /* Remove child references from bs->options and bs->explicit_options.
3366 * Child options were already removed in bdrv_reopen_queue_child() */
3367 QLIST_FOREACH(child, &bs->children, next) {
3368 qdict_del(bs->explicit_options, child->name);
3369 qdict_del(bs->options, child->name);
3370 }
3371
50bf65ba 3372 bdrv_refresh_limits(bs, NULL);
cb9ff6c2 3373
30450259
KW
3374 bdrv_set_perm(reopen_state->bs, reopen_state->perm,
3375 reopen_state->shared_perm);
3376
cb9ff6c2
VSO
3377 new_can_write =
3378 !bdrv_is_read_only(bs) && !(bdrv_get_flags(bs) & BDRV_O_INACTIVE);
3379 if (!old_can_write && new_can_write && drv->bdrv_reopen_bitmaps_rw) {
3380 Error *local_err = NULL;
3381 if (drv->bdrv_reopen_bitmaps_rw(bs, &local_err) < 0) {
3382 /* This is not fatal, bitmaps just left read-only, so all following
3383 * writes will fail. User can remove read-only bitmaps to unblock
3384 * writes.
3385 */
3386 error_reportf_err(local_err,
3387 "%s: Failed to make dirty bitmaps writable: ",
3388 bdrv_get_node_name(bs));
3389 }
3390 }
e971aa12
JC
3391}
3392
3393/*
3394 * Abort the reopen, and delete and free the staged changes in
3395 * reopen_state
3396 */
3397void bdrv_reopen_abort(BDRVReopenState *reopen_state)
3398{
3399 BlockDriver *drv;
3400
3401 assert(reopen_state != NULL);
3402 drv = reopen_state->bs->drv;
3403 assert(drv != NULL);
3404
3405 if (drv->bdrv_reopen_abort) {
3406 drv->bdrv_reopen_abort(reopen_state);
3407 }
145f598e 3408
30450259 3409 bdrv_abort_perm_update(reopen_state->bs);
e971aa12
JC
3410}
3411
3412
64dff520 3413static void bdrv_close(BlockDriverState *bs)
fc01f7e7 3414{
33384421 3415 BdrvAioNotifier *ban, *ban_next;
50a3efb0 3416 BdrvChild *child, *next;
33384421 3417
ca9bd24c 3418 assert(!bs->job);
30f55fb8 3419 assert(!bs->refcnt);
99b7e775 3420
fc27291d 3421 bdrv_drained_begin(bs); /* complete I/O */
58fda173 3422 bdrv_flush(bs);
53ec73e2 3423 bdrv_drain(bs); /* in case flush left pending I/O */
fc27291d 3424
3cbc002c 3425 if (bs->drv) {
3c005293
VSO
3426 if (bs->drv->bdrv_close) {
3427 bs->drv->bdrv_close(bs);
3428 }
9a4f4c31 3429 bs->drv = NULL;
50a3efb0 3430 }
9a7dedbc 3431
50a3efb0 3432 bdrv_set_backing_hd(bs, NULL, &error_abort);
9a7dedbc 3433
50a3efb0
AG
3434 if (bs->file != NULL) {
3435 bdrv_unref_child(bs, bs->file);
3436 bs->file = NULL;
3437 }
9a4f4c31 3438
50a3efb0
AG
3439 QLIST_FOREACH_SAFE(child, &bs->children, next, next) {
3440 /* TODO Remove bdrv_unref() from drivers' close function and use
3441 * bdrv_unref_child() here */
3442 if (child->bs->inherits_from == bs) {
3443 child->bs->inherits_from = NULL;
6e93e7c4 3444 }
50a3efb0 3445 bdrv_detach_child(child);
b338082b 3446 }
98f90dba 3447
50a3efb0
AG
3448 g_free(bs->opaque);
3449 bs->opaque = NULL;
3450 atomic_set(&bs->copy_on_read, 0);
3451 bs->backing_file[0] = '\0';
3452 bs->backing_format[0] = '\0';
3453 bs->total_sectors = 0;
3454 bs->encrypted = false;
3455 bs->sg = false;
cb3e7f08
MAL
3456 qobject_unref(bs->options);
3457 qobject_unref(bs->explicit_options);
50a3efb0
AG
3458 bs->options = NULL;
3459 bs->explicit_options = NULL;
cb3e7f08 3460 qobject_unref(bs->full_open_options);
50a3efb0
AG
3461 bs->full_open_options = NULL;
3462
cca43ae1
VSO
3463 bdrv_release_named_dirty_bitmaps(bs);
3464 assert(QLIST_EMPTY(&bs->dirty_bitmaps));
3465
33384421
HR
3466 QLIST_FOREACH_SAFE(ban, &bs->aio_notifiers, list, ban_next) {
3467 g_free(ban);
3468 }
3469 QLIST_INIT(&bs->aio_notifiers);
fc27291d 3470 bdrv_drained_end(bs);
b338082b
FB
3471}
3472
2bc93fed
MK
3473void bdrv_close_all(void)
3474{
b3b5299d 3475 assert(job_next(NULL) == NULL);
cd7fca95 3476 nbd_export_close_all();
ca9bd24c
HR
3477
3478 /* Drop references from requests still in flight, such as canceled block
3479 * jobs whose AIO context has not been polled yet */
3480 bdrv_drain_all();
2bc93fed 3481
ca9bd24c
HR
3482 blk_remove_all_bs();
3483 blockdev_close_all_bdrv_states();
ed78cda3 3484
a1a2af07 3485 assert(QTAILQ_EMPTY(&all_bdrv_states));
2bc93fed
MK
3486}
3487
d0ac0380
KW
3488static bool should_update_child(BdrvChild *c, BlockDriverState *to)
3489{
3490 BdrvChild *to_c;
3491
3492 if (c->role->stay_at_node) {
3493 return false;
3494 }
3495
ec9f10fe
HR
3496 /* If the child @c belongs to the BDS @to, replacing the current
3497 * c->bs by @to would mean to create a loop.
3498 *
3499 * Such a case occurs when appending a BDS to a backing chain.
3500 * For instance, imagine the following chain:
3501 *
3502 * guest device -> node A -> further backing chain...
3503 *
3504 * Now we create a new BDS B which we want to put on top of this
3505 * chain, so we first attach A as its backing node:
3506 *
3507 * node B
3508 * |
3509 * v
3510 * guest device -> node A -> further backing chain...
3511 *
3512 * Finally we want to replace A by B. When doing that, we want to
3513 * replace all pointers to A by pointers to B -- except for the
3514 * pointer from B because (1) that would create a loop, and (2)
3515 * that pointer should simply stay intact:
3516 *
3517 * guest device -> node B
3518 * |
3519 * v
3520 * node A -> further backing chain...
3521 *
3522 * In general, when replacing a node A (c->bs) by a node B (@to),
3523 * if A is a child of B, that means we cannot replace A by B there
3524 * because that would create a loop. Silently detaching A from B
3525 * is also not really an option. So overall just leaving A in
3526 * place there is the most sensible choice. */
3527 QLIST_FOREACH(to_c, &to->children, next) {
3528 if (to_c == c) {
d0ac0380
KW
3529 return false;
3530 }
3531 }
3532
3533 return true;
3534}
3535
5fe31c25
KW
3536void bdrv_replace_node(BlockDriverState *from, BlockDriverState *to,
3537 Error **errp)
dd62f1ca 3538{
d0ac0380 3539 BdrvChild *c, *next;
234ac1a9
KW
3540 GSList *list = NULL, *p;
3541 uint64_t old_perm, old_shared;
3542 uint64_t perm = 0, shared = BLK_PERM_ALL;
3543 int ret;
3544
5fe31c25
KW
3545 assert(!atomic_read(&from->in_flight));
3546 assert(!atomic_read(&to->in_flight));
dd62f1ca 3547
234ac1a9
KW
3548 /* Make sure that @from doesn't go away until we have successfully attached
3549 * all of its parents to @to. */
3550 bdrv_ref(from);
dd62f1ca 3551
234ac1a9 3552 /* Put all parents into @list and calculate their cumulative permissions */
dd62f1ca 3553 QLIST_FOREACH_SAFE(c, &from->parents, next_parent, next) {
ec9f10fe 3554 assert(c->bs == from);
d0ac0380 3555 if (!should_update_child(c, to)) {
26de9438
KW
3556 continue;
3557 }
234ac1a9
KW
3558 list = g_slist_prepend(list, c);
3559 perm |= c->perm;
3560 shared &= c->shared_perm;
3561 }
3562
3563 /* Check whether the required permissions can be granted on @to, ignoring
3564 * all BdrvChild in @list so that they can't block themselves. */
3121fb45 3565 ret = bdrv_check_update_perm(to, NULL, perm, shared, list, errp);
234ac1a9
KW
3566 if (ret < 0) {
3567 bdrv_abort_perm_update(to);
3568 goto out;
3569 }
3570
3571 /* Now actually perform the change. We performed the permission check for
3572 * all elements of @list at once, so set the permissions all at once at the
3573 * very end. */
3574 for (p = list; p != NULL; p = p->next) {
3575 c = p->data;
9bd910e2 3576
dd62f1ca 3577 bdrv_ref(to);
234ac1a9 3578 bdrv_replace_child_noperm(c, to);
dd62f1ca
KW
3579 bdrv_unref(from);
3580 }
234ac1a9
KW
3581
3582 bdrv_get_cumulative_perm(to, &old_perm, &old_shared);
3583 bdrv_set_perm(to, old_perm | perm, old_shared | shared);
3584
3585out:
3586 g_slist_free(list);
3587 bdrv_unref(from);
dd62f1ca
KW
3588}
3589
4ddc07ca
PB
3590/*
3591 * Add new bs contents at the top of an image chain while the chain is
3592 * live, while keeping required fields on the top layer.
3593 *
3594 * This will modify the BlockDriverState fields, and swap contents
3595 * between bs_new and bs_top. Both bs_new and bs_top are modified.
3596 *
bfb197e0 3597 * bs_new must not be attached to a BlockBackend.
4ddc07ca
PB
3598 *
3599 * This function does not create any image files.
dd62f1ca
KW
3600 *
3601 * bdrv_append() takes ownership of a bs_new reference and unrefs it because
3602 * that's what the callers commonly need. bs_new will be referenced by the old
3603 * parents of bs_top after bdrv_append() returns. If the caller needs to keep a
3604 * reference of its own, it must call bdrv_ref().
4ddc07ca 3605 */
b2c2832c
KW
3606void bdrv_append(BlockDriverState *bs_new, BlockDriverState *bs_top,
3607 Error **errp)
4ddc07ca 3608{
b2c2832c
KW
3609 Error *local_err = NULL;
3610
b2c2832c
KW
3611 bdrv_set_backing_hd(bs_new, bs_top, &local_err);
3612 if (local_err) {
3613 error_propagate(errp, local_err);
3614 goto out;
3615 }
dd62f1ca 3616
5fe31c25 3617 bdrv_replace_node(bs_top, bs_new, &local_err);
234ac1a9
KW
3618 if (local_err) {
3619 error_propagate(errp, local_err);
3620 bdrv_set_backing_hd(bs_new, NULL, &error_abort);
3621 goto out;
3622 }
4ddc07ca 3623
dd62f1ca
KW
3624 /* bs_new is now referenced by its new parents, we don't need the
3625 * additional reference any more. */
b2c2832c 3626out:
dd62f1ca 3627 bdrv_unref(bs_new);
8802d1fd
JC
3628}
3629
4f6fd349 3630static void bdrv_delete(BlockDriverState *bs)
b338082b 3631{
3e914655 3632 assert(!bs->job);
3718d8ab 3633 assert(bdrv_op_blocker_is_empty(bs));
4f6fd349 3634 assert(!bs->refcnt);
18846dee 3635
e1b5c52e
SH
3636 bdrv_close(bs);
3637
1b7bdbc1 3638 /* remove from list, if necessary */
63eaaae0
KW
3639 if (bs->node_name[0] != '\0') {
3640 QTAILQ_REMOVE(&graph_bdrv_states, bs, node_list);
3641 }
2c1d04e0
HR
3642 QTAILQ_REMOVE(&all_bdrv_states, bs, bs_list);
3643
7267c094 3644 g_free(bs);
fc01f7e7
FB
3645}
3646
e97fc193
AL
3647/*
3648 * Run consistency checks on an image
3649 *
e076f338 3650 * Returns 0 if the check could be completed (it doesn't mean that the image is
a1c7273b 3651 * free of errors) or -errno when an internal error occurred. The results of the
e076f338 3652 * check are stored in res.
e97fc193 3653 */
2fd61638
PB
3654static int coroutine_fn bdrv_co_check(BlockDriverState *bs,
3655 BdrvCheckResult *res, BdrvCheckMode fix)
e97fc193 3656{
908bcd54
HR
3657 if (bs->drv == NULL) {
3658 return -ENOMEDIUM;
3659 }
2fd61638 3660 if (bs->drv->bdrv_co_check == NULL) {
e97fc193
AL
3661 return -ENOTSUP;
3662 }
3663
e076f338 3664 memset(res, 0, sizeof(*res));
2fd61638
PB
3665 return bs->drv->bdrv_co_check(bs, res, fix);
3666}
3667
3668typedef struct CheckCo {
3669 BlockDriverState *bs;
3670 BdrvCheckResult *res;
3671 BdrvCheckMode fix;
3672 int ret;
3673} CheckCo;
3674
3675static void bdrv_check_co_entry(void *opaque)
3676{
3677 CheckCo *cco = opaque;
3678 cco->ret = bdrv_co_check(cco->bs, cco->res, cco->fix);
3679}
3680
3681int bdrv_check(BlockDriverState *bs,
3682 BdrvCheckResult *res, BdrvCheckMode fix)
3683{
3684 Coroutine *co;
3685 CheckCo cco = {
3686 .bs = bs,
3687 .res = res,
3688 .ret = -EINPROGRESS,
3689 .fix = fix,
3690 };
3691
3692 if (qemu_in_coroutine()) {
3693 /* Fast-path if already in coroutine context */
3694 bdrv_check_co_entry(&cco);
3695 } else {
3696 co = qemu_coroutine_create(bdrv_check_co_entry, &cco);
3697 qemu_coroutine_enter(co);
3698 BDRV_POLL_WHILE(bs, cco.ret == -EINPROGRESS);
3699 }
3700
3701 return cco.ret;
e97fc193
AL
3702}
3703
756e6736
KW
3704/*
3705 * Return values:
3706 * 0 - success
3707 * -EINVAL - backing format specified, but no file
3708 * -ENOSPC - can't update the backing file because no space is left in the
3709 * image file header
3710 * -ENOTSUP - format driver doesn't support changing the backing file
3711 */
3712int bdrv_change_backing_file(BlockDriverState *bs,
3713 const char *backing_file, const char *backing_fmt)
3714{
3715 BlockDriver *drv = bs->drv;
469ef350 3716 int ret;
756e6736 3717
d470ad42
HR
3718 if (!drv) {
3719 return -ENOMEDIUM;
3720 }
3721
5f377794
PB
3722 /* Backing file format doesn't make sense without a backing file */
3723 if (backing_fmt && !backing_file) {
3724 return -EINVAL;
3725 }
3726
756e6736 3727 if (drv->bdrv_change_backing_file != NULL) {
469ef350 3728 ret = drv->bdrv_change_backing_file(bs, backing_file, backing_fmt);
756e6736 3729 } else {
469ef350 3730 ret = -ENOTSUP;
756e6736 3731 }
469ef350
PB
3732
3733 if (ret == 0) {
3734 pstrcpy(bs->backing_file, sizeof(bs->backing_file), backing_file ?: "");
3735 pstrcpy(bs->backing_format, sizeof(bs->backing_format), backing_fmt ?: "");
3736 }
3737 return ret;
756e6736
KW
3738}
3739
6ebdcee2
JC
3740/*
3741 * Finds the image layer in the chain that has 'bs' as its backing file.
3742 *
3743 * active is the current topmost image.
3744 *
3745 * Returns NULL if bs is not found in active's image chain,
3746 * or if active == bs.
4caf0fcd
JC
3747 *
3748 * Returns the bottommost base image if bs == NULL.
6ebdcee2
JC
3749 */
3750BlockDriverState *bdrv_find_overlay(BlockDriverState *active,
3751 BlockDriverState *bs)
3752{
760e0063
KW
3753 while (active && bs != backing_bs(active)) {
3754 active = backing_bs(active);
6ebdcee2
JC
3755 }
3756
4caf0fcd
JC
3757 return active;
3758}
6ebdcee2 3759
4caf0fcd
JC
3760/* Given a BDS, searches for the base layer. */
3761BlockDriverState *bdrv_find_base(BlockDriverState *bs)
3762{
3763 return bdrv_find_overlay(bs, NULL);
6ebdcee2
JC
3764}
3765
6ebdcee2
JC
3766/*
3767 * Drops images above 'base' up to and including 'top', and sets the image
3768 * above 'top' to have base as its backing file.
3769 *
3770 * Requires that the overlay to 'top' is opened r/w, so that the backing file
3771 * information in 'bs' can be properly updated.
3772 *
3773 * E.g., this will convert the following chain:
3774 * bottom <- base <- intermediate <- top <- active
3775 *
3776 * to
3777 *
3778 * bottom <- base <- active
3779 *
3780 * It is allowed for bottom==base, in which case it converts:
3781 *
3782 * base <- intermediate <- top <- active
3783 *
3784 * to
3785 *
3786 * base <- active
3787 *
54e26900
JC
3788 * If backing_file_str is non-NULL, it will be used when modifying top's
3789 * overlay image metadata.
3790 *
6ebdcee2
JC
3791 * Error conditions:
3792 * if active == top, that is considered an error
3793 *
3794 */
bde70715
KW
3795int bdrv_drop_intermediate(BlockDriverState *top, BlockDriverState *base,
3796 const char *backing_file_str)
6ebdcee2 3797{
61f09cea 3798 BdrvChild *c, *next;
12fa4af6 3799 Error *local_err = NULL;
6ebdcee2
JC
3800 int ret = -EIO;
3801
6858eba0
KW
3802 bdrv_ref(top);
3803
6ebdcee2
JC
3804 if (!top->drv || !base->drv) {
3805 goto exit;
3806 }
3807
5db15a57
KW
3808 /* Make sure that base is in the backing chain of top */
3809 if (!bdrv_chain_contains(top, base)) {
6ebdcee2
JC
3810 goto exit;
3811 }
3812
3813 /* success - we can delete the intermediate states, and link top->base */
bde70715
KW
3814 /* TODO Check graph modification op blockers (BLK_PERM_GRAPH_MOD) once
3815 * we've figured out how they should work. */
61f09cea
KW
3816 backing_file_str = backing_file_str ? backing_file_str : base->filename;
3817
3818 QLIST_FOREACH_SAFE(c, &top->parents, next_parent, next) {
3819 /* Check whether we are allowed to switch c from top to base */
3820 GSList *ignore_children = g_slist_prepend(NULL, c);
3821 bdrv_check_update_perm(base, NULL, c->perm, c->shared_perm,
3822 ignore_children, &local_err);
2c860e79 3823 g_slist_free(ignore_children);
61f09cea
KW
3824 if (local_err) {
3825 ret = -EPERM;
3826 error_report_err(local_err);
6858eba0
KW
3827 goto exit;
3828 }
12fa4af6 3829
61f09cea
KW
3830 /* If so, update the backing file path in the image file */
3831 if (c->role->update_filename) {
3832 ret = c->role->update_filename(c, base, backing_file_str,
3833 &local_err);
3834 if (ret < 0) {
3835 bdrv_abort_perm_update(base);
3836 error_report_err(local_err);
3837 goto exit;
3838 }
3839 }
3840
3841 /* Do the actual switch in the in-memory graph.
3842 * Completes bdrv_check_update_perm() transaction internally. */
3843 bdrv_ref(base);
3844 bdrv_replace_child(c, base);
3845 bdrv_unref(top);
12fa4af6 3846 }
6ebdcee2 3847
6ebdcee2 3848 ret = 0;
6ebdcee2 3849exit:
6858eba0 3850 bdrv_unref(top);
6ebdcee2
JC
3851 return ret;
3852}
3853
61007b31
SH
3854/**
3855 * Length of a allocated file in bytes. Sparse files are counted by actual
3856 * allocated space. Return < 0 if error or unknown.
3857 */
3858int64_t bdrv_get_allocated_file_size(BlockDriverState *bs)
71d0770c 3859{
61007b31
SH
3860 BlockDriver *drv = bs->drv;
3861 if (!drv) {
3862 return -ENOMEDIUM;
8f4754ed 3863 }
61007b31
SH
3864 if (drv->bdrv_get_allocated_file_size) {
3865 return drv->bdrv_get_allocated_file_size(bs);
3866 }
3867 if (bs->file) {
9a4f4c31 3868 return bdrv_get_allocated_file_size(bs->file->bs);
1c9805a3 3869 }
61007b31 3870 return -ENOTSUP;
1c9805a3 3871}
e7a8a783 3872
90880ff1
SH
3873/*
3874 * bdrv_measure:
3875 * @drv: Format driver
3876 * @opts: Creation options for new image
3877 * @in_bs: Existing image containing data for new image (may be NULL)
3878 * @errp: Error object
3879 * Returns: A #BlockMeasureInfo (free using qapi_free_BlockMeasureInfo())
3880 * or NULL on error
3881 *
3882 * Calculate file size required to create a new image.
3883 *
3884 * If @in_bs is given then space for allocated clusters and zero clusters
3885 * from that image are included in the calculation. If @opts contains a
3886 * backing file that is shared by @in_bs then backing clusters may be omitted
3887 * from the calculation.
3888 *
3889 * If @in_bs is NULL then the calculation includes no allocated clusters
3890 * unless a preallocation option is given in @opts.
3891 *
3892 * Note that @in_bs may use a different BlockDriver from @drv.
3893 *
3894 * If an error occurs the @errp pointer is set.
3895 */
3896BlockMeasureInfo *bdrv_measure(BlockDriver *drv, QemuOpts *opts,
3897 BlockDriverState *in_bs, Error **errp)
3898{
3899 if (!drv->bdrv_measure) {
3900 error_setg(errp, "Block driver '%s' does not support size measurement",
3901 drv->format_name);
3902 return NULL;
3903 }
3904
3905 return drv->bdrv_measure(opts, in_bs, errp);
3906}
3907
61007b31
SH
3908/**
3909 * Return number of sectors on success, -errno on error.
1c9805a3 3910 */
61007b31 3911int64_t bdrv_nb_sectors(BlockDriverState *bs)
1c9805a3 3912{
61007b31 3913 BlockDriver *drv = bs->drv;
498e386c 3914
61007b31
SH
3915 if (!drv)
3916 return -ENOMEDIUM;
2572b37a 3917
61007b31
SH
3918 if (drv->has_variable_length) {
3919 int ret = refresh_total_sectors(bs, bs->total_sectors);
3920 if (ret < 0) {
3921 return ret;
1c9805a3
SH
3922 }
3923 }
61007b31 3924 return bs->total_sectors;
1c9805a3 3925}
b338082b 3926
61007b31
SH
3927/**
3928 * Return length in bytes on success, -errno on error.
3929 * The length is always a multiple of BDRV_SECTOR_SIZE.
8d3b1a2d 3930 */
61007b31 3931int64_t bdrv_getlength(BlockDriverState *bs)
8d3b1a2d 3932{
61007b31 3933 int64_t ret = bdrv_nb_sectors(bs);
8d3b1a2d 3934
4a9c9ea0 3935 ret = ret > INT64_MAX / BDRV_SECTOR_SIZE ? -EFBIG : ret;
61007b31 3936 return ret < 0 ? ret : ret * BDRV_SECTOR_SIZE;
fc01f7e7
FB
3937}
3938
61007b31
SH
3939/* return 0 as number of sectors if no device present or error */
3940void bdrv_get_geometry(BlockDriverState *bs, uint64_t *nb_sectors_ptr)
07d27a44 3941{
61007b31 3942 int64_t nb_sectors = bdrv_nb_sectors(bs);
07d27a44 3943
61007b31 3944 *nb_sectors_ptr = nb_sectors < 0 ? 0 : nb_sectors;
07d27a44
MA
3945}
3946
54115412 3947bool bdrv_is_sg(BlockDriverState *bs)
f08145fe 3948{
61007b31 3949 return bs->sg;
f08145fe
KW
3950}
3951
54115412 3952bool bdrv_is_encrypted(BlockDriverState *bs)
fc3959e4 3953{
760e0063 3954 if (bs->backing && bs->backing->bs->encrypted) {
54115412 3955 return true;
760e0063 3956 }
61007b31 3957 return bs->encrypted;
fc3959e4
FZ
3958}
3959
61007b31 3960const char *bdrv_get_format_name(BlockDriverState *bs)
40b4f539 3961{
61007b31 3962 return bs->drv ? bs->drv->format_name : NULL;
40b4f539
KW
3963}
3964
61007b31 3965static int qsort_strcmp(const void *a, const void *b)
40b4f539 3966{
ceff5bd7 3967 return strcmp(*(char *const *)a, *(char *const *)b);
40b4f539
KW
3968}
3969
61007b31
SH
3970void bdrv_iterate_format(void (*it)(void *opaque, const char *name),
3971 void *opaque)
40b4f539 3972{
61007b31
SH
3973 BlockDriver *drv;
3974 int count = 0;
3975 int i;
3976 const char **formats = NULL;
40b4f539 3977
61007b31
SH
3978 QLIST_FOREACH(drv, &bdrv_drivers, list) {
3979 if (drv->format_name) {
3980 bool found = false;
3981 int i = count;
3982 while (formats && i && !found) {
3983 found = !strcmp(formats[--i], drv->format_name);
3984 }
e2a305fb 3985
61007b31
SH
3986 if (!found) {
3987 formats = g_renew(const char *, formats, count + 1);
3988 formats[count++] = drv->format_name;
3989 }
6c5a42ac 3990 }
61007b31 3991 }
6c5a42ac 3992
eb0df69f
HR
3993 for (i = 0; i < (int)ARRAY_SIZE(block_driver_modules); i++) {
3994 const char *format_name = block_driver_modules[i].format_name;
3995
3996 if (format_name) {
3997 bool found = false;
3998 int j = count;
3999
4000 while (formats && j && !found) {
4001 found = !strcmp(formats[--j], format_name);
4002 }
4003
4004 if (!found) {
4005 formats = g_renew(const char *, formats, count + 1);
4006 formats[count++] = format_name;
4007 }
4008 }
4009 }
4010
61007b31 4011 qsort(formats, count, sizeof(formats[0]), qsort_strcmp);
40b4f539 4012
61007b31
SH
4013 for (i = 0; i < count; i++) {
4014 it(opaque, formats[i]);
4015 }
40b4f539 4016
61007b31
SH
4017 g_free(formats);
4018}
40b4f539 4019
61007b31
SH
4020/* This function is to find a node in the bs graph */
4021BlockDriverState *bdrv_find_node(const char *node_name)
4022{
4023 BlockDriverState *bs;
391827eb 4024
61007b31 4025 assert(node_name);
40b4f539 4026
61007b31
SH
4027 QTAILQ_FOREACH(bs, &graph_bdrv_states, node_list) {
4028 if (!strcmp(node_name, bs->node_name)) {
4029 return bs;
40b4f539
KW
4030 }
4031 }
61007b31 4032 return NULL;
40b4f539
KW
4033}
4034
61007b31
SH
4035/* Put this QMP function here so it can access the static graph_bdrv_states. */
4036BlockDeviceInfoList *bdrv_named_nodes_list(Error **errp)
40b4f539 4037{
61007b31
SH
4038 BlockDeviceInfoList *list, *entry;
4039 BlockDriverState *bs;
40b4f539 4040
61007b31
SH
4041 list = NULL;
4042 QTAILQ_FOREACH(bs, &graph_bdrv_states, node_list) {
c83f9fba 4043 BlockDeviceInfo *info = bdrv_block_device_info(NULL, bs, errp);
61007b31
SH
4044 if (!info) {
4045 qapi_free_BlockDeviceInfoList(list);
4046 return NULL;
301db7c2 4047 }
61007b31
SH
4048 entry = g_malloc0(sizeof(*entry));
4049 entry->value = info;
4050 entry->next = list;
4051 list = entry;
301db7c2
RH
4052 }
4053
61007b31
SH
4054 return list;
4055}
40b4f539 4056
61007b31
SH
4057BlockDriverState *bdrv_lookup_bs(const char *device,
4058 const char *node_name,
4059 Error **errp)
4060{
4061 BlockBackend *blk;
4062 BlockDriverState *bs;
40b4f539 4063
61007b31
SH
4064 if (device) {
4065 blk = blk_by_name(device);
40b4f539 4066
61007b31 4067 if (blk) {
9f4ed6fb
AG
4068 bs = blk_bs(blk);
4069 if (!bs) {
5433c24f 4070 error_setg(errp, "Device '%s' has no medium", device);
5433c24f
HR
4071 }
4072
9f4ed6fb 4073 return bs;
61007b31
SH
4074 }
4075 }
40b4f539 4076
61007b31
SH
4077 if (node_name) {
4078 bs = bdrv_find_node(node_name);
6d519a5f 4079
61007b31
SH
4080 if (bs) {
4081 return bs;
4082 }
40b4f539
KW
4083 }
4084
61007b31
SH
4085 error_setg(errp, "Cannot find device=%s nor node_name=%s",
4086 device ? device : "",
4087 node_name ? node_name : "");
4088 return NULL;
40b4f539
KW
4089}
4090
61007b31
SH
4091/* If 'base' is in the same chain as 'top', return true. Otherwise,
4092 * return false. If either argument is NULL, return false. */
4093bool bdrv_chain_contains(BlockDriverState *top, BlockDriverState *base)
83f64091 4094{
61007b31 4095 while (top && top != base) {
760e0063 4096 top = backing_bs(top);
02c50efe 4097 }
61007b31
SH
4098
4099 return top != NULL;
02c50efe
FZ
4100}
4101
61007b31 4102BlockDriverState *bdrv_next_node(BlockDriverState *bs)
02c50efe 4103{
61007b31
SH
4104 if (!bs) {
4105 return QTAILQ_FIRST(&graph_bdrv_states);
02c50efe 4106 }
61007b31 4107 return QTAILQ_NEXT(bs, node_list);
83f64091
FB
4108}
4109
0f12264e
KW
4110BlockDriverState *bdrv_next_all_states(BlockDriverState *bs)
4111{
4112 if (!bs) {
4113 return QTAILQ_FIRST(&all_bdrv_states);
4114 }
4115 return QTAILQ_NEXT(bs, bs_list);
4116}
4117
61007b31 4118const char *bdrv_get_node_name(const BlockDriverState *bs)
83f64091 4119{
61007b31 4120 return bs->node_name;
beac80cd
FB
4121}
4122
1f0c461b 4123const char *bdrv_get_parent_name(const BlockDriverState *bs)
4c265bf9
KW
4124{
4125 BdrvChild *c;
4126 const char *name;
4127
4128 /* If multiple parents have a name, just pick the first one. */
4129 QLIST_FOREACH(c, &bs->parents, next_parent) {
4130 if (c->role->get_name) {
4131 name = c->role->get_name(c);
4132 if (name && *name) {
4133 return name;
4134 }
4135 }
4136 }
4137
4138 return NULL;
4139}
4140
61007b31
SH
4141/* TODO check what callers really want: bs->node_name or blk_name() */
4142const char *bdrv_get_device_name(const BlockDriverState *bs)
beac80cd 4143{
4c265bf9 4144 return bdrv_get_parent_name(bs) ?: "";
f141eafe 4145}
83f64091 4146
61007b31
SH
4147/* This can be used to identify nodes that might not have a device
4148 * name associated. Since node and device names live in the same
4149 * namespace, the result is unambiguous. The exception is if both are
4150 * absent, then this returns an empty (non-null) string. */
4151const char *bdrv_get_device_or_node_name(const BlockDriverState *bs)
f141eafe 4152{
4c265bf9 4153 return bdrv_get_parent_name(bs) ?: bs->node_name;
beac80cd 4154}
beac80cd 4155
61007b31 4156int bdrv_get_flags(BlockDriverState *bs)
0b5a2445 4157{
61007b31 4158 return bs->open_flags;
0b5a2445
PB
4159}
4160
61007b31 4161int bdrv_has_zero_init_1(BlockDriverState *bs)
68485420 4162{
61007b31 4163 return 1;
0b5a2445
PB
4164}
4165
61007b31 4166int bdrv_has_zero_init(BlockDriverState *bs)
0b5a2445 4167{
d470ad42
HR
4168 if (!bs->drv) {
4169 return 0;
4170 }
0b5a2445 4171
61007b31
SH
4172 /* If BS is a copy on write image, it is initialized to
4173 the contents of the base image, which may not be zeroes. */
760e0063 4174 if (bs->backing) {
61007b31
SH
4175 return 0;
4176 }
4177 if (bs->drv->bdrv_has_zero_init) {
4178 return bs->drv->bdrv_has_zero_init(bs);
0b5a2445 4179 }
5a612c00
MP
4180 if (bs->file && bs->drv->is_filter) {
4181 return bdrv_has_zero_init(bs->file->bs);
4182 }
61007b31
SH
4183
4184 /* safe default */
4185 return 0;
68485420
KW
4186}
4187
61007b31 4188bool bdrv_unallocated_blocks_are_zero(BlockDriverState *bs)
b2a61371 4189{
61007b31 4190 BlockDriverInfo bdi;
b2a61371 4191
760e0063 4192 if (bs->backing) {
61007b31
SH
4193 return false;
4194 }
4195
4196 if (bdrv_get_info(bs, &bdi) == 0) {
4197 return bdi.unallocated_blocks_are_zero;
b2a61371
SH
4198 }
4199
61007b31 4200 return false;
b2a61371
SH
4201}
4202
61007b31 4203bool bdrv_can_write_zeroes_with_unmap(BlockDriverState *bs)
68485420 4204{
2f0342ef 4205 if (!(bs->open_flags & BDRV_O_UNMAP)) {
61007b31
SH
4206 return false;
4207 }
68485420 4208
e24d813b 4209 return bs->supported_zero_flags & BDRV_REQ_MAY_UNMAP;
68485420
KW
4210}
4211
61007b31 4212const char *bdrv_get_encrypted_filename(BlockDriverState *bs)
b2e12bc6 4213{
760e0063 4214 if (bs->backing && bs->backing->bs->encrypted)
61007b31
SH
4215 return bs->backing_file;
4216 else if (bs->encrypted)
4217 return bs->filename;
4218 else
4219 return NULL;
b2e12bc6
CH
4220}
4221
61007b31
SH
4222void bdrv_get_backing_filename(BlockDriverState *bs,
4223 char *filename, int filename_size)
016f5cf6 4224{
61007b31
SH
4225 pstrcpy(filename, filename_size, bs->backing_file);
4226}
d318aea9 4227
61007b31
SH
4228int bdrv_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
4229{
4230 BlockDriver *drv = bs->drv;
5a612c00
MP
4231 /* if bs->drv == NULL, bs is closed, so there's nothing to do here */
4232 if (!drv) {
61007b31 4233 return -ENOMEDIUM;
5a612c00
MP
4234 }
4235 if (!drv->bdrv_get_info) {
4236 if (bs->file && drv->is_filter) {
4237 return bdrv_get_info(bs->file->bs, bdi);
4238 }
61007b31 4239 return -ENOTSUP;
5a612c00 4240 }
61007b31
SH
4241 memset(bdi, 0, sizeof(*bdi));
4242 return drv->bdrv_get_info(bs, bdi);
4243}
016f5cf6 4244
61007b31
SH
4245ImageInfoSpecific *bdrv_get_specific_info(BlockDriverState *bs)
4246{
4247 BlockDriver *drv = bs->drv;
4248 if (drv && drv->bdrv_get_specific_info) {
4249 return drv->bdrv_get_specific_info(bs);
4250 }
4251 return NULL;
016f5cf6
AG
4252}
4253
a31939e6 4254void bdrv_debug_event(BlockDriverState *bs, BlkdebugEvent event)
4265d620 4255{
61007b31
SH
4256 if (!bs || !bs->drv || !bs->drv->bdrv_debug_event) {
4257 return;
4258 }
4265d620 4259
61007b31 4260 bs->drv->bdrv_debug_event(bs, event);
4265d620
PB
4261}
4262
61007b31
SH
4263int bdrv_debug_breakpoint(BlockDriverState *bs, const char *event,
4264 const char *tag)
4265d620 4265{
61007b31 4266 while (bs && bs->drv && !bs->drv->bdrv_debug_breakpoint) {
9a4f4c31 4267 bs = bs->file ? bs->file->bs : NULL;
61007b31 4268 }
4265d620 4269
61007b31
SH
4270 if (bs && bs->drv && bs->drv->bdrv_debug_breakpoint) {
4271 return bs->drv->bdrv_debug_breakpoint(bs, event, tag);
4272 }
4265d620 4273
61007b31 4274 return -ENOTSUP;
4265d620
PB
4275}
4276
61007b31 4277int bdrv_debug_remove_breakpoint(BlockDriverState *bs, const char *tag)
ea2384d3 4278{
61007b31 4279 while (bs && bs->drv && !bs->drv->bdrv_debug_remove_breakpoint) {
9a4f4c31 4280 bs = bs->file ? bs->file->bs : NULL;
61007b31 4281 }
ce1a14dc 4282
61007b31
SH
4283 if (bs && bs->drv && bs->drv->bdrv_debug_remove_breakpoint) {
4284 return bs->drv->bdrv_debug_remove_breakpoint(bs, tag);
4285 }
4286
4287 return -ENOTSUP;
eb852011
MA
4288}
4289
61007b31 4290int bdrv_debug_resume(BlockDriverState *bs, const char *tag)
ce1a14dc 4291{
61007b31 4292 while (bs && (!bs->drv || !bs->drv->bdrv_debug_resume)) {
9a4f4c31 4293 bs = bs->file ? bs->file->bs : NULL;
61007b31 4294 }
ce1a14dc 4295
61007b31
SH
4296 if (bs && bs->drv && bs->drv->bdrv_debug_resume) {
4297 return bs->drv->bdrv_debug_resume(bs, tag);
4298 }
ce1a14dc 4299
61007b31 4300 return -ENOTSUP;
f197fe2b
FZ
4301}
4302
61007b31 4303bool bdrv_debug_is_suspended(BlockDriverState *bs, const char *tag)
ce1a14dc 4304{
61007b31 4305 while (bs && bs->drv && !bs->drv->bdrv_debug_is_suspended) {
9a4f4c31 4306 bs = bs->file ? bs->file->bs : NULL;
f197fe2b 4307 }
19cb3738 4308
61007b31
SH
4309 if (bs && bs->drv && bs->drv->bdrv_debug_is_suspended) {
4310 return bs->drv->bdrv_debug_is_suspended(bs, tag);
4311 }
f9f05dc5 4312
61007b31
SH
4313 return false;
4314}
f9f05dc5 4315
61007b31
SH
4316/* backing_file can either be relative, or absolute, or a protocol. If it is
4317 * relative, it must be relative to the chain. So, passing in bs->filename
4318 * from a BDS as backing_file should not be done, as that may be relative to
4319 * the CWD rather than the chain. */
4320BlockDriverState *bdrv_find_backing_image(BlockDriverState *bs,
4321 const char *backing_file)
f9f05dc5 4322{
61007b31
SH
4323 char *filename_full = NULL;
4324 char *backing_file_full = NULL;
4325 char *filename_tmp = NULL;
4326 int is_protocol = 0;
4327 BlockDriverState *curr_bs = NULL;
4328 BlockDriverState *retval = NULL;
418661e0 4329 Error *local_error = NULL;
f9f05dc5 4330
61007b31
SH
4331 if (!bs || !bs->drv || !backing_file) {
4332 return NULL;
f9f05dc5
KW
4333 }
4334
61007b31
SH
4335 filename_full = g_malloc(PATH_MAX);
4336 backing_file_full = g_malloc(PATH_MAX);
4337 filename_tmp = g_malloc(PATH_MAX);
f9f05dc5 4338
61007b31 4339 is_protocol = path_has_protocol(backing_file);
f9f05dc5 4340
760e0063 4341 for (curr_bs = bs; curr_bs->backing; curr_bs = curr_bs->backing->bs) {
f9f05dc5 4342
61007b31
SH
4343 /* If either of the filename paths is actually a protocol, then
4344 * compare unmodified paths; otherwise make paths relative */
4345 if (is_protocol || path_has_protocol(curr_bs->backing_file)) {
4346 if (strcmp(backing_file, curr_bs->backing_file) == 0) {
760e0063 4347 retval = curr_bs->backing->bs;
61007b31
SH
4348 break;
4349 }
418661e0
JC
4350 /* Also check against the full backing filename for the image */
4351 bdrv_get_full_backing_filename(curr_bs, backing_file_full, PATH_MAX,
4352 &local_error);
4353 if (local_error == NULL) {
4354 if (strcmp(backing_file, backing_file_full) == 0) {
4355 retval = curr_bs->backing->bs;
4356 break;
4357 }
4358 } else {
4359 error_free(local_error);
4360 local_error = NULL;
4361 }
61007b31
SH
4362 } else {
4363 /* If not an absolute filename path, make it relative to the current
4364 * image's filename path */
4365 path_combine(filename_tmp, PATH_MAX, curr_bs->filename,
4366 backing_file);
f9f05dc5 4367
61007b31
SH
4368 /* We are going to compare absolute pathnames */
4369 if (!realpath(filename_tmp, filename_full)) {
4370 continue;
4371 }
07f07615 4372
61007b31
SH
4373 /* We need to make sure the backing filename we are comparing against
4374 * is relative to the current image filename (or absolute) */
4375 path_combine(filename_tmp, PATH_MAX, curr_bs->filename,
4376 curr_bs->backing_file);
07f07615 4377
61007b31
SH
4378 if (!realpath(filename_tmp, backing_file_full)) {
4379 continue;
4380 }
eb489bb1 4381
61007b31 4382 if (strcmp(backing_file_full, filename_full) == 0) {
760e0063 4383 retval = curr_bs->backing->bs;
61007b31
SH
4384 break;
4385 }
4386 }
eb489bb1
KW
4387 }
4388
61007b31
SH
4389 g_free(filename_full);
4390 g_free(backing_file_full);
4391 g_free(filename_tmp);
4392 return retval;
4393}
4394
61007b31
SH
4395void bdrv_init(void)
4396{
4397 module_call_init(MODULE_INIT_BLOCK);
4398}
29cdb251 4399
61007b31
SH
4400void bdrv_init_with_whitelist(void)
4401{
4402 use_bdrv_whitelist = 1;
4403 bdrv_init();
07f07615
PB
4404}
4405
2b148f39
PB
4406static void coroutine_fn bdrv_co_invalidate_cache(BlockDriverState *bs,
4407 Error **errp)
0f15423c 4408{
4417ab7a 4409 BdrvChild *child, *parent;
9c5e6594 4410 uint64_t perm, shared_perm;
5a8a30db
KW
4411 Error *local_err = NULL;
4412 int ret;
9c98f145 4413 BdrvDirtyBitmap *bm;
5a8a30db 4414
3456a8d1
KW
4415 if (!bs->drv) {
4416 return;
4417 }
4418
04c01a5c 4419 if (!(bs->open_flags & BDRV_O_INACTIVE)) {
7ea2d269
AK
4420 return;
4421 }
7ea2d269 4422
16e977d5 4423 QLIST_FOREACH(child, &bs->children, next) {
2b148f39 4424 bdrv_co_invalidate_cache(child->bs, &local_err);
0d1c5c91 4425 if (local_err) {
0d1c5c91
FZ
4426 error_propagate(errp, local_err);
4427 return;
4428 }
5a8a30db 4429 }
0d1c5c91 4430
dafe0960
KW
4431 /*
4432 * Update permissions, they may differ for inactive nodes.
4433 *
4434 * Note that the required permissions of inactive images are always a
4435 * subset of the permissions required after activating the image. This
4436 * allows us to just get the permissions upfront without restricting
4437 * drv->bdrv_invalidate_cache().
4438 *
4439 * It also means that in error cases, we don't have to try and revert to
4440 * the old permissions (which is an operation that could fail, too). We can
4441 * just keep the extended permissions for the next time that an activation
4442 * of the image is tried.
4443 */
16e977d5 4444 bs->open_flags &= ~BDRV_O_INACTIVE;
dafe0960
KW
4445 bdrv_get_cumulative_perm(bs, &perm, &shared_perm);
4446 ret = bdrv_check_perm(bs, NULL, perm, shared_perm, NULL, &local_err);
4447 if (ret < 0) {
4448 bs->open_flags |= BDRV_O_INACTIVE;
4449 error_propagate(errp, local_err);
4450 return;
4451 }
4452 bdrv_set_perm(bs, perm, shared_perm);
4453
2b148f39
PB
4454 if (bs->drv->bdrv_co_invalidate_cache) {
4455 bs->drv->bdrv_co_invalidate_cache(bs, &local_err);
0d1c5c91
FZ
4456 if (local_err) {
4457 bs->open_flags |= BDRV_O_INACTIVE;
4458 error_propagate(errp, local_err);
4459 return;
4460 }
0f15423c 4461 }
3456a8d1 4462
9c98f145
VSO
4463 for (bm = bdrv_dirty_bitmap_next(bs, NULL); bm;
4464 bm = bdrv_dirty_bitmap_next(bs, bm))
4465 {
4466 bdrv_dirty_bitmap_set_migration(bm, false);
4467 }
4468
5a8a30db
KW
4469 ret = refresh_total_sectors(bs, bs->total_sectors);
4470 if (ret < 0) {
04c01a5c 4471 bs->open_flags |= BDRV_O_INACTIVE;
5a8a30db
KW
4472 error_setg_errno(errp, -ret, "Could not refresh total sector count");
4473 return;
4474 }
4417ab7a
KW
4475
4476 QLIST_FOREACH(parent, &bs->parents, next_parent) {
4477 if (parent->role->activate) {
4478 parent->role->activate(parent, &local_err);
4479 if (local_err) {
4480 error_propagate(errp, local_err);
4481 return;
4482 }
4483 }
4484 }
0f15423c
AL
4485}
4486
2b148f39
PB
4487typedef struct InvalidateCacheCo {
4488 BlockDriverState *bs;
4489 Error **errp;
4490 bool done;
4491} InvalidateCacheCo;
4492
4493static void coroutine_fn bdrv_invalidate_cache_co_entry(void *opaque)
4494{
4495 InvalidateCacheCo *ico = opaque;
4496 bdrv_co_invalidate_cache(ico->bs, ico->errp);
4497 ico->done = true;
4498}
4499
4500void bdrv_invalidate_cache(BlockDriverState *bs, Error **errp)
4501{
4502 Coroutine *co;
4503 InvalidateCacheCo ico = {
4504 .bs = bs,
4505 .done = false,
4506 .errp = errp
4507 };
4508
4509 if (qemu_in_coroutine()) {
4510 /* Fast-path if already in coroutine context */
4511 bdrv_invalidate_cache_co_entry(&ico);
4512 } else {
4513 co = qemu_coroutine_create(bdrv_invalidate_cache_co_entry, &ico);
4514 qemu_coroutine_enter(co);
4515 BDRV_POLL_WHILE(bs, !ico.done);
4516 }
4517}
4518
5a8a30db 4519void bdrv_invalidate_cache_all(Error **errp)
0f15423c 4520{
7c8eece4 4521 BlockDriverState *bs;
5a8a30db 4522 Error *local_err = NULL;
88be7b4b 4523 BdrvNextIterator it;
0f15423c 4524
88be7b4b 4525 for (bs = bdrv_first(&it); bs; bs = bdrv_next(&it)) {
ed78cda3
SH
4526 AioContext *aio_context = bdrv_get_aio_context(bs);
4527
4528 aio_context_acquire(aio_context);
5a8a30db 4529 bdrv_invalidate_cache(bs, &local_err);
ed78cda3 4530 aio_context_release(aio_context);
5a8a30db
KW
4531 if (local_err) {
4532 error_propagate(errp, local_err);
5e003f17 4533 bdrv_next_cleanup(&it);
5a8a30db
KW
4534 return;
4535 }
0f15423c
AL
4536 }
4537}
4538
aad0b7a0
FZ
4539static int bdrv_inactivate_recurse(BlockDriverState *bs,
4540 bool setting_flag)
76b1c7fe 4541{
cfa1a572 4542 BdrvChild *child, *parent;
76b1c7fe
KW
4543 int ret;
4544
d470ad42
HR
4545 if (!bs->drv) {
4546 return -ENOMEDIUM;
4547 }
4548
aad0b7a0 4549 if (!setting_flag && bs->drv->bdrv_inactivate) {
76b1c7fe
KW
4550 ret = bs->drv->bdrv_inactivate(bs);
4551 if (ret < 0) {
4552 return ret;
4553 }
4554 }
4555
7d5b5261 4556 if (setting_flag && !(bs->open_flags & BDRV_O_INACTIVE)) {
9c5e6594
KW
4557 uint64_t perm, shared_perm;
4558
cfa1a572
KW
4559 QLIST_FOREACH(parent, &bs->parents, next_parent) {
4560 if (parent->role->inactivate) {
4561 ret = parent->role->inactivate(parent);
4562 if (ret < 0) {
cfa1a572
KW
4563 return ret;
4564 }
4565 }
4566 }
9c5e6594 4567
7d5b5261
SH
4568 bs->open_flags |= BDRV_O_INACTIVE;
4569
9c5e6594
KW
4570 /* Update permissions, they may differ for inactive nodes */
4571 bdrv_get_cumulative_perm(bs, &perm, &shared_perm);
3121fb45 4572 bdrv_check_perm(bs, NULL, perm, shared_perm, NULL, &error_abort);
9c5e6594 4573 bdrv_set_perm(bs, perm, shared_perm);
aad0b7a0 4574 }
38701b6a
KW
4575
4576 QLIST_FOREACH(child, &bs->children, next) {
4577 ret = bdrv_inactivate_recurse(child->bs, setting_flag);
4578 if (ret < 0) {
4579 return ret;
4580 }
4581 }
4582
76b1c7fe
KW
4583 return 0;
4584}
4585
4586int bdrv_inactivate_all(void)
4587{
79720af6 4588 BlockDriverState *bs = NULL;
88be7b4b 4589 BdrvNextIterator it;
aad0b7a0
FZ
4590 int ret = 0;
4591 int pass;
bd6458e4 4592 GSList *aio_ctxs = NULL, *ctx;
76b1c7fe 4593
88be7b4b 4594 for (bs = bdrv_first(&it); bs; bs = bdrv_next(&it)) {
bd6458e4
PB
4595 AioContext *aio_context = bdrv_get_aio_context(bs);
4596
4597 if (!g_slist_find(aio_ctxs, aio_context)) {
4598 aio_ctxs = g_slist_prepend(aio_ctxs, aio_context);
4599 aio_context_acquire(aio_context);
4600 }
aad0b7a0 4601 }
76b1c7fe 4602
aad0b7a0
FZ
4603 /* We do two passes of inactivation. The first pass calls to drivers'
4604 * .bdrv_inactivate callbacks recursively so all cache is flushed to disk;
4605 * the second pass sets the BDRV_O_INACTIVE flag so that no further write
4606 * is allowed. */
4607 for (pass = 0; pass < 2; pass++) {
88be7b4b 4608 for (bs = bdrv_first(&it); bs; bs = bdrv_next(&it)) {
aad0b7a0
FZ
4609 ret = bdrv_inactivate_recurse(bs, pass);
4610 if (ret < 0) {
5e003f17 4611 bdrv_next_cleanup(&it);
aad0b7a0
FZ
4612 goto out;
4613 }
76b1c7fe
KW
4614 }
4615 }
4616
aad0b7a0 4617out:
bd6458e4
PB
4618 for (ctx = aio_ctxs; ctx != NULL; ctx = ctx->next) {
4619 AioContext *aio_context = ctx->data;
4620 aio_context_release(aio_context);
aad0b7a0 4621 }
bd6458e4 4622 g_slist_free(aio_ctxs);
aad0b7a0
FZ
4623
4624 return ret;
76b1c7fe
KW
4625}
4626
19cb3738
FB
4627/**************************************************************/
4628/* removable device support */
4629
4630/**
4631 * Return TRUE if the media is present
4632 */
e031f750 4633bool bdrv_is_inserted(BlockDriverState *bs)
19cb3738
FB
4634{
4635 BlockDriver *drv = bs->drv;
28d7a789 4636 BdrvChild *child;
a1aff5bf 4637
e031f750
HR
4638 if (!drv) {
4639 return false;
4640 }
28d7a789
HR
4641 if (drv->bdrv_is_inserted) {
4642 return drv->bdrv_is_inserted(bs);
4643 }
4644 QLIST_FOREACH(child, &bs->children, next) {
4645 if (!bdrv_is_inserted(child->bs)) {
4646 return false;
4647 }
e031f750 4648 }
28d7a789 4649 return true;
19cb3738
FB
4650}
4651
19cb3738
FB
4652/**
4653 * If eject_flag is TRUE, eject the media. Otherwise, close the tray
4654 */
f36f3949 4655void bdrv_eject(BlockDriverState *bs, bool eject_flag)
19cb3738
FB
4656{
4657 BlockDriver *drv = bs->drv;
19cb3738 4658
822e1cd1
MA
4659 if (drv && drv->bdrv_eject) {
4660 drv->bdrv_eject(bs, eject_flag);
19cb3738
FB
4661 }
4662}
4663
19cb3738
FB
4664/**
4665 * Lock or unlock the media (if it is locked, the user won't be able
4666 * to eject it manually).
4667 */
025e849a 4668void bdrv_lock_medium(BlockDriverState *bs, bool locked)
19cb3738
FB
4669{
4670 BlockDriver *drv = bs->drv;
4671
025e849a 4672 trace_bdrv_lock_medium(bs, locked);
b8c6d095 4673
025e849a
MA
4674 if (drv && drv->bdrv_lock_medium) {
4675 drv->bdrv_lock_medium(bs, locked);
19cb3738
FB
4676 }
4677}
985a03b0 4678
9fcb0251
FZ
4679/* Get a reference to bs */
4680void bdrv_ref(BlockDriverState *bs)
4681{
4682 bs->refcnt++;
4683}
4684
4685/* Release a previously grabbed reference to bs.
4686 * If after releasing, reference count is zero, the BlockDriverState is
4687 * deleted. */
4688void bdrv_unref(BlockDriverState *bs)
4689{
9a4d5ca6
JC
4690 if (!bs) {
4691 return;
4692 }
9fcb0251
FZ
4693 assert(bs->refcnt > 0);
4694 if (--bs->refcnt == 0) {
4695 bdrv_delete(bs);
4696 }
4697}
4698
fbe40ff7
FZ
4699struct BdrvOpBlocker {
4700 Error *reason;
4701 QLIST_ENTRY(BdrvOpBlocker) list;
4702};
4703
4704bool bdrv_op_is_blocked(BlockDriverState *bs, BlockOpType op, Error **errp)
4705{
4706 BdrvOpBlocker *blocker;
4707 assert((int) op >= 0 && op < BLOCK_OP_TYPE_MAX);
4708 if (!QLIST_EMPTY(&bs->op_blockers[op])) {
4709 blocker = QLIST_FIRST(&bs->op_blockers[op]);
4b576648
MA
4710 error_propagate_prepend(errp, error_copy(blocker->reason),
4711 "Node '%s' is busy: ",
4712 bdrv_get_device_or_node_name(bs));
fbe40ff7
FZ
4713 return true;
4714 }
4715 return false;
4716}
4717
4718void bdrv_op_block(BlockDriverState *bs, BlockOpType op, Error *reason)
4719{
4720 BdrvOpBlocker *blocker;
4721 assert((int) op >= 0 && op < BLOCK_OP_TYPE_MAX);
4722
5839e53b 4723 blocker = g_new0(BdrvOpBlocker, 1);
fbe40ff7
FZ
4724 blocker->reason = reason;
4725 QLIST_INSERT_HEAD(&bs->op_blockers[op], blocker, list);
4726}
4727
4728void bdrv_op_unblock(BlockDriverState *bs, BlockOpType op, Error *reason)
4729{
4730 BdrvOpBlocker *blocker, *next;
4731 assert((int) op >= 0 && op < BLOCK_OP_TYPE_MAX);
4732 QLIST_FOREACH_SAFE(blocker, &bs->op_blockers[op], list, next) {
4733 if (blocker->reason == reason) {
4734 QLIST_REMOVE(blocker, list);
4735 g_free(blocker);
4736 }
4737 }
4738}
4739
4740void bdrv_op_block_all(BlockDriverState *bs, Error *reason)
4741{
4742 int i;
4743 for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
4744 bdrv_op_block(bs, i, reason);
4745 }
4746}
4747
4748void bdrv_op_unblock_all(BlockDriverState *bs, Error *reason)
4749{
4750 int i;
4751 for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
4752 bdrv_op_unblock(bs, i, reason);
4753 }
4754}
4755
4756bool bdrv_op_blocker_is_empty(BlockDriverState *bs)
4757{
4758 int i;
4759
4760 for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
4761 if (!QLIST_EMPTY(&bs->op_blockers[i])) {
4762 return false;
4763 }
4764 }
4765 return true;
4766}
4767
d92ada22
LC
4768void bdrv_img_create(const char *filename, const char *fmt,
4769 const char *base_filename, const char *base_fmt,
9217283d
FZ
4770 char *options, uint64_t img_size, int flags, bool quiet,
4771 Error **errp)
f88e1a42 4772{
83d0521a
CL
4773 QemuOptsList *create_opts = NULL;
4774 QemuOpts *opts = NULL;
4775 const char *backing_fmt, *backing_file;
4776 int64_t size;
f88e1a42 4777 BlockDriver *drv, *proto_drv;
cc84d90f 4778 Error *local_err = NULL;
f88e1a42
JS
4779 int ret = 0;
4780
4781 /* Find driver and parse its options */
4782 drv = bdrv_find_format(fmt);
4783 if (!drv) {
71c79813 4784 error_setg(errp, "Unknown file format '%s'", fmt);
d92ada22 4785 return;
f88e1a42
JS
4786 }
4787
b65a5e12 4788 proto_drv = bdrv_find_protocol(filename, true, errp);
f88e1a42 4789 if (!proto_drv) {
d92ada22 4790 return;
f88e1a42
JS
4791 }
4792
c6149724
HR
4793 if (!drv->create_opts) {
4794 error_setg(errp, "Format driver '%s' does not support image creation",
4795 drv->format_name);
4796 return;
4797 }
4798
4799 if (!proto_drv->create_opts) {
4800 error_setg(errp, "Protocol driver '%s' does not support image creation",
4801 proto_drv->format_name);
4802 return;
4803 }
4804
c282e1fd
CL
4805 create_opts = qemu_opts_append(create_opts, drv->create_opts);
4806 create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
f88e1a42
JS
4807
4808 /* Create parameter list with default values */
83d0521a 4809 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
39101f25 4810 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, img_size, &error_abort);
f88e1a42
JS
4811
4812 /* Parse -o options */
4813 if (options) {
dc523cd3
MA
4814 qemu_opts_do_parse(opts, options, NULL, &local_err);
4815 if (local_err) {
f88e1a42
JS
4816 goto out;
4817 }
4818 }
4819
4820 if (base_filename) {
f43e47db 4821 qemu_opt_set(opts, BLOCK_OPT_BACKING_FILE, base_filename, &local_err);
6be4194b 4822 if (local_err) {
71c79813
LC
4823 error_setg(errp, "Backing file not supported for file format '%s'",
4824 fmt);
f88e1a42
JS
4825 goto out;
4826 }
4827 }
4828
4829 if (base_fmt) {
f43e47db 4830 qemu_opt_set(opts, BLOCK_OPT_BACKING_FMT, base_fmt, &local_err);
6be4194b 4831 if (local_err) {
71c79813
LC
4832 error_setg(errp, "Backing file format not supported for file "
4833 "format '%s'", fmt);
f88e1a42
JS
4834 goto out;
4835 }
4836 }
4837
83d0521a
CL
4838 backing_file = qemu_opt_get(opts, BLOCK_OPT_BACKING_FILE);
4839 if (backing_file) {
4840 if (!strcmp(filename, backing_file)) {
71c79813
LC
4841 error_setg(errp, "Error: Trying to create an image with the "
4842 "same filename as the backing file");
792da93a
JS
4843 goto out;
4844 }
4845 }
4846
83d0521a 4847 backing_fmt = qemu_opt_get(opts, BLOCK_OPT_BACKING_FMT);
f88e1a42 4848
6e6e55f5
JS
4849 /* The size for the image must always be specified, unless we have a backing
4850 * file and we have not been forbidden from opening it. */
a8b42a1c 4851 size = qemu_opt_get_size(opts, BLOCK_OPT_SIZE, img_size);
6e6e55f5
JS
4852 if (backing_file && !(flags & BDRV_O_NO_BACKING)) {
4853 BlockDriverState *bs;
4854 char *full_backing = g_new0(char, PATH_MAX);
4855 int back_flags;
4856 QDict *backing_options = NULL;
4857
4858 bdrv_get_full_backing_filename_from_filename(filename, backing_file,
4859 full_backing, PATH_MAX,
4860 &local_err);
4861 if (local_err) {
4862 g_free(full_backing);
4863 goto out;
4864 }
29168018 4865
6e6e55f5
JS
4866 /* backing files always opened read-only */
4867 back_flags = flags;
4868 back_flags &= ~(BDRV_O_RDWR | BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING);
f88e1a42 4869
cc954f01 4870 backing_options = qdict_new();
6e6e55f5 4871 if (backing_fmt) {
6e6e55f5
JS
4872 qdict_put_str(backing_options, "driver", backing_fmt);
4873 }
cc954f01 4874 qdict_put_bool(backing_options, BDRV_OPT_FORCE_SHARE, true);
e6641719 4875
6e6e55f5
JS
4876 bs = bdrv_open(full_backing, NULL, backing_options, back_flags,
4877 &local_err);
4878 g_free(full_backing);
4879 if (!bs && size != -1) {
4880 /* Couldn't open BS, but we have a size, so it's nonfatal */
4881 warn_reportf_err(local_err,
4882 "Could not verify backing image. "
4883 "This may become an error in future versions.\n");
4884 local_err = NULL;
4885 } else if (!bs) {
4886 /* Couldn't open bs, do not have size */
4887 error_append_hint(&local_err,
4888 "Could not open backing image to determine size.\n");
4889 goto out;
4890 } else {
4891 if (size == -1) {
4892 /* Opened BS, have no size */
4893 size = bdrv_getlength(bs);
4894 if (size < 0) {
4895 error_setg_errno(errp, -size, "Could not get size of '%s'",
4896 backing_file);
4897 bdrv_unref(bs);
4898 goto out;
4899 }
4900 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, size, &error_abort);
52bf1e72 4901 }
66f6b814 4902 bdrv_unref(bs);
f88e1a42 4903 }
6e6e55f5
JS
4904 } /* (backing_file && !(flags & BDRV_O_NO_BACKING)) */
4905
4906 if (size == -1) {
4907 error_setg(errp, "Image creation needs a size parameter");
4908 goto out;
f88e1a42
JS
4909 }
4910
f382d43a 4911 if (!quiet) {
fe646693 4912 printf("Formatting '%s', fmt=%s ", filename, fmt);
43c5d8f8 4913 qemu_opts_print(opts, " ");
f382d43a
MR
4914 puts("");
4915 }
83d0521a 4916
c282e1fd 4917 ret = bdrv_create(drv, filename, opts, &local_err);
83d0521a 4918
cc84d90f
HR
4919 if (ret == -EFBIG) {
4920 /* This is generally a better message than whatever the driver would
4921 * deliver (especially because of the cluster_size_hint), since that
4922 * is most probably not much different from "image too large". */
4923 const char *cluster_size_hint = "";
83d0521a 4924 if (qemu_opt_get_size(opts, BLOCK_OPT_CLUSTER_SIZE, 0)) {
cc84d90f 4925 cluster_size_hint = " (try using a larger cluster size)";
f88e1a42 4926 }
cc84d90f
HR
4927 error_setg(errp, "The image size is too large for file format '%s'"
4928 "%s", fmt, cluster_size_hint);
4929 error_free(local_err);
4930 local_err = NULL;
f88e1a42
JS
4931 }
4932
4933out:
83d0521a
CL
4934 qemu_opts_del(opts);
4935 qemu_opts_free(create_opts);
621ff94d 4936 error_propagate(errp, local_err);
f88e1a42 4937}
85d126f3
SH
4938
4939AioContext *bdrv_get_aio_context(BlockDriverState *bs)
4940{
33f2a757 4941 return bs ? bs->aio_context : qemu_get_aio_context();
dcd04228
SH
4942}
4943
052a7572
FZ
4944void bdrv_coroutine_enter(BlockDriverState *bs, Coroutine *co)
4945{
4946 aio_co_enter(bdrv_get_aio_context(bs), co);
4947}
4948
e8a095da
SH
4949static void bdrv_do_remove_aio_context_notifier(BdrvAioNotifier *ban)
4950{
4951 QLIST_REMOVE(ban, list);
4952 g_free(ban);
4953}
4954
dcd04228
SH
4955void bdrv_detach_aio_context(BlockDriverState *bs)
4956{
e8a095da 4957 BdrvAioNotifier *baf, *baf_tmp;
b97511c7 4958 BdrvChild *child;
33384421 4959
dcd04228
SH
4960 if (!bs->drv) {
4961 return;
4962 }
4963
e8a095da
SH
4964 assert(!bs->walking_aio_notifiers);
4965 bs->walking_aio_notifiers = true;
4966 QLIST_FOREACH_SAFE(baf, &bs->aio_notifiers, list, baf_tmp) {
4967 if (baf->deleted) {
4968 bdrv_do_remove_aio_context_notifier(baf);
4969 } else {
4970 baf->detach_aio_context(baf->opaque);
4971 }
33384421 4972 }
e8a095da
SH
4973 /* Never mind iterating again to check for ->deleted. bdrv_close() will
4974 * remove remaining aio notifiers if we aren't called again.
4975 */
4976 bs->walking_aio_notifiers = false;
33384421 4977
dcd04228
SH
4978 if (bs->drv->bdrv_detach_aio_context) {
4979 bs->drv->bdrv_detach_aio_context(bs);
4980 }
b97511c7
HR
4981 QLIST_FOREACH(child, &bs->children, next) {
4982 bdrv_detach_aio_context(child->bs);
dcd04228
SH
4983 }
4984
4985 bs->aio_context = NULL;
4986}
4987
4988void bdrv_attach_aio_context(BlockDriverState *bs,
4989 AioContext *new_context)
4990{
e8a095da 4991 BdrvAioNotifier *ban, *ban_tmp;
b97511c7 4992 BdrvChild *child;
33384421 4993
dcd04228
SH
4994 if (!bs->drv) {
4995 return;
4996 }
4997
4998 bs->aio_context = new_context;
4999
b97511c7
HR
5000 QLIST_FOREACH(child, &bs->children, next) {
5001 bdrv_attach_aio_context(child->bs, new_context);
dcd04228
SH
5002 }
5003 if (bs->drv->bdrv_attach_aio_context) {
5004 bs->drv->bdrv_attach_aio_context(bs, new_context);
5005 }
33384421 5006
e8a095da
SH
5007 assert(!bs->walking_aio_notifiers);
5008 bs->walking_aio_notifiers = true;
5009 QLIST_FOREACH_SAFE(ban, &bs->aio_notifiers, list, ban_tmp) {
5010 if (ban->deleted) {
5011 bdrv_do_remove_aio_context_notifier(ban);
5012 } else {
5013 ban->attached_aio_context(new_context, ban->opaque);
5014 }
33384421 5015 }
e8a095da 5016 bs->walking_aio_notifiers = false;
dcd04228
SH
5017}
5018
5019void bdrv_set_aio_context(BlockDriverState *bs, AioContext *new_context)
5020{
aabf5910 5021 AioContext *ctx = bdrv_get_aio_context(bs);
c2b6428d 5022
aabf5910 5023 aio_disable_external(ctx);
6cd5c9d7 5024 bdrv_parent_drained_begin(bs, NULL, false);
53ec73e2 5025 bdrv_drain(bs); /* ensure there are no in-flight requests */
dcd04228 5026
c2b6428d
PB
5027 while (aio_poll(ctx, false)) {
5028 /* wait for all bottom halves to execute */
5029 }
5030
dcd04228
SH
5031 bdrv_detach_aio_context(bs);
5032
5033 /* This function executes in the old AioContext so acquire the new one in
5034 * case it runs in a different thread.
5035 */
5036 aio_context_acquire(new_context);
5037 bdrv_attach_aio_context(bs, new_context);
6cd5c9d7 5038 bdrv_parent_drained_end(bs, NULL, false);
aabf5910 5039 aio_enable_external(ctx);
dcd04228 5040 aio_context_release(new_context);
85d126f3 5041}
d616b224 5042
33384421
HR
5043void bdrv_add_aio_context_notifier(BlockDriverState *bs,
5044 void (*attached_aio_context)(AioContext *new_context, void *opaque),
5045 void (*detach_aio_context)(void *opaque), void *opaque)
5046{
5047 BdrvAioNotifier *ban = g_new(BdrvAioNotifier, 1);
5048 *ban = (BdrvAioNotifier){
5049 .attached_aio_context = attached_aio_context,
5050 .detach_aio_context = detach_aio_context,
5051 .opaque = opaque
5052 };
5053
5054 QLIST_INSERT_HEAD(&bs->aio_notifiers, ban, list);
5055}
5056
5057void bdrv_remove_aio_context_notifier(BlockDriverState *bs,
5058 void (*attached_aio_context)(AioContext *,
5059 void *),
5060 void (*detach_aio_context)(void *),
5061 void *opaque)
5062{
5063 BdrvAioNotifier *ban, *ban_next;
5064
5065 QLIST_FOREACH_SAFE(ban, &bs->aio_notifiers, list, ban_next) {
5066 if (ban->attached_aio_context == attached_aio_context &&
5067 ban->detach_aio_context == detach_aio_context &&
e8a095da
SH
5068 ban->opaque == opaque &&
5069 ban->deleted == false)
33384421 5070 {
e8a095da
SH
5071 if (bs->walking_aio_notifiers) {
5072 ban->deleted = true;
5073 } else {
5074 bdrv_do_remove_aio_context_notifier(ban);
5075 }
33384421
HR
5076 return;
5077 }
5078 }
5079
5080 abort();
5081}
5082
77485434 5083int bdrv_amend_options(BlockDriverState *bs, QemuOpts *opts,
d1402b50
HR
5084 BlockDriverAmendStatusCB *status_cb, void *cb_opaque,
5085 Error **errp)
6f176b48 5086{
d470ad42 5087 if (!bs->drv) {
d1402b50 5088 error_setg(errp, "Node is ejected");
d470ad42
HR
5089 return -ENOMEDIUM;
5090 }
c282e1fd 5091 if (!bs->drv->bdrv_amend_options) {
d1402b50
HR
5092 error_setg(errp, "Block driver '%s' does not support option amendment",
5093 bs->drv->format_name);
6f176b48
HR
5094 return -ENOTSUP;
5095 }
d1402b50 5096 return bs->drv->bdrv_amend_options(bs, opts, status_cb, cb_opaque, errp);
6f176b48 5097}
f6186f49 5098
b5042a36
BC
5099/* This function will be called by the bdrv_recurse_is_first_non_filter method
5100 * of block filter and by bdrv_is_first_non_filter.
5101 * It is used to test if the given bs is the candidate or recurse more in the
5102 * node graph.
212a5a8f 5103 */
b5042a36 5104bool bdrv_recurse_is_first_non_filter(BlockDriverState *bs,
212a5a8f 5105 BlockDriverState *candidate)
f6186f49 5106{
b5042a36
BC
5107 /* return false if basic checks fails */
5108 if (!bs || !bs->drv) {
212a5a8f 5109 return false;
f6186f49
BC
5110 }
5111
b5042a36
BC
5112 /* the code reached a non block filter driver -> check if the bs is
5113 * the same as the candidate. It's the recursion termination condition.
5114 */
5115 if (!bs->drv->is_filter) {
5116 return bs == candidate;
212a5a8f 5117 }
b5042a36 5118 /* Down this path the driver is a block filter driver */
212a5a8f 5119
b5042a36
BC
5120 /* If the block filter recursion method is defined use it to recurse down
5121 * the node graph.
5122 */
5123 if (bs->drv->bdrv_recurse_is_first_non_filter) {
212a5a8f 5124 return bs->drv->bdrv_recurse_is_first_non_filter(bs, candidate);
f6186f49
BC
5125 }
5126
b5042a36
BC
5127 /* the driver is a block filter but don't allow to recurse -> return false
5128 */
5129 return false;
f6186f49
BC
5130}
5131
212a5a8f
BC
5132/* This function checks if the candidate is the first non filter bs down it's
5133 * bs chain. Since we don't have pointers to parents it explore all bs chains
5134 * from the top. Some filters can choose not to pass down the recursion.
5135 */
5136bool bdrv_is_first_non_filter(BlockDriverState *candidate)
f6186f49 5137{
7c8eece4 5138 BlockDriverState *bs;
88be7b4b 5139 BdrvNextIterator it;
212a5a8f
BC
5140
5141 /* walk down the bs forest recursively */
88be7b4b 5142 for (bs = bdrv_first(&it); bs; bs = bdrv_next(&it)) {
212a5a8f
BC
5143 bool perm;
5144
b5042a36 5145 /* try to recurse in this top level bs */
e6dc8a1f 5146 perm = bdrv_recurse_is_first_non_filter(bs, candidate);
212a5a8f
BC
5147
5148 /* candidate is the first non filter */
5149 if (perm) {
5e003f17 5150 bdrv_next_cleanup(&it);
212a5a8f
BC
5151 return true;
5152 }
5153 }
5154
5155 return false;
f6186f49 5156}
09158f00 5157
e12f3784
WC
5158BlockDriverState *check_to_replace_node(BlockDriverState *parent_bs,
5159 const char *node_name, Error **errp)
09158f00
BC
5160{
5161 BlockDriverState *to_replace_bs = bdrv_find_node(node_name);
5a7e7a0b
SH
5162 AioContext *aio_context;
5163
09158f00
BC
5164 if (!to_replace_bs) {
5165 error_setg(errp, "Node name '%s' not found", node_name);
5166 return NULL;
5167 }
5168
5a7e7a0b
SH
5169 aio_context = bdrv_get_aio_context(to_replace_bs);
5170 aio_context_acquire(aio_context);
5171
09158f00 5172 if (bdrv_op_is_blocked(to_replace_bs, BLOCK_OP_TYPE_REPLACE, errp)) {
5a7e7a0b
SH
5173 to_replace_bs = NULL;
5174 goto out;
09158f00
BC
5175 }
5176
5177 /* We don't want arbitrary node of the BDS chain to be replaced only the top
5178 * most non filter in order to prevent data corruption.
5179 * Another benefit is that this tests exclude backing files which are
5180 * blocked by the backing blockers.
5181 */
e12f3784 5182 if (!bdrv_recurse_is_first_non_filter(parent_bs, to_replace_bs)) {
09158f00 5183 error_setg(errp, "Only top most non filter can be replaced");
5a7e7a0b
SH
5184 to_replace_bs = NULL;
5185 goto out;
09158f00
BC
5186 }
5187
5a7e7a0b
SH
5188out:
5189 aio_context_release(aio_context);
09158f00
BC
5190 return to_replace_bs;
5191}
448ad91d 5192
91af7014
HR
5193static bool append_open_options(QDict *d, BlockDriverState *bs)
5194{
5195 const QDictEntry *entry;
9e700c1a 5196 QemuOptDesc *desc;
91af7014
HR
5197 bool found_any = false;
5198
5199 for (entry = qdict_first(bs->options); entry;
5200 entry = qdict_next(bs->options, entry))
5201 {
a600aadd 5202 /* Exclude all non-driver-specific options */
9e700c1a
KW
5203 for (desc = bdrv_runtime_opts.desc; desc->name; desc++) {
5204 if (!strcmp(qdict_entry_key(entry), desc->name)) {
5205 break;
5206 }
5207 }
5208 if (desc->name) {
5209 continue;
5210 }
5211
f5a74a5a
MAL
5212 qdict_put_obj(d, qdict_entry_key(entry),
5213 qobject_ref(qdict_entry_value(entry)));
9e700c1a 5214 found_any = true;
91af7014
HR
5215 }
5216
5217 return found_any;
5218}
5219
5220/* Updates the following BDS fields:
5221 * - exact_filename: A filename which may be used for opening a block device
5222 * which (mostly) equals the given BDS (even without any
5223 * other options; so reading and writing must return the same
5224 * results, but caching etc. may be different)
5225 * - full_open_options: Options which, when given when opening a block device
5226 * (without a filename), result in a BDS (mostly)
5227 * equalling the given one
5228 * - filename: If exact_filename is set, it is copied here. Otherwise,
5229 * full_open_options is converted to a JSON object, prefixed with
5230 * "json:" (for use through the JSON pseudo protocol) and put here.
5231 */
5232void bdrv_refresh_filename(BlockDriverState *bs)
5233{
5234 BlockDriver *drv = bs->drv;
5235 QDict *opts;
5236
5237 if (!drv) {
5238 return;
5239 }
5240
5241 /* This BDS's file name will most probably depend on its file's name, so
5242 * refresh that first */
5243 if (bs->file) {
9a4f4c31 5244 bdrv_refresh_filename(bs->file->bs);
91af7014
HR
5245 }
5246
5247 if (drv->bdrv_refresh_filename) {
5248 /* Obsolete information is of no use here, so drop the old file name
5249 * information before refreshing it */
5250 bs->exact_filename[0] = '\0';
5251 if (bs->full_open_options) {
cb3e7f08 5252 qobject_unref(bs->full_open_options);
91af7014
HR
5253 bs->full_open_options = NULL;
5254 }
5255
4cdd01d3
KW
5256 opts = qdict_new();
5257 append_open_options(opts, bs);
5258 drv->bdrv_refresh_filename(bs, opts);
cb3e7f08 5259 qobject_unref(opts);
91af7014
HR
5260 } else if (bs->file) {
5261 /* Try to reconstruct valid information from the underlying file */
5262 bool has_open_options;
5263
5264 bs->exact_filename[0] = '\0';
5265 if (bs->full_open_options) {
cb3e7f08 5266 qobject_unref(bs->full_open_options);
91af7014
HR
5267 bs->full_open_options = NULL;
5268 }
5269
5270 opts = qdict_new();
5271 has_open_options = append_open_options(opts, bs);
5272
5273 /* If no specific options have been given for this BDS, the filename of
5274 * the underlying file should suffice for this one as well */
9a4f4c31
KW
5275 if (bs->file->bs->exact_filename[0] && !has_open_options) {
5276 strcpy(bs->exact_filename, bs->file->bs->exact_filename);
91af7014
HR
5277 }
5278 /* Reconstructing the full options QDict is simple for most format block
5279 * drivers, as long as the full options are known for the underlying
5280 * file BDS. The full options QDict of that file BDS should somehow
5281 * contain a representation of the filename, therefore the following
5282 * suffices without querying the (exact_)filename of this BDS. */
9a4f4c31 5283 if (bs->file->bs->full_open_options) {
46f5ac20 5284 qdict_put_str(opts, "driver", drv->format_name);
f5a74a5a
MAL
5285 qdict_put(opts, "file",
5286 qobject_ref(bs->file->bs->full_open_options));
91af7014
HR
5287
5288 bs->full_open_options = opts;
5289 } else {
cb3e7f08 5290 qobject_unref(opts);
91af7014
HR
5291 }
5292 } else if (!bs->full_open_options && qdict_size(bs->options)) {
5293 /* There is no underlying file BDS (at least referenced by BDS.file),
5294 * so the full options QDict should be equal to the options given
5295 * specifically for this block device when it was opened (plus the
5296 * driver specification).
5297 * Because those options don't change, there is no need to update
5298 * full_open_options when it's already set. */
5299
5300 opts = qdict_new();
5301 append_open_options(opts, bs);
46f5ac20 5302 qdict_put_str(opts, "driver", drv->format_name);
91af7014
HR
5303
5304 if (bs->exact_filename[0]) {
5305 /* This may not work for all block protocol drivers (some may
5306 * require this filename to be parsed), but we have to find some
5307 * default solution here, so just include it. If some block driver
5308 * does not support pure options without any filename at all or
5309 * needs some special format of the options QDict, it needs to
5310 * implement the driver-specific bdrv_refresh_filename() function.
5311 */
46f5ac20 5312 qdict_put_str(opts, "filename", bs->exact_filename);
91af7014
HR
5313 }
5314
5315 bs->full_open_options = opts;
5316 }
5317
5318 if (bs->exact_filename[0]) {
5319 pstrcpy(bs->filename, sizeof(bs->filename), bs->exact_filename);
5320 } else if (bs->full_open_options) {
5321 QString *json = qobject_to_json(QOBJECT(bs->full_open_options));
5322 snprintf(bs->filename, sizeof(bs->filename), "json:%s",
5323 qstring_get_str(json));
cb3e7f08 5324 qobject_unref(json);
91af7014
HR
5325 }
5326}
e06018ad
WC
5327
5328/*
5329 * Hot add/remove a BDS's child. So the user can take a child offline when
5330 * it is broken and take a new child online
5331 */
5332void bdrv_add_child(BlockDriverState *parent_bs, BlockDriverState *child_bs,
5333 Error **errp)
5334{
5335
5336 if (!parent_bs->drv || !parent_bs->drv->bdrv_add_child) {
5337 error_setg(errp, "The node %s does not support adding a child",
5338 bdrv_get_device_or_node_name(parent_bs));
5339 return;
5340 }
5341
5342 if (!QLIST_EMPTY(&child_bs->parents)) {
5343 error_setg(errp, "The node %s already has a parent",
5344 child_bs->node_name);
5345 return;
5346 }
5347
5348 parent_bs->drv->bdrv_add_child(parent_bs, child_bs, errp);
5349}
5350
5351void bdrv_del_child(BlockDriverState *parent_bs, BdrvChild *child, Error **errp)
5352{
5353 BdrvChild *tmp;
5354
5355 if (!parent_bs->drv || !parent_bs->drv->bdrv_del_child) {
5356 error_setg(errp, "The node %s does not support removing a child",
5357 bdrv_get_device_or_node_name(parent_bs));
5358 return;
5359 }
5360
5361 QLIST_FOREACH(tmp, &parent_bs->children, next) {
5362 if (tmp == child) {
5363 break;
5364 }
5365 }
5366
5367 if (!tmp) {
5368 error_setg(errp, "The node %s does not have a child named %s",
5369 bdrv_get_device_or_node_name(parent_bs),
5370 bdrv_get_device_or_node_name(child->bs));
5371 return;
5372 }
5373
5374 parent_bs->drv->bdrv_del_child(parent_bs, child, errp);
5375}
67b792f5
VSO
5376
5377bool bdrv_can_store_new_dirty_bitmap(BlockDriverState *bs, const char *name,
5378 uint32_t granularity, Error **errp)
5379{
5380 BlockDriver *drv = bs->drv;
5381
5382 if (!drv) {
5383 error_setg_errno(errp, ENOMEDIUM,
5384 "Can't store persistent bitmaps to %s",
5385 bdrv_get_device_or_node_name(bs));
5386 return false;
5387 }
5388
5389 if (!drv->bdrv_can_store_new_dirty_bitmap) {
5390 error_setg_errno(errp, ENOTSUP,
5391 "Can't store persistent bitmaps to %s",
5392 bdrv_get_device_or_node_name(bs));
5393 return false;
5394 }
5395
5396 return drv->bdrv_can_store_new_dirty_bitmap(bs, name, granularity, errp);
5397}