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