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