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