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