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