]> git.ipfire.org Git - thirdparty/qemu.git/blob - block.c
block: bdrv_get_full_backing_filename's ret. val.
[thirdparty/qemu.git] / block.c
1 /*
2 * QEMU System Emulator block driver
3 *
4 * Copyright (c) 2003 Fabrice Bellard
5 *
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 */
24
25 #include "qemu/osdep.h"
26 #include "block/trace.h"
27 #include "block/block_int.h"
28 #include "block/blockjob.h"
29 #include "block/nbd.h"
30 #include "block/qdict.h"
31 #include "qemu/error-report.h"
32 #include "module_block.h"
33 #include "qemu/module.h"
34 #include "qapi/error.h"
35 #include "qapi/qmp/qdict.h"
36 #include "qapi/qmp/qjson.h"
37 #include "qapi/qmp/qnull.h"
38 #include "qapi/qmp/qstring.h"
39 #include "qapi/qobject-output-visitor.h"
40 #include "qapi/qapi-visit-block-core.h"
41 #include "sysemu/block-backend.h"
42 #include "sysemu/sysemu.h"
43 #include "qemu/notify.h"
44 #include "qemu/option.h"
45 #include "qemu/coroutine.h"
46 #include "block/qapi.h"
47 #include "qemu/timer.h"
48 #include "qemu/cutils.h"
49 #include "qemu/id.h"
50
51 #ifdef CONFIG_BSD
52 #include <sys/ioctl.h>
53 #include <sys/queue.h>
54 #ifndef __DragonFly__
55 #include <sys/disk.h>
56 #endif
57 #endif
58
59 #ifdef _WIN32
60 #include <windows.h>
61 #endif
62
63 #define NOT_DONE 0x7fffffff /* used while emulated sync operation in progress */
64
65 static QTAILQ_HEAD(, BlockDriverState) graph_bdrv_states =
66 QTAILQ_HEAD_INITIALIZER(graph_bdrv_states);
67
68 static QTAILQ_HEAD(, BlockDriverState) all_bdrv_states =
69 QTAILQ_HEAD_INITIALIZER(all_bdrv_states);
70
71 static QLIST_HEAD(, BlockDriver) bdrv_drivers =
72 QLIST_HEAD_INITIALIZER(bdrv_drivers);
73
74 static BlockDriverState *bdrv_open_inherit(const char *filename,
75 const char *reference,
76 QDict *options, int flags,
77 BlockDriverState *parent,
78 const BdrvChildRole *child_role,
79 Error **errp);
80
81 /* If non-zero, use only whitelisted block drivers */
82 static int use_bdrv_whitelist;
83
84 #ifdef _WIN32
85 static int is_windows_drive_prefix(const char *filename)
86 {
87 return (((filename[0] >= 'a' && filename[0] <= 'z') ||
88 (filename[0] >= 'A' && filename[0] <= 'Z')) &&
89 filename[1] == ':');
90 }
91
92 int is_windows_drive(const char *filename)
93 {
94 if (is_windows_drive_prefix(filename) &&
95 filename[2] == '\0')
96 return 1;
97 if (strstart(filename, "\\\\.\\", NULL) ||
98 strstart(filename, "//./", NULL))
99 return 1;
100 return 0;
101 }
102 #endif
103
104 size_t bdrv_opt_mem_align(BlockDriverState *bs)
105 {
106 if (!bs || !bs->drv) {
107 /* page size or 4k (hdd sector size) should be on the safe side */
108 return MAX(4096, getpagesize());
109 }
110
111 return bs->bl.opt_mem_alignment;
112 }
113
114 size_t bdrv_min_mem_align(BlockDriverState *bs)
115 {
116 if (!bs || !bs->drv) {
117 /* page size or 4k (hdd sector size) should be on the safe side */
118 return MAX(4096, getpagesize());
119 }
120
121 return bs->bl.min_mem_alignment;
122 }
123
124 /* check if the path starts with "<protocol>:" */
125 int path_has_protocol(const char *path)
126 {
127 const char *p;
128
129 #ifdef _WIN32
130 if (is_windows_drive(path) ||
131 is_windows_drive_prefix(path)) {
132 return 0;
133 }
134 p = path + strcspn(path, ":/\\");
135 #else
136 p = path + strcspn(path, ":/");
137 #endif
138
139 return *p == ':';
140 }
141
142 int path_is_absolute(const char *path)
143 {
144 #ifdef _WIN32
145 /* specific case for names like: "\\.\d:" */
146 if (is_windows_drive(path) || is_windows_drive_prefix(path)) {
147 return 1;
148 }
149 return (*path == '/' || *path == '\\');
150 #else
151 return (*path == '/');
152 #endif
153 }
154
155 /* if filename is absolute, just return its duplicate. Otherwise, build a
156 path to it by considering it is relative to base_path. URL are
157 supported. */
158 char *path_combine(const char *base_path, const char *filename)
159 {
160 const char *protocol_stripped = NULL;
161 const char *p, *p1;
162 char *result;
163 int len;
164
165 if (path_is_absolute(filename)) {
166 return g_strdup(filename);
167 }
168
169 if (path_has_protocol(base_path)) {
170 protocol_stripped = strchr(base_path, ':');
171 if (protocol_stripped) {
172 protocol_stripped++;
173 }
174 }
175 p = protocol_stripped ?: base_path;
176
177 p1 = strrchr(base_path, '/');
178 #ifdef _WIN32
179 {
180 const char *p2;
181 p2 = strrchr(base_path, '\\');
182 if (!p1 || p2 > p1) {
183 p1 = p2;
184 }
185 }
186 #endif
187 if (p1) {
188 p1++;
189 } else {
190 p1 = base_path;
191 }
192 if (p1 > p) {
193 p = p1;
194 }
195 len = p - base_path;
196
197 result = g_malloc(len + strlen(filename) + 1);
198 memcpy(result, base_path, len);
199 strcpy(result + len, filename);
200
201 return result;
202 }
203
204 static void path_combine_deprecated(char *dest, int dest_size,
205 const char *base_path,
206 const char *filename)
207 {
208 char *combined = path_combine(base_path, filename);
209 pstrcpy(dest, dest_size, combined);
210 g_free(combined);
211 }
212
213 /*
214 * Helper function for bdrv_parse_filename() implementations to remove optional
215 * protocol prefixes (especially "file:") from a filename and for putting the
216 * stripped filename into the options QDict if there is such a prefix.
217 */
218 void bdrv_parse_filename_strip_prefix(const char *filename, const char *prefix,
219 QDict *options)
220 {
221 if (strstart(filename, prefix, &filename)) {
222 /* Stripping the explicit protocol prefix may result in a protocol
223 * prefix being (wrongly) detected (if the filename contains a colon) */
224 if (path_has_protocol(filename)) {
225 QString *fat_filename;
226
227 /* This means there is some colon before the first slash; therefore,
228 * this cannot be an absolute path */
229 assert(!path_is_absolute(filename));
230
231 /* And we can thus fix the protocol detection issue by prefixing it
232 * by "./" */
233 fat_filename = qstring_from_str("./");
234 qstring_append(fat_filename, filename);
235
236 assert(!path_has_protocol(qstring_get_str(fat_filename)));
237
238 qdict_put(options, "filename", fat_filename);
239 } else {
240 /* If no protocol prefix was detected, we can use the shortened
241 * filename as-is */
242 qdict_put_str(options, "filename", filename);
243 }
244 }
245 }
246
247
248 /* Returns whether the image file is opened as read-only. Note that this can
249 * return false and writing to the image file is still not possible because the
250 * image is inactivated. */
251 bool bdrv_is_read_only(BlockDriverState *bs)
252 {
253 return bs->read_only;
254 }
255
256 int bdrv_can_set_read_only(BlockDriverState *bs, bool read_only,
257 bool ignore_allow_rdw, Error **errp)
258 {
259 /* Do not set read_only if copy_on_read is enabled */
260 if (bs->copy_on_read && read_only) {
261 error_setg(errp, "Can't set node '%s' to r/o with copy-on-read enabled",
262 bdrv_get_device_or_node_name(bs));
263 return -EINVAL;
264 }
265
266 /* Do not clear read_only if it is prohibited */
267 if (!read_only && !(bs->open_flags & BDRV_O_ALLOW_RDWR) &&
268 !ignore_allow_rdw)
269 {
270 error_setg(errp, "Node '%s' is read only",
271 bdrv_get_device_or_node_name(bs));
272 return -EPERM;
273 }
274
275 return 0;
276 }
277
278 /*
279 * Called by a driver that can only provide a read-only image.
280 *
281 * Returns 0 if the node is already read-only or it could switch the node to
282 * read-only because BDRV_O_AUTO_RDONLY is set.
283 *
284 * Returns -EACCES if the node is read-write and BDRV_O_AUTO_RDONLY is not set
285 * or bdrv_can_set_read_only() forbids making the node read-only. If @errmsg
286 * is not NULL, it is used as the error message for the Error object.
287 */
288 int bdrv_apply_auto_read_only(BlockDriverState *bs, const char *errmsg,
289 Error **errp)
290 {
291 int ret = 0;
292
293 if (!(bs->open_flags & BDRV_O_RDWR)) {
294 return 0;
295 }
296 if (!(bs->open_flags & BDRV_O_AUTO_RDONLY)) {
297 goto fail;
298 }
299
300 ret = bdrv_can_set_read_only(bs, true, false, NULL);
301 if (ret < 0) {
302 goto fail;
303 }
304
305 bs->read_only = true;
306 bs->open_flags &= ~BDRV_O_RDWR;
307
308 return 0;
309
310 fail:
311 error_setg(errp, "%s", errmsg ?: "Image is read-only");
312 return -EACCES;
313 }
314
315 /*
316 * If @backing is empty, this function returns NULL without setting
317 * @errp. In all other cases, NULL will only be returned with @errp
318 * set.
319 *
320 * Therefore, a return value of NULL without @errp set means that
321 * there is no backing file; if @errp is set, there is one but its
322 * absolute filename cannot be generated.
323 */
324 char *bdrv_get_full_backing_filename_from_filename(const char *backed,
325 const char *backing,
326 Error **errp)
327 {
328 if (backing[0] == '\0') {
329 return NULL;
330 } else if (path_has_protocol(backing) || path_is_absolute(backing)) {
331 return g_strdup(backing);
332 } else if (backed[0] == '\0' || strstart(backed, "json:", NULL)) {
333 error_setg(errp, "Cannot use relative backing file names for '%s'",
334 backed);
335 return NULL;
336 } else {
337 return path_combine(backed, backing);
338 }
339 }
340
341 char *bdrv_get_full_backing_filename(BlockDriverState *bs, Error **errp)
342 {
343 char *backed;
344
345 bdrv_refresh_filename(bs);
346
347 backed = bs->exact_filename[0] ? bs->exact_filename : bs->filename;
348 return bdrv_get_full_backing_filename_from_filename(backed,
349 bs->backing_file,
350 errp);
351 }
352
353 void bdrv_register(BlockDriver *bdrv)
354 {
355 QLIST_INSERT_HEAD(&bdrv_drivers, bdrv, list);
356 }
357
358 BlockDriverState *bdrv_new(void)
359 {
360 BlockDriverState *bs;
361 int i;
362
363 bs = g_new0(BlockDriverState, 1);
364 QLIST_INIT(&bs->dirty_bitmaps);
365 for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
366 QLIST_INIT(&bs->op_blockers[i]);
367 }
368 notifier_with_return_list_init(&bs->before_write_notifiers);
369 qemu_co_mutex_init(&bs->reqs_lock);
370 qemu_mutex_init(&bs->dirty_bitmap_mutex);
371 bs->refcnt = 1;
372 bs->aio_context = qemu_get_aio_context();
373
374 qemu_co_queue_init(&bs->flush_queue);
375
376 for (i = 0; i < bdrv_drain_all_count; i++) {
377 bdrv_drained_begin(bs);
378 }
379
380 QTAILQ_INSERT_TAIL(&all_bdrv_states, bs, bs_list);
381
382 return bs;
383 }
384
385 static BlockDriver *bdrv_do_find_format(const char *format_name)
386 {
387 BlockDriver *drv1;
388
389 QLIST_FOREACH(drv1, &bdrv_drivers, list) {
390 if (!strcmp(drv1->format_name, format_name)) {
391 return drv1;
392 }
393 }
394
395 return NULL;
396 }
397
398 BlockDriver *bdrv_find_format(const char *format_name)
399 {
400 BlockDriver *drv1;
401 int i;
402
403 drv1 = bdrv_do_find_format(format_name);
404 if (drv1) {
405 return drv1;
406 }
407
408 /* The driver isn't registered, maybe we need to load a module */
409 for (i = 0; i < (int)ARRAY_SIZE(block_driver_modules); ++i) {
410 if (!strcmp(block_driver_modules[i].format_name, format_name)) {
411 block_module_load_one(block_driver_modules[i].library_name);
412 break;
413 }
414 }
415
416 return bdrv_do_find_format(format_name);
417 }
418
419 int bdrv_is_whitelisted(BlockDriver *drv, bool read_only)
420 {
421 static const char *whitelist_rw[] = {
422 CONFIG_BDRV_RW_WHITELIST
423 };
424 static const char *whitelist_ro[] = {
425 CONFIG_BDRV_RO_WHITELIST
426 };
427 const char **p;
428
429 if (!whitelist_rw[0] && !whitelist_ro[0]) {
430 return 1; /* no whitelist, anything goes */
431 }
432
433 for (p = whitelist_rw; *p; p++) {
434 if (!strcmp(drv->format_name, *p)) {
435 return 1;
436 }
437 }
438 if (read_only) {
439 for (p = whitelist_ro; *p; p++) {
440 if (!strcmp(drv->format_name, *p)) {
441 return 1;
442 }
443 }
444 }
445 return 0;
446 }
447
448 bool bdrv_uses_whitelist(void)
449 {
450 return use_bdrv_whitelist;
451 }
452
453 typedef struct CreateCo {
454 BlockDriver *drv;
455 char *filename;
456 QemuOpts *opts;
457 int ret;
458 Error *err;
459 } CreateCo;
460
461 static void coroutine_fn bdrv_create_co_entry(void *opaque)
462 {
463 Error *local_err = NULL;
464 int ret;
465
466 CreateCo *cco = opaque;
467 assert(cco->drv);
468
469 ret = cco->drv->bdrv_co_create_opts(cco->filename, cco->opts, &local_err);
470 error_propagate(&cco->err, local_err);
471 cco->ret = ret;
472 }
473
474 int bdrv_create(BlockDriver *drv, const char* filename,
475 QemuOpts *opts, Error **errp)
476 {
477 int ret;
478
479 Coroutine *co;
480 CreateCo cco = {
481 .drv = drv,
482 .filename = g_strdup(filename),
483 .opts = opts,
484 .ret = NOT_DONE,
485 .err = NULL,
486 };
487
488 if (!drv->bdrv_co_create_opts) {
489 error_setg(errp, "Driver '%s' does not support image creation", drv->format_name);
490 ret = -ENOTSUP;
491 goto out;
492 }
493
494 if (qemu_in_coroutine()) {
495 /* Fast-path if already in coroutine context */
496 bdrv_create_co_entry(&cco);
497 } else {
498 co = qemu_coroutine_create(bdrv_create_co_entry, &cco);
499 qemu_coroutine_enter(co);
500 while (cco.ret == NOT_DONE) {
501 aio_poll(qemu_get_aio_context(), true);
502 }
503 }
504
505 ret = cco.ret;
506 if (ret < 0) {
507 if (cco.err) {
508 error_propagate(errp, cco.err);
509 } else {
510 error_setg_errno(errp, -ret, "Could not create image");
511 }
512 }
513
514 out:
515 g_free(cco.filename);
516 return ret;
517 }
518
519 int bdrv_create_file(const char *filename, QemuOpts *opts, Error **errp)
520 {
521 BlockDriver *drv;
522 Error *local_err = NULL;
523 int ret;
524
525 drv = bdrv_find_protocol(filename, true, errp);
526 if (drv == NULL) {
527 return -ENOENT;
528 }
529
530 ret = bdrv_create(drv, filename, opts, &local_err);
531 error_propagate(errp, local_err);
532 return ret;
533 }
534
535 /**
536 * Try to get @bs's logical and physical block size.
537 * On success, store them in @bsz struct and return 0.
538 * On failure return -errno.
539 * @bs must not be empty.
540 */
541 int bdrv_probe_blocksizes(BlockDriverState *bs, BlockSizes *bsz)
542 {
543 BlockDriver *drv = bs->drv;
544
545 if (drv && drv->bdrv_probe_blocksizes) {
546 return drv->bdrv_probe_blocksizes(bs, bsz);
547 } else if (drv && drv->is_filter && bs->file) {
548 return bdrv_probe_blocksizes(bs->file->bs, bsz);
549 }
550
551 return -ENOTSUP;
552 }
553
554 /**
555 * Try to get @bs's geometry (cyls, heads, sectors).
556 * On success, store them in @geo struct and return 0.
557 * On failure return -errno.
558 * @bs must not be empty.
559 */
560 int bdrv_probe_geometry(BlockDriverState *bs, HDGeometry *geo)
561 {
562 BlockDriver *drv = bs->drv;
563
564 if (drv && drv->bdrv_probe_geometry) {
565 return drv->bdrv_probe_geometry(bs, geo);
566 } else if (drv && drv->is_filter && bs->file) {
567 return bdrv_probe_geometry(bs->file->bs, geo);
568 }
569
570 return -ENOTSUP;
571 }
572
573 /*
574 * Create a uniquely-named empty temporary file.
575 * Return 0 upon success, otherwise a negative errno value.
576 */
577 int get_tmp_filename(char *filename, int size)
578 {
579 #ifdef _WIN32
580 char temp_dir[MAX_PATH];
581 /* GetTempFileName requires that its output buffer (4th param)
582 have length MAX_PATH or greater. */
583 assert(size >= MAX_PATH);
584 return (GetTempPath(MAX_PATH, temp_dir)
585 && GetTempFileName(temp_dir, "qem", 0, filename)
586 ? 0 : -GetLastError());
587 #else
588 int fd;
589 const char *tmpdir;
590 tmpdir = getenv("TMPDIR");
591 if (!tmpdir) {
592 tmpdir = "/var/tmp";
593 }
594 if (snprintf(filename, size, "%s/vl.XXXXXX", tmpdir) >= size) {
595 return -EOVERFLOW;
596 }
597 fd = mkstemp(filename);
598 if (fd < 0) {
599 return -errno;
600 }
601 if (close(fd) != 0) {
602 unlink(filename);
603 return -errno;
604 }
605 return 0;
606 #endif
607 }
608
609 /*
610 * Detect host devices. By convention, /dev/cdrom[N] is always
611 * recognized as a host CDROM.
612 */
613 static BlockDriver *find_hdev_driver(const char *filename)
614 {
615 int score_max = 0, score;
616 BlockDriver *drv = NULL, *d;
617
618 QLIST_FOREACH(d, &bdrv_drivers, list) {
619 if (d->bdrv_probe_device) {
620 score = d->bdrv_probe_device(filename);
621 if (score > score_max) {
622 score_max = score;
623 drv = d;
624 }
625 }
626 }
627
628 return drv;
629 }
630
631 static BlockDriver *bdrv_do_find_protocol(const char *protocol)
632 {
633 BlockDriver *drv1;
634
635 QLIST_FOREACH(drv1, &bdrv_drivers, list) {
636 if (drv1->protocol_name && !strcmp(drv1->protocol_name, protocol)) {
637 return drv1;
638 }
639 }
640
641 return NULL;
642 }
643
644 BlockDriver *bdrv_find_protocol(const char *filename,
645 bool allow_protocol_prefix,
646 Error **errp)
647 {
648 BlockDriver *drv1;
649 char protocol[128];
650 int len;
651 const char *p;
652 int i;
653
654 /* TODO Drivers without bdrv_file_open must be specified explicitly */
655
656 /*
657 * XXX(hch): we really should not let host device detection
658 * override an explicit protocol specification, but moving this
659 * later breaks access to device names with colons in them.
660 * Thanks to the brain-dead persistent naming schemes on udev-
661 * based Linux systems those actually are quite common.
662 */
663 drv1 = find_hdev_driver(filename);
664 if (drv1) {
665 return drv1;
666 }
667
668 if (!path_has_protocol(filename) || !allow_protocol_prefix) {
669 return &bdrv_file;
670 }
671
672 p = strchr(filename, ':');
673 assert(p != NULL);
674 len = p - filename;
675 if (len > sizeof(protocol) - 1)
676 len = sizeof(protocol) - 1;
677 memcpy(protocol, filename, len);
678 protocol[len] = '\0';
679
680 drv1 = bdrv_do_find_protocol(protocol);
681 if (drv1) {
682 return drv1;
683 }
684
685 for (i = 0; i < (int)ARRAY_SIZE(block_driver_modules); ++i) {
686 if (block_driver_modules[i].protocol_name &&
687 !strcmp(block_driver_modules[i].protocol_name, protocol)) {
688 block_module_load_one(block_driver_modules[i].library_name);
689 break;
690 }
691 }
692
693 drv1 = bdrv_do_find_protocol(protocol);
694 if (!drv1) {
695 error_setg(errp, "Unknown protocol '%s'", protocol);
696 }
697 return drv1;
698 }
699
700 /*
701 * Guess image format by probing its contents.
702 * This is not a good idea when your image is raw (CVE-2008-2004), but
703 * we do it anyway for backward compatibility.
704 *
705 * @buf contains the image's first @buf_size bytes.
706 * @buf_size is the buffer size in bytes (generally BLOCK_PROBE_BUF_SIZE,
707 * but can be smaller if the image file is smaller)
708 * @filename is its filename.
709 *
710 * For all block drivers, call the bdrv_probe() method to get its
711 * probing score.
712 * Return the first block driver with the highest probing score.
713 */
714 BlockDriver *bdrv_probe_all(const uint8_t *buf, int buf_size,
715 const char *filename)
716 {
717 int score_max = 0, score;
718 BlockDriver *drv = NULL, *d;
719
720 QLIST_FOREACH(d, &bdrv_drivers, list) {
721 if (d->bdrv_probe) {
722 score = d->bdrv_probe(buf, buf_size, filename);
723 if (score > score_max) {
724 score_max = score;
725 drv = d;
726 }
727 }
728 }
729
730 return drv;
731 }
732
733 static int find_image_format(BlockBackend *file, const char *filename,
734 BlockDriver **pdrv, Error **errp)
735 {
736 BlockDriver *drv;
737 uint8_t buf[BLOCK_PROBE_BUF_SIZE];
738 int ret = 0;
739
740 /* Return the raw BlockDriver * to scsi-generic devices or empty drives */
741 if (blk_is_sg(file) || !blk_is_inserted(file) || blk_getlength(file) == 0) {
742 *pdrv = &bdrv_raw;
743 return ret;
744 }
745
746 ret = blk_pread(file, 0, buf, sizeof(buf));
747 if (ret < 0) {
748 error_setg_errno(errp, -ret, "Could not read image for determining its "
749 "format");
750 *pdrv = NULL;
751 return ret;
752 }
753
754 drv = bdrv_probe_all(buf, ret, filename);
755 if (!drv) {
756 error_setg(errp, "Could not determine image format: No compatible "
757 "driver found");
758 ret = -ENOENT;
759 }
760 *pdrv = drv;
761 return ret;
762 }
763
764 /**
765 * Set the current 'total_sectors' value
766 * Return 0 on success, -errno on error.
767 */
768 int refresh_total_sectors(BlockDriverState *bs, int64_t hint)
769 {
770 BlockDriver *drv = bs->drv;
771
772 if (!drv) {
773 return -ENOMEDIUM;
774 }
775
776 /* Do not attempt drv->bdrv_getlength() on scsi-generic devices */
777 if (bdrv_is_sg(bs))
778 return 0;
779
780 /* query actual device if possible, otherwise just trust the hint */
781 if (drv->bdrv_getlength) {
782 int64_t length = drv->bdrv_getlength(bs);
783 if (length < 0) {
784 return length;
785 }
786 hint = DIV_ROUND_UP(length, BDRV_SECTOR_SIZE);
787 }
788
789 bs->total_sectors = hint;
790 return 0;
791 }
792
793 /**
794 * Combines a QDict of new block driver @options with any missing options taken
795 * from @old_options, so that leaving out an option defaults to its old value.
796 */
797 static void bdrv_join_options(BlockDriverState *bs, QDict *options,
798 QDict *old_options)
799 {
800 if (bs->drv && bs->drv->bdrv_join_options) {
801 bs->drv->bdrv_join_options(options, old_options);
802 } else {
803 qdict_join(options, old_options, false);
804 }
805 }
806
807 static BlockdevDetectZeroesOptions bdrv_parse_detect_zeroes(QemuOpts *opts,
808 int open_flags,
809 Error **errp)
810 {
811 Error *local_err = NULL;
812 char *value = qemu_opt_get_del(opts, "detect-zeroes");
813 BlockdevDetectZeroesOptions detect_zeroes =
814 qapi_enum_parse(&BlockdevDetectZeroesOptions_lookup, value,
815 BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF, &local_err);
816 g_free(value);
817 if (local_err) {
818 error_propagate(errp, local_err);
819 return detect_zeroes;
820 }
821
822 if (detect_zeroes == BLOCKDEV_DETECT_ZEROES_OPTIONS_UNMAP &&
823 !(open_flags & BDRV_O_UNMAP))
824 {
825 error_setg(errp, "setting detect-zeroes to unmap is not allowed "
826 "without setting discard operation to unmap");
827 }
828
829 return detect_zeroes;
830 }
831
832 /**
833 * Set open flags for a given discard mode
834 *
835 * Return 0 on success, -1 if the discard mode was invalid.
836 */
837 int bdrv_parse_discard_flags(const char *mode, int *flags)
838 {
839 *flags &= ~BDRV_O_UNMAP;
840
841 if (!strcmp(mode, "off") || !strcmp(mode, "ignore")) {
842 /* do nothing */
843 } else if (!strcmp(mode, "on") || !strcmp(mode, "unmap")) {
844 *flags |= BDRV_O_UNMAP;
845 } else {
846 return -1;
847 }
848
849 return 0;
850 }
851
852 /**
853 * Set open flags for a given cache mode
854 *
855 * Return 0 on success, -1 if the cache mode was invalid.
856 */
857 int bdrv_parse_cache_mode(const char *mode, int *flags, bool *writethrough)
858 {
859 *flags &= ~BDRV_O_CACHE_MASK;
860
861 if (!strcmp(mode, "off") || !strcmp(mode, "none")) {
862 *writethrough = false;
863 *flags |= BDRV_O_NOCACHE;
864 } else if (!strcmp(mode, "directsync")) {
865 *writethrough = true;
866 *flags |= BDRV_O_NOCACHE;
867 } else if (!strcmp(mode, "writeback")) {
868 *writethrough = false;
869 } else if (!strcmp(mode, "unsafe")) {
870 *writethrough = false;
871 *flags |= BDRV_O_NO_FLUSH;
872 } else if (!strcmp(mode, "writethrough")) {
873 *writethrough = true;
874 } else {
875 return -1;
876 }
877
878 return 0;
879 }
880
881 static char *bdrv_child_get_parent_desc(BdrvChild *c)
882 {
883 BlockDriverState *parent = c->opaque;
884 return g_strdup(bdrv_get_device_or_node_name(parent));
885 }
886
887 static void bdrv_child_cb_drained_begin(BdrvChild *child)
888 {
889 BlockDriverState *bs = child->opaque;
890 bdrv_do_drained_begin_quiesce(bs, NULL, false);
891 }
892
893 static bool bdrv_child_cb_drained_poll(BdrvChild *child)
894 {
895 BlockDriverState *bs = child->opaque;
896 return bdrv_drain_poll(bs, false, NULL, false);
897 }
898
899 static void bdrv_child_cb_drained_end(BdrvChild *child)
900 {
901 BlockDriverState *bs = child->opaque;
902 bdrv_drained_end(bs);
903 }
904
905 static void bdrv_child_cb_attach(BdrvChild *child)
906 {
907 BlockDriverState *bs = child->opaque;
908 bdrv_apply_subtree_drain(child, bs);
909 }
910
911 static void bdrv_child_cb_detach(BdrvChild *child)
912 {
913 BlockDriverState *bs = child->opaque;
914 bdrv_unapply_subtree_drain(child, bs);
915 }
916
917 static int bdrv_child_cb_inactivate(BdrvChild *child)
918 {
919 BlockDriverState *bs = child->opaque;
920 assert(bs->open_flags & BDRV_O_INACTIVE);
921 return 0;
922 }
923
924 /*
925 * Returns the options and flags that a temporary snapshot should get, based on
926 * the originally requested flags (the originally requested image will have
927 * flags like a backing file)
928 */
929 static void bdrv_temp_snapshot_options(int *child_flags, QDict *child_options,
930 int parent_flags, QDict *parent_options)
931 {
932 *child_flags = (parent_flags & ~BDRV_O_SNAPSHOT) | BDRV_O_TEMPORARY;
933
934 /* For temporary files, unconditional cache=unsafe is fine */
935 qdict_set_default_str(child_options, BDRV_OPT_CACHE_DIRECT, "off");
936 qdict_set_default_str(child_options, BDRV_OPT_CACHE_NO_FLUSH, "on");
937
938 /* Copy the read-only option from the parent */
939 qdict_copy_default(child_options, parent_options, BDRV_OPT_READ_ONLY);
940
941 /* aio=native doesn't work for cache.direct=off, so disable it for the
942 * temporary snapshot */
943 *child_flags &= ~BDRV_O_NATIVE_AIO;
944 }
945
946 /*
947 * Returns the options and flags that bs->file should get if a protocol driver
948 * is expected, based on the given options and flags for the parent BDS
949 */
950 static void bdrv_inherited_options(int *child_flags, QDict *child_options,
951 int parent_flags, QDict *parent_options)
952 {
953 int flags = parent_flags;
954
955 /* Enable protocol handling, disable format probing for bs->file */
956 flags |= BDRV_O_PROTOCOL;
957
958 /* If the cache mode isn't explicitly set, inherit direct and no-flush from
959 * the parent. */
960 qdict_copy_default(child_options, parent_options, BDRV_OPT_CACHE_DIRECT);
961 qdict_copy_default(child_options, parent_options, BDRV_OPT_CACHE_NO_FLUSH);
962 qdict_copy_default(child_options, parent_options, BDRV_OPT_FORCE_SHARE);
963
964 /* Inherit the read-only option from the parent if it's not set */
965 qdict_copy_default(child_options, parent_options, BDRV_OPT_READ_ONLY);
966 qdict_copy_default(child_options, parent_options, BDRV_OPT_AUTO_READ_ONLY);
967
968 /* Our block drivers take care to send flushes and respect unmap policy,
969 * so we can default to enable both on lower layers regardless of the
970 * corresponding parent options. */
971 qdict_set_default_str(child_options, BDRV_OPT_DISCARD, "unmap");
972
973 /* Clear flags that only apply to the top layer */
974 flags &= ~(BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING | BDRV_O_COPY_ON_READ |
975 BDRV_O_NO_IO);
976
977 *child_flags = flags;
978 }
979
980 const BdrvChildRole child_file = {
981 .parent_is_bds = true,
982 .get_parent_desc = bdrv_child_get_parent_desc,
983 .inherit_options = bdrv_inherited_options,
984 .drained_begin = bdrv_child_cb_drained_begin,
985 .drained_poll = bdrv_child_cb_drained_poll,
986 .drained_end = bdrv_child_cb_drained_end,
987 .attach = bdrv_child_cb_attach,
988 .detach = bdrv_child_cb_detach,
989 .inactivate = bdrv_child_cb_inactivate,
990 };
991
992 /*
993 * Returns the options and flags that bs->file should get if the use of formats
994 * (and not only protocols) is permitted for it, based on the given options and
995 * flags for the parent BDS
996 */
997 static void bdrv_inherited_fmt_options(int *child_flags, QDict *child_options,
998 int parent_flags, QDict *parent_options)
999 {
1000 child_file.inherit_options(child_flags, child_options,
1001 parent_flags, parent_options);
1002
1003 *child_flags &= ~(BDRV_O_PROTOCOL | BDRV_O_NO_IO);
1004 }
1005
1006 const BdrvChildRole child_format = {
1007 .parent_is_bds = true,
1008 .get_parent_desc = bdrv_child_get_parent_desc,
1009 .inherit_options = bdrv_inherited_fmt_options,
1010 .drained_begin = bdrv_child_cb_drained_begin,
1011 .drained_poll = bdrv_child_cb_drained_poll,
1012 .drained_end = bdrv_child_cb_drained_end,
1013 .attach = bdrv_child_cb_attach,
1014 .detach = bdrv_child_cb_detach,
1015 .inactivate = bdrv_child_cb_inactivate,
1016 };
1017
1018 static void bdrv_backing_attach(BdrvChild *c)
1019 {
1020 BlockDriverState *parent = c->opaque;
1021 BlockDriverState *backing_hd = c->bs;
1022
1023 assert(!parent->backing_blocker);
1024 error_setg(&parent->backing_blocker,
1025 "node is used as backing hd of '%s'",
1026 bdrv_get_device_or_node_name(parent));
1027
1028 bdrv_refresh_filename(backing_hd);
1029
1030 parent->open_flags &= ~BDRV_O_NO_BACKING;
1031 pstrcpy(parent->backing_file, sizeof(parent->backing_file),
1032 backing_hd->filename);
1033 pstrcpy(parent->backing_format, sizeof(parent->backing_format),
1034 backing_hd->drv ? backing_hd->drv->format_name : "");
1035
1036 bdrv_op_block_all(backing_hd, parent->backing_blocker);
1037 /* Otherwise we won't be able to commit or stream */
1038 bdrv_op_unblock(backing_hd, BLOCK_OP_TYPE_COMMIT_TARGET,
1039 parent->backing_blocker);
1040 bdrv_op_unblock(backing_hd, BLOCK_OP_TYPE_STREAM,
1041 parent->backing_blocker);
1042 /*
1043 * We do backup in 3 ways:
1044 * 1. drive backup
1045 * The target bs is new opened, and the source is top BDS
1046 * 2. blockdev backup
1047 * Both the source and the target are top BDSes.
1048 * 3. internal backup(used for block replication)
1049 * Both the source and the target are backing file
1050 *
1051 * In case 1 and 2, neither the source nor the target is the backing file.
1052 * In case 3, we will block the top BDS, so there is only one block job
1053 * for the top BDS and its backing chain.
1054 */
1055 bdrv_op_unblock(backing_hd, BLOCK_OP_TYPE_BACKUP_SOURCE,
1056 parent->backing_blocker);
1057 bdrv_op_unblock(backing_hd, BLOCK_OP_TYPE_BACKUP_TARGET,
1058 parent->backing_blocker);
1059
1060 bdrv_child_cb_attach(c);
1061 }
1062
1063 static void bdrv_backing_detach(BdrvChild *c)
1064 {
1065 BlockDriverState *parent = c->opaque;
1066
1067 assert(parent->backing_blocker);
1068 bdrv_op_unblock_all(c->bs, parent->backing_blocker);
1069 error_free(parent->backing_blocker);
1070 parent->backing_blocker = NULL;
1071
1072 bdrv_child_cb_detach(c);
1073 }
1074
1075 /*
1076 * Returns the options and flags that bs->backing should get, based on the
1077 * given options and flags for the parent BDS
1078 */
1079 static void bdrv_backing_options(int *child_flags, QDict *child_options,
1080 int parent_flags, QDict *parent_options)
1081 {
1082 int flags = parent_flags;
1083
1084 /* The cache mode is inherited unmodified for backing files; except WCE,
1085 * which is only applied on the top level (BlockBackend) */
1086 qdict_copy_default(child_options, parent_options, BDRV_OPT_CACHE_DIRECT);
1087 qdict_copy_default(child_options, parent_options, BDRV_OPT_CACHE_NO_FLUSH);
1088 qdict_copy_default(child_options, parent_options, BDRV_OPT_FORCE_SHARE);
1089
1090 /* backing files always opened read-only */
1091 qdict_set_default_str(child_options, BDRV_OPT_READ_ONLY, "on");
1092 qdict_set_default_str(child_options, BDRV_OPT_AUTO_READ_ONLY, "off");
1093 flags &= ~BDRV_O_COPY_ON_READ;
1094
1095 /* snapshot=on is handled on the top layer */
1096 flags &= ~(BDRV_O_SNAPSHOT | BDRV_O_TEMPORARY);
1097
1098 *child_flags = flags;
1099 }
1100
1101 static int bdrv_backing_update_filename(BdrvChild *c, BlockDriverState *base,
1102 const char *filename, Error **errp)
1103 {
1104 BlockDriverState *parent = c->opaque;
1105 bool read_only = bdrv_is_read_only(parent);
1106 int ret;
1107
1108 if (read_only) {
1109 ret = bdrv_reopen_set_read_only(parent, false, errp);
1110 if (ret < 0) {
1111 return ret;
1112 }
1113 }
1114
1115 ret = bdrv_change_backing_file(parent, filename,
1116 base->drv ? base->drv->format_name : "");
1117 if (ret < 0) {
1118 error_setg_errno(errp, -ret, "Could not update backing file link");
1119 }
1120
1121 if (read_only) {
1122 bdrv_reopen_set_read_only(parent, true, NULL);
1123 }
1124
1125 return ret;
1126 }
1127
1128 const BdrvChildRole child_backing = {
1129 .parent_is_bds = true,
1130 .get_parent_desc = bdrv_child_get_parent_desc,
1131 .attach = bdrv_backing_attach,
1132 .detach = bdrv_backing_detach,
1133 .inherit_options = bdrv_backing_options,
1134 .drained_begin = bdrv_child_cb_drained_begin,
1135 .drained_poll = bdrv_child_cb_drained_poll,
1136 .drained_end = bdrv_child_cb_drained_end,
1137 .inactivate = bdrv_child_cb_inactivate,
1138 .update_filename = bdrv_backing_update_filename,
1139 };
1140
1141 static int bdrv_open_flags(BlockDriverState *bs, int flags)
1142 {
1143 int open_flags = flags;
1144
1145 /*
1146 * Clear flags that are internal to the block layer before opening the
1147 * image.
1148 */
1149 open_flags &= ~(BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING | BDRV_O_PROTOCOL);
1150
1151 /*
1152 * Snapshots should be writable.
1153 */
1154 if (flags & BDRV_O_TEMPORARY) {
1155 open_flags |= BDRV_O_RDWR;
1156 }
1157
1158 return open_flags;
1159 }
1160
1161 static void update_flags_from_options(int *flags, QemuOpts *opts)
1162 {
1163 *flags &= ~(BDRV_O_CACHE_MASK | BDRV_O_RDWR | BDRV_O_AUTO_RDONLY);
1164
1165 if (qemu_opt_get_bool_del(opts, BDRV_OPT_CACHE_NO_FLUSH, false)) {
1166 *flags |= BDRV_O_NO_FLUSH;
1167 }
1168
1169 if (qemu_opt_get_bool_del(opts, BDRV_OPT_CACHE_DIRECT, false)) {
1170 *flags |= BDRV_O_NOCACHE;
1171 }
1172
1173 if (!qemu_opt_get_bool_del(opts, BDRV_OPT_READ_ONLY, false)) {
1174 *flags |= BDRV_O_RDWR;
1175 }
1176
1177 if (qemu_opt_get_bool_del(opts, BDRV_OPT_AUTO_READ_ONLY, false)) {
1178 *flags |= BDRV_O_AUTO_RDONLY;
1179 }
1180 }
1181
1182 static void update_options_from_flags(QDict *options, int flags)
1183 {
1184 if (!qdict_haskey(options, BDRV_OPT_CACHE_DIRECT)) {
1185 qdict_put_bool(options, BDRV_OPT_CACHE_DIRECT, flags & BDRV_O_NOCACHE);
1186 }
1187 if (!qdict_haskey(options, BDRV_OPT_CACHE_NO_FLUSH)) {
1188 qdict_put_bool(options, BDRV_OPT_CACHE_NO_FLUSH,
1189 flags & BDRV_O_NO_FLUSH);
1190 }
1191 if (!qdict_haskey(options, BDRV_OPT_READ_ONLY)) {
1192 qdict_put_bool(options, BDRV_OPT_READ_ONLY, !(flags & BDRV_O_RDWR));
1193 }
1194 if (!qdict_haskey(options, BDRV_OPT_AUTO_READ_ONLY)) {
1195 qdict_put_bool(options, BDRV_OPT_AUTO_READ_ONLY,
1196 flags & BDRV_O_AUTO_RDONLY);
1197 }
1198 }
1199
1200 static void bdrv_assign_node_name(BlockDriverState *bs,
1201 const char *node_name,
1202 Error **errp)
1203 {
1204 char *gen_node_name = NULL;
1205
1206 if (!node_name) {
1207 node_name = gen_node_name = id_generate(ID_BLOCK);
1208 } else if (!id_wellformed(node_name)) {
1209 /*
1210 * Check for empty string or invalid characters, but not if it is
1211 * generated (generated names use characters not available to the user)
1212 */
1213 error_setg(errp, "Invalid node name");
1214 return;
1215 }
1216
1217 /* takes care of avoiding namespaces collisions */
1218 if (blk_by_name(node_name)) {
1219 error_setg(errp, "node-name=%s is conflicting with a device id",
1220 node_name);
1221 goto out;
1222 }
1223
1224 /* takes care of avoiding duplicates node names */
1225 if (bdrv_find_node(node_name)) {
1226 error_setg(errp, "Duplicate node name");
1227 goto out;
1228 }
1229
1230 /* Make sure that the node name isn't truncated */
1231 if (strlen(node_name) >= sizeof(bs->node_name)) {
1232 error_setg(errp, "Node name too long");
1233 goto out;
1234 }
1235
1236 /* copy node name into the bs and insert it into the graph list */
1237 pstrcpy(bs->node_name, sizeof(bs->node_name), node_name);
1238 QTAILQ_INSERT_TAIL(&graph_bdrv_states, bs, node_list);
1239 out:
1240 g_free(gen_node_name);
1241 }
1242
1243 static int bdrv_open_driver(BlockDriverState *bs, BlockDriver *drv,
1244 const char *node_name, QDict *options,
1245 int open_flags, Error **errp)
1246 {
1247 Error *local_err = NULL;
1248 int i, ret;
1249
1250 bdrv_assign_node_name(bs, node_name, &local_err);
1251 if (local_err) {
1252 error_propagate(errp, local_err);
1253 return -EINVAL;
1254 }
1255
1256 bs->drv = drv;
1257 bs->read_only = !(bs->open_flags & BDRV_O_RDWR);
1258 bs->opaque = g_malloc0(drv->instance_size);
1259
1260 if (drv->bdrv_file_open) {
1261 assert(!drv->bdrv_needs_filename || bs->filename[0]);
1262 ret = drv->bdrv_file_open(bs, options, open_flags, &local_err);
1263 } else if (drv->bdrv_open) {
1264 ret = drv->bdrv_open(bs, options, open_flags, &local_err);
1265 } else {
1266 ret = 0;
1267 }
1268
1269 if (ret < 0) {
1270 if (local_err) {
1271 error_propagate(errp, local_err);
1272 } else if (bs->filename[0]) {
1273 error_setg_errno(errp, -ret, "Could not open '%s'", bs->filename);
1274 } else {
1275 error_setg_errno(errp, -ret, "Could not open image");
1276 }
1277 goto open_failed;
1278 }
1279
1280 ret = refresh_total_sectors(bs, bs->total_sectors);
1281 if (ret < 0) {
1282 error_setg_errno(errp, -ret, "Could not refresh total sector count");
1283 return ret;
1284 }
1285
1286 bdrv_refresh_limits(bs, &local_err);
1287 if (local_err) {
1288 error_propagate(errp, local_err);
1289 return -EINVAL;
1290 }
1291
1292 assert(bdrv_opt_mem_align(bs) != 0);
1293 assert(bdrv_min_mem_align(bs) != 0);
1294 assert(is_power_of_2(bs->bl.request_alignment));
1295
1296 for (i = 0; i < bs->quiesce_counter; i++) {
1297 if (drv->bdrv_co_drain_begin) {
1298 drv->bdrv_co_drain_begin(bs);
1299 }
1300 }
1301
1302 return 0;
1303 open_failed:
1304 bs->drv = NULL;
1305 if (bs->file != NULL) {
1306 bdrv_unref_child(bs, bs->file);
1307 bs->file = NULL;
1308 }
1309 g_free(bs->opaque);
1310 bs->opaque = NULL;
1311 return ret;
1312 }
1313
1314 BlockDriverState *bdrv_new_open_driver(BlockDriver *drv, const char *node_name,
1315 int flags, Error **errp)
1316 {
1317 BlockDriverState *bs;
1318 int ret;
1319
1320 bs = bdrv_new();
1321 bs->open_flags = flags;
1322 bs->explicit_options = qdict_new();
1323 bs->options = qdict_new();
1324 bs->opaque = NULL;
1325
1326 update_options_from_flags(bs->options, flags);
1327
1328 ret = bdrv_open_driver(bs, drv, node_name, bs->options, flags, errp);
1329 if (ret < 0) {
1330 qobject_unref(bs->explicit_options);
1331 bs->explicit_options = NULL;
1332 qobject_unref(bs->options);
1333 bs->options = NULL;
1334 bdrv_unref(bs);
1335 return NULL;
1336 }
1337
1338 return bs;
1339 }
1340
1341 QemuOptsList bdrv_runtime_opts = {
1342 .name = "bdrv_common",
1343 .head = QTAILQ_HEAD_INITIALIZER(bdrv_runtime_opts.head),
1344 .desc = {
1345 {
1346 .name = "node-name",
1347 .type = QEMU_OPT_STRING,
1348 .help = "Node name of the block device node",
1349 },
1350 {
1351 .name = "driver",
1352 .type = QEMU_OPT_STRING,
1353 .help = "Block driver to use for the node",
1354 },
1355 {
1356 .name = BDRV_OPT_CACHE_DIRECT,
1357 .type = QEMU_OPT_BOOL,
1358 .help = "Bypass software writeback cache on the host",
1359 },
1360 {
1361 .name = BDRV_OPT_CACHE_NO_FLUSH,
1362 .type = QEMU_OPT_BOOL,
1363 .help = "Ignore flush requests",
1364 },
1365 {
1366 .name = BDRV_OPT_READ_ONLY,
1367 .type = QEMU_OPT_BOOL,
1368 .help = "Node is opened in read-only mode",
1369 },
1370 {
1371 .name = BDRV_OPT_AUTO_READ_ONLY,
1372 .type = QEMU_OPT_BOOL,
1373 .help = "Node can become read-only if opening read-write fails",
1374 },
1375 {
1376 .name = "detect-zeroes",
1377 .type = QEMU_OPT_STRING,
1378 .help = "try to optimize zero writes (off, on, unmap)",
1379 },
1380 {
1381 .name = BDRV_OPT_DISCARD,
1382 .type = QEMU_OPT_STRING,
1383 .help = "discard operation (ignore/off, unmap/on)",
1384 },
1385 {
1386 .name = BDRV_OPT_FORCE_SHARE,
1387 .type = QEMU_OPT_BOOL,
1388 .help = "always accept other writers (default: off)",
1389 },
1390 { /* end of list */ }
1391 },
1392 };
1393
1394 /*
1395 * Common part for opening disk images and files
1396 *
1397 * Removes all processed options from *options.
1398 */
1399 static int bdrv_open_common(BlockDriverState *bs, BlockBackend *file,
1400 QDict *options, Error **errp)
1401 {
1402 int ret, open_flags;
1403 const char *filename;
1404 const char *driver_name = NULL;
1405 const char *node_name = NULL;
1406 const char *discard;
1407 QemuOpts *opts;
1408 BlockDriver *drv;
1409 Error *local_err = NULL;
1410
1411 assert(bs->file == NULL);
1412 assert(options != NULL && bs->options != options);
1413
1414 opts = qemu_opts_create(&bdrv_runtime_opts, NULL, 0, &error_abort);
1415 qemu_opts_absorb_qdict(opts, options, &local_err);
1416 if (local_err) {
1417 error_propagate(errp, local_err);
1418 ret = -EINVAL;
1419 goto fail_opts;
1420 }
1421
1422 update_flags_from_options(&bs->open_flags, opts);
1423
1424 driver_name = qemu_opt_get(opts, "driver");
1425 drv = bdrv_find_format(driver_name);
1426 assert(drv != NULL);
1427
1428 bs->force_share = qemu_opt_get_bool(opts, BDRV_OPT_FORCE_SHARE, false);
1429
1430 if (bs->force_share && (bs->open_flags & BDRV_O_RDWR)) {
1431 error_setg(errp,
1432 BDRV_OPT_FORCE_SHARE
1433 "=on can only be used with read-only images");
1434 ret = -EINVAL;
1435 goto fail_opts;
1436 }
1437
1438 if (file != NULL) {
1439 bdrv_refresh_filename(blk_bs(file));
1440 filename = blk_bs(file)->filename;
1441 } else {
1442 /*
1443 * Caution: while qdict_get_try_str() is fine, getting
1444 * non-string types would require more care. When @options
1445 * come from -blockdev or blockdev_add, its members are typed
1446 * according to the QAPI schema, but when they come from
1447 * -drive, they're all QString.
1448 */
1449 filename = qdict_get_try_str(options, "filename");
1450 }
1451
1452 if (drv->bdrv_needs_filename && (!filename || !filename[0])) {
1453 error_setg(errp, "The '%s' block driver requires a file name",
1454 drv->format_name);
1455 ret = -EINVAL;
1456 goto fail_opts;
1457 }
1458
1459 trace_bdrv_open_common(bs, filename ?: "", bs->open_flags,
1460 drv->format_name);
1461
1462 bs->read_only = !(bs->open_flags & BDRV_O_RDWR);
1463
1464 if (use_bdrv_whitelist && !bdrv_is_whitelisted(drv, bs->read_only)) {
1465 if (!bs->read_only && bdrv_is_whitelisted(drv, true)) {
1466 ret = bdrv_apply_auto_read_only(bs, NULL, NULL);
1467 } else {
1468 ret = -ENOTSUP;
1469 }
1470 if (ret < 0) {
1471 error_setg(errp,
1472 !bs->read_only && bdrv_is_whitelisted(drv, true)
1473 ? "Driver '%s' can only be used for read-only devices"
1474 : "Driver '%s' is not whitelisted",
1475 drv->format_name);
1476 goto fail_opts;
1477 }
1478 }
1479
1480 /* bdrv_new() and bdrv_close() make it so */
1481 assert(atomic_read(&bs->copy_on_read) == 0);
1482
1483 if (bs->open_flags & BDRV_O_COPY_ON_READ) {
1484 if (!bs->read_only) {
1485 bdrv_enable_copy_on_read(bs);
1486 } else {
1487 error_setg(errp, "Can't use copy-on-read on read-only device");
1488 ret = -EINVAL;
1489 goto fail_opts;
1490 }
1491 }
1492
1493 discard = qemu_opt_get(opts, BDRV_OPT_DISCARD);
1494 if (discard != NULL) {
1495 if (bdrv_parse_discard_flags(discard, &bs->open_flags) != 0) {
1496 error_setg(errp, "Invalid discard option");
1497 ret = -EINVAL;
1498 goto fail_opts;
1499 }
1500 }
1501
1502 bs->detect_zeroes =
1503 bdrv_parse_detect_zeroes(opts, bs->open_flags, &local_err);
1504 if (local_err) {
1505 error_propagate(errp, local_err);
1506 ret = -EINVAL;
1507 goto fail_opts;
1508 }
1509
1510 if (filename != NULL) {
1511 pstrcpy(bs->filename, sizeof(bs->filename), filename);
1512 } else {
1513 bs->filename[0] = '\0';
1514 }
1515 pstrcpy(bs->exact_filename, sizeof(bs->exact_filename), bs->filename);
1516
1517 /* Open the image, either directly or using a protocol */
1518 open_flags = bdrv_open_flags(bs, bs->open_flags);
1519 node_name = qemu_opt_get(opts, "node-name");
1520
1521 assert(!drv->bdrv_file_open || file == NULL);
1522 ret = bdrv_open_driver(bs, drv, node_name, options, open_flags, errp);
1523 if (ret < 0) {
1524 goto fail_opts;
1525 }
1526
1527 qemu_opts_del(opts);
1528 return 0;
1529
1530 fail_opts:
1531 qemu_opts_del(opts);
1532 return ret;
1533 }
1534
1535 static QDict *parse_json_filename(const char *filename, Error **errp)
1536 {
1537 QObject *options_obj;
1538 QDict *options;
1539 int ret;
1540
1541 ret = strstart(filename, "json:", &filename);
1542 assert(ret);
1543
1544 options_obj = qobject_from_json(filename, errp);
1545 if (!options_obj) {
1546 error_prepend(errp, "Could not parse the JSON options: ");
1547 return NULL;
1548 }
1549
1550 options = qobject_to(QDict, options_obj);
1551 if (!options) {
1552 qobject_unref(options_obj);
1553 error_setg(errp, "Invalid JSON object given");
1554 return NULL;
1555 }
1556
1557 qdict_flatten(options);
1558
1559 return options;
1560 }
1561
1562 static void parse_json_protocol(QDict *options, const char **pfilename,
1563 Error **errp)
1564 {
1565 QDict *json_options;
1566 Error *local_err = NULL;
1567
1568 /* Parse json: pseudo-protocol */
1569 if (!*pfilename || !g_str_has_prefix(*pfilename, "json:")) {
1570 return;
1571 }
1572
1573 json_options = parse_json_filename(*pfilename, &local_err);
1574 if (local_err) {
1575 error_propagate(errp, local_err);
1576 return;
1577 }
1578
1579 /* Options given in the filename have lower priority than options
1580 * specified directly */
1581 qdict_join(options, json_options, false);
1582 qobject_unref(json_options);
1583 *pfilename = NULL;
1584 }
1585
1586 /*
1587 * Fills in default options for opening images and converts the legacy
1588 * filename/flags pair to option QDict entries.
1589 * The BDRV_O_PROTOCOL flag in *flags will be set or cleared accordingly if a
1590 * block driver has been specified explicitly.
1591 */
1592 static int bdrv_fill_options(QDict **options, const char *filename,
1593 int *flags, Error **errp)
1594 {
1595 const char *drvname;
1596 bool protocol = *flags & BDRV_O_PROTOCOL;
1597 bool parse_filename = false;
1598 BlockDriver *drv = NULL;
1599 Error *local_err = NULL;
1600
1601 /*
1602 * Caution: while qdict_get_try_str() is fine, getting non-string
1603 * types would require more care. When @options come from
1604 * -blockdev or blockdev_add, its members are typed according to
1605 * the QAPI schema, but when they come from -drive, they're all
1606 * QString.
1607 */
1608 drvname = qdict_get_try_str(*options, "driver");
1609 if (drvname) {
1610 drv = bdrv_find_format(drvname);
1611 if (!drv) {
1612 error_setg(errp, "Unknown driver '%s'", drvname);
1613 return -ENOENT;
1614 }
1615 /* If the user has explicitly specified the driver, this choice should
1616 * override the BDRV_O_PROTOCOL flag */
1617 protocol = drv->bdrv_file_open;
1618 }
1619
1620 if (protocol) {
1621 *flags |= BDRV_O_PROTOCOL;
1622 } else {
1623 *flags &= ~BDRV_O_PROTOCOL;
1624 }
1625
1626 /* Translate cache options from flags into options */
1627 update_options_from_flags(*options, *flags);
1628
1629 /* Fetch the file name from the options QDict if necessary */
1630 if (protocol && filename) {
1631 if (!qdict_haskey(*options, "filename")) {
1632 qdict_put_str(*options, "filename", filename);
1633 parse_filename = true;
1634 } else {
1635 error_setg(errp, "Can't specify 'file' and 'filename' options at "
1636 "the same time");
1637 return -EINVAL;
1638 }
1639 }
1640
1641 /* Find the right block driver */
1642 /* See cautionary note on accessing @options above */
1643 filename = qdict_get_try_str(*options, "filename");
1644
1645 if (!drvname && protocol) {
1646 if (filename) {
1647 drv = bdrv_find_protocol(filename, parse_filename, errp);
1648 if (!drv) {
1649 return -EINVAL;
1650 }
1651
1652 drvname = drv->format_name;
1653 qdict_put_str(*options, "driver", drvname);
1654 } else {
1655 error_setg(errp, "Must specify either driver or file");
1656 return -EINVAL;
1657 }
1658 }
1659
1660 assert(drv || !protocol);
1661
1662 /* Driver-specific filename parsing */
1663 if (drv && drv->bdrv_parse_filename && parse_filename) {
1664 drv->bdrv_parse_filename(filename, *options, &local_err);
1665 if (local_err) {
1666 error_propagate(errp, local_err);
1667 return -EINVAL;
1668 }
1669
1670 if (!drv->bdrv_needs_filename) {
1671 qdict_del(*options, "filename");
1672 }
1673 }
1674
1675 return 0;
1676 }
1677
1678 static int bdrv_child_check_perm(BdrvChild *c, BlockReopenQueue *q,
1679 uint64_t perm, uint64_t shared,
1680 GSList *ignore_children, Error **errp);
1681 static void bdrv_child_abort_perm_update(BdrvChild *c);
1682 static void bdrv_child_set_perm(BdrvChild *c, uint64_t perm, uint64_t shared);
1683
1684 typedef struct BlockReopenQueueEntry {
1685 bool prepared;
1686 BDRVReopenState state;
1687 QSIMPLEQ_ENTRY(BlockReopenQueueEntry) entry;
1688 } BlockReopenQueueEntry;
1689
1690 /*
1691 * Return the flags that @bs will have after the reopens in @q have
1692 * successfully completed. If @q is NULL (or @bs is not contained in @q),
1693 * return the current flags.
1694 */
1695 static int bdrv_reopen_get_flags(BlockReopenQueue *q, BlockDriverState *bs)
1696 {
1697 BlockReopenQueueEntry *entry;
1698
1699 if (q != NULL) {
1700 QSIMPLEQ_FOREACH(entry, q, entry) {
1701 if (entry->state.bs == bs) {
1702 return entry->state.flags;
1703 }
1704 }
1705 }
1706
1707 return bs->open_flags;
1708 }
1709
1710 /* Returns whether the image file can be written to after the reopen queue @q
1711 * has been successfully applied, or right now if @q is NULL. */
1712 static bool bdrv_is_writable_after_reopen(BlockDriverState *bs,
1713 BlockReopenQueue *q)
1714 {
1715 int flags = bdrv_reopen_get_flags(q, bs);
1716
1717 return (flags & (BDRV_O_RDWR | BDRV_O_INACTIVE)) == BDRV_O_RDWR;
1718 }
1719
1720 /*
1721 * Return whether the BDS can be written to. This is not necessarily
1722 * the same as !bdrv_is_read_only(bs), as inactivated images may not
1723 * be written to but do not count as read-only images.
1724 */
1725 bool bdrv_is_writable(BlockDriverState *bs)
1726 {
1727 return bdrv_is_writable_after_reopen(bs, NULL);
1728 }
1729
1730 static void bdrv_child_perm(BlockDriverState *bs, BlockDriverState *child_bs,
1731 BdrvChild *c, const BdrvChildRole *role,
1732 BlockReopenQueue *reopen_queue,
1733 uint64_t parent_perm, uint64_t parent_shared,
1734 uint64_t *nperm, uint64_t *nshared)
1735 {
1736 if (bs->drv && bs->drv->bdrv_child_perm) {
1737 bs->drv->bdrv_child_perm(bs, c, role, reopen_queue,
1738 parent_perm, parent_shared,
1739 nperm, nshared);
1740 }
1741 /* TODO Take force_share from reopen_queue */
1742 if (child_bs && child_bs->force_share) {
1743 *nshared = BLK_PERM_ALL;
1744 }
1745 }
1746
1747 /*
1748 * Check whether permissions on this node can be changed in a way that
1749 * @cumulative_perms and @cumulative_shared_perms are the new cumulative
1750 * permissions of all its parents. This involves checking whether all necessary
1751 * permission changes to child nodes can be performed.
1752 *
1753 * A call to this function must always be followed by a call to bdrv_set_perm()
1754 * or bdrv_abort_perm_update().
1755 */
1756 static int bdrv_check_perm(BlockDriverState *bs, BlockReopenQueue *q,
1757 uint64_t cumulative_perms,
1758 uint64_t cumulative_shared_perms,
1759 GSList *ignore_children, Error **errp)
1760 {
1761 BlockDriver *drv = bs->drv;
1762 BdrvChild *c;
1763 int ret;
1764
1765 /* Write permissions never work with read-only images */
1766 if ((cumulative_perms & (BLK_PERM_WRITE | BLK_PERM_WRITE_UNCHANGED)) &&
1767 !bdrv_is_writable_after_reopen(bs, q))
1768 {
1769 error_setg(errp, "Block node is read-only");
1770 return -EPERM;
1771 }
1772
1773 /* Check this node */
1774 if (!drv) {
1775 return 0;
1776 }
1777
1778 if (drv->bdrv_check_perm) {
1779 return drv->bdrv_check_perm(bs, cumulative_perms,
1780 cumulative_shared_perms, errp);
1781 }
1782
1783 /* Drivers that never have children can omit .bdrv_child_perm() */
1784 if (!drv->bdrv_child_perm) {
1785 assert(QLIST_EMPTY(&bs->children));
1786 return 0;
1787 }
1788
1789 /* Check all children */
1790 QLIST_FOREACH(c, &bs->children, next) {
1791 uint64_t cur_perm, cur_shared;
1792 bdrv_child_perm(bs, c->bs, c, c->role, q,
1793 cumulative_perms, cumulative_shared_perms,
1794 &cur_perm, &cur_shared);
1795 ret = bdrv_child_check_perm(c, q, cur_perm, cur_shared,
1796 ignore_children, errp);
1797 if (ret < 0) {
1798 return ret;
1799 }
1800 }
1801
1802 return 0;
1803 }
1804
1805 /*
1806 * Notifies drivers that after a previous bdrv_check_perm() call, the
1807 * permission update is not performed and any preparations made for it (e.g.
1808 * taken file locks) need to be undone.
1809 *
1810 * This function recursively notifies all child nodes.
1811 */
1812 static void bdrv_abort_perm_update(BlockDriverState *bs)
1813 {
1814 BlockDriver *drv = bs->drv;
1815 BdrvChild *c;
1816
1817 if (!drv) {
1818 return;
1819 }
1820
1821 if (drv->bdrv_abort_perm_update) {
1822 drv->bdrv_abort_perm_update(bs);
1823 }
1824
1825 QLIST_FOREACH(c, &bs->children, next) {
1826 bdrv_child_abort_perm_update(c);
1827 }
1828 }
1829
1830 static void bdrv_set_perm(BlockDriverState *bs, uint64_t cumulative_perms,
1831 uint64_t cumulative_shared_perms)
1832 {
1833 BlockDriver *drv = bs->drv;
1834 BdrvChild *c;
1835
1836 if (!drv) {
1837 return;
1838 }
1839
1840 /* Update this node */
1841 if (drv->bdrv_set_perm) {
1842 drv->bdrv_set_perm(bs, cumulative_perms, cumulative_shared_perms);
1843 }
1844
1845 /* Drivers that never have children can omit .bdrv_child_perm() */
1846 if (!drv->bdrv_child_perm) {
1847 assert(QLIST_EMPTY(&bs->children));
1848 return;
1849 }
1850
1851 /* Update all children */
1852 QLIST_FOREACH(c, &bs->children, next) {
1853 uint64_t cur_perm, cur_shared;
1854 bdrv_child_perm(bs, c->bs, c, c->role, NULL,
1855 cumulative_perms, cumulative_shared_perms,
1856 &cur_perm, &cur_shared);
1857 bdrv_child_set_perm(c, cur_perm, cur_shared);
1858 }
1859 }
1860
1861 static void bdrv_get_cumulative_perm(BlockDriverState *bs, uint64_t *perm,
1862 uint64_t *shared_perm)
1863 {
1864 BdrvChild *c;
1865 uint64_t cumulative_perms = 0;
1866 uint64_t cumulative_shared_perms = BLK_PERM_ALL;
1867
1868 QLIST_FOREACH(c, &bs->parents, next_parent) {
1869 cumulative_perms |= c->perm;
1870 cumulative_shared_perms &= c->shared_perm;
1871 }
1872
1873 *perm = cumulative_perms;
1874 *shared_perm = cumulative_shared_perms;
1875 }
1876
1877 static char *bdrv_child_user_desc(BdrvChild *c)
1878 {
1879 if (c->role->get_parent_desc) {
1880 return c->role->get_parent_desc(c);
1881 }
1882
1883 return g_strdup("another user");
1884 }
1885
1886 char *bdrv_perm_names(uint64_t perm)
1887 {
1888 struct perm_name {
1889 uint64_t perm;
1890 const char *name;
1891 } permissions[] = {
1892 { BLK_PERM_CONSISTENT_READ, "consistent read" },
1893 { BLK_PERM_WRITE, "write" },
1894 { BLK_PERM_WRITE_UNCHANGED, "write unchanged" },
1895 { BLK_PERM_RESIZE, "resize" },
1896 { BLK_PERM_GRAPH_MOD, "change children" },
1897 { 0, NULL }
1898 };
1899
1900 char *result = g_strdup("");
1901 struct perm_name *p;
1902
1903 for (p = permissions; p->name; p++) {
1904 if (perm & p->perm) {
1905 char *old = result;
1906 result = g_strdup_printf("%s%s%s", old, *old ? ", " : "", p->name);
1907 g_free(old);
1908 }
1909 }
1910
1911 return result;
1912 }
1913
1914 /*
1915 * Checks whether a new reference to @bs can be added if the new user requires
1916 * @new_used_perm/@new_shared_perm as its permissions. If @ignore_children is
1917 * set, the BdrvChild objects in this list are ignored in the calculations;
1918 * this allows checking permission updates for an existing reference.
1919 *
1920 * Needs to be followed by a call to either bdrv_set_perm() or
1921 * bdrv_abort_perm_update(). */
1922 static int bdrv_check_update_perm(BlockDriverState *bs, BlockReopenQueue *q,
1923 uint64_t new_used_perm,
1924 uint64_t new_shared_perm,
1925 GSList *ignore_children, Error **errp)
1926 {
1927 BdrvChild *c;
1928 uint64_t cumulative_perms = new_used_perm;
1929 uint64_t cumulative_shared_perms = new_shared_perm;
1930
1931 /* There is no reason why anyone couldn't tolerate write_unchanged */
1932 assert(new_shared_perm & BLK_PERM_WRITE_UNCHANGED);
1933
1934 QLIST_FOREACH(c, &bs->parents, next_parent) {
1935 if (g_slist_find(ignore_children, c)) {
1936 continue;
1937 }
1938
1939 if ((new_used_perm & c->shared_perm) != new_used_perm) {
1940 char *user = bdrv_child_user_desc(c);
1941 char *perm_names = bdrv_perm_names(new_used_perm & ~c->shared_perm);
1942 error_setg(errp, "Conflicts with use by %s as '%s', which does not "
1943 "allow '%s' on %s",
1944 user, c->name, perm_names, bdrv_get_node_name(c->bs));
1945 g_free(user);
1946 g_free(perm_names);
1947 return -EPERM;
1948 }
1949
1950 if ((c->perm & new_shared_perm) != c->perm) {
1951 char *user = bdrv_child_user_desc(c);
1952 char *perm_names = bdrv_perm_names(c->perm & ~new_shared_perm);
1953 error_setg(errp, "Conflicts with use by %s as '%s', which uses "
1954 "'%s' on %s",
1955 user, c->name, perm_names, bdrv_get_node_name(c->bs));
1956 g_free(user);
1957 g_free(perm_names);
1958 return -EPERM;
1959 }
1960
1961 cumulative_perms |= c->perm;
1962 cumulative_shared_perms &= c->shared_perm;
1963 }
1964
1965 return bdrv_check_perm(bs, q, cumulative_perms, cumulative_shared_perms,
1966 ignore_children, errp);
1967 }
1968
1969 /* Needs to be followed by a call to either bdrv_child_set_perm() or
1970 * bdrv_child_abort_perm_update(). */
1971 static int bdrv_child_check_perm(BdrvChild *c, BlockReopenQueue *q,
1972 uint64_t perm, uint64_t shared,
1973 GSList *ignore_children, Error **errp)
1974 {
1975 int ret;
1976
1977 ignore_children = g_slist_prepend(g_slist_copy(ignore_children), c);
1978 ret = bdrv_check_update_perm(c->bs, q, perm, shared, ignore_children, errp);
1979 g_slist_free(ignore_children);
1980
1981 if (ret < 0) {
1982 return ret;
1983 }
1984
1985 if (!c->has_backup_perm) {
1986 c->has_backup_perm = true;
1987 c->backup_perm = c->perm;
1988 c->backup_shared_perm = c->shared_perm;
1989 }
1990 /*
1991 * Note: it's OK if c->has_backup_perm was already set, as we can find the
1992 * same child twice during check_perm procedure
1993 */
1994
1995 c->perm = perm;
1996 c->shared_perm = shared;
1997
1998 return 0;
1999 }
2000
2001 static void bdrv_child_set_perm(BdrvChild *c, uint64_t perm, uint64_t shared)
2002 {
2003 uint64_t cumulative_perms, cumulative_shared_perms;
2004
2005 c->has_backup_perm = false;
2006
2007 c->perm = perm;
2008 c->shared_perm = shared;
2009
2010 bdrv_get_cumulative_perm(c->bs, &cumulative_perms,
2011 &cumulative_shared_perms);
2012 bdrv_set_perm(c->bs, cumulative_perms, cumulative_shared_perms);
2013 }
2014
2015 static void bdrv_child_abort_perm_update(BdrvChild *c)
2016 {
2017 if (c->has_backup_perm) {
2018 c->perm = c->backup_perm;
2019 c->shared_perm = c->backup_shared_perm;
2020 c->has_backup_perm = false;
2021 }
2022
2023 bdrv_abort_perm_update(c->bs);
2024 }
2025
2026 int bdrv_child_try_set_perm(BdrvChild *c, uint64_t perm, uint64_t shared,
2027 Error **errp)
2028 {
2029 int ret;
2030
2031 ret = bdrv_child_check_perm(c, NULL, perm, shared, NULL, errp);
2032 if (ret < 0) {
2033 bdrv_child_abort_perm_update(c);
2034 return ret;
2035 }
2036
2037 bdrv_child_set_perm(c, perm, shared);
2038
2039 return 0;
2040 }
2041
2042 void bdrv_filter_default_perms(BlockDriverState *bs, BdrvChild *c,
2043 const BdrvChildRole *role,
2044 BlockReopenQueue *reopen_queue,
2045 uint64_t perm, uint64_t shared,
2046 uint64_t *nperm, uint64_t *nshared)
2047 {
2048 if (c == NULL) {
2049 *nperm = perm & DEFAULT_PERM_PASSTHROUGH;
2050 *nshared = (shared & DEFAULT_PERM_PASSTHROUGH) | DEFAULT_PERM_UNCHANGED;
2051 return;
2052 }
2053
2054 *nperm = (perm & DEFAULT_PERM_PASSTHROUGH) |
2055 (c->perm & DEFAULT_PERM_UNCHANGED);
2056 *nshared = (shared & DEFAULT_PERM_PASSTHROUGH) |
2057 (c->shared_perm & DEFAULT_PERM_UNCHANGED);
2058 }
2059
2060 void bdrv_format_default_perms(BlockDriverState *bs, BdrvChild *c,
2061 const BdrvChildRole *role,
2062 BlockReopenQueue *reopen_queue,
2063 uint64_t perm, uint64_t shared,
2064 uint64_t *nperm, uint64_t *nshared)
2065 {
2066 bool backing = (role == &child_backing);
2067 assert(role == &child_backing || role == &child_file);
2068
2069 if (!backing) {
2070 int flags = bdrv_reopen_get_flags(reopen_queue, bs);
2071
2072 /* Apart from the modifications below, the same permissions are
2073 * forwarded and left alone as for filters */
2074 bdrv_filter_default_perms(bs, c, role, reopen_queue, perm, shared,
2075 &perm, &shared);
2076
2077 /* Format drivers may touch metadata even if the guest doesn't write */
2078 if (bdrv_is_writable_after_reopen(bs, reopen_queue)) {
2079 perm |= BLK_PERM_WRITE | BLK_PERM_RESIZE;
2080 }
2081
2082 /* bs->file always needs to be consistent because of the metadata. We
2083 * can never allow other users to resize or write to it. */
2084 if (!(flags & BDRV_O_NO_IO)) {
2085 perm |= BLK_PERM_CONSISTENT_READ;
2086 }
2087 shared &= ~(BLK_PERM_WRITE | BLK_PERM_RESIZE);
2088 } else {
2089 /* We want consistent read from backing files if the parent needs it.
2090 * No other operations are performed on backing files. */
2091 perm &= BLK_PERM_CONSISTENT_READ;
2092
2093 /* If the parent can deal with changing data, we're okay with a
2094 * writable and resizable backing file. */
2095 /* TODO Require !(perm & BLK_PERM_CONSISTENT_READ), too? */
2096 if (shared & BLK_PERM_WRITE) {
2097 shared = BLK_PERM_WRITE | BLK_PERM_RESIZE;
2098 } else {
2099 shared = 0;
2100 }
2101
2102 shared |= BLK_PERM_CONSISTENT_READ | BLK_PERM_GRAPH_MOD |
2103 BLK_PERM_WRITE_UNCHANGED;
2104 }
2105
2106 if (bs->open_flags & BDRV_O_INACTIVE) {
2107 shared |= BLK_PERM_WRITE | BLK_PERM_RESIZE;
2108 }
2109
2110 *nperm = perm;
2111 *nshared = shared;
2112 }
2113
2114 static void bdrv_replace_child_noperm(BdrvChild *child,
2115 BlockDriverState *new_bs)
2116 {
2117 BlockDriverState *old_bs = child->bs;
2118 int i;
2119
2120 if (old_bs && new_bs) {
2121 assert(bdrv_get_aio_context(old_bs) == bdrv_get_aio_context(new_bs));
2122 }
2123 if (old_bs) {
2124 /* Detach first so that the recursive drain sections coming from @child
2125 * are already gone and we only end the drain sections that came from
2126 * elsewhere. */
2127 if (child->role->detach) {
2128 child->role->detach(child);
2129 }
2130 if (old_bs->quiesce_counter && child->role->drained_end) {
2131 int num = old_bs->quiesce_counter;
2132 if (child->role->parent_is_bds) {
2133 num -= bdrv_drain_all_count;
2134 }
2135 assert(num >= 0);
2136 for (i = 0; i < num; i++) {
2137 child->role->drained_end(child);
2138 }
2139 }
2140 QLIST_REMOVE(child, next_parent);
2141 }
2142
2143 child->bs = new_bs;
2144
2145 if (new_bs) {
2146 QLIST_INSERT_HEAD(&new_bs->parents, child, next_parent);
2147 if (new_bs->quiesce_counter && child->role->drained_begin) {
2148 int num = new_bs->quiesce_counter;
2149 if (child->role->parent_is_bds) {
2150 num -= bdrv_drain_all_count;
2151 }
2152 assert(num >= 0);
2153 for (i = 0; i < num; i++) {
2154 bdrv_parent_drained_begin_single(child, true);
2155 }
2156 }
2157
2158 /* Attach only after starting new drained sections, so that recursive
2159 * drain sections coming from @child don't get an extra .drained_begin
2160 * callback. */
2161 if (child->role->attach) {
2162 child->role->attach(child);
2163 }
2164 }
2165 }
2166
2167 /*
2168 * Updates @child to change its reference to point to @new_bs, including
2169 * checking and applying the necessary permisson updates both to the old node
2170 * and to @new_bs.
2171 *
2172 * NULL is passed as @new_bs for removing the reference before freeing @child.
2173 *
2174 * If @new_bs is not NULL, bdrv_check_perm() must be called beforehand, as this
2175 * function uses bdrv_set_perm() to update the permissions according to the new
2176 * reference that @new_bs gets.
2177 */
2178 static void bdrv_replace_child(BdrvChild *child, BlockDriverState *new_bs)
2179 {
2180 BlockDriverState *old_bs = child->bs;
2181 uint64_t perm, shared_perm;
2182
2183 bdrv_replace_child_noperm(child, new_bs);
2184
2185 if (old_bs) {
2186 /* Update permissions for old node. This is guaranteed to succeed
2187 * because we're just taking a parent away, so we're loosening
2188 * restrictions. */
2189 bdrv_get_cumulative_perm(old_bs, &perm, &shared_perm);
2190 bdrv_check_perm(old_bs, NULL, perm, shared_perm, NULL, &error_abort);
2191 bdrv_set_perm(old_bs, perm, shared_perm);
2192 }
2193
2194 if (new_bs) {
2195 bdrv_get_cumulative_perm(new_bs, &perm, &shared_perm);
2196 bdrv_set_perm(new_bs, perm, shared_perm);
2197 }
2198 }
2199
2200 BdrvChild *bdrv_root_attach_child(BlockDriverState *child_bs,
2201 const char *child_name,
2202 const BdrvChildRole *child_role,
2203 uint64_t perm, uint64_t shared_perm,
2204 void *opaque, Error **errp)
2205 {
2206 BdrvChild *child;
2207 int ret;
2208
2209 ret = bdrv_check_update_perm(child_bs, NULL, perm, shared_perm, NULL, errp);
2210 if (ret < 0) {
2211 bdrv_abort_perm_update(child_bs);
2212 return NULL;
2213 }
2214
2215 child = g_new(BdrvChild, 1);
2216 *child = (BdrvChild) {
2217 .bs = NULL,
2218 .name = g_strdup(child_name),
2219 .role = child_role,
2220 .perm = perm,
2221 .shared_perm = shared_perm,
2222 .opaque = opaque,
2223 };
2224
2225 /* This performs the matching bdrv_set_perm() for the above check. */
2226 bdrv_replace_child(child, child_bs);
2227
2228 return child;
2229 }
2230
2231 BdrvChild *bdrv_attach_child(BlockDriverState *parent_bs,
2232 BlockDriverState *child_bs,
2233 const char *child_name,
2234 const BdrvChildRole *child_role,
2235 Error **errp)
2236 {
2237 BdrvChild *child;
2238 uint64_t perm, shared_perm;
2239
2240 bdrv_get_cumulative_perm(parent_bs, &perm, &shared_perm);
2241
2242 assert(parent_bs->drv);
2243 assert(bdrv_get_aio_context(parent_bs) == bdrv_get_aio_context(child_bs));
2244 bdrv_child_perm(parent_bs, child_bs, NULL, child_role, NULL,
2245 perm, shared_perm, &perm, &shared_perm);
2246
2247 child = bdrv_root_attach_child(child_bs, child_name, child_role,
2248 perm, shared_perm, parent_bs, errp);
2249 if (child == NULL) {
2250 return NULL;
2251 }
2252
2253 QLIST_INSERT_HEAD(&parent_bs->children, child, next);
2254 return child;
2255 }
2256
2257 static void bdrv_detach_child(BdrvChild *child)
2258 {
2259 if (child->next.le_prev) {
2260 QLIST_REMOVE(child, next);
2261 child->next.le_prev = NULL;
2262 }
2263
2264 bdrv_replace_child(child, NULL);
2265
2266 g_free(child->name);
2267 g_free(child);
2268 }
2269
2270 void bdrv_root_unref_child(BdrvChild *child)
2271 {
2272 BlockDriverState *child_bs;
2273
2274 child_bs = child->bs;
2275 bdrv_detach_child(child);
2276 bdrv_unref(child_bs);
2277 }
2278
2279 void bdrv_unref_child(BlockDriverState *parent, BdrvChild *child)
2280 {
2281 if (child == NULL) {
2282 return;
2283 }
2284
2285 if (child->bs->inherits_from == parent) {
2286 BdrvChild *c;
2287
2288 /* Remove inherits_from only when the last reference between parent and
2289 * child->bs goes away. */
2290 QLIST_FOREACH(c, &parent->children, next) {
2291 if (c != child && c->bs == child->bs) {
2292 break;
2293 }
2294 }
2295 if (c == NULL) {
2296 child->bs->inherits_from = NULL;
2297 }
2298 }
2299
2300 bdrv_root_unref_child(child);
2301 }
2302
2303
2304 static void bdrv_parent_cb_change_media(BlockDriverState *bs, bool load)
2305 {
2306 BdrvChild *c;
2307 QLIST_FOREACH(c, &bs->parents, next_parent) {
2308 if (c->role->change_media) {
2309 c->role->change_media(c, load);
2310 }
2311 }
2312 }
2313
2314 /* Return true if you can reach parent going through child->inherits_from
2315 * recursively. If parent or child are NULL, return false */
2316 static bool bdrv_inherits_from_recursive(BlockDriverState *child,
2317 BlockDriverState *parent)
2318 {
2319 while (child && child != parent) {
2320 child = child->inherits_from;
2321 }
2322
2323 return child != NULL;
2324 }
2325
2326 /*
2327 * Sets the backing file link of a BDS. A new reference is created; callers
2328 * which don't need their own reference any more must call bdrv_unref().
2329 */
2330 void bdrv_set_backing_hd(BlockDriverState *bs, BlockDriverState *backing_hd,
2331 Error **errp)
2332 {
2333 bool update_inherits_from = bdrv_chain_contains(bs, backing_hd) &&
2334 bdrv_inherits_from_recursive(backing_hd, bs);
2335
2336 if (backing_hd) {
2337 bdrv_ref(backing_hd);
2338 }
2339
2340 if (bs->backing) {
2341 bdrv_unref_child(bs, bs->backing);
2342 }
2343
2344 if (!backing_hd) {
2345 bs->backing = NULL;
2346 goto out;
2347 }
2348
2349 bs->backing = bdrv_attach_child(bs, backing_hd, "backing", &child_backing,
2350 errp);
2351 /* If backing_hd was already part of bs's backing chain, and
2352 * inherits_from pointed recursively to bs then let's update it to
2353 * point directly to bs (else it will become NULL). */
2354 if (update_inherits_from) {
2355 backing_hd->inherits_from = bs;
2356 }
2357 if (!bs->backing) {
2358 bdrv_unref(backing_hd);
2359 }
2360
2361 out:
2362 bdrv_refresh_limits(bs, NULL);
2363 }
2364
2365 /*
2366 * Opens the backing file for a BlockDriverState if not yet open
2367 *
2368 * bdref_key specifies the key for the image's BlockdevRef in the options QDict.
2369 * That QDict has to be flattened; therefore, if the BlockdevRef is a QDict
2370 * itself, all options starting with "${bdref_key}." are considered part of the
2371 * BlockdevRef.
2372 *
2373 * TODO Can this be unified with bdrv_open_image()?
2374 */
2375 int bdrv_open_backing_file(BlockDriverState *bs, QDict *parent_options,
2376 const char *bdref_key, Error **errp)
2377 {
2378 char *backing_filename = NULL;
2379 char *bdref_key_dot;
2380 const char *reference = NULL;
2381 int ret = 0;
2382 bool implicit_backing = false;
2383 BlockDriverState *backing_hd;
2384 QDict *options;
2385 QDict *tmp_parent_options = NULL;
2386 Error *local_err = NULL;
2387
2388 if (bs->backing != NULL) {
2389 goto free_exit;
2390 }
2391
2392 /* NULL means an empty set of options */
2393 if (parent_options == NULL) {
2394 tmp_parent_options = qdict_new();
2395 parent_options = tmp_parent_options;
2396 }
2397
2398 bs->open_flags &= ~BDRV_O_NO_BACKING;
2399
2400 bdref_key_dot = g_strdup_printf("%s.", bdref_key);
2401 qdict_extract_subqdict(parent_options, &options, bdref_key_dot);
2402 g_free(bdref_key_dot);
2403
2404 /*
2405 * Caution: while qdict_get_try_str() is fine, getting non-string
2406 * types would require more care. When @parent_options come from
2407 * -blockdev or blockdev_add, its members are typed according to
2408 * the QAPI schema, but when they come from -drive, they're all
2409 * QString.
2410 */
2411 reference = qdict_get_try_str(parent_options, bdref_key);
2412 if (reference || qdict_haskey(options, "file.filename")) {
2413 /* keep backing_filename NULL */
2414 } else if (bs->backing_file[0] == '\0' && qdict_size(options) == 0) {
2415 qobject_unref(options);
2416 goto free_exit;
2417 } else {
2418 if (qdict_size(options) == 0) {
2419 /* If the user specifies options that do not modify the
2420 * backing file's behavior, we might still consider it the
2421 * implicit backing file. But it's easier this way, and
2422 * just specifying some of the backing BDS's options is
2423 * only possible with -drive anyway (otherwise the QAPI
2424 * schema forces the user to specify everything). */
2425 implicit_backing = !strcmp(bs->auto_backing_file, bs->backing_file);
2426 }
2427
2428 backing_filename = bdrv_get_full_backing_filename(bs, &local_err);
2429 if (local_err) {
2430 ret = -EINVAL;
2431 error_propagate(errp, local_err);
2432 qobject_unref(options);
2433 goto free_exit;
2434 }
2435 }
2436
2437 if (!bs->drv || !bs->drv->supports_backing) {
2438 ret = -EINVAL;
2439 error_setg(errp, "Driver doesn't support backing files");
2440 qobject_unref(options);
2441 goto free_exit;
2442 }
2443
2444 if (!reference &&
2445 bs->backing_format[0] != '\0' && !qdict_haskey(options, "driver")) {
2446 qdict_put_str(options, "driver", bs->backing_format);
2447 }
2448
2449 backing_hd = bdrv_open_inherit(backing_filename, reference, options, 0, bs,
2450 &child_backing, errp);
2451 if (!backing_hd) {
2452 bs->open_flags |= BDRV_O_NO_BACKING;
2453 error_prepend(errp, "Could not open backing file: ");
2454 ret = -EINVAL;
2455 goto free_exit;
2456 }
2457 bdrv_set_aio_context(backing_hd, bdrv_get_aio_context(bs));
2458
2459 if (implicit_backing) {
2460 bdrv_refresh_filename(backing_hd);
2461 pstrcpy(bs->auto_backing_file, sizeof(bs->auto_backing_file),
2462 backing_hd->filename);
2463 }
2464
2465 /* Hook up the backing file link; drop our reference, bs owns the
2466 * backing_hd reference now */
2467 bdrv_set_backing_hd(bs, backing_hd, &local_err);
2468 bdrv_unref(backing_hd);
2469 if (local_err) {
2470 error_propagate(errp, local_err);
2471 ret = -EINVAL;
2472 goto free_exit;
2473 }
2474
2475 qdict_del(parent_options, bdref_key);
2476
2477 free_exit:
2478 g_free(backing_filename);
2479 qobject_unref(tmp_parent_options);
2480 return ret;
2481 }
2482
2483 static BlockDriverState *
2484 bdrv_open_child_bs(const char *filename, QDict *options, const char *bdref_key,
2485 BlockDriverState *parent, const BdrvChildRole *child_role,
2486 bool allow_none, Error **errp)
2487 {
2488 BlockDriverState *bs = NULL;
2489 QDict *image_options;
2490 char *bdref_key_dot;
2491 const char *reference;
2492
2493 assert(child_role != NULL);
2494
2495 bdref_key_dot = g_strdup_printf("%s.", bdref_key);
2496 qdict_extract_subqdict(options, &image_options, bdref_key_dot);
2497 g_free(bdref_key_dot);
2498
2499 /*
2500 * Caution: while qdict_get_try_str() is fine, getting non-string
2501 * types would require more care. When @options come from
2502 * -blockdev or blockdev_add, its members are typed according to
2503 * the QAPI schema, but when they come from -drive, they're all
2504 * QString.
2505 */
2506 reference = qdict_get_try_str(options, bdref_key);
2507 if (!filename && !reference && !qdict_size(image_options)) {
2508 if (!allow_none) {
2509 error_setg(errp, "A block device must be specified for \"%s\"",
2510 bdref_key);
2511 }
2512 qobject_unref(image_options);
2513 goto done;
2514 }
2515
2516 bs = bdrv_open_inherit(filename, reference, image_options, 0,
2517 parent, child_role, errp);
2518 if (!bs) {
2519 goto done;
2520 }
2521
2522 done:
2523 qdict_del(options, bdref_key);
2524 return bs;
2525 }
2526
2527 /*
2528 * Opens a disk image whose options are given as BlockdevRef in another block
2529 * device's options.
2530 *
2531 * If allow_none is true, no image will be opened if filename is false and no
2532 * BlockdevRef is given. NULL will be returned, but errp remains unset.
2533 *
2534 * bdrev_key specifies the key for the image's BlockdevRef in the options QDict.
2535 * That QDict has to be flattened; therefore, if the BlockdevRef is a QDict
2536 * itself, all options starting with "${bdref_key}." are considered part of the
2537 * BlockdevRef.
2538 *
2539 * The BlockdevRef will be removed from the options QDict.
2540 */
2541 BdrvChild *bdrv_open_child(const char *filename,
2542 QDict *options, const char *bdref_key,
2543 BlockDriverState *parent,
2544 const BdrvChildRole *child_role,
2545 bool allow_none, Error **errp)
2546 {
2547 BdrvChild *c;
2548 BlockDriverState *bs;
2549
2550 bs = bdrv_open_child_bs(filename, options, bdref_key, parent, child_role,
2551 allow_none, errp);
2552 if (bs == NULL) {
2553 return NULL;
2554 }
2555
2556 c = bdrv_attach_child(parent, bs, bdref_key, child_role, errp);
2557 if (!c) {
2558 bdrv_unref(bs);
2559 return NULL;
2560 }
2561
2562 return c;
2563 }
2564
2565 /* TODO Future callers may need to specify parent/child_role in order for
2566 * option inheritance to work. Existing callers use it for the root node. */
2567 BlockDriverState *bdrv_open_blockdev_ref(BlockdevRef *ref, Error **errp)
2568 {
2569 BlockDriverState *bs = NULL;
2570 Error *local_err = NULL;
2571 QObject *obj = NULL;
2572 QDict *qdict = NULL;
2573 const char *reference = NULL;
2574 Visitor *v = NULL;
2575
2576 if (ref->type == QTYPE_QSTRING) {
2577 reference = ref->u.reference;
2578 } else {
2579 BlockdevOptions *options = &ref->u.definition;
2580 assert(ref->type == QTYPE_QDICT);
2581
2582 v = qobject_output_visitor_new(&obj);
2583 visit_type_BlockdevOptions(v, NULL, &options, &local_err);
2584 if (local_err) {
2585 error_propagate(errp, local_err);
2586 goto fail;
2587 }
2588 visit_complete(v, &obj);
2589
2590 qdict = qobject_to(QDict, obj);
2591 qdict_flatten(qdict);
2592
2593 /* bdrv_open_inherit() defaults to the values in bdrv_flags (for
2594 * compatibility with other callers) rather than what we want as the
2595 * real defaults. Apply the defaults here instead. */
2596 qdict_set_default_str(qdict, BDRV_OPT_CACHE_DIRECT, "off");
2597 qdict_set_default_str(qdict, BDRV_OPT_CACHE_NO_FLUSH, "off");
2598 qdict_set_default_str(qdict, BDRV_OPT_READ_ONLY, "off");
2599 qdict_set_default_str(qdict, BDRV_OPT_AUTO_READ_ONLY, "off");
2600
2601 }
2602
2603 bs = bdrv_open_inherit(NULL, reference, qdict, 0, NULL, NULL, errp);
2604 obj = NULL;
2605
2606 fail:
2607 qobject_unref(obj);
2608 visit_free(v);
2609 return bs;
2610 }
2611
2612 static BlockDriverState *bdrv_append_temp_snapshot(BlockDriverState *bs,
2613 int flags,
2614 QDict *snapshot_options,
2615 Error **errp)
2616 {
2617 /* TODO: extra byte is a hack to ensure MAX_PATH space on Windows. */
2618 char *tmp_filename = g_malloc0(PATH_MAX + 1);
2619 int64_t total_size;
2620 QemuOpts *opts = NULL;
2621 BlockDriverState *bs_snapshot = NULL;
2622 Error *local_err = NULL;
2623 int ret;
2624
2625 /* if snapshot, we create a temporary backing file and open it
2626 instead of opening 'filename' directly */
2627
2628 /* Get the required size from the image */
2629 total_size = bdrv_getlength(bs);
2630 if (total_size < 0) {
2631 error_setg_errno(errp, -total_size, "Could not get image size");
2632 goto out;
2633 }
2634
2635 /* Create the temporary image */
2636 ret = get_tmp_filename(tmp_filename, PATH_MAX + 1);
2637 if (ret < 0) {
2638 error_setg_errno(errp, -ret, "Could not get temporary filename");
2639 goto out;
2640 }
2641
2642 opts = qemu_opts_create(bdrv_qcow2.create_opts, NULL, 0,
2643 &error_abort);
2644 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, total_size, &error_abort);
2645 ret = bdrv_create(&bdrv_qcow2, tmp_filename, opts, errp);
2646 qemu_opts_del(opts);
2647 if (ret < 0) {
2648 error_prepend(errp, "Could not create temporary overlay '%s': ",
2649 tmp_filename);
2650 goto out;
2651 }
2652
2653 /* Prepare options QDict for the temporary file */
2654 qdict_put_str(snapshot_options, "file.driver", "file");
2655 qdict_put_str(snapshot_options, "file.filename", tmp_filename);
2656 qdict_put_str(snapshot_options, "driver", "qcow2");
2657
2658 bs_snapshot = bdrv_open(NULL, NULL, snapshot_options, flags, errp);
2659 snapshot_options = NULL;
2660 if (!bs_snapshot) {
2661 goto out;
2662 }
2663
2664 /* bdrv_append() consumes a strong reference to bs_snapshot
2665 * (i.e. it will call bdrv_unref() on it) even on error, so in
2666 * order to be able to return one, we have to increase
2667 * bs_snapshot's refcount here */
2668 bdrv_ref(bs_snapshot);
2669 bdrv_append(bs_snapshot, bs, &local_err);
2670 if (local_err) {
2671 error_propagate(errp, local_err);
2672 bs_snapshot = NULL;
2673 goto out;
2674 }
2675
2676 out:
2677 qobject_unref(snapshot_options);
2678 g_free(tmp_filename);
2679 return bs_snapshot;
2680 }
2681
2682 /*
2683 * Opens a disk image (raw, qcow2, vmdk, ...)
2684 *
2685 * options is a QDict of options to pass to the block drivers, or NULL for an
2686 * empty set of options. The reference to the QDict belongs to the block layer
2687 * after the call (even on failure), so if the caller intends to reuse the
2688 * dictionary, it needs to use qobject_ref() before calling bdrv_open.
2689 *
2690 * If *pbs is NULL, a new BDS will be created with a pointer to it stored there.
2691 * If it is not NULL, the referenced BDS will be reused.
2692 *
2693 * The reference parameter may be used to specify an existing block device which
2694 * should be opened. If specified, neither options nor a filename may be given,
2695 * nor can an existing BDS be reused (that is, *pbs has to be NULL).
2696 */
2697 static BlockDriverState *bdrv_open_inherit(const char *filename,
2698 const char *reference,
2699 QDict *options, int flags,
2700 BlockDriverState *parent,
2701 const BdrvChildRole *child_role,
2702 Error **errp)
2703 {
2704 int ret;
2705 BlockBackend *file = NULL;
2706 BlockDriverState *bs;
2707 BlockDriver *drv = NULL;
2708 BdrvChild *child;
2709 const char *drvname;
2710 const char *backing;
2711 Error *local_err = NULL;
2712 QDict *snapshot_options = NULL;
2713 int snapshot_flags = 0;
2714
2715 assert(!child_role || !flags);
2716 assert(!child_role == !parent);
2717
2718 if (reference) {
2719 bool options_non_empty = options ? qdict_size(options) : false;
2720 qobject_unref(options);
2721
2722 if (filename || options_non_empty) {
2723 error_setg(errp, "Cannot reference an existing block device with "
2724 "additional options or a new filename");
2725 return NULL;
2726 }
2727
2728 bs = bdrv_lookup_bs(reference, reference, errp);
2729 if (!bs) {
2730 return NULL;
2731 }
2732
2733 bdrv_ref(bs);
2734 return bs;
2735 }
2736
2737 bs = bdrv_new();
2738
2739 /* NULL means an empty set of options */
2740 if (options == NULL) {
2741 options = qdict_new();
2742 }
2743
2744 /* json: syntax counts as explicit options, as if in the QDict */
2745 parse_json_protocol(options, &filename, &local_err);
2746 if (local_err) {
2747 goto fail;
2748 }
2749
2750 bs->explicit_options = qdict_clone_shallow(options);
2751
2752 if (child_role) {
2753 bs->inherits_from = parent;
2754 child_role->inherit_options(&flags, options,
2755 parent->open_flags, parent->options);
2756 }
2757
2758 ret = bdrv_fill_options(&options, filename, &flags, &local_err);
2759 if (local_err) {
2760 goto fail;
2761 }
2762
2763 /*
2764 * Set the BDRV_O_RDWR and BDRV_O_ALLOW_RDWR flags.
2765 * Caution: getting a boolean member of @options requires care.
2766 * When @options come from -blockdev or blockdev_add, members are
2767 * typed according to the QAPI schema, but when they come from
2768 * -drive, they're all QString.
2769 */
2770 if (g_strcmp0(qdict_get_try_str(options, BDRV_OPT_READ_ONLY), "on") &&
2771 !qdict_get_try_bool(options, BDRV_OPT_READ_ONLY, false)) {
2772 flags |= (BDRV_O_RDWR | BDRV_O_ALLOW_RDWR);
2773 } else {
2774 flags &= ~BDRV_O_RDWR;
2775 }
2776
2777 if (flags & BDRV_O_SNAPSHOT) {
2778 snapshot_options = qdict_new();
2779 bdrv_temp_snapshot_options(&snapshot_flags, snapshot_options,
2780 flags, options);
2781 /* Let bdrv_backing_options() override "read-only" */
2782 qdict_del(options, BDRV_OPT_READ_ONLY);
2783 bdrv_backing_options(&flags, options, flags, options);
2784 }
2785
2786 bs->open_flags = flags;
2787 bs->options = options;
2788 options = qdict_clone_shallow(options);
2789
2790 /* Find the right image format driver */
2791 /* See cautionary note on accessing @options above */
2792 drvname = qdict_get_try_str(options, "driver");
2793 if (drvname) {
2794 drv = bdrv_find_format(drvname);
2795 if (!drv) {
2796 error_setg(errp, "Unknown driver: '%s'", drvname);
2797 goto fail;
2798 }
2799 }
2800
2801 assert(drvname || !(flags & BDRV_O_PROTOCOL));
2802
2803 /* See cautionary note on accessing @options above */
2804 backing = qdict_get_try_str(options, "backing");
2805 if (qobject_to(QNull, qdict_get(options, "backing")) != NULL ||
2806 (backing && *backing == '\0'))
2807 {
2808 if (backing) {
2809 warn_report("Use of \"backing\": \"\" is deprecated; "
2810 "use \"backing\": null instead");
2811 }
2812 flags |= BDRV_O_NO_BACKING;
2813 qdict_del(options, "backing");
2814 }
2815
2816 /* Open image file without format layer. This BlockBackend is only used for
2817 * probing, the block drivers will do their own bdrv_open_child() for the
2818 * same BDS, which is why we put the node name back into options. */
2819 if ((flags & BDRV_O_PROTOCOL) == 0) {
2820 BlockDriverState *file_bs;
2821
2822 file_bs = bdrv_open_child_bs(filename, options, "file", bs,
2823 &child_file, true, &local_err);
2824 if (local_err) {
2825 goto fail;
2826 }
2827 if (file_bs != NULL) {
2828 /* Not requesting BLK_PERM_CONSISTENT_READ because we're only
2829 * looking at the header to guess the image format. This works even
2830 * in cases where a guest would not see a consistent state. */
2831 file = blk_new(0, BLK_PERM_ALL);
2832 blk_insert_bs(file, file_bs, &local_err);
2833 bdrv_unref(file_bs);
2834 if (local_err) {
2835 goto fail;
2836 }
2837
2838 qdict_put_str(options, "file", bdrv_get_node_name(file_bs));
2839 }
2840 }
2841
2842 /* Image format probing */
2843 bs->probed = !drv;
2844 if (!drv && file) {
2845 ret = find_image_format(file, filename, &drv, &local_err);
2846 if (ret < 0) {
2847 goto fail;
2848 }
2849 /*
2850 * This option update would logically belong in bdrv_fill_options(),
2851 * but we first need to open bs->file for the probing to work, while
2852 * opening bs->file already requires the (mostly) final set of options
2853 * so that cache mode etc. can be inherited.
2854 *
2855 * Adding the driver later is somewhat ugly, but it's not an option
2856 * that would ever be inherited, so it's correct. We just need to make
2857 * sure to update both bs->options (which has the full effective
2858 * options for bs) and options (which has file.* already removed).
2859 */
2860 qdict_put_str(bs->options, "driver", drv->format_name);
2861 qdict_put_str(options, "driver", drv->format_name);
2862 } else if (!drv) {
2863 error_setg(errp, "Must specify either driver or file");
2864 goto fail;
2865 }
2866
2867 /* BDRV_O_PROTOCOL must be set iff a protocol BDS is about to be created */
2868 assert(!!(flags & BDRV_O_PROTOCOL) == !!drv->bdrv_file_open);
2869 /* file must be NULL if a protocol BDS is about to be created
2870 * (the inverse results in an error message from bdrv_open_common()) */
2871 assert(!(flags & BDRV_O_PROTOCOL) || !file);
2872
2873 /* Open the image */
2874 ret = bdrv_open_common(bs, file, options, &local_err);
2875 if (ret < 0) {
2876 goto fail;
2877 }
2878
2879 if (file) {
2880 blk_unref(file);
2881 file = NULL;
2882 }
2883
2884 /* If there is a backing file, use it */
2885 if ((flags & BDRV_O_NO_BACKING) == 0) {
2886 ret = bdrv_open_backing_file(bs, options, "backing", &local_err);
2887 if (ret < 0) {
2888 goto close_and_fail;
2889 }
2890 }
2891
2892 /* Remove all children options and references
2893 * from bs->options and bs->explicit_options */
2894 QLIST_FOREACH(child, &bs->children, next) {
2895 char *child_key_dot;
2896 child_key_dot = g_strdup_printf("%s.", child->name);
2897 qdict_extract_subqdict(bs->explicit_options, NULL, child_key_dot);
2898 qdict_extract_subqdict(bs->options, NULL, child_key_dot);
2899 qdict_del(bs->explicit_options, child->name);
2900 qdict_del(bs->options, child->name);
2901 g_free(child_key_dot);
2902 }
2903
2904 /* Check if any unknown options were used */
2905 if (qdict_size(options) != 0) {
2906 const QDictEntry *entry = qdict_first(options);
2907 if (flags & BDRV_O_PROTOCOL) {
2908 error_setg(errp, "Block protocol '%s' doesn't support the option "
2909 "'%s'", drv->format_name, entry->key);
2910 } else {
2911 error_setg(errp,
2912 "Block format '%s' does not support the option '%s'",
2913 drv->format_name, entry->key);
2914 }
2915
2916 goto close_and_fail;
2917 }
2918
2919 bdrv_parent_cb_change_media(bs, true);
2920
2921 qobject_unref(options);
2922 options = NULL;
2923
2924 /* For snapshot=on, create a temporary qcow2 overlay. bs points to the
2925 * temporary snapshot afterwards. */
2926 if (snapshot_flags) {
2927 BlockDriverState *snapshot_bs;
2928 snapshot_bs = bdrv_append_temp_snapshot(bs, snapshot_flags,
2929 snapshot_options, &local_err);
2930 snapshot_options = NULL;
2931 if (local_err) {
2932 goto close_and_fail;
2933 }
2934 /* We are not going to return bs but the overlay on top of it
2935 * (snapshot_bs); thus, we have to drop the strong reference to bs
2936 * (which we obtained by calling bdrv_new()). bs will not be deleted,
2937 * though, because the overlay still has a reference to it. */
2938 bdrv_unref(bs);
2939 bs = snapshot_bs;
2940 }
2941
2942 return bs;
2943
2944 fail:
2945 blk_unref(file);
2946 qobject_unref(snapshot_options);
2947 qobject_unref(bs->explicit_options);
2948 qobject_unref(bs->options);
2949 qobject_unref(options);
2950 bs->options = NULL;
2951 bs->explicit_options = NULL;
2952 bdrv_unref(bs);
2953 error_propagate(errp, local_err);
2954 return NULL;
2955
2956 close_and_fail:
2957 bdrv_unref(bs);
2958 qobject_unref(snapshot_options);
2959 qobject_unref(options);
2960 error_propagate(errp, local_err);
2961 return NULL;
2962 }
2963
2964 BlockDriverState *bdrv_open(const char *filename, const char *reference,
2965 QDict *options, int flags, Error **errp)
2966 {
2967 return bdrv_open_inherit(filename, reference, options, flags, NULL,
2968 NULL, errp);
2969 }
2970
2971 /*
2972 * Adds a BlockDriverState to a simple queue for an atomic, transactional
2973 * reopen of multiple devices.
2974 *
2975 * bs_queue can either be an existing BlockReopenQueue that has had QSIMPLE_INIT
2976 * already performed, or alternatively may be NULL a new BlockReopenQueue will
2977 * be created and initialized. This newly created BlockReopenQueue should be
2978 * passed back in for subsequent calls that are intended to be of the same
2979 * atomic 'set'.
2980 *
2981 * bs is the BlockDriverState to add to the reopen queue.
2982 *
2983 * options contains the changed options for the associated bs
2984 * (the BlockReopenQueue takes ownership)
2985 *
2986 * flags contains the open flags for the associated bs
2987 *
2988 * returns a pointer to bs_queue, which is either the newly allocated
2989 * bs_queue, or the existing bs_queue being used.
2990 *
2991 * bs must be drained between bdrv_reopen_queue() and bdrv_reopen_multiple().
2992 */
2993 static BlockReopenQueue *bdrv_reopen_queue_child(BlockReopenQueue *bs_queue,
2994 BlockDriverState *bs,
2995 QDict *options,
2996 const BdrvChildRole *role,
2997 QDict *parent_options,
2998 int parent_flags)
2999 {
3000 assert(bs != NULL);
3001
3002 BlockReopenQueueEntry *bs_entry;
3003 BdrvChild *child;
3004 QDict *old_options, *explicit_options, *options_copy;
3005 int flags;
3006 QemuOpts *opts;
3007
3008 /* Make sure that the caller remembered to use a drained section. This is
3009 * important to avoid graph changes between the recursive queuing here and
3010 * bdrv_reopen_multiple(). */
3011 assert(bs->quiesce_counter > 0);
3012
3013 if (bs_queue == NULL) {
3014 bs_queue = g_new0(BlockReopenQueue, 1);
3015 QSIMPLEQ_INIT(bs_queue);
3016 }
3017
3018 if (!options) {
3019 options = qdict_new();
3020 }
3021
3022 /* Check if this BlockDriverState is already in the queue */
3023 QSIMPLEQ_FOREACH(bs_entry, bs_queue, entry) {
3024 if (bs == bs_entry->state.bs) {
3025 break;
3026 }
3027 }
3028
3029 /*
3030 * Precedence of options:
3031 * 1. Explicitly passed in options (highest)
3032 * 2. Retained from explicitly set options of bs
3033 * 3. Inherited from parent node
3034 * 4. Retained from effective options of bs
3035 */
3036
3037 /* Old explicitly set values (don't overwrite by inherited value) */
3038 if (bs_entry) {
3039 old_options = qdict_clone_shallow(bs_entry->state.explicit_options);
3040 } else {
3041 old_options = qdict_clone_shallow(bs->explicit_options);
3042 }
3043 bdrv_join_options(bs, options, old_options);
3044 qobject_unref(old_options);
3045
3046 explicit_options = qdict_clone_shallow(options);
3047
3048 /* Inherit from parent node */
3049 if (parent_options) {
3050 flags = 0;
3051 role->inherit_options(&flags, options, parent_flags, parent_options);
3052 } else {
3053 flags = bdrv_get_flags(bs);
3054 }
3055
3056 /* Old values are used for options that aren't set yet */
3057 old_options = qdict_clone_shallow(bs->options);
3058 bdrv_join_options(bs, options, old_options);
3059 qobject_unref(old_options);
3060
3061 /* We have the final set of options so let's update the flags */
3062 options_copy = qdict_clone_shallow(options);
3063 opts = qemu_opts_create(&bdrv_runtime_opts, NULL, 0, &error_abort);
3064 qemu_opts_absorb_qdict(opts, options_copy, NULL);
3065 update_flags_from_options(&flags, opts);
3066 qemu_opts_del(opts);
3067 qobject_unref(options_copy);
3068
3069 /* bdrv_open_inherit() sets and clears some additional flags internally */
3070 flags &= ~BDRV_O_PROTOCOL;
3071 if (flags & BDRV_O_RDWR) {
3072 flags |= BDRV_O_ALLOW_RDWR;
3073 }
3074
3075 if (!bs_entry) {
3076 bs_entry = g_new0(BlockReopenQueueEntry, 1);
3077 QSIMPLEQ_INSERT_TAIL(bs_queue, bs_entry, entry);
3078 } else {
3079 qobject_unref(bs_entry->state.options);
3080 qobject_unref(bs_entry->state.explicit_options);
3081 }
3082
3083 bs_entry->state.bs = bs;
3084 bs_entry->state.options = options;
3085 bs_entry->state.explicit_options = explicit_options;
3086 bs_entry->state.flags = flags;
3087
3088 /* This needs to be overwritten in bdrv_reopen_prepare() */
3089 bs_entry->state.perm = UINT64_MAX;
3090 bs_entry->state.shared_perm = 0;
3091
3092 QLIST_FOREACH(child, &bs->children, next) {
3093 QDict *new_child_options;
3094 char *child_key_dot;
3095
3096 /* reopen can only change the options of block devices that were
3097 * implicitly created and inherited options. For other (referenced)
3098 * block devices, a syntax like "backing.foo" results in an error. */
3099 if (child->bs->inherits_from != bs) {
3100 continue;
3101 }
3102
3103 child_key_dot = g_strdup_printf("%s.", child->name);
3104 qdict_extract_subqdict(explicit_options, NULL, child_key_dot);
3105 qdict_extract_subqdict(options, &new_child_options, child_key_dot);
3106 g_free(child_key_dot);
3107
3108 bdrv_reopen_queue_child(bs_queue, child->bs, new_child_options,
3109 child->role, options, flags);
3110 }
3111
3112 return bs_queue;
3113 }
3114
3115 BlockReopenQueue *bdrv_reopen_queue(BlockReopenQueue *bs_queue,
3116 BlockDriverState *bs,
3117 QDict *options)
3118 {
3119 return bdrv_reopen_queue_child(bs_queue, bs, options, NULL, NULL, 0);
3120 }
3121
3122 /*
3123 * Reopen multiple BlockDriverStates atomically & transactionally.
3124 *
3125 * The queue passed in (bs_queue) must have been built up previous
3126 * via bdrv_reopen_queue().
3127 *
3128 * Reopens all BDS specified in the queue, with the appropriate
3129 * flags. All devices are prepared for reopen, and failure of any
3130 * device will cause all device changes to be abandoned, and intermediate
3131 * data cleaned up.
3132 *
3133 * If all devices prepare successfully, then the changes are committed
3134 * to all devices.
3135 *
3136 * All affected nodes must be drained between bdrv_reopen_queue() and
3137 * bdrv_reopen_multiple().
3138 */
3139 int bdrv_reopen_multiple(AioContext *ctx, BlockReopenQueue *bs_queue, Error **errp)
3140 {
3141 int ret = -1;
3142 BlockReopenQueueEntry *bs_entry, *next;
3143 Error *local_err = NULL;
3144
3145 assert(bs_queue != NULL);
3146
3147 QSIMPLEQ_FOREACH(bs_entry, bs_queue, entry) {
3148 assert(bs_entry->state.bs->quiesce_counter > 0);
3149 if (bdrv_reopen_prepare(&bs_entry->state, bs_queue, &local_err)) {
3150 error_propagate(errp, local_err);
3151 goto cleanup;
3152 }
3153 bs_entry->prepared = true;
3154 }
3155
3156 /* If we reach this point, we have success and just need to apply the
3157 * changes
3158 */
3159 QSIMPLEQ_FOREACH(bs_entry, bs_queue, entry) {
3160 bdrv_reopen_commit(&bs_entry->state);
3161 }
3162
3163 ret = 0;
3164
3165 cleanup:
3166 QSIMPLEQ_FOREACH_SAFE(bs_entry, bs_queue, entry, next) {
3167 if (ret) {
3168 if (bs_entry->prepared) {
3169 bdrv_reopen_abort(&bs_entry->state);
3170 }
3171 qobject_unref(bs_entry->state.explicit_options);
3172 qobject_unref(bs_entry->state.options);
3173 }
3174 g_free(bs_entry);
3175 }
3176 g_free(bs_queue);
3177
3178 return ret;
3179 }
3180
3181 int bdrv_reopen_set_read_only(BlockDriverState *bs, bool read_only,
3182 Error **errp)
3183 {
3184 int ret;
3185 BlockReopenQueue *queue;
3186 QDict *opts = qdict_new();
3187
3188 qdict_put_bool(opts, BDRV_OPT_READ_ONLY, read_only);
3189
3190 bdrv_subtree_drained_begin(bs);
3191 queue = bdrv_reopen_queue(NULL, bs, opts);
3192 ret = bdrv_reopen_multiple(bdrv_get_aio_context(bs), queue, errp);
3193 bdrv_subtree_drained_end(bs);
3194
3195 return ret;
3196 }
3197
3198 static BlockReopenQueueEntry *find_parent_in_reopen_queue(BlockReopenQueue *q,
3199 BdrvChild *c)
3200 {
3201 BlockReopenQueueEntry *entry;
3202
3203 QSIMPLEQ_FOREACH(entry, q, entry) {
3204 BlockDriverState *bs = entry->state.bs;
3205 BdrvChild *child;
3206
3207 QLIST_FOREACH(child, &bs->children, next) {
3208 if (child == c) {
3209 return entry;
3210 }
3211 }
3212 }
3213
3214 return NULL;
3215 }
3216
3217 static void bdrv_reopen_perm(BlockReopenQueue *q, BlockDriverState *bs,
3218 uint64_t *perm, uint64_t *shared)
3219 {
3220 BdrvChild *c;
3221 BlockReopenQueueEntry *parent;
3222 uint64_t cumulative_perms = 0;
3223 uint64_t cumulative_shared_perms = BLK_PERM_ALL;
3224
3225 QLIST_FOREACH(c, &bs->parents, next_parent) {
3226 parent = find_parent_in_reopen_queue(q, c);
3227 if (!parent) {
3228 cumulative_perms |= c->perm;
3229 cumulative_shared_perms &= c->shared_perm;
3230 } else {
3231 uint64_t nperm, nshared;
3232
3233 bdrv_child_perm(parent->state.bs, bs, c, c->role, q,
3234 parent->state.perm, parent->state.shared_perm,
3235 &nperm, &nshared);
3236
3237 cumulative_perms |= nperm;
3238 cumulative_shared_perms &= nshared;
3239 }
3240 }
3241 *perm = cumulative_perms;
3242 *shared = cumulative_shared_perms;
3243 }
3244
3245 /*
3246 * Prepares a BlockDriverState for reopen. All changes are staged in the
3247 * 'opaque' field of the BDRVReopenState, which is used and allocated by
3248 * the block driver layer .bdrv_reopen_prepare()
3249 *
3250 * bs is the BlockDriverState to reopen
3251 * flags are the new open flags
3252 * queue is the reopen queue
3253 *
3254 * Returns 0 on success, non-zero on error. On error errp will be set
3255 * as well.
3256 *
3257 * On failure, bdrv_reopen_abort() will be called to clean up any data.
3258 * It is the responsibility of the caller to then call the abort() or
3259 * commit() for any other BDS that have been left in a prepare() state
3260 *
3261 */
3262 int bdrv_reopen_prepare(BDRVReopenState *reopen_state, BlockReopenQueue *queue,
3263 Error **errp)
3264 {
3265 int ret = -1;
3266 int old_flags;
3267 Error *local_err = NULL;
3268 BlockDriver *drv;
3269 QemuOpts *opts;
3270 QDict *orig_reopen_opts;
3271 char *discard = NULL;
3272 bool read_only;
3273 bool drv_prepared = false;
3274
3275 assert(reopen_state != NULL);
3276 assert(reopen_state->bs->drv != NULL);
3277 drv = reopen_state->bs->drv;
3278
3279 /* This function and each driver's bdrv_reopen_prepare() remove
3280 * entries from reopen_state->options as they are processed, so
3281 * we need to make a copy of the original QDict. */
3282 orig_reopen_opts = qdict_clone_shallow(reopen_state->options);
3283
3284 /* Process generic block layer options */
3285 opts = qemu_opts_create(&bdrv_runtime_opts, NULL, 0, &error_abort);
3286 qemu_opts_absorb_qdict(opts, reopen_state->options, &local_err);
3287 if (local_err) {
3288 error_propagate(errp, local_err);
3289 ret = -EINVAL;
3290 goto error;
3291 }
3292
3293 /* This was already called in bdrv_reopen_queue_child() so the flags
3294 * are up-to-date. This time we simply want to remove the options from
3295 * QemuOpts in order to indicate that they have been processed. */
3296 old_flags = reopen_state->flags;
3297 update_flags_from_options(&reopen_state->flags, opts);
3298 assert(old_flags == reopen_state->flags);
3299
3300 discard = qemu_opt_get_del(opts, BDRV_OPT_DISCARD);
3301 if (discard != NULL) {
3302 if (bdrv_parse_discard_flags(discard, &reopen_state->flags) != 0) {
3303 error_setg(errp, "Invalid discard option");
3304 ret = -EINVAL;
3305 goto error;
3306 }
3307 }
3308
3309 reopen_state->detect_zeroes =
3310 bdrv_parse_detect_zeroes(opts, reopen_state->flags, &local_err);
3311 if (local_err) {
3312 error_propagate(errp, local_err);
3313 ret = -EINVAL;
3314 goto error;
3315 }
3316
3317 /* All other options (including node-name and driver) must be unchanged.
3318 * Put them back into the QDict, so that they are checked at the end
3319 * of this function. */
3320 qemu_opts_to_qdict(opts, reopen_state->options);
3321
3322 /* If we are to stay read-only, do not allow permission change
3323 * to r/w. Attempting to set to r/w may fail if either BDRV_O_ALLOW_RDWR is
3324 * not set, or if the BDS still has copy_on_read enabled */
3325 read_only = !(reopen_state->flags & BDRV_O_RDWR);
3326 ret = bdrv_can_set_read_only(reopen_state->bs, read_only, true, &local_err);
3327 if (local_err) {
3328 error_propagate(errp, local_err);
3329 goto error;
3330 }
3331
3332 /* Calculate required permissions after reopening */
3333 bdrv_reopen_perm(queue, reopen_state->bs,
3334 &reopen_state->perm, &reopen_state->shared_perm);
3335
3336 ret = bdrv_flush(reopen_state->bs);
3337 if (ret) {
3338 error_setg_errno(errp, -ret, "Error flushing drive");
3339 goto error;
3340 }
3341
3342 if (drv->bdrv_reopen_prepare) {
3343 ret = drv->bdrv_reopen_prepare(reopen_state, queue, &local_err);
3344 if (ret) {
3345 if (local_err != NULL) {
3346 error_propagate(errp, local_err);
3347 } else {
3348 bdrv_refresh_filename(reopen_state->bs);
3349 error_setg(errp, "failed while preparing to reopen image '%s'",
3350 reopen_state->bs->filename);
3351 }
3352 goto error;
3353 }
3354 } else {
3355 /* It is currently mandatory to have a bdrv_reopen_prepare()
3356 * handler for each supported drv. */
3357 error_setg(errp, "Block format '%s' used by node '%s' "
3358 "does not support reopening files", drv->format_name,
3359 bdrv_get_device_or_node_name(reopen_state->bs));
3360 ret = -1;
3361 goto error;
3362 }
3363
3364 drv_prepared = true;
3365
3366 /* Options that are not handled are only okay if they are unchanged
3367 * compared to the old state. It is expected that some options are only
3368 * used for the initial open, but not reopen (e.g. filename) */
3369 if (qdict_size(reopen_state->options)) {
3370 const QDictEntry *entry = qdict_first(reopen_state->options);
3371
3372 do {
3373 QObject *new = entry->value;
3374 QObject *old = qdict_get(reopen_state->bs->options, entry->key);
3375
3376 /* Allow child references (child_name=node_name) as long as they
3377 * point to the current child (i.e. everything stays the same). */
3378 if (qobject_type(new) == QTYPE_QSTRING) {
3379 BdrvChild *child;
3380 QLIST_FOREACH(child, &reopen_state->bs->children, next) {
3381 if (!strcmp(child->name, entry->key)) {
3382 break;
3383 }
3384 }
3385
3386 if (child) {
3387 const char *str = qobject_get_try_str(new);
3388 if (!strcmp(child->bs->node_name, str)) {
3389 continue; /* Found child with this name, skip option */
3390 }
3391 }
3392 }
3393
3394 /*
3395 * TODO: When using -drive to specify blockdev options, all values
3396 * will be strings; however, when using -blockdev, blockdev-add or
3397 * filenames using the json:{} pseudo-protocol, they will be
3398 * correctly typed.
3399 * In contrast, reopening options are (currently) always strings
3400 * (because you can only specify them through qemu-io; all other
3401 * callers do not specify any options).
3402 * Therefore, when using anything other than -drive to create a BDS,
3403 * this cannot detect non-string options as unchanged, because
3404 * qobject_is_equal() always returns false for objects of different
3405 * type. In the future, this should be remedied by correctly typing
3406 * all options. For now, this is not too big of an issue because
3407 * the user can simply omit options which cannot be changed anyway,
3408 * so they will stay unchanged.
3409 */
3410 if (!qobject_is_equal(new, old)) {
3411 error_setg(errp, "Cannot change the option '%s'", entry->key);
3412 ret = -EINVAL;
3413 goto error;
3414 }
3415 } while ((entry = qdict_next(reopen_state->options, entry)));
3416 }
3417
3418 ret = bdrv_check_perm(reopen_state->bs, queue, reopen_state->perm,
3419 reopen_state->shared_perm, NULL, errp);
3420 if (ret < 0) {
3421 goto error;
3422 }
3423
3424 ret = 0;
3425
3426 /* Restore the original reopen_state->options QDict */
3427 qobject_unref(reopen_state->options);
3428 reopen_state->options = qobject_ref(orig_reopen_opts);
3429
3430 error:
3431 if (ret < 0 && drv_prepared) {
3432 /* drv->bdrv_reopen_prepare() has succeeded, so we need to
3433 * call drv->bdrv_reopen_abort() before signaling an error
3434 * (bdrv_reopen_multiple() will not call bdrv_reopen_abort()
3435 * when the respective bdrv_reopen_prepare() has failed) */
3436 if (drv->bdrv_reopen_abort) {
3437 drv->bdrv_reopen_abort(reopen_state);
3438 }
3439 }
3440 qemu_opts_del(opts);
3441 qobject_unref(orig_reopen_opts);
3442 g_free(discard);
3443 return ret;
3444 }
3445
3446 /*
3447 * Takes the staged changes for the reopen from bdrv_reopen_prepare(), and
3448 * makes them final by swapping the staging BlockDriverState contents into
3449 * the active BlockDriverState contents.
3450 */
3451 void bdrv_reopen_commit(BDRVReopenState *reopen_state)
3452 {
3453 BlockDriver *drv;
3454 BlockDriverState *bs;
3455 BdrvChild *child;
3456 bool old_can_write, new_can_write;
3457
3458 assert(reopen_state != NULL);
3459 bs = reopen_state->bs;
3460 drv = bs->drv;
3461 assert(drv != NULL);
3462
3463 old_can_write =
3464 !bdrv_is_read_only(bs) && !(bdrv_get_flags(bs) & BDRV_O_INACTIVE);
3465
3466 /* If there are any driver level actions to take */
3467 if (drv->bdrv_reopen_commit) {
3468 drv->bdrv_reopen_commit(reopen_state);
3469 }
3470
3471 /* set BDS specific flags now */
3472 qobject_unref(bs->explicit_options);
3473 qobject_unref(bs->options);
3474
3475 bs->explicit_options = reopen_state->explicit_options;
3476 bs->options = reopen_state->options;
3477 bs->open_flags = reopen_state->flags;
3478 bs->read_only = !(reopen_state->flags & BDRV_O_RDWR);
3479 bs->detect_zeroes = reopen_state->detect_zeroes;
3480
3481 /* Remove child references from bs->options and bs->explicit_options.
3482 * Child options were already removed in bdrv_reopen_queue_child() */
3483 QLIST_FOREACH(child, &bs->children, next) {
3484 qdict_del(bs->explicit_options, child->name);
3485 qdict_del(bs->options, child->name);
3486 }
3487
3488 bdrv_refresh_limits(bs, NULL);
3489
3490 bdrv_set_perm(reopen_state->bs, reopen_state->perm,
3491 reopen_state->shared_perm);
3492
3493 new_can_write =
3494 !bdrv_is_read_only(bs) && !(bdrv_get_flags(bs) & BDRV_O_INACTIVE);
3495 if (!old_can_write && new_can_write && drv->bdrv_reopen_bitmaps_rw) {
3496 Error *local_err = NULL;
3497 if (drv->bdrv_reopen_bitmaps_rw(bs, &local_err) < 0) {
3498 /* This is not fatal, bitmaps just left read-only, so all following
3499 * writes will fail. User can remove read-only bitmaps to unblock
3500 * writes.
3501 */
3502 error_reportf_err(local_err,
3503 "%s: Failed to make dirty bitmaps writable: ",
3504 bdrv_get_node_name(bs));
3505 }
3506 }
3507 }
3508
3509 /*
3510 * Abort the reopen, and delete and free the staged changes in
3511 * reopen_state
3512 */
3513 void bdrv_reopen_abort(BDRVReopenState *reopen_state)
3514 {
3515 BlockDriver *drv;
3516
3517 assert(reopen_state != NULL);
3518 drv = reopen_state->bs->drv;
3519 assert(drv != NULL);
3520
3521 if (drv->bdrv_reopen_abort) {
3522 drv->bdrv_reopen_abort(reopen_state);
3523 }
3524
3525 bdrv_abort_perm_update(reopen_state->bs);
3526 }
3527
3528
3529 static void bdrv_close(BlockDriverState *bs)
3530 {
3531 BdrvAioNotifier *ban, *ban_next;
3532 BdrvChild *child, *next;
3533
3534 assert(!bs->job);
3535 assert(!bs->refcnt);
3536
3537 bdrv_drained_begin(bs); /* complete I/O */
3538 bdrv_flush(bs);
3539 bdrv_drain(bs); /* in case flush left pending I/O */
3540
3541 if (bs->drv) {
3542 if (bs->drv->bdrv_close) {
3543 bs->drv->bdrv_close(bs);
3544 }
3545 bs->drv = NULL;
3546 }
3547
3548 bdrv_set_backing_hd(bs, NULL, &error_abort);
3549
3550 if (bs->file != NULL) {
3551 bdrv_unref_child(bs, bs->file);
3552 bs->file = NULL;
3553 }
3554
3555 QLIST_FOREACH_SAFE(child, &bs->children, next, next) {
3556 /* TODO Remove bdrv_unref() from drivers' close function and use
3557 * bdrv_unref_child() here */
3558 if (child->bs->inherits_from == bs) {
3559 child->bs->inherits_from = NULL;
3560 }
3561 bdrv_detach_child(child);
3562 }
3563
3564 g_free(bs->opaque);
3565 bs->opaque = NULL;
3566 atomic_set(&bs->copy_on_read, 0);
3567 bs->backing_file[0] = '\0';
3568 bs->backing_format[0] = '\0';
3569 bs->total_sectors = 0;
3570 bs->encrypted = false;
3571 bs->sg = false;
3572 qobject_unref(bs->options);
3573 qobject_unref(bs->explicit_options);
3574 bs->options = NULL;
3575 bs->explicit_options = NULL;
3576 qobject_unref(bs->full_open_options);
3577 bs->full_open_options = NULL;
3578
3579 bdrv_release_named_dirty_bitmaps(bs);
3580 assert(QLIST_EMPTY(&bs->dirty_bitmaps));
3581
3582 QLIST_FOREACH_SAFE(ban, &bs->aio_notifiers, list, ban_next) {
3583 g_free(ban);
3584 }
3585 QLIST_INIT(&bs->aio_notifiers);
3586 bdrv_drained_end(bs);
3587 }
3588
3589 void bdrv_close_all(void)
3590 {
3591 assert(job_next(NULL) == NULL);
3592 nbd_export_close_all();
3593
3594 /* Drop references from requests still in flight, such as canceled block
3595 * jobs whose AIO context has not been polled yet */
3596 bdrv_drain_all();
3597
3598 blk_remove_all_bs();
3599 blockdev_close_all_bdrv_states();
3600
3601 assert(QTAILQ_EMPTY(&all_bdrv_states));
3602 }
3603
3604 static bool should_update_child(BdrvChild *c, BlockDriverState *to)
3605 {
3606 GQueue *queue;
3607 GHashTable *found;
3608 bool ret;
3609
3610 if (c->role->stay_at_node) {
3611 return false;
3612 }
3613
3614 /* If the child @c belongs to the BDS @to, replacing the current
3615 * c->bs by @to would mean to create a loop.
3616 *
3617 * Such a case occurs when appending a BDS to a backing chain.
3618 * For instance, imagine the following chain:
3619 *
3620 * guest device -> node A -> further backing chain...
3621 *
3622 * Now we create a new BDS B which we want to put on top of this
3623 * chain, so we first attach A as its backing node:
3624 *
3625 * node B
3626 * |
3627 * v
3628 * guest device -> node A -> further backing chain...
3629 *
3630 * Finally we want to replace A by B. When doing that, we want to
3631 * replace all pointers to A by pointers to B -- except for the
3632 * pointer from B because (1) that would create a loop, and (2)
3633 * that pointer should simply stay intact:
3634 *
3635 * guest device -> node B
3636 * |
3637 * v
3638 * node A -> further backing chain...
3639 *
3640 * In general, when replacing a node A (c->bs) by a node B (@to),
3641 * if A is a child of B, that means we cannot replace A by B there
3642 * because that would create a loop. Silently detaching A from B
3643 * is also not really an option. So overall just leaving A in
3644 * place there is the most sensible choice.
3645 *
3646 * We would also create a loop in any cases where @c is only
3647 * indirectly referenced by @to. Prevent this by returning false
3648 * if @c is found (by breadth-first search) anywhere in the whole
3649 * subtree of @to.
3650 */
3651
3652 ret = true;
3653 found = g_hash_table_new(NULL, NULL);
3654 g_hash_table_add(found, to);
3655 queue = g_queue_new();
3656 g_queue_push_tail(queue, to);
3657
3658 while (!g_queue_is_empty(queue)) {
3659 BlockDriverState *v = g_queue_pop_head(queue);
3660 BdrvChild *c2;
3661
3662 QLIST_FOREACH(c2, &v->children, next) {
3663 if (c2 == c) {
3664 ret = false;
3665 break;
3666 }
3667
3668 if (g_hash_table_contains(found, c2->bs)) {
3669 continue;
3670 }
3671
3672 g_queue_push_tail(queue, c2->bs);
3673 g_hash_table_add(found, c2->bs);
3674 }
3675 }
3676
3677 g_queue_free(queue);
3678 g_hash_table_destroy(found);
3679
3680 return ret;
3681 }
3682
3683 void bdrv_replace_node(BlockDriverState *from, BlockDriverState *to,
3684 Error **errp)
3685 {
3686 BdrvChild *c, *next;
3687 GSList *list = NULL, *p;
3688 uint64_t old_perm, old_shared;
3689 uint64_t perm = 0, shared = BLK_PERM_ALL;
3690 int ret;
3691
3692 assert(!atomic_read(&from->in_flight));
3693 assert(!atomic_read(&to->in_flight));
3694
3695 /* Make sure that @from doesn't go away until we have successfully attached
3696 * all of its parents to @to. */
3697 bdrv_ref(from);
3698
3699 /* Put all parents into @list and calculate their cumulative permissions */
3700 QLIST_FOREACH_SAFE(c, &from->parents, next_parent, next) {
3701 assert(c->bs == from);
3702 if (!should_update_child(c, to)) {
3703 continue;
3704 }
3705 list = g_slist_prepend(list, c);
3706 perm |= c->perm;
3707 shared &= c->shared_perm;
3708 }
3709
3710 /* Check whether the required permissions can be granted on @to, ignoring
3711 * all BdrvChild in @list so that they can't block themselves. */
3712 ret = bdrv_check_update_perm(to, NULL, perm, shared, list, errp);
3713 if (ret < 0) {
3714 bdrv_abort_perm_update(to);
3715 goto out;
3716 }
3717
3718 /* Now actually perform the change. We performed the permission check for
3719 * all elements of @list at once, so set the permissions all at once at the
3720 * very end. */
3721 for (p = list; p != NULL; p = p->next) {
3722 c = p->data;
3723
3724 bdrv_ref(to);
3725 bdrv_replace_child_noperm(c, to);
3726 bdrv_unref(from);
3727 }
3728
3729 bdrv_get_cumulative_perm(to, &old_perm, &old_shared);
3730 bdrv_set_perm(to, old_perm | perm, old_shared | shared);
3731
3732 out:
3733 g_slist_free(list);
3734 bdrv_unref(from);
3735 }
3736
3737 /*
3738 * Add new bs contents at the top of an image chain while the chain is
3739 * live, while keeping required fields on the top layer.
3740 *
3741 * This will modify the BlockDriverState fields, and swap contents
3742 * between bs_new and bs_top. Both bs_new and bs_top are modified.
3743 *
3744 * bs_new must not be attached to a BlockBackend.
3745 *
3746 * This function does not create any image files.
3747 *
3748 * bdrv_append() takes ownership of a bs_new reference and unrefs it because
3749 * that's what the callers commonly need. bs_new will be referenced by the old
3750 * parents of bs_top after bdrv_append() returns. If the caller needs to keep a
3751 * reference of its own, it must call bdrv_ref().
3752 */
3753 void bdrv_append(BlockDriverState *bs_new, BlockDriverState *bs_top,
3754 Error **errp)
3755 {
3756 Error *local_err = NULL;
3757
3758 bdrv_set_backing_hd(bs_new, bs_top, &local_err);
3759 if (local_err) {
3760 error_propagate(errp, local_err);
3761 goto out;
3762 }
3763
3764 bdrv_replace_node(bs_top, bs_new, &local_err);
3765 if (local_err) {
3766 error_propagate(errp, local_err);
3767 bdrv_set_backing_hd(bs_new, NULL, &error_abort);
3768 goto out;
3769 }
3770
3771 /* bs_new is now referenced by its new parents, we don't need the
3772 * additional reference any more. */
3773 out:
3774 bdrv_unref(bs_new);
3775 }
3776
3777 static void bdrv_delete(BlockDriverState *bs)
3778 {
3779 assert(!bs->job);
3780 assert(bdrv_op_blocker_is_empty(bs));
3781 assert(!bs->refcnt);
3782
3783 bdrv_close(bs);
3784
3785 /* remove from list, if necessary */
3786 if (bs->node_name[0] != '\0') {
3787 QTAILQ_REMOVE(&graph_bdrv_states, bs, node_list);
3788 }
3789 QTAILQ_REMOVE(&all_bdrv_states, bs, bs_list);
3790
3791 g_free(bs);
3792 }
3793
3794 /*
3795 * Run consistency checks on an image
3796 *
3797 * Returns 0 if the check could be completed (it doesn't mean that the image is
3798 * free of errors) or -errno when an internal error occurred. The results of the
3799 * check are stored in res.
3800 */
3801 static int coroutine_fn bdrv_co_check(BlockDriverState *bs,
3802 BdrvCheckResult *res, BdrvCheckMode fix)
3803 {
3804 if (bs->drv == NULL) {
3805 return -ENOMEDIUM;
3806 }
3807 if (bs->drv->bdrv_co_check == NULL) {
3808 return -ENOTSUP;
3809 }
3810
3811 memset(res, 0, sizeof(*res));
3812 return bs->drv->bdrv_co_check(bs, res, fix);
3813 }
3814
3815 typedef struct CheckCo {
3816 BlockDriverState *bs;
3817 BdrvCheckResult *res;
3818 BdrvCheckMode fix;
3819 int ret;
3820 } CheckCo;
3821
3822 static void bdrv_check_co_entry(void *opaque)
3823 {
3824 CheckCo *cco = opaque;
3825 cco->ret = bdrv_co_check(cco->bs, cco->res, cco->fix);
3826 aio_wait_kick();
3827 }
3828
3829 int bdrv_check(BlockDriverState *bs,
3830 BdrvCheckResult *res, BdrvCheckMode fix)
3831 {
3832 Coroutine *co;
3833 CheckCo cco = {
3834 .bs = bs,
3835 .res = res,
3836 .ret = -EINPROGRESS,
3837 .fix = fix,
3838 };
3839
3840 if (qemu_in_coroutine()) {
3841 /* Fast-path if already in coroutine context */
3842 bdrv_check_co_entry(&cco);
3843 } else {
3844 co = qemu_coroutine_create(bdrv_check_co_entry, &cco);
3845 bdrv_coroutine_enter(bs, co);
3846 BDRV_POLL_WHILE(bs, cco.ret == -EINPROGRESS);
3847 }
3848
3849 return cco.ret;
3850 }
3851
3852 /*
3853 * Return values:
3854 * 0 - success
3855 * -EINVAL - backing format specified, but no file
3856 * -ENOSPC - can't update the backing file because no space is left in the
3857 * image file header
3858 * -ENOTSUP - format driver doesn't support changing the backing file
3859 */
3860 int bdrv_change_backing_file(BlockDriverState *bs,
3861 const char *backing_file, const char *backing_fmt)
3862 {
3863 BlockDriver *drv = bs->drv;
3864 int ret;
3865
3866 if (!drv) {
3867 return -ENOMEDIUM;
3868 }
3869
3870 /* Backing file format doesn't make sense without a backing file */
3871 if (backing_fmt && !backing_file) {
3872 return -EINVAL;
3873 }
3874
3875 if (drv->bdrv_change_backing_file != NULL) {
3876 ret = drv->bdrv_change_backing_file(bs, backing_file, backing_fmt);
3877 } else {
3878 ret = -ENOTSUP;
3879 }
3880
3881 if (ret == 0) {
3882 pstrcpy(bs->backing_file, sizeof(bs->backing_file), backing_file ?: "");
3883 pstrcpy(bs->backing_format, sizeof(bs->backing_format), backing_fmt ?: "");
3884 pstrcpy(bs->auto_backing_file, sizeof(bs->auto_backing_file),
3885 backing_file ?: "");
3886 }
3887 return ret;
3888 }
3889
3890 /*
3891 * Finds the image layer in the chain that has 'bs' as its backing file.
3892 *
3893 * active is the current topmost image.
3894 *
3895 * Returns NULL if bs is not found in active's image chain,
3896 * or if active == bs.
3897 *
3898 * Returns the bottommost base image if bs == NULL.
3899 */
3900 BlockDriverState *bdrv_find_overlay(BlockDriverState *active,
3901 BlockDriverState *bs)
3902 {
3903 while (active && bs != backing_bs(active)) {
3904 active = backing_bs(active);
3905 }
3906
3907 return active;
3908 }
3909
3910 /* Given a BDS, searches for the base layer. */
3911 BlockDriverState *bdrv_find_base(BlockDriverState *bs)
3912 {
3913 return bdrv_find_overlay(bs, NULL);
3914 }
3915
3916 /*
3917 * Drops images above 'base' up to and including 'top', and sets the image
3918 * above 'top' to have base as its backing file.
3919 *
3920 * Requires that the overlay to 'top' is opened r/w, so that the backing file
3921 * information in 'bs' can be properly updated.
3922 *
3923 * E.g., this will convert the following chain:
3924 * bottom <- base <- intermediate <- top <- active
3925 *
3926 * to
3927 *
3928 * bottom <- base <- active
3929 *
3930 * It is allowed for bottom==base, in which case it converts:
3931 *
3932 * base <- intermediate <- top <- active
3933 *
3934 * to
3935 *
3936 * base <- active
3937 *
3938 * If backing_file_str is non-NULL, it will be used when modifying top's
3939 * overlay image metadata.
3940 *
3941 * Error conditions:
3942 * if active == top, that is considered an error
3943 *
3944 */
3945 int bdrv_drop_intermediate(BlockDriverState *top, BlockDriverState *base,
3946 const char *backing_file_str)
3947 {
3948 BlockDriverState *explicit_top = top;
3949 bool update_inherits_from;
3950 BdrvChild *c, *next;
3951 Error *local_err = NULL;
3952 int ret = -EIO;
3953
3954 bdrv_ref(top);
3955
3956 if (!top->drv || !base->drv) {
3957 goto exit;
3958 }
3959
3960 /* Make sure that base is in the backing chain of top */
3961 if (!bdrv_chain_contains(top, base)) {
3962 goto exit;
3963 }
3964
3965 /* If 'base' recursively inherits from 'top' then we should set
3966 * base->inherits_from to top->inherits_from after 'top' and all
3967 * other intermediate nodes have been dropped.
3968 * If 'top' is an implicit node (e.g. "commit_top") we should skip
3969 * it because no one inherits from it. We use explicit_top for that. */
3970 while (explicit_top && explicit_top->implicit) {
3971 explicit_top = backing_bs(explicit_top);
3972 }
3973 update_inherits_from = bdrv_inherits_from_recursive(base, explicit_top);
3974
3975 /* success - we can delete the intermediate states, and link top->base */
3976 /* TODO Check graph modification op blockers (BLK_PERM_GRAPH_MOD) once
3977 * we've figured out how they should work. */
3978 if (!backing_file_str) {
3979 bdrv_refresh_filename(base);
3980 backing_file_str = base->filename;
3981 }
3982
3983 QLIST_FOREACH_SAFE(c, &top->parents, next_parent, next) {
3984 /* Check whether we are allowed to switch c from top to base */
3985 GSList *ignore_children = g_slist_prepend(NULL, c);
3986 bdrv_check_update_perm(base, NULL, c->perm, c->shared_perm,
3987 ignore_children, &local_err);
3988 g_slist_free(ignore_children);
3989 if (local_err) {
3990 ret = -EPERM;
3991 error_report_err(local_err);
3992 goto exit;
3993 }
3994
3995 /* If so, update the backing file path in the image file */
3996 if (c->role->update_filename) {
3997 ret = c->role->update_filename(c, base, backing_file_str,
3998 &local_err);
3999 if (ret < 0) {
4000 bdrv_abort_perm_update(base);
4001 error_report_err(local_err);
4002 goto exit;
4003 }
4004 }
4005
4006 /* Do the actual switch in the in-memory graph.
4007 * Completes bdrv_check_update_perm() transaction internally. */
4008 bdrv_ref(base);
4009 bdrv_replace_child(c, base);
4010 bdrv_unref(top);
4011 }
4012
4013 if (update_inherits_from) {
4014 base->inherits_from = explicit_top->inherits_from;
4015 }
4016
4017 ret = 0;
4018 exit:
4019 bdrv_unref(top);
4020 return ret;
4021 }
4022
4023 /**
4024 * Length of a allocated file in bytes. Sparse files are counted by actual
4025 * allocated space. Return < 0 if error or unknown.
4026 */
4027 int64_t bdrv_get_allocated_file_size(BlockDriverState *bs)
4028 {
4029 BlockDriver *drv = bs->drv;
4030 if (!drv) {
4031 return -ENOMEDIUM;
4032 }
4033 if (drv->bdrv_get_allocated_file_size) {
4034 return drv->bdrv_get_allocated_file_size(bs);
4035 }
4036 if (bs->file) {
4037 return bdrv_get_allocated_file_size(bs->file->bs);
4038 }
4039 return -ENOTSUP;
4040 }
4041
4042 /*
4043 * bdrv_measure:
4044 * @drv: Format driver
4045 * @opts: Creation options for new image
4046 * @in_bs: Existing image containing data for new image (may be NULL)
4047 * @errp: Error object
4048 * Returns: A #BlockMeasureInfo (free using qapi_free_BlockMeasureInfo())
4049 * or NULL on error
4050 *
4051 * Calculate file size required to create a new image.
4052 *
4053 * If @in_bs is given then space for allocated clusters and zero clusters
4054 * from that image are included in the calculation. If @opts contains a
4055 * backing file that is shared by @in_bs then backing clusters may be omitted
4056 * from the calculation.
4057 *
4058 * If @in_bs is NULL then the calculation includes no allocated clusters
4059 * unless a preallocation option is given in @opts.
4060 *
4061 * Note that @in_bs may use a different BlockDriver from @drv.
4062 *
4063 * If an error occurs the @errp pointer is set.
4064 */
4065 BlockMeasureInfo *bdrv_measure(BlockDriver *drv, QemuOpts *opts,
4066 BlockDriverState *in_bs, Error **errp)
4067 {
4068 if (!drv->bdrv_measure) {
4069 error_setg(errp, "Block driver '%s' does not support size measurement",
4070 drv->format_name);
4071 return NULL;
4072 }
4073
4074 return drv->bdrv_measure(opts, in_bs, errp);
4075 }
4076
4077 /**
4078 * Return number of sectors on success, -errno on error.
4079 */
4080 int64_t bdrv_nb_sectors(BlockDriverState *bs)
4081 {
4082 BlockDriver *drv = bs->drv;
4083
4084 if (!drv)
4085 return -ENOMEDIUM;
4086
4087 if (drv->has_variable_length) {
4088 int ret = refresh_total_sectors(bs, bs->total_sectors);
4089 if (ret < 0) {
4090 return ret;
4091 }
4092 }
4093 return bs->total_sectors;
4094 }
4095
4096 /**
4097 * Return length in bytes on success, -errno on error.
4098 * The length is always a multiple of BDRV_SECTOR_SIZE.
4099 */
4100 int64_t bdrv_getlength(BlockDriverState *bs)
4101 {
4102 int64_t ret = bdrv_nb_sectors(bs);
4103
4104 ret = ret > INT64_MAX / BDRV_SECTOR_SIZE ? -EFBIG : ret;
4105 return ret < 0 ? ret : ret * BDRV_SECTOR_SIZE;
4106 }
4107
4108 /* return 0 as number of sectors if no device present or error */
4109 void bdrv_get_geometry(BlockDriverState *bs, uint64_t *nb_sectors_ptr)
4110 {
4111 int64_t nb_sectors = bdrv_nb_sectors(bs);
4112
4113 *nb_sectors_ptr = nb_sectors < 0 ? 0 : nb_sectors;
4114 }
4115
4116 bool bdrv_is_sg(BlockDriverState *bs)
4117 {
4118 return bs->sg;
4119 }
4120
4121 bool bdrv_is_encrypted(BlockDriverState *bs)
4122 {
4123 if (bs->backing && bs->backing->bs->encrypted) {
4124 return true;
4125 }
4126 return bs->encrypted;
4127 }
4128
4129 const char *bdrv_get_format_name(BlockDriverState *bs)
4130 {
4131 return bs->drv ? bs->drv->format_name : NULL;
4132 }
4133
4134 static int qsort_strcmp(const void *a, const void *b)
4135 {
4136 return strcmp(*(char *const *)a, *(char *const *)b);
4137 }
4138
4139 void bdrv_iterate_format(void (*it)(void *opaque, const char *name),
4140 void *opaque)
4141 {
4142 BlockDriver *drv;
4143 int count = 0;
4144 int i;
4145 const char **formats = NULL;
4146
4147 QLIST_FOREACH(drv, &bdrv_drivers, list) {
4148 if (drv->format_name) {
4149 bool found = false;
4150 int i = count;
4151 while (formats && i && !found) {
4152 found = !strcmp(formats[--i], drv->format_name);
4153 }
4154
4155 if (!found) {
4156 formats = g_renew(const char *, formats, count + 1);
4157 formats[count++] = drv->format_name;
4158 }
4159 }
4160 }
4161
4162 for (i = 0; i < (int)ARRAY_SIZE(block_driver_modules); i++) {
4163 const char *format_name = block_driver_modules[i].format_name;
4164
4165 if (format_name) {
4166 bool found = false;
4167 int j = count;
4168
4169 while (formats && j && !found) {
4170 found = !strcmp(formats[--j], format_name);
4171 }
4172
4173 if (!found) {
4174 formats = g_renew(const char *, formats, count + 1);
4175 formats[count++] = format_name;
4176 }
4177 }
4178 }
4179
4180 qsort(formats, count, sizeof(formats[0]), qsort_strcmp);
4181
4182 for (i = 0; i < count; i++) {
4183 it(opaque, formats[i]);
4184 }
4185
4186 g_free(formats);
4187 }
4188
4189 /* This function is to find a node in the bs graph */
4190 BlockDriverState *bdrv_find_node(const char *node_name)
4191 {
4192 BlockDriverState *bs;
4193
4194 assert(node_name);
4195
4196 QTAILQ_FOREACH(bs, &graph_bdrv_states, node_list) {
4197 if (!strcmp(node_name, bs->node_name)) {
4198 return bs;
4199 }
4200 }
4201 return NULL;
4202 }
4203
4204 /* Put this QMP function here so it can access the static graph_bdrv_states. */
4205 BlockDeviceInfoList *bdrv_named_nodes_list(Error **errp)
4206 {
4207 BlockDeviceInfoList *list, *entry;
4208 BlockDriverState *bs;
4209
4210 list = NULL;
4211 QTAILQ_FOREACH(bs, &graph_bdrv_states, node_list) {
4212 BlockDeviceInfo *info = bdrv_block_device_info(NULL, bs, errp);
4213 if (!info) {
4214 qapi_free_BlockDeviceInfoList(list);
4215 return NULL;
4216 }
4217 entry = g_malloc0(sizeof(*entry));
4218 entry->value = info;
4219 entry->next = list;
4220 list = entry;
4221 }
4222
4223 return list;
4224 }
4225
4226 #define QAPI_LIST_ADD(list, element) do { \
4227 typeof(list) _tmp = g_new(typeof(*(list)), 1); \
4228 _tmp->value = (element); \
4229 _tmp->next = (list); \
4230 (list) = _tmp; \
4231 } while (0)
4232
4233 typedef struct XDbgBlockGraphConstructor {
4234 XDbgBlockGraph *graph;
4235 GHashTable *graph_nodes;
4236 } XDbgBlockGraphConstructor;
4237
4238 static XDbgBlockGraphConstructor *xdbg_graph_new(void)
4239 {
4240 XDbgBlockGraphConstructor *gr = g_new(XDbgBlockGraphConstructor, 1);
4241
4242 gr->graph = g_new0(XDbgBlockGraph, 1);
4243 gr->graph_nodes = g_hash_table_new(NULL, NULL);
4244
4245 return gr;
4246 }
4247
4248 static XDbgBlockGraph *xdbg_graph_finalize(XDbgBlockGraphConstructor *gr)
4249 {
4250 XDbgBlockGraph *graph = gr->graph;
4251
4252 g_hash_table_destroy(gr->graph_nodes);
4253 g_free(gr);
4254
4255 return graph;
4256 }
4257
4258 static uintptr_t xdbg_graph_node_num(XDbgBlockGraphConstructor *gr, void *node)
4259 {
4260 uintptr_t ret = (uintptr_t)g_hash_table_lookup(gr->graph_nodes, node);
4261
4262 if (ret != 0) {
4263 return ret;
4264 }
4265
4266 /*
4267 * Start counting from 1, not 0, because 0 interferes with not-found (NULL)
4268 * answer of g_hash_table_lookup.
4269 */
4270 ret = g_hash_table_size(gr->graph_nodes) + 1;
4271 g_hash_table_insert(gr->graph_nodes, node, (void *)ret);
4272
4273 return ret;
4274 }
4275
4276 static void xdbg_graph_add_node(XDbgBlockGraphConstructor *gr, void *node,
4277 XDbgBlockGraphNodeType type, const char *name)
4278 {
4279 XDbgBlockGraphNode *n;
4280
4281 n = g_new0(XDbgBlockGraphNode, 1);
4282
4283 n->id = xdbg_graph_node_num(gr, node);
4284 n->type = type;
4285 n->name = g_strdup(name);
4286
4287 QAPI_LIST_ADD(gr->graph->nodes, n);
4288 }
4289
4290 static void xdbg_graph_add_edge(XDbgBlockGraphConstructor *gr, void *parent,
4291 const BdrvChild *child)
4292 {
4293 typedef struct {
4294 unsigned int flag;
4295 BlockPermission num;
4296 } PermissionMap;
4297
4298 static const PermissionMap permissions[] = {
4299 { BLK_PERM_CONSISTENT_READ, BLOCK_PERMISSION_CONSISTENT_READ },
4300 { BLK_PERM_WRITE, BLOCK_PERMISSION_WRITE },
4301 { BLK_PERM_WRITE_UNCHANGED, BLOCK_PERMISSION_WRITE_UNCHANGED },
4302 { BLK_PERM_RESIZE, BLOCK_PERMISSION_RESIZE },
4303 { BLK_PERM_GRAPH_MOD, BLOCK_PERMISSION_GRAPH_MOD },
4304 { 0, 0 }
4305 };
4306 const PermissionMap *p;
4307 XDbgBlockGraphEdge *edge;
4308
4309 QEMU_BUILD_BUG_ON(1UL << (ARRAY_SIZE(permissions) - 1) != BLK_PERM_ALL + 1);
4310
4311 edge = g_new0(XDbgBlockGraphEdge, 1);
4312
4313 edge->parent = xdbg_graph_node_num(gr, parent);
4314 edge->child = xdbg_graph_node_num(gr, child->bs);
4315 edge->name = g_strdup(child->name);
4316
4317 for (p = permissions; p->flag; p++) {
4318 if (p->flag & child->perm) {
4319 QAPI_LIST_ADD(edge->perm, p->num);
4320 }
4321 if (p->flag & child->shared_perm) {
4322 QAPI_LIST_ADD(edge->shared_perm, p->num);
4323 }
4324 }
4325
4326 QAPI_LIST_ADD(gr->graph->edges, edge);
4327 }
4328
4329
4330 XDbgBlockGraph *bdrv_get_xdbg_block_graph(Error **errp)
4331 {
4332 BlockBackend *blk;
4333 BlockJob *job;
4334 BlockDriverState *bs;
4335 BdrvChild *child;
4336 XDbgBlockGraphConstructor *gr = xdbg_graph_new();
4337
4338 for (blk = blk_all_next(NULL); blk; blk = blk_all_next(blk)) {
4339 char *allocated_name = NULL;
4340 const char *name = blk_name(blk);
4341
4342 if (!*name) {
4343 name = allocated_name = blk_get_attached_dev_id(blk);
4344 }
4345 xdbg_graph_add_node(gr, blk, X_DBG_BLOCK_GRAPH_NODE_TYPE_BLOCK_BACKEND,
4346 name);
4347 g_free(allocated_name);
4348 if (blk_root(blk)) {
4349 xdbg_graph_add_edge(gr, blk, blk_root(blk));
4350 }
4351 }
4352
4353 for (job = block_job_next(NULL); job; job = block_job_next(job)) {
4354 GSList *el;
4355
4356 xdbg_graph_add_node(gr, job, X_DBG_BLOCK_GRAPH_NODE_TYPE_BLOCK_JOB,
4357 job->job.id);
4358 for (el = job->nodes; el; el = el->next) {
4359 xdbg_graph_add_edge(gr, job, (BdrvChild *)el->data);
4360 }
4361 }
4362
4363 QTAILQ_FOREACH(bs, &graph_bdrv_states, node_list) {
4364 xdbg_graph_add_node(gr, bs, X_DBG_BLOCK_GRAPH_NODE_TYPE_BLOCK_DRIVER,
4365 bs->node_name);
4366 QLIST_FOREACH(child, &bs->children, next) {
4367 xdbg_graph_add_edge(gr, bs, child);
4368 }
4369 }
4370
4371 return xdbg_graph_finalize(gr);
4372 }
4373
4374 BlockDriverState *bdrv_lookup_bs(const char *device,
4375 const char *node_name,
4376 Error **errp)
4377 {
4378 BlockBackend *blk;
4379 BlockDriverState *bs;
4380
4381 if (device) {
4382 blk = blk_by_name(device);
4383
4384 if (blk) {
4385 bs = blk_bs(blk);
4386 if (!bs) {
4387 error_setg(errp, "Device '%s' has no medium", device);
4388 }
4389
4390 return bs;
4391 }
4392 }
4393
4394 if (node_name) {
4395 bs = bdrv_find_node(node_name);
4396
4397 if (bs) {
4398 return bs;
4399 }
4400 }
4401
4402 error_setg(errp, "Cannot find device=%s nor node_name=%s",
4403 device ? device : "",
4404 node_name ? node_name : "");
4405 return NULL;
4406 }
4407
4408 /* If 'base' is in the same chain as 'top', return true. Otherwise,
4409 * return false. If either argument is NULL, return false. */
4410 bool bdrv_chain_contains(BlockDriverState *top, BlockDriverState *base)
4411 {
4412 while (top && top != base) {
4413 top = backing_bs(top);
4414 }
4415
4416 return top != NULL;
4417 }
4418
4419 BlockDriverState *bdrv_next_node(BlockDriverState *bs)
4420 {
4421 if (!bs) {
4422 return QTAILQ_FIRST(&graph_bdrv_states);
4423 }
4424 return QTAILQ_NEXT(bs, node_list);
4425 }
4426
4427 BlockDriverState *bdrv_next_all_states(BlockDriverState *bs)
4428 {
4429 if (!bs) {
4430 return QTAILQ_FIRST(&all_bdrv_states);
4431 }
4432 return QTAILQ_NEXT(bs, bs_list);
4433 }
4434
4435 const char *bdrv_get_node_name(const BlockDriverState *bs)
4436 {
4437 return bs->node_name;
4438 }
4439
4440 const char *bdrv_get_parent_name(const BlockDriverState *bs)
4441 {
4442 BdrvChild *c;
4443 const char *name;
4444
4445 /* If multiple parents have a name, just pick the first one. */
4446 QLIST_FOREACH(c, &bs->parents, next_parent) {
4447 if (c->role->get_name) {
4448 name = c->role->get_name(c);
4449 if (name && *name) {
4450 return name;
4451 }
4452 }
4453 }
4454
4455 return NULL;
4456 }
4457
4458 /* TODO check what callers really want: bs->node_name or blk_name() */
4459 const char *bdrv_get_device_name(const BlockDriverState *bs)
4460 {
4461 return bdrv_get_parent_name(bs) ?: "";
4462 }
4463
4464 /* This can be used to identify nodes that might not have a device
4465 * name associated. Since node and device names live in the same
4466 * namespace, the result is unambiguous. The exception is if both are
4467 * absent, then this returns an empty (non-null) string. */
4468 const char *bdrv_get_device_or_node_name(const BlockDriverState *bs)
4469 {
4470 return bdrv_get_parent_name(bs) ?: bs->node_name;
4471 }
4472
4473 int bdrv_get_flags(BlockDriverState *bs)
4474 {
4475 return bs->open_flags;
4476 }
4477
4478 int bdrv_has_zero_init_1(BlockDriverState *bs)
4479 {
4480 return 1;
4481 }
4482
4483 int bdrv_has_zero_init(BlockDriverState *bs)
4484 {
4485 if (!bs->drv) {
4486 return 0;
4487 }
4488
4489 /* If BS is a copy on write image, it is initialized to
4490 the contents of the base image, which may not be zeroes. */
4491 if (bs->backing) {
4492 return 0;
4493 }
4494 if (bs->drv->bdrv_has_zero_init) {
4495 return bs->drv->bdrv_has_zero_init(bs);
4496 }
4497 if (bs->file && bs->drv->is_filter) {
4498 return bdrv_has_zero_init(bs->file->bs);
4499 }
4500
4501 /* safe default */
4502 return 0;
4503 }
4504
4505 bool bdrv_unallocated_blocks_are_zero(BlockDriverState *bs)
4506 {
4507 BlockDriverInfo bdi;
4508
4509 if (bs->backing) {
4510 return false;
4511 }
4512
4513 if (bdrv_get_info(bs, &bdi) == 0) {
4514 return bdi.unallocated_blocks_are_zero;
4515 }
4516
4517 return false;
4518 }
4519
4520 bool bdrv_can_write_zeroes_with_unmap(BlockDriverState *bs)
4521 {
4522 if (!(bs->open_flags & BDRV_O_UNMAP)) {
4523 return false;
4524 }
4525
4526 return bs->supported_zero_flags & BDRV_REQ_MAY_UNMAP;
4527 }
4528
4529 void bdrv_get_backing_filename(BlockDriverState *bs,
4530 char *filename, int filename_size)
4531 {
4532 pstrcpy(filename, filename_size, bs->backing_file);
4533 }
4534
4535 int bdrv_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
4536 {
4537 BlockDriver *drv = bs->drv;
4538 /* if bs->drv == NULL, bs is closed, so there's nothing to do here */
4539 if (!drv) {
4540 return -ENOMEDIUM;
4541 }
4542 if (!drv->bdrv_get_info) {
4543 if (bs->file && drv->is_filter) {
4544 return bdrv_get_info(bs->file->bs, bdi);
4545 }
4546 return -ENOTSUP;
4547 }
4548 memset(bdi, 0, sizeof(*bdi));
4549 return drv->bdrv_get_info(bs, bdi);
4550 }
4551
4552 ImageInfoSpecific *bdrv_get_specific_info(BlockDriverState *bs,
4553 Error **errp)
4554 {
4555 BlockDriver *drv = bs->drv;
4556 if (drv && drv->bdrv_get_specific_info) {
4557 return drv->bdrv_get_specific_info(bs, errp);
4558 }
4559 return NULL;
4560 }
4561
4562 void bdrv_debug_event(BlockDriverState *bs, BlkdebugEvent event)
4563 {
4564 if (!bs || !bs->drv || !bs->drv->bdrv_debug_event) {
4565 return;
4566 }
4567
4568 bs->drv->bdrv_debug_event(bs, event);
4569 }
4570
4571 int bdrv_debug_breakpoint(BlockDriverState *bs, const char *event,
4572 const char *tag)
4573 {
4574 while (bs && bs->drv && !bs->drv->bdrv_debug_breakpoint) {
4575 bs = bs->file ? bs->file->bs : NULL;
4576 }
4577
4578 if (bs && bs->drv && bs->drv->bdrv_debug_breakpoint) {
4579 return bs->drv->bdrv_debug_breakpoint(bs, event, tag);
4580 }
4581
4582 return -ENOTSUP;
4583 }
4584
4585 int bdrv_debug_remove_breakpoint(BlockDriverState *bs, const char *tag)
4586 {
4587 while (bs && bs->drv && !bs->drv->bdrv_debug_remove_breakpoint) {
4588 bs = bs->file ? bs->file->bs : NULL;
4589 }
4590
4591 if (bs && bs->drv && bs->drv->bdrv_debug_remove_breakpoint) {
4592 return bs->drv->bdrv_debug_remove_breakpoint(bs, tag);
4593 }
4594
4595 return -ENOTSUP;
4596 }
4597
4598 int bdrv_debug_resume(BlockDriverState *bs, const char *tag)
4599 {
4600 while (bs && (!bs->drv || !bs->drv->bdrv_debug_resume)) {
4601 bs = bs->file ? bs->file->bs : NULL;
4602 }
4603
4604 if (bs && bs->drv && bs->drv->bdrv_debug_resume) {
4605 return bs->drv->bdrv_debug_resume(bs, tag);
4606 }
4607
4608 return -ENOTSUP;
4609 }
4610
4611 bool bdrv_debug_is_suspended(BlockDriverState *bs, const char *tag)
4612 {
4613 while (bs && bs->drv && !bs->drv->bdrv_debug_is_suspended) {
4614 bs = bs->file ? bs->file->bs : NULL;
4615 }
4616
4617 if (bs && bs->drv && bs->drv->bdrv_debug_is_suspended) {
4618 return bs->drv->bdrv_debug_is_suspended(bs, tag);
4619 }
4620
4621 return false;
4622 }
4623
4624 /* backing_file can either be relative, or absolute, or a protocol. If it is
4625 * relative, it must be relative to the chain. So, passing in bs->filename
4626 * from a BDS as backing_file should not be done, as that may be relative to
4627 * the CWD rather than the chain. */
4628 BlockDriverState *bdrv_find_backing_image(BlockDriverState *bs,
4629 const char *backing_file)
4630 {
4631 char *filename_full = NULL;
4632 char *backing_file_full = NULL;
4633 char *filename_tmp = NULL;
4634 int is_protocol = 0;
4635 BlockDriverState *curr_bs = NULL;
4636 BlockDriverState *retval = NULL;
4637
4638 if (!bs || !bs->drv || !backing_file) {
4639 return NULL;
4640 }
4641
4642 filename_full = g_malloc(PATH_MAX);
4643 backing_file_full = g_malloc(PATH_MAX);
4644 filename_tmp = g_malloc(PATH_MAX);
4645
4646 is_protocol = path_has_protocol(backing_file);
4647
4648 /* This will recursively refresh everything in the backing chain */
4649 bdrv_refresh_filename(bs);
4650
4651 for (curr_bs = bs; curr_bs->backing; curr_bs = curr_bs->backing->bs) {
4652
4653 /* If either of the filename paths is actually a protocol, then
4654 * compare unmodified paths; otherwise make paths relative */
4655 if (is_protocol || path_has_protocol(curr_bs->backing_file)) {
4656 char *backing_file_full_ret;
4657
4658 if (strcmp(backing_file, curr_bs->backing_file) == 0) {
4659 retval = curr_bs->backing->bs;
4660 break;
4661 }
4662 /* Also check against the full backing filename for the image */
4663 backing_file_full_ret = bdrv_get_full_backing_filename(curr_bs,
4664 NULL);
4665 if (backing_file_full_ret) {
4666 bool equal = strcmp(backing_file, backing_file_full_ret) == 0;
4667 g_free(backing_file_full_ret);
4668 if (equal) {
4669 retval = curr_bs->backing->bs;
4670 break;
4671 }
4672 }
4673 } else {
4674 /* If not an absolute filename path, make it relative to the current
4675 * image's filename path */
4676 path_combine_deprecated(filename_tmp, PATH_MAX, curr_bs->filename,
4677 backing_file);
4678
4679 /* We are going to compare absolute pathnames */
4680 if (!realpath(filename_tmp, filename_full)) {
4681 continue;
4682 }
4683
4684 /* We need to make sure the backing filename we are comparing against
4685 * is relative to the current image filename (or absolute) */
4686 path_combine_deprecated(filename_tmp, PATH_MAX, curr_bs->filename,
4687 curr_bs->backing_file);
4688
4689 if (!realpath(filename_tmp, backing_file_full)) {
4690 continue;
4691 }
4692
4693 if (strcmp(backing_file_full, filename_full) == 0) {
4694 retval = curr_bs->backing->bs;
4695 break;
4696 }
4697 }
4698 }
4699
4700 g_free(filename_full);
4701 g_free(backing_file_full);
4702 g_free(filename_tmp);
4703 return retval;
4704 }
4705
4706 void bdrv_init(void)
4707 {
4708 module_call_init(MODULE_INIT_BLOCK);
4709 }
4710
4711 void bdrv_init_with_whitelist(void)
4712 {
4713 use_bdrv_whitelist = 1;
4714 bdrv_init();
4715 }
4716
4717 static void coroutine_fn bdrv_co_invalidate_cache(BlockDriverState *bs,
4718 Error **errp)
4719 {
4720 BdrvChild *child, *parent;
4721 uint64_t perm, shared_perm;
4722 Error *local_err = NULL;
4723 int ret;
4724 BdrvDirtyBitmap *bm;
4725
4726 if (!bs->drv) {
4727 return;
4728 }
4729
4730 if (!(bs->open_flags & BDRV_O_INACTIVE)) {
4731 return;
4732 }
4733
4734 QLIST_FOREACH(child, &bs->children, next) {
4735 bdrv_co_invalidate_cache(child->bs, &local_err);
4736 if (local_err) {
4737 error_propagate(errp, local_err);
4738 return;
4739 }
4740 }
4741
4742 /*
4743 * Update permissions, they may differ for inactive nodes.
4744 *
4745 * Note that the required permissions of inactive images are always a
4746 * subset of the permissions required after activating the image. This
4747 * allows us to just get the permissions upfront without restricting
4748 * drv->bdrv_invalidate_cache().
4749 *
4750 * It also means that in error cases, we don't have to try and revert to
4751 * the old permissions (which is an operation that could fail, too). We can
4752 * just keep the extended permissions for the next time that an activation
4753 * of the image is tried.
4754 */
4755 bs->open_flags &= ~BDRV_O_INACTIVE;
4756 bdrv_get_cumulative_perm(bs, &perm, &shared_perm);
4757 ret = bdrv_check_perm(bs, NULL, perm, shared_perm, NULL, &local_err);
4758 if (ret < 0) {
4759 bs->open_flags |= BDRV_O_INACTIVE;
4760 error_propagate(errp, local_err);
4761 return;
4762 }
4763 bdrv_set_perm(bs, perm, shared_perm);
4764
4765 if (bs->drv->bdrv_co_invalidate_cache) {
4766 bs->drv->bdrv_co_invalidate_cache(bs, &local_err);
4767 if (local_err) {
4768 bs->open_flags |= BDRV_O_INACTIVE;
4769 error_propagate(errp, local_err);
4770 return;
4771 }
4772 }
4773
4774 for (bm = bdrv_dirty_bitmap_next(bs, NULL); bm;
4775 bm = bdrv_dirty_bitmap_next(bs, bm))
4776 {
4777 bdrv_dirty_bitmap_set_migration(bm, false);
4778 }
4779
4780 ret = refresh_total_sectors(bs, bs->total_sectors);
4781 if (ret < 0) {
4782 bs->open_flags |= BDRV_O_INACTIVE;
4783 error_setg_errno(errp, -ret, "Could not refresh total sector count");
4784 return;
4785 }
4786
4787 QLIST_FOREACH(parent, &bs->parents, next_parent) {
4788 if (parent->role->activate) {
4789 parent->role->activate(parent, &local_err);
4790 if (local_err) {
4791 bs->open_flags |= BDRV_O_INACTIVE;
4792 error_propagate(errp, local_err);
4793 return;
4794 }
4795 }
4796 }
4797 }
4798
4799 typedef struct InvalidateCacheCo {
4800 BlockDriverState *bs;
4801 Error **errp;
4802 bool done;
4803 } InvalidateCacheCo;
4804
4805 static void coroutine_fn bdrv_invalidate_cache_co_entry(void *opaque)
4806 {
4807 InvalidateCacheCo *ico = opaque;
4808 bdrv_co_invalidate_cache(ico->bs, ico->errp);
4809 ico->done = true;
4810 aio_wait_kick();
4811 }
4812
4813 void bdrv_invalidate_cache(BlockDriverState *bs, Error **errp)
4814 {
4815 Coroutine *co;
4816 InvalidateCacheCo ico = {
4817 .bs = bs,
4818 .done = false,
4819 .errp = errp
4820 };
4821
4822 if (qemu_in_coroutine()) {
4823 /* Fast-path if already in coroutine context */
4824 bdrv_invalidate_cache_co_entry(&ico);
4825 } else {
4826 co = qemu_coroutine_create(bdrv_invalidate_cache_co_entry, &ico);
4827 bdrv_coroutine_enter(bs, co);
4828 BDRV_POLL_WHILE(bs, !ico.done);
4829 }
4830 }
4831
4832 void bdrv_invalidate_cache_all(Error **errp)
4833 {
4834 BlockDriverState *bs;
4835 Error *local_err = NULL;
4836 BdrvNextIterator it;
4837
4838 for (bs = bdrv_first(&it); bs; bs = bdrv_next(&it)) {
4839 AioContext *aio_context = bdrv_get_aio_context(bs);
4840
4841 aio_context_acquire(aio_context);
4842 bdrv_invalidate_cache(bs, &local_err);
4843 aio_context_release(aio_context);
4844 if (local_err) {
4845 error_propagate(errp, local_err);
4846 bdrv_next_cleanup(&it);
4847 return;
4848 }
4849 }
4850 }
4851
4852 static bool bdrv_has_bds_parent(BlockDriverState *bs, bool only_active)
4853 {
4854 BdrvChild *parent;
4855
4856 QLIST_FOREACH(parent, &bs->parents, next_parent) {
4857 if (parent->role->parent_is_bds) {
4858 BlockDriverState *parent_bs = parent->opaque;
4859 if (!only_active || !(parent_bs->open_flags & BDRV_O_INACTIVE)) {
4860 return true;
4861 }
4862 }
4863 }
4864
4865 return false;
4866 }
4867
4868 static int bdrv_inactivate_recurse(BlockDriverState *bs)
4869 {
4870 BdrvChild *child, *parent;
4871 uint64_t perm, shared_perm;
4872 int ret;
4873
4874 if (!bs->drv) {
4875 return -ENOMEDIUM;
4876 }
4877
4878 /* Make sure that we don't inactivate a child before its parent.
4879 * It will be covered by recursion from the yet active parent. */
4880 if (bdrv_has_bds_parent(bs, true)) {
4881 return 0;
4882 }
4883
4884 assert(!(bs->open_flags & BDRV_O_INACTIVE));
4885
4886 /* Inactivate this node */
4887 if (bs->drv->bdrv_inactivate) {
4888 ret = bs->drv->bdrv_inactivate(bs);
4889 if (ret < 0) {
4890 return ret;
4891 }
4892 }
4893
4894 QLIST_FOREACH(parent, &bs->parents, next_parent) {
4895 if (parent->role->inactivate) {
4896 ret = parent->role->inactivate(parent);
4897 if (ret < 0) {
4898 return ret;
4899 }
4900 }
4901 }
4902
4903 bs->open_flags |= BDRV_O_INACTIVE;
4904
4905 /* Update permissions, they may differ for inactive nodes */
4906 bdrv_get_cumulative_perm(bs, &perm, &shared_perm);
4907 bdrv_check_perm(bs, NULL, perm, shared_perm, NULL, &error_abort);
4908 bdrv_set_perm(bs, perm, shared_perm);
4909
4910
4911 /* Recursively inactivate children */
4912 QLIST_FOREACH(child, &bs->children, next) {
4913 ret = bdrv_inactivate_recurse(child->bs);
4914 if (ret < 0) {
4915 return ret;
4916 }
4917 }
4918
4919 return 0;
4920 }
4921
4922 int bdrv_inactivate_all(void)
4923 {
4924 BlockDriverState *bs = NULL;
4925 BdrvNextIterator it;
4926 int ret = 0;
4927 GSList *aio_ctxs = NULL, *ctx;
4928
4929 for (bs = bdrv_first(&it); bs; bs = bdrv_next(&it)) {
4930 AioContext *aio_context = bdrv_get_aio_context(bs);
4931
4932 if (!g_slist_find(aio_ctxs, aio_context)) {
4933 aio_ctxs = g_slist_prepend(aio_ctxs, aio_context);
4934 aio_context_acquire(aio_context);
4935 }
4936 }
4937
4938 for (bs = bdrv_first(&it); bs; bs = bdrv_next(&it)) {
4939 /* Nodes with BDS parents are covered by recursion from the last
4940 * parent that gets inactivated. Don't inactivate them a second
4941 * time if that has already happened. */
4942 if (bdrv_has_bds_parent(bs, false)) {
4943 continue;
4944 }
4945 ret = bdrv_inactivate_recurse(bs);
4946 if (ret < 0) {
4947 bdrv_next_cleanup(&it);
4948 goto out;
4949 }
4950 }
4951
4952 out:
4953 for (ctx = aio_ctxs; ctx != NULL; ctx = ctx->next) {
4954 AioContext *aio_context = ctx->data;
4955 aio_context_release(aio_context);
4956 }
4957 g_slist_free(aio_ctxs);
4958
4959 return ret;
4960 }
4961
4962 /**************************************************************/
4963 /* removable device support */
4964
4965 /**
4966 * Return TRUE if the media is present
4967 */
4968 bool bdrv_is_inserted(BlockDriverState *bs)
4969 {
4970 BlockDriver *drv = bs->drv;
4971 BdrvChild *child;
4972
4973 if (!drv) {
4974 return false;
4975 }
4976 if (drv->bdrv_is_inserted) {
4977 return drv->bdrv_is_inserted(bs);
4978 }
4979 QLIST_FOREACH(child, &bs->children, next) {
4980 if (!bdrv_is_inserted(child->bs)) {
4981 return false;
4982 }
4983 }
4984 return true;
4985 }
4986
4987 /**
4988 * If eject_flag is TRUE, eject the media. Otherwise, close the tray
4989 */
4990 void bdrv_eject(BlockDriverState *bs, bool eject_flag)
4991 {
4992 BlockDriver *drv = bs->drv;
4993
4994 if (drv && drv->bdrv_eject) {
4995 drv->bdrv_eject(bs, eject_flag);
4996 }
4997 }
4998
4999 /**
5000 * Lock or unlock the media (if it is locked, the user won't be able
5001 * to eject it manually).
5002 */
5003 void bdrv_lock_medium(BlockDriverState *bs, bool locked)
5004 {
5005 BlockDriver *drv = bs->drv;
5006
5007 trace_bdrv_lock_medium(bs, locked);
5008
5009 if (drv && drv->bdrv_lock_medium) {
5010 drv->bdrv_lock_medium(bs, locked);
5011 }
5012 }
5013
5014 /* Get a reference to bs */
5015 void bdrv_ref(BlockDriverState *bs)
5016 {
5017 bs->refcnt++;
5018 }
5019
5020 /* Release a previously grabbed reference to bs.
5021 * If after releasing, reference count is zero, the BlockDriverState is
5022 * deleted. */
5023 void bdrv_unref(BlockDriverState *bs)
5024 {
5025 if (!bs) {
5026 return;
5027 }
5028 assert(bs->refcnt > 0);
5029 if (--bs->refcnt == 0) {
5030 bdrv_delete(bs);
5031 }
5032 }
5033
5034 struct BdrvOpBlocker {
5035 Error *reason;
5036 QLIST_ENTRY(BdrvOpBlocker) list;
5037 };
5038
5039 bool bdrv_op_is_blocked(BlockDriverState *bs, BlockOpType op, Error **errp)
5040 {
5041 BdrvOpBlocker *blocker;
5042 assert((int) op >= 0 && op < BLOCK_OP_TYPE_MAX);
5043 if (!QLIST_EMPTY(&bs->op_blockers[op])) {
5044 blocker = QLIST_FIRST(&bs->op_blockers[op]);
5045 error_propagate_prepend(errp, error_copy(blocker->reason),
5046 "Node '%s' is busy: ",
5047 bdrv_get_device_or_node_name(bs));
5048 return true;
5049 }
5050 return false;
5051 }
5052
5053 void bdrv_op_block(BlockDriverState *bs, BlockOpType op, Error *reason)
5054 {
5055 BdrvOpBlocker *blocker;
5056 assert((int) op >= 0 && op < BLOCK_OP_TYPE_MAX);
5057
5058 blocker = g_new0(BdrvOpBlocker, 1);
5059 blocker->reason = reason;
5060 QLIST_INSERT_HEAD(&bs->op_blockers[op], blocker, list);
5061 }
5062
5063 void bdrv_op_unblock(BlockDriverState *bs, BlockOpType op, Error *reason)
5064 {
5065 BdrvOpBlocker *blocker, *next;
5066 assert((int) op >= 0 && op < BLOCK_OP_TYPE_MAX);
5067 QLIST_FOREACH_SAFE(blocker, &bs->op_blockers[op], list, next) {
5068 if (blocker->reason == reason) {
5069 QLIST_REMOVE(blocker, list);
5070 g_free(blocker);
5071 }
5072 }
5073 }
5074
5075 void bdrv_op_block_all(BlockDriverState *bs, Error *reason)
5076 {
5077 int i;
5078 for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
5079 bdrv_op_block(bs, i, reason);
5080 }
5081 }
5082
5083 void bdrv_op_unblock_all(BlockDriverState *bs, Error *reason)
5084 {
5085 int i;
5086 for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
5087 bdrv_op_unblock(bs, i, reason);
5088 }
5089 }
5090
5091 bool bdrv_op_blocker_is_empty(BlockDriverState *bs)
5092 {
5093 int i;
5094
5095 for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
5096 if (!QLIST_EMPTY(&bs->op_blockers[i])) {
5097 return false;
5098 }
5099 }
5100 return true;
5101 }
5102
5103 void bdrv_img_create(const char *filename, const char *fmt,
5104 const char *base_filename, const char *base_fmt,
5105 char *options, uint64_t img_size, int flags, bool quiet,
5106 Error **errp)
5107 {
5108 QemuOptsList *create_opts = NULL;
5109 QemuOpts *opts = NULL;
5110 const char *backing_fmt, *backing_file;
5111 int64_t size;
5112 BlockDriver *drv, *proto_drv;
5113 Error *local_err = NULL;
5114 int ret = 0;
5115
5116 /* Find driver and parse its options */
5117 drv = bdrv_find_format(fmt);
5118 if (!drv) {
5119 error_setg(errp, "Unknown file format '%s'", fmt);
5120 return;
5121 }
5122
5123 proto_drv = bdrv_find_protocol(filename, true, errp);
5124 if (!proto_drv) {
5125 return;
5126 }
5127
5128 if (!drv->create_opts) {
5129 error_setg(errp, "Format driver '%s' does not support image creation",
5130 drv->format_name);
5131 return;
5132 }
5133
5134 if (!proto_drv->create_opts) {
5135 error_setg(errp, "Protocol driver '%s' does not support image creation",
5136 proto_drv->format_name);
5137 return;
5138 }
5139
5140 create_opts = qemu_opts_append(create_opts, drv->create_opts);
5141 create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
5142
5143 /* Create parameter list with default values */
5144 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
5145 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, img_size, &error_abort);
5146
5147 /* Parse -o options */
5148 if (options) {
5149 qemu_opts_do_parse(opts, options, NULL, &local_err);
5150 if (local_err) {
5151 goto out;
5152 }
5153 }
5154
5155 if (base_filename) {
5156 qemu_opt_set(opts, BLOCK_OPT_BACKING_FILE, base_filename, &local_err);
5157 if (local_err) {
5158 error_setg(errp, "Backing file not supported for file format '%s'",
5159 fmt);
5160 goto out;
5161 }
5162 }
5163
5164 if (base_fmt) {
5165 qemu_opt_set(opts, BLOCK_OPT_BACKING_FMT, base_fmt, &local_err);
5166 if (local_err) {
5167 error_setg(errp, "Backing file format not supported for file "
5168 "format '%s'", fmt);
5169 goto out;
5170 }
5171 }
5172
5173 backing_file = qemu_opt_get(opts, BLOCK_OPT_BACKING_FILE);
5174 if (backing_file) {
5175 if (!strcmp(filename, backing_file)) {
5176 error_setg(errp, "Error: Trying to create an image with the "
5177 "same filename as the backing file");
5178 goto out;
5179 }
5180 }
5181
5182 backing_fmt = qemu_opt_get(opts, BLOCK_OPT_BACKING_FMT);
5183
5184 /* The size for the image must always be specified, unless we have a backing
5185 * file and we have not been forbidden from opening it. */
5186 size = qemu_opt_get_size(opts, BLOCK_OPT_SIZE, img_size);
5187 if (backing_file && !(flags & BDRV_O_NO_BACKING)) {
5188 BlockDriverState *bs;
5189 char *full_backing;
5190 int back_flags;
5191 QDict *backing_options = NULL;
5192
5193 full_backing =
5194 bdrv_get_full_backing_filename_from_filename(filename, backing_file,
5195 &local_err);
5196 if (local_err) {
5197 goto out;
5198 }
5199 assert(full_backing);
5200
5201 /* backing files always opened read-only */
5202 back_flags = flags;
5203 back_flags &= ~(BDRV_O_RDWR | BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING);
5204
5205 backing_options = qdict_new();
5206 if (backing_fmt) {
5207 qdict_put_str(backing_options, "driver", backing_fmt);
5208 }
5209 qdict_put_bool(backing_options, BDRV_OPT_FORCE_SHARE, true);
5210
5211 bs = bdrv_open(full_backing, NULL, backing_options, back_flags,
5212 &local_err);
5213 g_free(full_backing);
5214 if (!bs && size != -1) {
5215 /* Couldn't open BS, but we have a size, so it's nonfatal */
5216 warn_reportf_err(local_err,
5217 "Could not verify backing image. "
5218 "This may become an error in future versions.\n");
5219 local_err = NULL;
5220 } else if (!bs) {
5221 /* Couldn't open bs, do not have size */
5222 error_append_hint(&local_err,
5223 "Could not open backing image to determine size.\n");
5224 goto out;
5225 } else {
5226 if (size == -1) {
5227 /* Opened BS, have no size */
5228 size = bdrv_getlength(bs);
5229 if (size < 0) {
5230 error_setg_errno(errp, -size, "Could not get size of '%s'",
5231 backing_file);
5232 bdrv_unref(bs);
5233 goto out;
5234 }
5235 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, size, &error_abort);
5236 }
5237 bdrv_unref(bs);
5238 }
5239 } /* (backing_file && !(flags & BDRV_O_NO_BACKING)) */
5240
5241 if (size == -1) {
5242 error_setg(errp, "Image creation needs a size parameter");
5243 goto out;
5244 }
5245
5246 if (!quiet) {
5247 printf("Formatting '%s', fmt=%s ", filename, fmt);
5248 qemu_opts_print(opts, " ");
5249 puts("");
5250 }
5251
5252 ret = bdrv_create(drv, filename, opts, &local_err);
5253
5254 if (ret == -EFBIG) {
5255 /* This is generally a better message than whatever the driver would
5256 * deliver (especially because of the cluster_size_hint), since that
5257 * is most probably not much different from "image too large". */
5258 const char *cluster_size_hint = "";
5259 if (qemu_opt_get_size(opts, BLOCK_OPT_CLUSTER_SIZE, 0)) {
5260 cluster_size_hint = " (try using a larger cluster size)";
5261 }
5262 error_setg(errp, "The image size is too large for file format '%s'"
5263 "%s", fmt, cluster_size_hint);
5264 error_free(local_err);
5265 local_err = NULL;
5266 }
5267
5268 out:
5269 qemu_opts_del(opts);
5270 qemu_opts_free(create_opts);
5271 error_propagate(errp, local_err);
5272 }
5273
5274 AioContext *bdrv_get_aio_context(BlockDriverState *bs)
5275 {
5276 return bs ? bs->aio_context : qemu_get_aio_context();
5277 }
5278
5279 void bdrv_coroutine_enter(BlockDriverState *bs, Coroutine *co)
5280 {
5281 aio_co_enter(bdrv_get_aio_context(bs), co);
5282 }
5283
5284 static void bdrv_do_remove_aio_context_notifier(BdrvAioNotifier *ban)
5285 {
5286 QLIST_REMOVE(ban, list);
5287 g_free(ban);
5288 }
5289
5290 void bdrv_detach_aio_context(BlockDriverState *bs)
5291 {
5292 BdrvAioNotifier *baf, *baf_tmp;
5293 BdrvChild *child;
5294
5295 if (!bs->drv) {
5296 return;
5297 }
5298
5299 assert(!bs->walking_aio_notifiers);
5300 bs->walking_aio_notifiers = true;
5301 QLIST_FOREACH_SAFE(baf, &bs->aio_notifiers, list, baf_tmp) {
5302 if (baf->deleted) {
5303 bdrv_do_remove_aio_context_notifier(baf);
5304 } else {
5305 baf->detach_aio_context(baf->opaque);
5306 }
5307 }
5308 /* Never mind iterating again to check for ->deleted. bdrv_close() will
5309 * remove remaining aio notifiers if we aren't called again.
5310 */
5311 bs->walking_aio_notifiers = false;
5312
5313 if (bs->drv->bdrv_detach_aio_context) {
5314 bs->drv->bdrv_detach_aio_context(bs);
5315 }
5316 QLIST_FOREACH(child, &bs->children, next) {
5317 bdrv_detach_aio_context(child->bs);
5318 }
5319
5320 if (bs->quiesce_counter) {
5321 aio_enable_external(bs->aio_context);
5322 }
5323 bs->aio_context = NULL;
5324 }
5325
5326 void bdrv_attach_aio_context(BlockDriverState *bs,
5327 AioContext *new_context)
5328 {
5329 BdrvAioNotifier *ban, *ban_tmp;
5330 BdrvChild *child;
5331
5332 if (!bs->drv) {
5333 return;
5334 }
5335
5336 if (bs->quiesce_counter) {
5337 aio_disable_external(new_context);
5338 }
5339
5340 bs->aio_context = new_context;
5341
5342 QLIST_FOREACH(child, &bs->children, next) {
5343 bdrv_attach_aio_context(child->bs, new_context);
5344 }
5345 if (bs->drv->bdrv_attach_aio_context) {
5346 bs->drv->bdrv_attach_aio_context(bs, new_context);
5347 }
5348
5349 assert(!bs->walking_aio_notifiers);
5350 bs->walking_aio_notifiers = true;
5351 QLIST_FOREACH_SAFE(ban, &bs->aio_notifiers, list, ban_tmp) {
5352 if (ban->deleted) {
5353 bdrv_do_remove_aio_context_notifier(ban);
5354 } else {
5355 ban->attached_aio_context(new_context, ban->opaque);
5356 }
5357 }
5358 bs->walking_aio_notifiers = false;
5359 }
5360
5361 /* The caller must own the AioContext lock for the old AioContext of bs, but it
5362 * must not own the AioContext lock for new_context (unless new_context is
5363 * the same as the current context of bs). */
5364 void bdrv_set_aio_context(BlockDriverState *bs, AioContext *new_context)
5365 {
5366 if (bdrv_get_aio_context(bs) == new_context) {
5367 return;
5368 }
5369
5370 bdrv_drained_begin(bs);
5371 bdrv_detach_aio_context(bs);
5372
5373 /* This function executes in the old AioContext so acquire the new one in
5374 * case it runs in a different thread.
5375 */
5376 aio_context_acquire(new_context);
5377 bdrv_attach_aio_context(bs, new_context);
5378 bdrv_drained_end(bs);
5379 aio_context_release(new_context);
5380 }
5381
5382 void bdrv_add_aio_context_notifier(BlockDriverState *bs,
5383 void (*attached_aio_context)(AioContext *new_context, void *opaque),
5384 void (*detach_aio_context)(void *opaque), void *opaque)
5385 {
5386 BdrvAioNotifier *ban = g_new(BdrvAioNotifier, 1);
5387 *ban = (BdrvAioNotifier){
5388 .attached_aio_context = attached_aio_context,
5389 .detach_aio_context = detach_aio_context,
5390 .opaque = opaque
5391 };
5392
5393 QLIST_INSERT_HEAD(&bs->aio_notifiers, ban, list);
5394 }
5395
5396 void bdrv_remove_aio_context_notifier(BlockDriverState *bs,
5397 void (*attached_aio_context)(AioContext *,
5398 void *),
5399 void (*detach_aio_context)(void *),
5400 void *opaque)
5401 {
5402 BdrvAioNotifier *ban, *ban_next;
5403
5404 QLIST_FOREACH_SAFE(ban, &bs->aio_notifiers, list, ban_next) {
5405 if (ban->attached_aio_context == attached_aio_context &&
5406 ban->detach_aio_context == detach_aio_context &&
5407 ban->opaque == opaque &&
5408 ban->deleted == false)
5409 {
5410 if (bs->walking_aio_notifiers) {
5411 ban->deleted = true;
5412 } else {
5413 bdrv_do_remove_aio_context_notifier(ban);
5414 }
5415 return;
5416 }
5417 }
5418
5419 abort();
5420 }
5421
5422 int bdrv_amend_options(BlockDriverState *bs, QemuOpts *opts,
5423 BlockDriverAmendStatusCB *status_cb, void *cb_opaque,
5424 Error **errp)
5425 {
5426 if (!bs->drv) {
5427 error_setg(errp, "Node is ejected");
5428 return -ENOMEDIUM;
5429 }
5430 if (!bs->drv->bdrv_amend_options) {
5431 error_setg(errp, "Block driver '%s' does not support option amendment",
5432 bs->drv->format_name);
5433 return -ENOTSUP;
5434 }
5435 return bs->drv->bdrv_amend_options(bs, opts, status_cb, cb_opaque, errp);
5436 }
5437
5438 /* This function will be called by the bdrv_recurse_is_first_non_filter method
5439 * of block filter and by bdrv_is_first_non_filter.
5440 * It is used to test if the given bs is the candidate or recurse more in the
5441 * node graph.
5442 */
5443 bool bdrv_recurse_is_first_non_filter(BlockDriverState *bs,
5444 BlockDriverState *candidate)
5445 {
5446 /* return false if basic checks fails */
5447 if (!bs || !bs->drv) {
5448 return false;
5449 }
5450
5451 /* the code reached a non block filter driver -> check if the bs is
5452 * the same as the candidate. It's the recursion termination condition.
5453 */
5454 if (!bs->drv->is_filter) {
5455 return bs == candidate;
5456 }
5457 /* Down this path the driver is a block filter driver */
5458
5459 /* If the block filter recursion method is defined use it to recurse down
5460 * the node graph.
5461 */
5462 if (bs->drv->bdrv_recurse_is_first_non_filter) {
5463 return bs->drv->bdrv_recurse_is_first_non_filter(bs, candidate);
5464 }
5465
5466 /* the driver is a block filter but don't allow to recurse -> return false
5467 */
5468 return false;
5469 }
5470
5471 /* This function checks if the candidate is the first non filter bs down it's
5472 * bs chain. Since we don't have pointers to parents it explore all bs chains
5473 * from the top. Some filters can choose not to pass down the recursion.
5474 */
5475 bool bdrv_is_first_non_filter(BlockDriverState *candidate)
5476 {
5477 BlockDriverState *bs;
5478 BdrvNextIterator it;
5479
5480 /* walk down the bs forest recursively */
5481 for (bs = bdrv_first(&it); bs; bs = bdrv_next(&it)) {
5482 bool perm;
5483
5484 /* try to recurse in this top level bs */
5485 perm = bdrv_recurse_is_first_non_filter(bs, candidate);
5486
5487 /* candidate is the first non filter */
5488 if (perm) {
5489 bdrv_next_cleanup(&it);
5490 return true;
5491 }
5492 }
5493
5494 return false;
5495 }
5496
5497 BlockDriverState *check_to_replace_node(BlockDriverState *parent_bs,
5498 const char *node_name, Error **errp)
5499 {
5500 BlockDriverState *to_replace_bs = bdrv_find_node(node_name);
5501 AioContext *aio_context;
5502
5503 if (!to_replace_bs) {
5504 error_setg(errp, "Node name '%s' not found", node_name);
5505 return NULL;
5506 }
5507
5508 aio_context = bdrv_get_aio_context(to_replace_bs);
5509 aio_context_acquire(aio_context);
5510
5511 if (bdrv_op_is_blocked(to_replace_bs, BLOCK_OP_TYPE_REPLACE, errp)) {
5512 to_replace_bs = NULL;
5513 goto out;
5514 }
5515
5516 /* We don't want arbitrary node of the BDS chain to be replaced only the top
5517 * most non filter in order to prevent data corruption.
5518 * Another benefit is that this tests exclude backing files which are
5519 * blocked by the backing blockers.
5520 */
5521 if (!bdrv_recurse_is_first_non_filter(parent_bs, to_replace_bs)) {
5522 error_setg(errp, "Only top most non filter can be replaced");
5523 to_replace_bs = NULL;
5524 goto out;
5525 }
5526
5527 out:
5528 aio_context_release(aio_context);
5529 return to_replace_bs;
5530 }
5531
5532 static bool append_open_options(QDict *d, BlockDriverState *bs)
5533 {
5534 const QDictEntry *entry;
5535 QemuOptDesc *desc;
5536 bool found_any = false;
5537
5538 for (entry = qdict_first(bs->options); entry;
5539 entry = qdict_next(bs->options, entry))
5540 {
5541 /* Exclude all non-driver-specific options */
5542 for (desc = bdrv_runtime_opts.desc; desc->name; desc++) {
5543 if (!strcmp(qdict_entry_key(entry), desc->name)) {
5544 break;
5545 }
5546 }
5547 if (desc->name) {
5548 continue;
5549 }
5550
5551 qdict_put_obj(d, qdict_entry_key(entry),
5552 qobject_ref(qdict_entry_value(entry)));
5553 found_any = true;
5554 }
5555
5556 return found_any;
5557 }
5558
5559 /* Note: This function may return false positives; it may return true
5560 * even if opening the backing file specified by bs's image header
5561 * would result in exactly bs->backing. */
5562 static bool bdrv_backing_overridden(BlockDriverState *bs)
5563 {
5564 if (bs->backing) {
5565 return strcmp(bs->auto_backing_file,
5566 bs->backing->bs->filename);
5567 } else {
5568 /* No backing BDS, so if the image header reports any backing
5569 * file, it must have been suppressed */
5570 return bs->auto_backing_file[0] != '\0';
5571 }
5572 }
5573
5574 /* Updates the following BDS fields:
5575 * - exact_filename: A filename which may be used for opening a block device
5576 * which (mostly) equals the given BDS (even without any
5577 * other options; so reading and writing must return the same
5578 * results, but caching etc. may be different)
5579 * - full_open_options: Options which, when given when opening a block device
5580 * (without a filename), result in a BDS (mostly)
5581 * equalling the given one
5582 * - filename: If exact_filename is set, it is copied here. Otherwise,
5583 * full_open_options is converted to a JSON object, prefixed with
5584 * "json:" (for use through the JSON pseudo protocol) and put here.
5585 */
5586 void bdrv_refresh_filename(BlockDriverState *bs)
5587 {
5588 BlockDriver *drv = bs->drv;
5589 BdrvChild *child;
5590 QDict *opts;
5591 bool backing_overridden;
5592
5593 if (!drv) {
5594 return;
5595 }
5596
5597 /* This BDS's file name may depend on any of its children's file names, so
5598 * refresh those first */
5599 QLIST_FOREACH(child, &bs->children, next) {
5600 bdrv_refresh_filename(child->bs);
5601 }
5602
5603 if (bs->implicit) {
5604 /* For implicit nodes, just copy everything from the single child */
5605 child = QLIST_FIRST(&bs->children);
5606 assert(QLIST_NEXT(child, next) == NULL);
5607
5608 pstrcpy(bs->exact_filename, sizeof(bs->exact_filename),
5609 child->bs->exact_filename);
5610 pstrcpy(bs->filename, sizeof(bs->filename), child->bs->filename);
5611
5612 bs->full_open_options = qobject_ref(child->bs->full_open_options);
5613
5614 return;
5615 }
5616
5617 backing_overridden = bdrv_backing_overridden(bs);
5618
5619 if (bs->open_flags & BDRV_O_NO_IO) {
5620 /* Without I/O, the backing file does not change anything.
5621 * Therefore, in such a case (primarily qemu-img), we can
5622 * pretend the backing file has not been overridden even if
5623 * it technically has been. */
5624 backing_overridden = false;
5625 }
5626
5627 if (drv->bdrv_refresh_filename) {
5628 /* Obsolete information is of no use here, so drop the old file name
5629 * information before refreshing it */
5630 bs->exact_filename[0] = '\0';
5631 if (bs->full_open_options) {
5632 qobject_unref(bs->full_open_options);
5633 bs->full_open_options = NULL;
5634 }
5635
5636 opts = qdict_new();
5637 append_open_options(opts, bs);
5638 drv->bdrv_refresh_filename(bs, opts);
5639 qobject_unref(opts);
5640 } else if (bs->file) {
5641 /* Try to reconstruct valid information from the underlying file */
5642 bool has_open_options;
5643
5644 bs->exact_filename[0] = '\0';
5645 if (bs->full_open_options) {
5646 qobject_unref(bs->full_open_options);
5647 bs->full_open_options = NULL;
5648 }
5649
5650 opts = qdict_new();
5651 has_open_options = append_open_options(opts, bs);
5652 has_open_options |= backing_overridden;
5653
5654 /* If no specific options have been given for this BDS, the filename of
5655 * the underlying file should suffice for this one as well */
5656 if (bs->file->bs->exact_filename[0] && !has_open_options) {
5657 strcpy(bs->exact_filename, bs->file->bs->exact_filename);
5658 }
5659 /* Reconstructing the full options QDict is simple for most format block
5660 * drivers, as long as the full options are known for the underlying
5661 * file BDS. The full options QDict of that file BDS should somehow
5662 * contain a representation of the filename, therefore the following
5663 * suffices without querying the (exact_)filename of this BDS. */
5664 if (bs->file->bs->full_open_options &&
5665 (!bs->backing || bs->backing->bs->full_open_options))
5666 {
5667 qdict_put_str(opts, "driver", drv->format_name);
5668 qdict_put(opts, "file",
5669 qobject_ref(bs->file->bs->full_open_options));
5670
5671 if (bs->backing) {
5672 qdict_put(opts, "backing",
5673 qobject_ref(bs->backing->bs->full_open_options));
5674 } else if (backing_overridden) {
5675 qdict_put_null(opts, "backing");
5676 }
5677
5678 bs->full_open_options = opts;
5679 } else {
5680 qobject_unref(opts);
5681 }
5682 } else if (!bs->full_open_options && qdict_size(bs->options)) {
5683 /* There is no underlying file BDS (at least referenced by BDS.file),
5684 * so the full options QDict should be equal to the options given
5685 * specifically for this block device when it was opened (plus the
5686 * driver specification).
5687 * Because those options don't change, there is no need to update
5688 * full_open_options when it's already set. */
5689
5690 opts = qdict_new();
5691 append_open_options(opts, bs);
5692 qdict_put_str(opts, "driver", drv->format_name);
5693
5694 if (bs->exact_filename[0]) {
5695 /* This may not work for all block protocol drivers (some may
5696 * require this filename to be parsed), but we have to find some
5697 * default solution here, so just include it. If some block driver
5698 * does not support pure options without any filename at all or
5699 * needs some special format of the options QDict, it needs to
5700 * implement the driver-specific bdrv_refresh_filename() function.
5701 */
5702 qdict_put_str(opts, "filename", bs->exact_filename);
5703 }
5704
5705 bs->full_open_options = opts;
5706 }
5707
5708 if (bs->exact_filename[0]) {
5709 pstrcpy(bs->filename, sizeof(bs->filename), bs->exact_filename);
5710 } else if (bs->full_open_options) {
5711 QString *json = qobject_to_json(QOBJECT(bs->full_open_options));
5712 snprintf(bs->filename, sizeof(bs->filename), "json:%s",
5713 qstring_get_str(json));
5714 qobject_unref(json);
5715 }
5716 }
5717
5718 /*
5719 * Hot add/remove a BDS's child. So the user can take a child offline when
5720 * it is broken and take a new child online
5721 */
5722 void bdrv_add_child(BlockDriverState *parent_bs, BlockDriverState *child_bs,
5723 Error **errp)
5724 {
5725
5726 if (!parent_bs->drv || !parent_bs->drv->bdrv_add_child) {
5727 error_setg(errp, "The node %s does not support adding a child",
5728 bdrv_get_device_or_node_name(parent_bs));
5729 return;
5730 }
5731
5732 if (!QLIST_EMPTY(&child_bs->parents)) {
5733 error_setg(errp, "The node %s already has a parent",
5734 child_bs->node_name);
5735 return;
5736 }
5737
5738 parent_bs->drv->bdrv_add_child(parent_bs, child_bs, errp);
5739 }
5740
5741 void bdrv_del_child(BlockDriverState *parent_bs, BdrvChild *child, Error **errp)
5742 {
5743 BdrvChild *tmp;
5744
5745 if (!parent_bs->drv || !parent_bs->drv->bdrv_del_child) {
5746 error_setg(errp, "The node %s does not support removing a child",
5747 bdrv_get_device_or_node_name(parent_bs));
5748 return;
5749 }
5750
5751 QLIST_FOREACH(tmp, &parent_bs->children, next) {
5752 if (tmp == child) {
5753 break;
5754 }
5755 }
5756
5757 if (!tmp) {
5758 error_setg(errp, "The node %s does not have a child named %s",
5759 bdrv_get_device_or_node_name(parent_bs),
5760 bdrv_get_device_or_node_name(child->bs));
5761 return;
5762 }
5763
5764 parent_bs->drv->bdrv_del_child(parent_bs, child, errp);
5765 }
5766
5767 bool bdrv_can_store_new_dirty_bitmap(BlockDriverState *bs, const char *name,
5768 uint32_t granularity, Error **errp)
5769 {
5770 BlockDriver *drv = bs->drv;
5771
5772 if (!drv) {
5773 error_setg_errno(errp, ENOMEDIUM,
5774 "Can't store persistent bitmaps to %s",
5775 bdrv_get_device_or_node_name(bs));
5776 return false;
5777 }
5778
5779 if (!drv->bdrv_can_store_new_dirty_bitmap) {
5780 error_setg_errno(errp, ENOTSUP,
5781 "Can't store persistent bitmaps to %s",
5782 bdrv_get_device_or_node_name(bs));
5783 return false;
5784 }
5785
5786 return drv->bdrv_can_store_new_dirty_bitmap(bs, name, granularity, errp);
5787 }