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