block: honor BDRV_O_ALLOW_RDWR when clearing bs->read_only
[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 #include "qemu/osdep.h"
25 #include "block/trace.h"
26 #include "block/block_int.h"
27 #include "block/blockjob.h"
28 #include "block/nbd.h"
29 #include "qemu/error-report.h"
30 #include "module_block.h"
31 #include "qemu/module.h"
32 #include "qapi/qmp/qerror.h"
33 #include "qapi/qmp/qbool.h"
34 #include "qapi/qmp/qjson.h"
35 #include "sysemu/block-backend.h"
36 #include "sysemu/sysemu.h"
37 #include "qemu/notify.h"
38 #include "qemu/coroutine.h"
39 #include "block/qapi.h"
40 #include "qmp-commands.h"
41 #include "qemu/timer.h"
42 #include "qapi-event.h"
43 #include "qemu/cutils.h"
44 #include "qemu/id.h"
45 #include "qapi/util.h"
46
47 #ifdef CONFIG_BSD
48 #include <sys/ioctl.h>
49 #include <sys/queue.h>
50 #ifndef __DragonFly__
51 #include <sys/disk.h>
52 #endif
53 #endif
54
55 #ifdef _WIN32
56 #include <windows.h>
57 #endif
58
59 #define NOT_DONE 0x7fffffff /* used while emulated sync operation in progress */
60
61 static QTAILQ_HEAD(, BlockDriverState) graph_bdrv_states =
62 QTAILQ_HEAD_INITIALIZER(graph_bdrv_states);
63
64 static QTAILQ_HEAD(, BlockDriverState) all_bdrv_states =
65 QTAILQ_HEAD_INITIALIZER(all_bdrv_states);
66
67 static QLIST_HEAD(, BlockDriver) bdrv_drivers =
68 QLIST_HEAD_INITIALIZER(bdrv_drivers);
69
70 static BlockDriverState *bdrv_open_inherit(const char *filename,
71 const char *reference,
72 QDict *options, int flags,
73 BlockDriverState *parent,
74 const BdrvChildRole *child_role,
75 Error **errp);
76
77 /* If non-zero, use only whitelisted block drivers */
78 static int use_bdrv_whitelist;
79
80 #ifdef _WIN32
81 static int is_windows_drive_prefix(const char *filename)
82 {
83 return (((filename[0] >= 'a' && filename[0] <= 'z') ||
84 (filename[0] >= 'A' && filename[0] <= 'Z')) &&
85 filename[1] == ':');
86 }
87
88 int is_windows_drive(const char *filename)
89 {
90 if (is_windows_drive_prefix(filename) &&
91 filename[2] == '\0')
92 return 1;
93 if (strstart(filename, "\\\\.\\", NULL) ||
94 strstart(filename, "//./", NULL))
95 return 1;
96 return 0;
97 }
98 #endif
99
100 size_t bdrv_opt_mem_align(BlockDriverState *bs)
101 {
102 if (!bs || !bs->drv) {
103 /* page size or 4k (hdd sector size) should be on the safe side */
104 return MAX(4096, getpagesize());
105 }
106
107 return bs->bl.opt_mem_alignment;
108 }
109
110 size_t bdrv_min_mem_align(BlockDriverState *bs)
111 {
112 if (!bs || !bs->drv) {
113 /* page size or 4k (hdd sector size) should be on the safe side */
114 return MAX(4096, getpagesize());
115 }
116
117 return bs->bl.min_mem_alignment;
118 }
119
120 /* check if the path starts with "<protocol>:" */
121 int path_has_protocol(const char *path)
122 {
123 const char *p;
124
125 #ifdef _WIN32
126 if (is_windows_drive(path) ||
127 is_windows_drive_prefix(path)) {
128 return 0;
129 }
130 p = path + strcspn(path, ":/\\");
131 #else
132 p = path + strcspn(path, ":/");
133 #endif
134
135 return *p == ':';
136 }
137
138 int path_is_absolute(const char *path)
139 {
140 #ifdef _WIN32
141 /* specific case for names like: "\\.\d:" */
142 if (is_windows_drive(path) || is_windows_drive_prefix(path)) {
143 return 1;
144 }
145 return (*path == '/' || *path == '\\');
146 #else
147 return (*path == '/');
148 #endif
149 }
150
151 /* if filename is absolute, just copy it to dest. Otherwise, build a
152 path to it by considering it is relative to base_path. URL are
153 supported. */
154 void path_combine(char *dest, int dest_size,
155 const char *base_path,
156 const char *filename)
157 {
158 const char *p, *p1;
159 int len;
160
161 if (dest_size <= 0)
162 return;
163 if (path_is_absolute(filename)) {
164 pstrcpy(dest, dest_size, filename);
165 } else {
166 p = strchr(base_path, ':');
167 if (p)
168 p++;
169 else
170 p = base_path;
171 p1 = strrchr(base_path, '/');
172 #ifdef _WIN32
173 {
174 const char *p2;
175 p2 = strrchr(base_path, '\\');
176 if (!p1 || p2 > p1)
177 p1 = p2;
178 }
179 #endif
180 if (p1)
181 p1++;
182 else
183 p1 = base_path;
184 if (p1 > p)
185 p = p1;
186 len = p - base_path;
187 if (len > dest_size - 1)
188 len = dest_size - 1;
189 memcpy(dest, base_path, len);
190 dest[len] = '\0';
191 pstrcat(dest, dest_size, filename);
192 }
193 }
194
195 int bdrv_set_read_only(BlockDriverState *bs, bool read_only, Error **errp)
196 {
197 /* Do not set read_only if copy_on_read is enabled */
198 if (bs->copy_on_read && read_only) {
199 error_setg(errp, "Can't set node '%s' to r/o with copy-on-read enabled",
200 bdrv_get_device_or_node_name(bs));
201 return -EINVAL;
202 }
203
204 /* Do not clear read_only if it is prohibited */
205 if (!read_only && !(bs->open_flags & BDRV_O_ALLOW_RDWR)) {
206 error_setg(errp, "Node '%s' is read only",
207 bdrv_get_device_or_node_name(bs));
208 return -EPERM;
209 }
210
211 bs->read_only = read_only;
212 return 0;
213 }
214
215 void bdrv_get_full_backing_filename_from_filename(const char *backed,
216 const char *backing,
217 char *dest, size_t sz,
218 Error **errp)
219 {
220 if (backing[0] == '\0' || path_has_protocol(backing) ||
221 path_is_absolute(backing))
222 {
223 pstrcpy(dest, sz, backing);
224 } else if (backed[0] == '\0' || strstart(backed, "json:", NULL)) {
225 error_setg(errp, "Cannot use relative backing file names for '%s'",
226 backed);
227 } else {
228 path_combine(dest, sz, backed, backing);
229 }
230 }
231
232 void bdrv_get_full_backing_filename(BlockDriverState *bs, char *dest, size_t sz,
233 Error **errp)
234 {
235 char *backed = bs->exact_filename[0] ? bs->exact_filename : bs->filename;
236
237 bdrv_get_full_backing_filename_from_filename(backed, bs->backing_file,
238 dest, sz, errp);
239 }
240
241 void bdrv_register(BlockDriver *bdrv)
242 {
243 QLIST_INSERT_HEAD(&bdrv_drivers, bdrv, list);
244 }
245
246 BlockDriverState *bdrv_new(void)
247 {
248 BlockDriverState *bs;
249 int i;
250
251 bs = g_new0(BlockDriverState, 1);
252 QLIST_INIT(&bs->dirty_bitmaps);
253 for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
254 QLIST_INIT(&bs->op_blockers[i]);
255 }
256 notifier_with_return_list_init(&bs->before_write_notifiers);
257 bs->refcnt = 1;
258 bs->aio_context = qemu_get_aio_context();
259
260 qemu_co_queue_init(&bs->flush_queue);
261
262 QTAILQ_INSERT_TAIL(&all_bdrv_states, bs, bs_list);
263
264 return bs;
265 }
266
267 static BlockDriver *bdrv_do_find_format(const char *format_name)
268 {
269 BlockDriver *drv1;
270
271 QLIST_FOREACH(drv1, &bdrv_drivers, list) {
272 if (!strcmp(drv1->format_name, format_name)) {
273 return drv1;
274 }
275 }
276
277 return NULL;
278 }
279
280 BlockDriver *bdrv_find_format(const char *format_name)
281 {
282 BlockDriver *drv1;
283 int i;
284
285 drv1 = bdrv_do_find_format(format_name);
286 if (drv1) {
287 return drv1;
288 }
289
290 /* The driver isn't registered, maybe we need to load a module */
291 for (i = 0; i < (int)ARRAY_SIZE(block_driver_modules); ++i) {
292 if (!strcmp(block_driver_modules[i].format_name, format_name)) {
293 block_module_load_one(block_driver_modules[i].library_name);
294 break;
295 }
296 }
297
298 return bdrv_do_find_format(format_name);
299 }
300
301 static int bdrv_is_whitelisted(BlockDriver *drv, bool read_only)
302 {
303 static const char *whitelist_rw[] = {
304 CONFIG_BDRV_RW_WHITELIST
305 };
306 static const char *whitelist_ro[] = {
307 CONFIG_BDRV_RO_WHITELIST
308 };
309 const char **p;
310
311 if (!whitelist_rw[0] && !whitelist_ro[0]) {
312 return 1; /* no whitelist, anything goes */
313 }
314
315 for (p = whitelist_rw; *p; p++) {
316 if (!strcmp(drv->format_name, *p)) {
317 return 1;
318 }
319 }
320 if (read_only) {
321 for (p = whitelist_ro; *p; p++) {
322 if (!strcmp(drv->format_name, *p)) {
323 return 1;
324 }
325 }
326 }
327 return 0;
328 }
329
330 bool bdrv_uses_whitelist(void)
331 {
332 return use_bdrv_whitelist;
333 }
334
335 typedef struct CreateCo {
336 BlockDriver *drv;
337 char *filename;
338 QemuOpts *opts;
339 int ret;
340 Error *err;
341 } CreateCo;
342
343 static void coroutine_fn bdrv_create_co_entry(void *opaque)
344 {
345 Error *local_err = NULL;
346 int ret;
347
348 CreateCo *cco = opaque;
349 assert(cco->drv);
350
351 ret = cco->drv->bdrv_create(cco->filename, cco->opts, &local_err);
352 error_propagate(&cco->err, local_err);
353 cco->ret = ret;
354 }
355
356 int bdrv_create(BlockDriver *drv, const char* filename,
357 QemuOpts *opts, Error **errp)
358 {
359 int ret;
360
361 Coroutine *co;
362 CreateCo cco = {
363 .drv = drv,
364 .filename = g_strdup(filename),
365 .opts = opts,
366 .ret = NOT_DONE,
367 .err = NULL,
368 };
369
370 if (!drv->bdrv_create) {
371 error_setg(errp, "Driver '%s' does not support image creation", drv->format_name);
372 ret = -ENOTSUP;
373 goto out;
374 }
375
376 if (qemu_in_coroutine()) {
377 /* Fast-path if already in coroutine context */
378 bdrv_create_co_entry(&cco);
379 } else {
380 co = qemu_coroutine_create(bdrv_create_co_entry, &cco);
381 qemu_coroutine_enter(co);
382 while (cco.ret == NOT_DONE) {
383 aio_poll(qemu_get_aio_context(), true);
384 }
385 }
386
387 ret = cco.ret;
388 if (ret < 0) {
389 if (cco.err) {
390 error_propagate(errp, cco.err);
391 } else {
392 error_setg_errno(errp, -ret, "Could not create image");
393 }
394 }
395
396 out:
397 g_free(cco.filename);
398 return ret;
399 }
400
401 int bdrv_create_file(const char *filename, QemuOpts *opts, Error **errp)
402 {
403 BlockDriver *drv;
404 Error *local_err = NULL;
405 int ret;
406
407 drv = bdrv_find_protocol(filename, true, errp);
408 if (drv == NULL) {
409 return -ENOENT;
410 }
411
412 ret = bdrv_create(drv, filename, opts, &local_err);
413 error_propagate(errp, local_err);
414 return ret;
415 }
416
417 /**
418 * Try to get @bs's logical and physical block size.
419 * On success, store them in @bsz struct and return 0.
420 * On failure return -errno.
421 * @bs must not be empty.
422 */
423 int bdrv_probe_blocksizes(BlockDriverState *bs, BlockSizes *bsz)
424 {
425 BlockDriver *drv = bs->drv;
426
427 if (drv && drv->bdrv_probe_blocksizes) {
428 return drv->bdrv_probe_blocksizes(bs, bsz);
429 }
430
431 return -ENOTSUP;
432 }
433
434 /**
435 * Try to get @bs's geometry (cyls, heads, sectors).
436 * On success, store them in @geo struct and return 0.
437 * On failure return -errno.
438 * @bs must not be empty.
439 */
440 int bdrv_probe_geometry(BlockDriverState *bs, HDGeometry *geo)
441 {
442 BlockDriver *drv = bs->drv;
443
444 if (drv && drv->bdrv_probe_geometry) {
445 return drv->bdrv_probe_geometry(bs, geo);
446 }
447
448 return -ENOTSUP;
449 }
450
451 /*
452 * Create a uniquely-named empty temporary file.
453 * Return 0 upon success, otherwise a negative errno value.
454 */
455 int get_tmp_filename(char *filename, int size)
456 {
457 #ifdef _WIN32
458 char temp_dir[MAX_PATH];
459 /* GetTempFileName requires that its output buffer (4th param)
460 have length MAX_PATH or greater. */
461 assert(size >= MAX_PATH);
462 return (GetTempPath(MAX_PATH, temp_dir)
463 && GetTempFileName(temp_dir, "qem", 0, filename)
464 ? 0 : -GetLastError());
465 #else
466 int fd;
467 const char *tmpdir;
468 tmpdir = getenv("TMPDIR");
469 if (!tmpdir) {
470 tmpdir = "/var/tmp";
471 }
472 if (snprintf(filename, size, "%s/vl.XXXXXX", tmpdir) >= size) {
473 return -EOVERFLOW;
474 }
475 fd = mkstemp(filename);
476 if (fd < 0) {
477 return -errno;
478 }
479 if (close(fd) != 0) {
480 unlink(filename);
481 return -errno;
482 }
483 return 0;
484 #endif
485 }
486
487 /*
488 * Detect host devices. By convention, /dev/cdrom[N] is always
489 * recognized as a host CDROM.
490 */
491 static BlockDriver *find_hdev_driver(const char *filename)
492 {
493 int score_max = 0, score;
494 BlockDriver *drv = NULL, *d;
495
496 QLIST_FOREACH(d, &bdrv_drivers, list) {
497 if (d->bdrv_probe_device) {
498 score = d->bdrv_probe_device(filename);
499 if (score > score_max) {
500 score_max = score;
501 drv = d;
502 }
503 }
504 }
505
506 return drv;
507 }
508
509 static BlockDriver *bdrv_do_find_protocol(const char *protocol)
510 {
511 BlockDriver *drv1;
512
513 QLIST_FOREACH(drv1, &bdrv_drivers, list) {
514 if (drv1->protocol_name && !strcmp(drv1->protocol_name, protocol)) {
515 return drv1;
516 }
517 }
518
519 return NULL;
520 }
521
522 BlockDriver *bdrv_find_protocol(const char *filename,
523 bool allow_protocol_prefix,
524 Error **errp)
525 {
526 BlockDriver *drv1;
527 char protocol[128];
528 int len;
529 const char *p;
530 int i;
531
532 /* TODO Drivers without bdrv_file_open must be specified explicitly */
533
534 /*
535 * XXX(hch): we really should not let host device detection
536 * override an explicit protocol specification, but moving this
537 * later breaks access to device names with colons in them.
538 * Thanks to the brain-dead persistent naming schemes on udev-
539 * based Linux systems those actually are quite common.
540 */
541 drv1 = find_hdev_driver(filename);
542 if (drv1) {
543 return drv1;
544 }
545
546 if (!path_has_protocol(filename) || !allow_protocol_prefix) {
547 return &bdrv_file;
548 }
549
550 p = strchr(filename, ':');
551 assert(p != NULL);
552 len = p - filename;
553 if (len > sizeof(protocol) - 1)
554 len = sizeof(protocol) - 1;
555 memcpy(protocol, filename, len);
556 protocol[len] = '\0';
557
558 drv1 = bdrv_do_find_protocol(protocol);
559 if (drv1) {
560 return drv1;
561 }
562
563 for (i = 0; i < (int)ARRAY_SIZE(block_driver_modules); ++i) {
564 if (block_driver_modules[i].protocol_name &&
565 !strcmp(block_driver_modules[i].protocol_name, protocol)) {
566 block_module_load_one(block_driver_modules[i].library_name);
567 break;
568 }
569 }
570
571 drv1 = bdrv_do_find_protocol(protocol);
572 if (!drv1) {
573 error_setg(errp, "Unknown protocol '%s'", protocol);
574 }
575 return drv1;
576 }
577
578 /*
579 * Guess image format by probing its contents.
580 * This is not a good idea when your image is raw (CVE-2008-2004), but
581 * we do it anyway for backward compatibility.
582 *
583 * @buf contains the image's first @buf_size bytes.
584 * @buf_size is the buffer size in bytes (generally BLOCK_PROBE_BUF_SIZE,
585 * but can be smaller if the image file is smaller)
586 * @filename is its filename.
587 *
588 * For all block drivers, call the bdrv_probe() method to get its
589 * probing score.
590 * Return the first block driver with the highest probing score.
591 */
592 BlockDriver *bdrv_probe_all(const uint8_t *buf, int buf_size,
593 const char *filename)
594 {
595 int score_max = 0, score;
596 BlockDriver *drv = NULL, *d;
597
598 QLIST_FOREACH(d, &bdrv_drivers, list) {
599 if (d->bdrv_probe) {
600 score = d->bdrv_probe(buf, buf_size, filename);
601 if (score > score_max) {
602 score_max = score;
603 drv = d;
604 }
605 }
606 }
607
608 return drv;
609 }
610
611 static int find_image_format(BlockBackend *file, const char *filename,
612 BlockDriver **pdrv, Error **errp)
613 {
614 BlockDriver *drv;
615 uint8_t buf[BLOCK_PROBE_BUF_SIZE];
616 int ret = 0;
617
618 /* Return the raw BlockDriver * to scsi-generic devices or empty drives */
619 if (blk_is_sg(file) || !blk_is_inserted(file) || blk_getlength(file) == 0) {
620 *pdrv = &bdrv_raw;
621 return ret;
622 }
623
624 ret = blk_pread(file, 0, buf, sizeof(buf));
625 if (ret < 0) {
626 error_setg_errno(errp, -ret, "Could not read image for determining its "
627 "format");
628 *pdrv = NULL;
629 return ret;
630 }
631
632 drv = bdrv_probe_all(buf, ret, filename);
633 if (!drv) {
634 error_setg(errp, "Could not determine image format: No compatible "
635 "driver found");
636 ret = -ENOENT;
637 }
638 *pdrv = drv;
639 return ret;
640 }
641
642 /**
643 * Set the current 'total_sectors' value
644 * Return 0 on success, -errno on error.
645 */
646 static int refresh_total_sectors(BlockDriverState *bs, int64_t hint)
647 {
648 BlockDriver *drv = bs->drv;
649
650 /* Do not attempt drv->bdrv_getlength() on scsi-generic devices */
651 if (bdrv_is_sg(bs))
652 return 0;
653
654 /* query actual device if possible, otherwise just trust the hint */
655 if (drv->bdrv_getlength) {
656 int64_t length = drv->bdrv_getlength(bs);
657 if (length < 0) {
658 return length;
659 }
660 hint = DIV_ROUND_UP(length, BDRV_SECTOR_SIZE);
661 }
662
663 bs->total_sectors = hint;
664 return 0;
665 }
666
667 /**
668 * Combines a QDict of new block driver @options with any missing options taken
669 * from @old_options, so that leaving out an option defaults to its old value.
670 */
671 static void bdrv_join_options(BlockDriverState *bs, QDict *options,
672 QDict *old_options)
673 {
674 if (bs->drv && bs->drv->bdrv_join_options) {
675 bs->drv->bdrv_join_options(options, old_options);
676 } else {
677 qdict_join(options, old_options, false);
678 }
679 }
680
681 /**
682 * Set open flags for a given discard mode
683 *
684 * Return 0 on success, -1 if the discard mode was invalid.
685 */
686 int bdrv_parse_discard_flags(const char *mode, int *flags)
687 {
688 *flags &= ~BDRV_O_UNMAP;
689
690 if (!strcmp(mode, "off") || !strcmp(mode, "ignore")) {
691 /* do nothing */
692 } else if (!strcmp(mode, "on") || !strcmp(mode, "unmap")) {
693 *flags |= BDRV_O_UNMAP;
694 } else {
695 return -1;
696 }
697
698 return 0;
699 }
700
701 /**
702 * Set open flags for a given cache mode
703 *
704 * Return 0 on success, -1 if the cache mode was invalid.
705 */
706 int bdrv_parse_cache_mode(const char *mode, int *flags, bool *writethrough)
707 {
708 *flags &= ~BDRV_O_CACHE_MASK;
709
710 if (!strcmp(mode, "off") || !strcmp(mode, "none")) {
711 *writethrough = false;
712 *flags |= BDRV_O_NOCACHE;
713 } else if (!strcmp(mode, "directsync")) {
714 *writethrough = true;
715 *flags |= BDRV_O_NOCACHE;
716 } else if (!strcmp(mode, "writeback")) {
717 *writethrough = false;
718 } else if (!strcmp(mode, "unsafe")) {
719 *writethrough = false;
720 *flags |= BDRV_O_NO_FLUSH;
721 } else if (!strcmp(mode, "writethrough")) {
722 *writethrough = true;
723 } else {
724 return -1;
725 }
726
727 return 0;
728 }
729
730 static char *bdrv_child_get_parent_desc(BdrvChild *c)
731 {
732 BlockDriverState *parent = c->opaque;
733 return g_strdup(bdrv_get_device_or_node_name(parent));
734 }
735
736 static void bdrv_child_cb_drained_begin(BdrvChild *child)
737 {
738 BlockDriverState *bs = child->opaque;
739 bdrv_drained_begin(bs);
740 }
741
742 static void bdrv_child_cb_drained_end(BdrvChild *child)
743 {
744 BlockDriverState *bs = child->opaque;
745 bdrv_drained_end(bs);
746 }
747
748 /*
749 * Returns the options and flags that a temporary snapshot should get, based on
750 * the originally requested flags (the originally requested image will have
751 * flags like a backing file)
752 */
753 static void bdrv_temp_snapshot_options(int *child_flags, QDict *child_options,
754 int parent_flags, QDict *parent_options)
755 {
756 *child_flags = (parent_flags & ~BDRV_O_SNAPSHOT) | BDRV_O_TEMPORARY;
757
758 /* For temporary files, unconditional cache=unsafe is fine */
759 qdict_set_default_str(child_options, BDRV_OPT_CACHE_DIRECT, "off");
760 qdict_set_default_str(child_options, BDRV_OPT_CACHE_NO_FLUSH, "on");
761
762 /* Copy the read-only option from the parent */
763 qdict_copy_default(child_options, parent_options, BDRV_OPT_READ_ONLY);
764
765 /* aio=native doesn't work for cache.direct=off, so disable it for the
766 * temporary snapshot */
767 *child_flags &= ~BDRV_O_NATIVE_AIO;
768 }
769
770 /*
771 * Returns the options and flags that bs->file should get if a protocol driver
772 * is expected, based on the given options and flags for the parent BDS
773 */
774 static void bdrv_inherited_options(int *child_flags, QDict *child_options,
775 int parent_flags, QDict *parent_options)
776 {
777 int flags = parent_flags;
778
779 /* Enable protocol handling, disable format probing for bs->file */
780 flags |= BDRV_O_PROTOCOL;
781
782 /* If the cache mode isn't explicitly set, inherit direct and no-flush from
783 * the parent. */
784 qdict_copy_default(child_options, parent_options, BDRV_OPT_CACHE_DIRECT);
785 qdict_copy_default(child_options, parent_options, BDRV_OPT_CACHE_NO_FLUSH);
786
787 /* Inherit the read-only option from the parent if it's not set */
788 qdict_copy_default(child_options, parent_options, BDRV_OPT_READ_ONLY);
789
790 /* Our block drivers take care to send flushes and respect unmap policy,
791 * so we can default to enable both on lower layers regardless of the
792 * corresponding parent options. */
793 qdict_set_default_str(child_options, BDRV_OPT_DISCARD, "unmap");
794
795 /* Clear flags that only apply to the top layer */
796 flags &= ~(BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING | BDRV_O_COPY_ON_READ |
797 BDRV_O_NO_IO);
798
799 *child_flags = flags;
800 }
801
802 const BdrvChildRole child_file = {
803 .get_parent_desc = bdrv_child_get_parent_desc,
804 .inherit_options = bdrv_inherited_options,
805 .drained_begin = bdrv_child_cb_drained_begin,
806 .drained_end = bdrv_child_cb_drained_end,
807 };
808
809 /*
810 * Returns the options and flags that bs->file should get if the use of formats
811 * (and not only protocols) is permitted for it, based on the given options and
812 * flags for the parent BDS
813 */
814 static void bdrv_inherited_fmt_options(int *child_flags, QDict *child_options,
815 int parent_flags, QDict *parent_options)
816 {
817 child_file.inherit_options(child_flags, child_options,
818 parent_flags, parent_options);
819
820 *child_flags &= ~(BDRV_O_PROTOCOL | BDRV_O_NO_IO);
821 }
822
823 const BdrvChildRole child_format = {
824 .get_parent_desc = bdrv_child_get_parent_desc,
825 .inherit_options = bdrv_inherited_fmt_options,
826 .drained_begin = bdrv_child_cb_drained_begin,
827 .drained_end = bdrv_child_cb_drained_end,
828 };
829
830 static void bdrv_backing_attach(BdrvChild *c)
831 {
832 BlockDriverState *parent = c->opaque;
833 BlockDriverState *backing_hd = c->bs;
834
835 assert(!parent->backing_blocker);
836 error_setg(&parent->backing_blocker,
837 "node is used as backing hd of '%s'",
838 bdrv_get_device_or_node_name(parent));
839
840 parent->open_flags &= ~BDRV_O_NO_BACKING;
841 pstrcpy(parent->backing_file, sizeof(parent->backing_file),
842 backing_hd->filename);
843 pstrcpy(parent->backing_format, sizeof(parent->backing_format),
844 backing_hd->drv ? backing_hd->drv->format_name : "");
845
846 bdrv_op_block_all(backing_hd, parent->backing_blocker);
847 /* Otherwise we won't be able to commit or stream */
848 bdrv_op_unblock(backing_hd, BLOCK_OP_TYPE_COMMIT_TARGET,
849 parent->backing_blocker);
850 bdrv_op_unblock(backing_hd, BLOCK_OP_TYPE_STREAM,
851 parent->backing_blocker);
852 /*
853 * We do backup in 3 ways:
854 * 1. drive backup
855 * The target bs is new opened, and the source is top BDS
856 * 2. blockdev backup
857 * Both the source and the target are top BDSes.
858 * 3. internal backup(used for block replication)
859 * Both the source and the target are backing file
860 *
861 * In case 1 and 2, neither the source nor the target is the backing file.
862 * In case 3, we will block the top BDS, so there is only one block job
863 * for the top BDS and its backing chain.
864 */
865 bdrv_op_unblock(backing_hd, BLOCK_OP_TYPE_BACKUP_SOURCE,
866 parent->backing_blocker);
867 bdrv_op_unblock(backing_hd, BLOCK_OP_TYPE_BACKUP_TARGET,
868 parent->backing_blocker);
869 }
870
871 static void bdrv_backing_detach(BdrvChild *c)
872 {
873 BlockDriverState *parent = c->opaque;
874
875 assert(parent->backing_blocker);
876 bdrv_op_unblock_all(c->bs, parent->backing_blocker);
877 error_free(parent->backing_blocker);
878 parent->backing_blocker = NULL;
879 }
880
881 /*
882 * Returns the options and flags that bs->backing should get, based on the
883 * given options and flags for the parent BDS
884 */
885 static void bdrv_backing_options(int *child_flags, QDict *child_options,
886 int parent_flags, QDict *parent_options)
887 {
888 int flags = parent_flags;
889
890 /* The cache mode is inherited unmodified for backing files; except WCE,
891 * which is only applied on the top level (BlockBackend) */
892 qdict_copy_default(child_options, parent_options, BDRV_OPT_CACHE_DIRECT);
893 qdict_copy_default(child_options, parent_options, BDRV_OPT_CACHE_NO_FLUSH);
894
895 /* backing files always opened read-only */
896 qdict_set_default_str(child_options, BDRV_OPT_READ_ONLY, "on");
897 flags &= ~BDRV_O_COPY_ON_READ;
898
899 /* snapshot=on is handled on the top layer */
900 flags &= ~(BDRV_O_SNAPSHOT | BDRV_O_TEMPORARY);
901
902 *child_flags = flags;
903 }
904
905 const BdrvChildRole child_backing = {
906 .get_parent_desc = bdrv_child_get_parent_desc,
907 .attach = bdrv_backing_attach,
908 .detach = bdrv_backing_detach,
909 .inherit_options = bdrv_backing_options,
910 .drained_begin = bdrv_child_cb_drained_begin,
911 .drained_end = bdrv_child_cb_drained_end,
912 };
913
914 static int bdrv_open_flags(BlockDriverState *bs, int flags)
915 {
916 int open_flags = flags;
917
918 /*
919 * Clear flags that are internal to the block layer before opening the
920 * image.
921 */
922 open_flags &= ~(BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING | BDRV_O_PROTOCOL);
923
924 /*
925 * Snapshots should be writable.
926 */
927 if (flags & BDRV_O_TEMPORARY) {
928 open_flags |= BDRV_O_RDWR;
929 }
930
931 return open_flags;
932 }
933
934 static void update_flags_from_options(int *flags, QemuOpts *opts)
935 {
936 *flags &= ~BDRV_O_CACHE_MASK;
937
938 assert(qemu_opt_find(opts, BDRV_OPT_CACHE_NO_FLUSH));
939 if (qemu_opt_get_bool(opts, BDRV_OPT_CACHE_NO_FLUSH, false)) {
940 *flags |= BDRV_O_NO_FLUSH;
941 }
942
943 assert(qemu_opt_find(opts, BDRV_OPT_CACHE_DIRECT));
944 if (qemu_opt_get_bool(opts, BDRV_OPT_CACHE_DIRECT, false)) {
945 *flags |= BDRV_O_NOCACHE;
946 }
947
948 *flags &= ~BDRV_O_RDWR;
949
950 assert(qemu_opt_find(opts, BDRV_OPT_READ_ONLY));
951 if (!qemu_opt_get_bool(opts, BDRV_OPT_READ_ONLY, false)) {
952 *flags |= BDRV_O_RDWR;
953 }
954
955 }
956
957 static void update_options_from_flags(QDict *options, int flags)
958 {
959 if (!qdict_haskey(options, BDRV_OPT_CACHE_DIRECT)) {
960 qdict_put(options, BDRV_OPT_CACHE_DIRECT,
961 qbool_from_bool(flags & BDRV_O_NOCACHE));
962 }
963 if (!qdict_haskey(options, BDRV_OPT_CACHE_NO_FLUSH)) {
964 qdict_put(options, BDRV_OPT_CACHE_NO_FLUSH,
965 qbool_from_bool(flags & BDRV_O_NO_FLUSH));
966 }
967 if (!qdict_haskey(options, BDRV_OPT_READ_ONLY)) {
968 qdict_put(options, BDRV_OPT_READ_ONLY,
969 qbool_from_bool(!(flags & BDRV_O_RDWR)));
970 }
971 }
972
973 static void bdrv_assign_node_name(BlockDriverState *bs,
974 const char *node_name,
975 Error **errp)
976 {
977 char *gen_node_name = NULL;
978
979 if (!node_name) {
980 node_name = gen_node_name = id_generate(ID_BLOCK);
981 } else if (!id_wellformed(node_name)) {
982 /*
983 * Check for empty string or invalid characters, but not if it is
984 * generated (generated names use characters not available to the user)
985 */
986 error_setg(errp, "Invalid node name");
987 return;
988 }
989
990 /* takes care of avoiding namespaces collisions */
991 if (blk_by_name(node_name)) {
992 error_setg(errp, "node-name=%s is conflicting with a device id",
993 node_name);
994 goto out;
995 }
996
997 /* takes care of avoiding duplicates node names */
998 if (bdrv_find_node(node_name)) {
999 error_setg(errp, "Duplicate node name");
1000 goto out;
1001 }
1002
1003 /* copy node name into the bs and insert it into the graph list */
1004 pstrcpy(bs->node_name, sizeof(bs->node_name), node_name);
1005 QTAILQ_INSERT_TAIL(&graph_bdrv_states, bs, node_list);
1006 out:
1007 g_free(gen_node_name);
1008 }
1009
1010 static int bdrv_open_driver(BlockDriverState *bs, BlockDriver *drv,
1011 const char *node_name, QDict *options,
1012 int open_flags, Error **errp)
1013 {
1014 Error *local_err = NULL;
1015 int ret;
1016
1017 bdrv_assign_node_name(bs, node_name, &local_err);
1018 if (local_err) {
1019 error_propagate(errp, local_err);
1020 return -EINVAL;
1021 }
1022
1023 bs->drv = drv;
1024 bs->read_only = !(bs->open_flags & BDRV_O_RDWR);
1025 bs->opaque = g_malloc0(drv->instance_size);
1026
1027 if (drv->bdrv_file_open) {
1028 assert(!drv->bdrv_needs_filename || bs->filename[0]);
1029 ret = drv->bdrv_file_open(bs, options, open_flags, &local_err);
1030 } else if (drv->bdrv_open) {
1031 ret = drv->bdrv_open(bs, options, open_flags, &local_err);
1032 } else {
1033 ret = 0;
1034 }
1035
1036 if (ret < 0) {
1037 if (local_err) {
1038 error_propagate(errp, local_err);
1039 } else if (bs->filename[0]) {
1040 error_setg_errno(errp, -ret, "Could not open '%s'", bs->filename);
1041 } else {
1042 error_setg_errno(errp, -ret, "Could not open image");
1043 }
1044 goto free_and_fail;
1045 }
1046
1047 ret = refresh_total_sectors(bs, bs->total_sectors);
1048 if (ret < 0) {
1049 error_setg_errno(errp, -ret, "Could not refresh total sector count");
1050 goto free_and_fail;
1051 }
1052
1053 bdrv_refresh_limits(bs, &local_err);
1054 if (local_err) {
1055 error_propagate(errp, local_err);
1056 ret = -EINVAL;
1057 goto free_and_fail;
1058 }
1059
1060 assert(bdrv_opt_mem_align(bs) != 0);
1061 assert(bdrv_min_mem_align(bs) != 0);
1062 assert(is_power_of_2(bs->bl.request_alignment));
1063
1064 return 0;
1065
1066 free_and_fail:
1067 /* FIXME Close bs first if already opened*/
1068 g_free(bs->opaque);
1069 bs->opaque = NULL;
1070 bs->drv = NULL;
1071 return ret;
1072 }
1073
1074 BlockDriverState *bdrv_new_open_driver(BlockDriver *drv, const char *node_name,
1075 int flags, Error **errp)
1076 {
1077 BlockDriverState *bs;
1078 int ret;
1079
1080 bs = bdrv_new();
1081 bs->open_flags = flags;
1082 bs->explicit_options = qdict_new();
1083 bs->options = qdict_new();
1084 bs->opaque = NULL;
1085
1086 update_options_from_flags(bs->options, flags);
1087
1088 ret = bdrv_open_driver(bs, drv, node_name, bs->options, flags, errp);
1089 if (ret < 0) {
1090 QDECREF(bs->explicit_options);
1091 QDECREF(bs->options);
1092 bdrv_unref(bs);
1093 return NULL;
1094 }
1095
1096 return bs;
1097 }
1098
1099 QemuOptsList bdrv_runtime_opts = {
1100 .name = "bdrv_common",
1101 .head = QTAILQ_HEAD_INITIALIZER(bdrv_runtime_opts.head),
1102 .desc = {
1103 {
1104 .name = "node-name",
1105 .type = QEMU_OPT_STRING,
1106 .help = "Node name of the block device node",
1107 },
1108 {
1109 .name = "driver",
1110 .type = QEMU_OPT_STRING,
1111 .help = "Block driver to use for the node",
1112 },
1113 {
1114 .name = BDRV_OPT_CACHE_DIRECT,
1115 .type = QEMU_OPT_BOOL,
1116 .help = "Bypass software writeback cache on the host",
1117 },
1118 {
1119 .name = BDRV_OPT_CACHE_NO_FLUSH,
1120 .type = QEMU_OPT_BOOL,
1121 .help = "Ignore flush requests",
1122 },
1123 {
1124 .name = BDRV_OPT_READ_ONLY,
1125 .type = QEMU_OPT_BOOL,
1126 .help = "Node is opened in read-only mode",
1127 },
1128 {
1129 .name = "detect-zeroes",
1130 .type = QEMU_OPT_STRING,
1131 .help = "try to optimize zero writes (off, on, unmap)",
1132 },
1133 {
1134 .name = "discard",
1135 .type = QEMU_OPT_STRING,
1136 .help = "discard operation (ignore/off, unmap/on)",
1137 },
1138 { /* end of list */ }
1139 },
1140 };
1141
1142 /*
1143 * Common part for opening disk images and files
1144 *
1145 * Removes all processed options from *options.
1146 */
1147 static int bdrv_open_common(BlockDriverState *bs, BlockBackend *file,
1148 QDict *options, Error **errp)
1149 {
1150 int ret, open_flags;
1151 const char *filename;
1152 const char *driver_name = NULL;
1153 const char *node_name = NULL;
1154 const char *discard;
1155 const char *detect_zeroes;
1156 QemuOpts *opts;
1157 BlockDriver *drv;
1158 Error *local_err = NULL;
1159
1160 assert(bs->file == NULL);
1161 assert(options != NULL && bs->options != options);
1162
1163 opts = qemu_opts_create(&bdrv_runtime_opts, NULL, 0, &error_abort);
1164 qemu_opts_absorb_qdict(opts, options, &local_err);
1165 if (local_err) {
1166 error_propagate(errp, local_err);
1167 ret = -EINVAL;
1168 goto fail_opts;
1169 }
1170
1171 update_flags_from_options(&bs->open_flags, opts);
1172
1173 driver_name = qemu_opt_get(opts, "driver");
1174 drv = bdrv_find_format(driver_name);
1175 assert(drv != NULL);
1176
1177 if (file != NULL) {
1178 filename = blk_bs(file)->filename;
1179 } else {
1180 /*
1181 * Caution: while qdict_get_try_str() is fine, getting
1182 * non-string types would require more care. When @options
1183 * come from -blockdev or blockdev_add, its members are typed
1184 * according to the QAPI schema, but when they come from
1185 * -drive, they're all QString.
1186 */
1187 filename = qdict_get_try_str(options, "filename");
1188 }
1189
1190 if (drv->bdrv_needs_filename && !filename) {
1191 error_setg(errp, "The '%s' block driver requires a file name",
1192 drv->format_name);
1193 ret = -EINVAL;
1194 goto fail_opts;
1195 }
1196
1197 trace_bdrv_open_common(bs, filename ?: "", bs->open_flags,
1198 drv->format_name);
1199
1200 bs->read_only = !(bs->open_flags & BDRV_O_RDWR);
1201
1202 if (use_bdrv_whitelist && !bdrv_is_whitelisted(drv, bs->read_only)) {
1203 error_setg(errp,
1204 !bs->read_only && bdrv_is_whitelisted(drv, true)
1205 ? "Driver '%s' can only be used for read-only devices"
1206 : "Driver '%s' is not whitelisted",
1207 drv->format_name);
1208 ret = -ENOTSUP;
1209 goto fail_opts;
1210 }
1211
1212 assert(bs->copy_on_read == 0); /* bdrv_new() and bdrv_close() make it so */
1213 if (bs->open_flags & BDRV_O_COPY_ON_READ) {
1214 if (!bs->read_only) {
1215 bdrv_enable_copy_on_read(bs);
1216 } else {
1217 error_setg(errp, "Can't use copy-on-read on read-only device");
1218 ret = -EINVAL;
1219 goto fail_opts;
1220 }
1221 }
1222
1223 discard = qemu_opt_get(opts, "discard");
1224 if (discard != NULL) {
1225 if (bdrv_parse_discard_flags(discard, &bs->open_flags) != 0) {
1226 error_setg(errp, "Invalid discard option");
1227 ret = -EINVAL;
1228 goto fail_opts;
1229 }
1230 }
1231
1232 detect_zeroes = qemu_opt_get(opts, "detect-zeroes");
1233 if (detect_zeroes) {
1234 BlockdevDetectZeroesOptions value =
1235 qapi_enum_parse(BlockdevDetectZeroesOptions_lookup,
1236 detect_zeroes,
1237 BLOCKDEV_DETECT_ZEROES_OPTIONS__MAX,
1238 BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF,
1239 &local_err);
1240 if (local_err) {
1241 error_propagate(errp, local_err);
1242 ret = -EINVAL;
1243 goto fail_opts;
1244 }
1245
1246 if (value == BLOCKDEV_DETECT_ZEROES_OPTIONS_UNMAP &&
1247 !(bs->open_flags & BDRV_O_UNMAP))
1248 {
1249 error_setg(errp, "setting detect-zeroes to unmap is not allowed "
1250 "without setting discard operation to unmap");
1251 ret = -EINVAL;
1252 goto fail_opts;
1253 }
1254
1255 bs->detect_zeroes = value;
1256 }
1257
1258 if (filename != NULL) {
1259 pstrcpy(bs->filename, sizeof(bs->filename), filename);
1260 } else {
1261 bs->filename[0] = '\0';
1262 }
1263 pstrcpy(bs->exact_filename, sizeof(bs->exact_filename), bs->filename);
1264
1265 /* Open the image, either directly or using a protocol */
1266 open_flags = bdrv_open_flags(bs, bs->open_flags);
1267 node_name = qemu_opt_get(opts, "node-name");
1268
1269 assert(!drv->bdrv_file_open || file == NULL);
1270 ret = bdrv_open_driver(bs, drv, node_name, options, open_flags, errp);
1271 if (ret < 0) {
1272 goto fail_opts;
1273 }
1274
1275 qemu_opts_del(opts);
1276 return 0;
1277
1278 fail_opts:
1279 qemu_opts_del(opts);
1280 return ret;
1281 }
1282
1283 static QDict *parse_json_filename(const char *filename, Error **errp)
1284 {
1285 QObject *options_obj;
1286 QDict *options;
1287 int ret;
1288
1289 ret = strstart(filename, "json:", &filename);
1290 assert(ret);
1291
1292 options_obj = qobject_from_json(filename, errp);
1293 if (!options_obj) {
1294 /* Work around qobject_from_json() lossage TODO fix that */
1295 if (errp && !*errp) {
1296 error_setg(errp, "Could not parse the JSON options");
1297 return NULL;
1298 }
1299 error_prepend(errp, "Could not parse the JSON options: ");
1300 return NULL;
1301 }
1302
1303 options = qobject_to_qdict(options_obj);
1304 if (!options) {
1305 qobject_decref(options_obj);
1306 error_setg(errp, "Invalid JSON object given");
1307 return NULL;
1308 }
1309
1310 qdict_flatten(options);
1311
1312 return options;
1313 }
1314
1315 static void parse_json_protocol(QDict *options, const char **pfilename,
1316 Error **errp)
1317 {
1318 QDict *json_options;
1319 Error *local_err = NULL;
1320
1321 /* Parse json: pseudo-protocol */
1322 if (!*pfilename || !g_str_has_prefix(*pfilename, "json:")) {
1323 return;
1324 }
1325
1326 json_options = parse_json_filename(*pfilename, &local_err);
1327 if (local_err) {
1328 error_propagate(errp, local_err);
1329 return;
1330 }
1331
1332 /* Options given in the filename have lower priority than options
1333 * specified directly */
1334 qdict_join(options, json_options, false);
1335 QDECREF(json_options);
1336 *pfilename = NULL;
1337 }
1338
1339 /*
1340 * Fills in default options for opening images and converts the legacy
1341 * filename/flags pair to option QDict entries.
1342 * The BDRV_O_PROTOCOL flag in *flags will be set or cleared accordingly if a
1343 * block driver has been specified explicitly.
1344 */
1345 static int bdrv_fill_options(QDict **options, const char *filename,
1346 int *flags, Error **errp)
1347 {
1348 const char *drvname;
1349 bool protocol = *flags & BDRV_O_PROTOCOL;
1350 bool parse_filename = false;
1351 BlockDriver *drv = NULL;
1352 Error *local_err = NULL;
1353
1354 /*
1355 * Caution: while qdict_get_try_str() is fine, getting non-string
1356 * types would require more care. When @options come from
1357 * -blockdev or blockdev_add, its members are typed according to
1358 * the QAPI schema, but when they come from -drive, they're all
1359 * QString.
1360 */
1361 drvname = qdict_get_try_str(*options, "driver");
1362 if (drvname) {
1363 drv = bdrv_find_format(drvname);
1364 if (!drv) {
1365 error_setg(errp, "Unknown driver '%s'", drvname);
1366 return -ENOENT;
1367 }
1368 /* If the user has explicitly specified the driver, this choice should
1369 * override the BDRV_O_PROTOCOL flag */
1370 protocol = drv->bdrv_file_open;
1371 }
1372
1373 if (protocol) {
1374 *flags |= BDRV_O_PROTOCOL;
1375 } else {
1376 *flags &= ~BDRV_O_PROTOCOL;
1377 }
1378
1379 /* Translate cache options from flags into options */
1380 update_options_from_flags(*options, *flags);
1381
1382 /* Fetch the file name from the options QDict if necessary */
1383 if (protocol && filename) {
1384 if (!qdict_haskey(*options, "filename")) {
1385 qdict_put(*options, "filename", qstring_from_str(filename));
1386 parse_filename = true;
1387 } else {
1388 error_setg(errp, "Can't specify 'file' and 'filename' options at "
1389 "the same time");
1390 return -EINVAL;
1391 }
1392 }
1393
1394 /* Find the right block driver */
1395 /* See cautionary note on accessing @options above */
1396 filename = qdict_get_try_str(*options, "filename");
1397
1398 if (!drvname && protocol) {
1399 if (filename) {
1400 drv = bdrv_find_protocol(filename, parse_filename, errp);
1401 if (!drv) {
1402 return -EINVAL;
1403 }
1404
1405 drvname = drv->format_name;
1406 qdict_put(*options, "driver", qstring_from_str(drvname));
1407 } else {
1408 error_setg(errp, "Must specify either driver or file");
1409 return -EINVAL;
1410 }
1411 }
1412
1413 assert(drv || !protocol);
1414
1415 /* Driver-specific filename parsing */
1416 if (drv && drv->bdrv_parse_filename && parse_filename) {
1417 drv->bdrv_parse_filename(filename, *options, &local_err);
1418 if (local_err) {
1419 error_propagate(errp, local_err);
1420 return -EINVAL;
1421 }
1422
1423 if (!drv->bdrv_needs_filename) {
1424 qdict_del(*options, "filename");
1425 }
1426 }
1427
1428 return 0;
1429 }
1430
1431 static int bdrv_child_check_perm(BdrvChild *c, uint64_t perm, uint64_t shared,
1432 GSList *ignore_children, Error **errp);
1433 static void bdrv_child_abort_perm_update(BdrvChild *c);
1434 static void bdrv_child_set_perm(BdrvChild *c, uint64_t perm, uint64_t shared);
1435
1436 /*
1437 * Check whether permissions on this node can be changed in a way that
1438 * @cumulative_perms and @cumulative_shared_perms are the new cumulative
1439 * permissions of all its parents. This involves checking whether all necessary
1440 * permission changes to child nodes can be performed.
1441 *
1442 * A call to this function must always be followed by a call to bdrv_set_perm()
1443 * or bdrv_abort_perm_update().
1444 */
1445 static int bdrv_check_perm(BlockDriverState *bs, uint64_t cumulative_perms,
1446 uint64_t cumulative_shared_perms,
1447 GSList *ignore_children, Error **errp)
1448 {
1449 BlockDriver *drv = bs->drv;
1450 BdrvChild *c;
1451 int ret;
1452
1453 /* Write permissions never work with read-only images */
1454 if ((cumulative_perms & (BLK_PERM_WRITE | BLK_PERM_WRITE_UNCHANGED)) &&
1455 bdrv_is_read_only(bs))
1456 {
1457 error_setg(errp, "Block node is read-only");
1458 return -EPERM;
1459 }
1460
1461 /* Check this node */
1462 if (!drv) {
1463 return 0;
1464 }
1465
1466 if (drv->bdrv_check_perm) {
1467 return drv->bdrv_check_perm(bs, cumulative_perms,
1468 cumulative_shared_perms, errp);
1469 }
1470
1471 /* Drivers that never have children can omit .bdrv_child_perm() */
1472 if (!drv->bdrv_child_perm) {
1473 assert(QLIST_EMPTY(&bs->children));
1474 return 0;
1475 }
1476
1477 /* Check all children */
1478 QLIST_FOREACH(c, &bs->children, next) {
1479 uint64_t cur_perm, cur_shared;
1480 drv->bdrv_child_perm(bs, c, c->role,
1481 cumulative_perms, cumulative_shared_perms,
1482 &cur_perm, &cur_shared);
1483 ret = bdrv_child_check_perm(c, cur_perm, cur_shared, ignore_children,
1484 errp);
1485 if (ret < 0) {
1486 return ret;
1487 }
1488 }
1489
1490 return 0;
1491 }
1492
1493 /*
1494 * Notifies drivers that after a previous bdrv_check_perm() call, the
1495 * permission update is not performed and any preparations made for it (e.g.
1496 * taken file locks) need to be undone.
1497 *
1498 * This function recursively notifies all child nodes.
1499 */
1500 static void bdrv_abort_perm_update(BlockDriverState *bs)
1501 {
1502 BlockDriver *drv = bs->drv;
1503 BdrvChild *c;
1504
1505 if (!drv) {
1506 return;
1507 }
1508
1509 if (drv->bdrv_abort_perm_update) {
1510 drv->bdrv_abort_perm_update(bs);
1511 }
1512
1513 QLIST_FOREACH(c, &bs->children, next) {
1514 bdrv_child_abort_perm_update(c);
1515 }
1516 }
1517
1518 static void bdrv_set_perm(BlockDriverState *bs, uint64_t cumulative_perms,
1519 uint64_t cumulative_shared_perms)
1520 {
1521 BlockDriver *drv = bs->drv;
1522 BdrvChild *c;
1523
1524 if (!drv) {
1525 return;
1526 }
1527
1528 /* Update this node */
1529 if (drv->bdrv_set_perm) {
1530 drv->bdrv_set_perm(bs, cumulative_perms, cumulative_shared_perms);
1531 }
1532
1533 /* Drivers that never have children can omit .bdrv_child_perm() */
1534 if (!drv->bdrv_child_perm) {
1535 assert(QLIST_EMPTY(&bs->children));
1536 return;
1537 }
1538
1539 /* Update all children */
1540 QLIST_FOREACH(c, &bs->children, next) {
1541 uint64_t cur_perm, cur_shared;
1542 drv->bdrv_child_perm(bs, c, c->role,
1543 cumulative_perms, cumulative_shared_perms,
1544 &cur_perm, &cur_shared);
1545 bdrv_child_set_perm(c, cur_perm, cur_shared);
1546 }
1547 }
1548
1549 static void bdrv_get_cumulative_perm(BlockDriverState *bs, uint64_t *perm,
1550 uint64_t *shared_perm)
1551 {
1552 BdrvChild *c;
1553 uint64_t cumulative_perms = 0;
1554 uint64_t cumulative_shared_perms = BLK_PERM_ALL;
1555
1556 QLIST_FOREACH(c, &bs->parents, next_parent) {
1557 cumulative_perms |= c->perm;
1558 cumulative_shared_perms &= c->shared_perm;
1559 }
1560
1561 *perm = cumulative_perms;
1562 *shared_perm = cumulative_shared_perms;
1563 }
1564
1565 static char *bdrv_child_user_desc(BdrvChild *c)
1566 {
1567 if (c->role->get_parent_desc) {
1568 return c->role->get_parent_desc(c);
1569 }
1570
1571 return g_strdup("another user");
1572 }
1573
1574 static char *bdrv_perm_names(uint64_t perm)
1575 {
1576 struct perm_name {
1577 uint64_t perm;
1578 const char *name;
1579 } permissions[] = {
1580 { BLK_PERM_CONSISTENT_READ, "consistent read" },
1581 { BLK_PERM_WRITE, "write" },
1582 { BLK_PERM_WRITE_UNCHANGED, "write unchanged" },
1583 { BLK_PERM_RESIZE, "resize" },
1584 { BLK_PERM_GRAPH_MOD, "change children" },
1585 { 0, NULL }
1586 };
1587
1588 char *result = g_strdup("");
1589 struct perm_name *p;
1590
1591 for (p = permissions; p->name; p++) {
1592 if (perm & p->perm) {
1593 char *old = result;
1594 result = g_strdup_printf("%s%s%s", old, *old ? ", " : "", p->name);
1595 g_free(old);
1596 }
1597 }
1598
1599 return result;
1600 }
1601
1602 /*
1603 * Checks whether a new reference to @bs can be added if the new user requires
1604 * @new_used_perm/@new_shared_perm as its permissions. If @ignore_children is
1605 * set, the BdrvChild objects in this list are ignored in the calculations;
1606 * this allows checking permission updates for an existing reference.
1607 *
1608 * Needs to be followed by a call to either bdrv_set_perm() or
1609 * bdrv_abort_perm_update(). */
1610 static int bdrv_check_update_perm(BlockDriverState *bs, uint64_t new_used_perm,
1611 uint64_t new_shared_perm,
1612 GSList *ignore_children, Error **errp)
1613 {
1614 BdrvChild *c;
1615 uint64_t cumulative_perms = new_used_perm;
1616 uint64_t cumulative_shared_perms = new_shared_perm;
1617
1618 /* There is no reason why anyone couldn't tolerate write_unchanged */
1619 assert(new_shared_perm & BLK_PERM_WRITE_UNCHANGED);
1620
1621 QLIST_FOREACH(c, &bs->parents, next_parent) {
1622 if (g_slist_find(ignore_children, c)) {
1623 continue;
1624 }
1625
1626 if ((new_used_perm & c->shared_perm) != new_used_perm) {
1627 char *user = bdrv_child_user_desc(c);
1628 char *perm_names = bdrv_perm_names(new_used_perm & ~c->shared_perm);
1629 error_setg(errp, "Conflicts with use by %s as '%s', which does not "
1630 "allow '%s' on %s",
1631 user, c->name, perm_names, bdrv_get_node_name(c->bs));
1632 g_free(user);
1633 g_free(perm_names);
1634 return -EPERM;
1635 }
1636
1637 if ((c->perm & new_shared_perm) != c->perm) {
1638 char *user = bdrv_child_user_desc(c);
1639 char *perm_names = bdrv_perm_names(c->perm & ~new_shared_perm);
1640 error_setg(errp, "Conflicts with use by %s as '%s', which uses "
1641 "'%s' on %s",
1642 user, c->name, perm_names, bdrv_get_node_name(c->bs));
1643 g_free(user);
1644 g_free(perm_names);
1645 return -EPERM;
1646 }
1647
1648 cumulative_perms |= c->perm;
1649 cumulative_shared_perms &= c->shared_perm;
1650 }
1651
1652 return bdrv_check_perm(bs, cumulative_perms, cumulative_shared_perms,
1653 ignore_children, errp);
1654 }
1655
1656 /* Needs to be followed by a call to either bdrv_child_set_perm() or
1657 * bdrv_child_abort_perm_update(). */
1658 static int bdrv_child_check_perm(BdrvChild *c, uint64_t perm, uint64_t shared,
1659 GSList *ignore_children, Error **errp)
1660 {
1661 int ret;
1662
1663 ignore_children = g_slist_prepend(g_slist_copy(ignore_children), c);
1664 ret = bdrv_check_update_perm(c->bs, perm, shared, ignore_children, errp);
1665 g_slist_free(ignore_children);
1666
1667 return ret;
1668 }
1669
1670 static void bdrv_child_set_perm(BdrvChild *c, uint64_t perm, uint64_t shared)
1671 {
1672 uint64_t cumulative_perms, cumulative_shared_perms;
1673
1674 c->perm = perm;
1675 c->shared_perm = shared;
1676
1677 bdrv_get_cumulative_perm(c->bs, &cumulative_perms,
1678 &cumulative_shared_perms);
1679 bdrv_set_perm(c->bs, cumulative_perms, cumulative_shared_perms);
1680 }
1681
1682 static void bdrv_child_abort_perm_update(BdrvChild *c)
1683 {
1684 bdrv_abort_perm_update(c->bs);
1685 }
1686
1687 int bdrv_child_try_set_perm(BdrvChild *c, uint64_t perm, uint64_t shared,
1688 Error **errp)
1689 {
1690 int ret;
1691
1692 ret = bdrv_child_check_perm(c, perm, shared, NULL, errp);
1693 if (ret < 0) {
1694 bdrv_child_abort_perm_update(c);
1695 return ret;
1696 }
1697
1698 bdrv_child_set_perm(c, perm, shared);
1699
1700 return 0;
1701 }
1702
1703 #define DEFAULT_PERM_PASSTHROUGH (BLK_PERM_CONSISTENT_READ \
1704 | BLK_PERM_WRITE \
1705 | BLK_PERM_WRITE_UNCHANGED \
1706 | BLK_PERM_RESIZE)
1707 #define DEFAULT_PERM_UNCHANGED (BLK_PERM_ALL & ~DEFAULT_PERM_PASSTHROUGH)
1708
1709 void bdrv_filter_default_perms(BlockDriverState *bs, BdrvChild *c,
1710 const BdrvChildRole *role,
1711 uint64_t perm, uint64_t shared,
1712 uint64_t *nperm, uint64_t *nshared)
1713 {
1714 if (c == NULL) {
1715 *nperm = perm & DEFAULT_PERM_PASSTHROUGH;
1716 *nshared = (shared & DEFAULT_PERM_PASSTHROUGH) | DEFAULT_PERM_UNCHANGED;
1717 return;
1718 }
1719
1720 *nperm = (perm & DEFAULT_PERM_PASSTHROUGH) |
1721 (c->perm & DEFAULT_PERM_UNCHANGED);
1722 *nshared = (shared & DEFAULT_PERM_PASSTHROUGH) |
1723 (c->shared_perm & DEFAULT_PERM_UNCHANGED);
1724 }
1725
1726 void bdrv_format_default_perms(BlockDriverState *bs, BdrvChild *c,
1727 const BdrvChildRole *role,
1728 uint64_t perm, uint64_t shared,
1729 uint64_t *nperm, uint64_t *nshared)
1730 {
1731 bool backing = (role == &child_backing);
1732 assert(role == &child_backing || role == &child_file);
1733
1734 if (!backing) {
1735 /* Apart from the modifications below, the same permissions are
1736 * forwarded and left alone as for filters */
1737 bdrv_filter_default_perms(bs, c, role, perm, shared, &perm, &shared);
1738
1739 /* Format drivers may touch metadata even if the guest doesn't write */
1740 if (!bdrv_is_read_only(bs)) {
1741 perm |= BLK_PERM_WRITE | BLK_PERM_RESIZE;
1742 }
1743
1744 /* bs->file always needs to be consistent because of the metadata. We
1745 * can never allow other users to resize or write to it. */
1746 perm |= BLK_PERM_CONSISTENT_READ;
1747 shared &= ~(BLK_PERM_WRITE | BLK_PERM_RESIZE);
1748 } else {
1749 /* We want consistent read from backing files if the parent needs it.
1750 * No other operations are performed on backing files. */
1751 perm &= BLK_PERM_CONSISTENT_READ;
1752
1753 /* If the parent can deal with changing data, we're okay with a
1754 * writable and resizable backing file. */
1755 /* TODO Require !(perm & BLK_PERM_CONSISTENT_READ), too? */
1756 if (shared & BLK_PERM_WRITE) {
1757 shared = BLK_PERM_WRITE | BLK_PERM_RESIZE;
1758 } else {
1759 shared = 0;
1760 }
1761
1762 shared |= BLK_PERM_CONSISTENT_READ | BLK_PERM_GRAPH_MOD |
1763 BLK_PERM_WRITE_UNCHANGED;
1764 }
1765
1766 *nperm = perm;
1767 *nshared = shared;
1768 }
1769
1770 static void bdrv_replace_child_noperm(BdrvChild *child,
1771 BlockDriverState *new_bs)
1772 {
1773 BlockDriverState *old_bs = child->bs;
1774
1775 if (old_bs && new_bs) {
1776 assert(bdrv_get_aio_context(old_bs) == bdrv_get_aio_context(new_bs));
1777 }
1778 if (old_bs) {
1779 if (old_bs->quiesce_counter && child->role->drained_end) {
1780 child->role->drained_end(child);
1781 }
1782 if (child->role->detach) {
1783 child->role->detach(child);
1784 }
1785 QLIST_REMOVE(child, next_parent);
1786 }
1787
1788 child->bs = new_bs;
1789
1790 if (new_bs) {
1791 QLIST_INSERT_HEAD(&new_bs->parents, child, next_parent);
1792 if (new_bs->quiesce_counter && child->role->drained_begin) {
1793 child->role->drained_begin(child);
1794 }
1795
1796 if (child->role->attach) {
1797 child->role->attach(child);
1798 }
1799 }
1800 }
1801
1802 /*
1803 * Updates @child to change its reference to point to @new_bs, including
1804 * checking and applying the necessary permisson updates both to the old node
1805 * and to @new_bs.
1806 *
1807 * NULL is passed as @new_bs for removing the reference before freeing @child.
1808 *
1809 * If @new_bs is not NULL, bdrv_check_perm() must be called beforehand, as this
1810 * function uses bdrv_set_perm() to update the permissions according to the new
1811 * reference that @new_bs gets.
1812 */
1813 static void bdrv_replace_child(BdrvChild *child, BlockDriverState *new_bs)
1814 {
1815 BlockDriverState *old_bs = child->bs;
1816 uint64_t perm, shared_perm;
1817
1818 if (old_bs) {
1819 /* Update permissions for old node. This is guaranteed to succeed
1820 * because we're just taking a parent away, so we're loosening
1821 * restrictions. */
1822 bdrv_get_cumulative_perm(old_bs, &perm, &shared_perm);
1823 bdrv_check_perm(old_bs, perm, shared_perm, NULL, &error_abort);
1824 bdrv_set_perm(old_bs, perm, shared_perm);
1825 }
1826
1827 bdrv_replace_child_noperm(child, new_bs);
1828
1829 if (new_bs) {
1830 bdrv_get_cumulative_perm(new_bs, &perm, &shared_perm);
1831 bdrv_set_perm(new_bs, perm, shared_perm);
1832 }
1833 }
1834
1835 BdrvChild *bdrv_root_attach_child(BlockDriverState *child_bs,
1836 const char *child_name,
1837 const BdrvChildRole *child_role,
1838 uint64_t perm, uint64_t shared_perm,
1839 void *opaque, Error **errp)
1840 {
1841 BdrvChild *child;
1842 int ret;
1843
1844 ret = bdrv_check_update_perm(child_bs, perm, shared_perm, NULL, errp);
1845 if (ret < 0) {
1846 bdrv_abort_perm_update(child_bs);
1847 return NULL;
1848 }
1849
1850 child = g_new(BdrvChild, 1);
1851 *child = (BdrvChild) {
1852 .bs = NULL,
1853 .name = g_strdup(child_name),
1854 .role = child_role,
1855 .perm = perm,
1856 .shared_perm = shared_perm,
1857 .opaque = opaque,
1858 };
1859
1860 /* This performs the matching bdrv_set_perm() for the above check. */
1861 bdrv_replace_child(child, child_bs);
1862
1863 return child;
1864 }
1865
1866 BdrvChild *bdrv_attach_child(BlockDriverState *parent_bs,
1867 BlockDriverState *child_bs,
1868 const char *child_name,
1869 const BdrvChildRole *child_role,
1870 Error **errp)
1871 {
1872 BdrvChild *child;
1873 uint64_t perm, shared_perm;
1874
1875 bdrv_get_cumulative_perm(parent_bs, &perm, &shared_perm);
1876
1877 assert(parent_bs->drv);
1878 assert(bdrv_get_aio_context(parent_bs) == bdrv_get_aio_context(child_bs));
1879 parent_bs->drv->bdrv_child_perm(parent_bs, NULL, child_role,
1880 perm, shared_perm, &perm, &shared_perm);
1881
1882 child = bdrv_root_attach_child(child_bs, child_name, child_role,
1883 perm, shared_perm, parent_bs, errp);
1884 if (child == NULL) {
1885 return NULL;
1886 }
1887
1888 QLIST_INSERT_HEAD(&parent_bs->children, child, next);
1889 return child;
1890 }
1891
1892 static void bdrv_detach_child(BdrvChild *child)
1893 {
1894 if (child->next.le_prev) {
1895 QLIST_REMOVE(child, next);
1896 child->next.le_prev = NULL;
1897 }
1898
1899 bdrv_replace_child(child, NULL);
1900
1901 g_free(child->name);
1902 g_free(child);
1903 }
1904
1905 void bdrv_root_unref_child(BdrvChild *child)
1906 {
1907 BlockDriverState *child_bs;
1908
1909 child_bs = child->bs;
1910 bdrv_detach_child(child);
1911 bdrv_unref(child_bs);
1912 }
1913
1914 void bdrv_unref_child(BlockDriverState *parent, BdrvChild *child)
1915 {
1916 if (child == NULL) {
1917 return;
1918 }
1919
1920 if (child->bs->inherits_from == parent) {
1921 BdrvChild *c;
1922
1923 /* Remove inherits_from only when the last reference between parent and
1924 * child->bs goes away. */
1925 QLIST_FOREACH(c, &parent->children, next) {
1926 if (c != child && c->bs == child->bs) {
1927 break;
1928 }
1929 }
1930 if (c == NULL) {
1931 child->bs->inherits_from = NULL;
1932 }
1933 }
1934
1935 bdrv_root_unref_child(child);
1936 }
1937
1938
1939 static void bdrv_parent_cb_change_media(BlockDriverState *bs, bool load)
1940 {
1941 BdrvChild *c;
1942 QLIST_FOREACH(c, &bs->parents, next_parent) {
1943 if (c->role->change_media) {
1944 c->role->change_media(c, load);
1945 }
1946 }
1947 }
1948
1949 static void bdrv_parent_cb_resize(BlockDriverState *bs)
1950 {
1951 BdrvChild *c;
1952 QLIST_FOREACH(c, &bs->parents, next_parent) {
1953 if (c->role->resize) {
1954 c->role->resize(c);
1955 }
1956 }
1957 }
1958
1959 /*
1960 * Sets the backing file link of a BDS. A new reference is created; callers
1961 * which don't need their own reference any more must call bdrv_unref().
1962 */
1963 void bdrv_set_backing_hd(BlockDriverState *bs, BlockDriverState *backing_hd,
1964 Error **errp)
1965 {
1966 if (backing_hd) {
1967 bdrv_ref(backing_hd);
1968 }
1969
1970 if (bs->backing) {
1971 bdrv_unref_child(bs, bs->backing);
1972 }
1973
1974 if (!backing_hd) {
1975 bs->backing = NULL;
1976 goto out;
1977 }
1978
1979 bs->backing = bdrv_attach_child(bs, backing_hd, "backing", &child_backing,
1980 errp);
1981 if (!bs->backing) {
1982 bdrv_unref(backing_hd);
1983 }
1984
1985 bdrv_refresh_filename(bs);
1986
1987 out:
1988 bdrv_refresh_limits(bs, NULL);
1989 }
1990
1991 /*
1992 * Opens the backing file for a BlockDriverState if not yet open
1993 *
1994 * bdref_key specifies the key for the image's BlockdevRef in the options QDict.
1995 * That QDict has to be flattened; therefore, if the BlockdevRef is a QDict
1996 * itself, all options starting with "${bdref_key}." are considered part of the
1997 * BlockdevRef.
1998 *
1999 * TODO Can this be unified with bdrv_open_image()?
2000 */
2001 int bdrv_open_backing_file(BlockDriverState *bs, QDict *parent_options,
2002 const char *bdref_key, Error **errp)
2003 {
2004 char *backing_filename = g_malloc0(PATH_MAX);
2005 char *bdref_key_dot;
2006 const char *reference = NULL;
2007 int ret = 0;
2008 BlockDriverState *backing_hd;
2009 QDict *options;
2010 QDict *tmp_parent_options = NULL;
2011 Error *local_err = NULL;
2012
2013 if (bs->backing != NULL) {
2014 goto free_exit;
2015 }
2016
2017 /* NULL means an empty set of options */
2018 if (parent_options == NULL) {
2019 tmp_parent_options = qdict_new();
2020 parent_options = tmp_parent_options;
2021 }
2022
2023 bs->open_flags &= ~BDRV_O_NO_BACKING;
2024
2025 bdref_key_dot = g_strdup_printf("%s.", bdref_key);
2026 qdict_extract_subqdict(parent_options, &options, bdref_key_dot);
2027 g_free(bdref_key_dot);
2028
2029 /*
2030 * Caution: while qdict_get_try_str() is fine, getting non-string
2031 * types would require more care. When @parent_options come from
2032 * -blockdev or blockdev_add, its members are typed according to
2033 * the QAPI schema, but when they come from -drive, they're all
2034 * QString.
2035 */
2036 reference = qdict_get_try_str(parent_options, bdref_key);
2037 if (reference || qdict_haskey(options, "file.filename")) {
2038 backing_filename[0] = '\0';
2039 } else if (bs->backing_file[0] == '\0' && qdict_size(options) == 0) {
2040 QDECREF(options);
2041 goto free_exit;
2042 } else {
2043 bdrv_get_full_backing_filename(bs, backing_filename, PATH_MAX,
2044 &local_err);
2045 if (local_err) {
2046 ret = -EINVAL;
2047 error_propagate(errp, local_err);
2048 QDECREF(options);
2049 goto free_exit;
2050 }
2051 }
2052
2053 if (!bs->drv || !bs->drv->supports_backing) {
2054 ret = -EINVAL;
2055 error_setg(errp, "Driver doesn't support backing files");
2056 QDECREF(options);
2057 goto free_exit;
2058 }
2059
2060 if (bs->backing_format[0] != '\0' && !qdict_haskey(options, "driver")) {
2061 qdict_put(options, "driver", qstring_from_str(bs->backing_format));
2062 }
2063
2064 backing_hd = bdrv_open_inherit(*backing_filename ? backing_filename : NULL,
2065 reference, options, 0, bs, &child_backing,
2066 errp);
2067 if (!backing_hd) {
2068 bs->open_flags |= BDRV_O_NO_BACKING;
2069 error_prepend(errp, "Could not open backing file: ");
2070 ret = -EINVAL;
2071 goto free_exit;
2072 }
2073
2074 /* Hook up the backing file link; drop our reference, bs owns the
2075 * backing_hd reference now */
2076 bdrv_set_backing_hd(bs, backing_hd, &local_err);
2077 bdrv_unref(backing_hd);
2078 if (local_err) {
2079 error_propagate(errp, local_err);
2080 ret = -EINVAL;
2081 goto free_exit;
2082 }
2083
2084 qdict_del(parent_options, bdref_key);
2085
2086 free_exit:
2087 g_free(backing_filename);
2088 QDECREF(tmp_parent_options);
2089 return ret;
2090 }
2091
2092 static BlockDriverState *
2093 bdrv_open_child_bs(const char *filename, QDict *options, const char *bdref_key,
2094 BlockDriverState *parent, const BdrvChildRole *child_role,
2095 bool allow_none, Error **errp)
2096 {
2097 BlockDriverState *bs = NULL;
2098 QDict *image_options;
2099 char *bdref_key_dot;
2100 const char *reference;
2101
2102 assert(child_role != NULL);
2103
2104 bdref_key_dot = g_strdup_printf("%s.", bdref_key);
2105 qdict_extract_subqdict(options, &image_options, bdref_key_dot);
2106 g_free(bdref_key_dot);
2107
2108 /*
2109 * Caution: while qdict_get_try_str() is fine, getting non-string
2110 * types would require more care. When @options come from
2111 * -blockdev or blockdev_add, its members are typed according to
2112 * the QAPI schema, but when they come from -drive, they're all
2113 * QString.
2114 */
2115 reference = qdict_get_try_str(options, bdref_key);
2116 if (!filename && !reference && !qdict_size(image_options)) {
2117 if (!allow_none) {
2118 error_setg(errp, "A block device must be specified for \"%s\"",
2119 bdref_key);
2120 }
2121 QDECREF(image_options);
2122 goto done;
2123 }
2124
2125 bs = bdrv_open_inherit(filename, reference, image_options, 0,
2126 parent, child_role, errp);
2127 if (!bs) {
2128 goto done;
2129 }
2130
2131 done:
2132 qdict_del(options, bdref_key);
2133 return bs;
2134 }
2135
2136 /*
2137 * Opens a disk image whose options are given as BlockdevRef in another block
2138 * device's options.
2139 *
2140 * If allow_none is true, no image will be opened if filename is false and no
2141 * BlockdevRef is given. NULL will be returned, but errp remains unset.
2142 *
2143 * bdrev_key specifies the key for the image's BlockdevRef in the options QDict.
2144 * That QDict has to be flattened; therefore, if the BlockdevRef is a QDict
2145 * itself, all options starting with "${bdref_key}." are considered part of the
2146 * BlockdevRef.
2147 *
2148 * The BlockdevRef will be removed from the options QDict.
2149 */
2150 BdrvChild *bdrv_open_child(const char *filename,
2151 QDict *options, const char *bdref_key,
2152 BlockDriverState *parent,
2153 const BdrvChildRole *child_role,
2154 bool allow_none, Error **errp)
2155 {
2156 BdrvChild *c;
2157 BlockDriverState *bs;
2158
2159 bs = bdrv_open_child_bs(filename, options, bdref_key, parent, child_role,
2160 allow_none, errp);
2161 if (bs == NULL) {
2162 return NULL;
2163 }
2164
2165 c = bdrv_attach_child(parent, bs, bdref_key, child_role, errp);
2166 if (!c) {
2167 bdrv_unref(bs);
2168 return NULL;
2169 }
2170
2171 return c;
2172 }
2173
2174 static BlockDriverState *bdrv_append_temp_snapshot(BlockDriverState *bs,
2175 int flags,
2176 QDict *snapshot_options,
2177 Error **errp)
2178 {
2179 /* TODO: extra byte is a hack to ensure MAX_PATH space on Windows. */
2180 char *tmp_filename = g_malloc0(PATH_MAX + 1);
2181 int64_t total_size;
2182 QemuOpts *opts = NULL;
2183 BlockDriverState *bs_snapshot;
2184 Error *local_err = NULL;
2185 int ret;
2186
2187 /* if snapshot, we create a temporary backing file and open it
2188 instead of opening 'filename' directly */
2189
2190 /* Get the required size from the image */
2191 total_size = bdrv_getlength(bs);
2192 if (total_size < 0) {
2193 error_setg_errno(errp, -total_size, "Could not get image size");
2194 goto out;
2195 }
2196
2197 /* Create the temporary image */
2198 ret = get_tmp_filename(tmp_filename, PATH_MAX + 1);
2199 if (ret < 0) {
2200 error_setg_errno(errp, -ret, "Could not get temporary filename");
2201 goto out;
2202 }
2203
2204 opts = qemu_opts_create(bdrv_qcow2.create_opts, NULL, 0,
2205 &error_abort);
2206 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, total_size, &error_abort);
2207 ret = bdrv_create(&bdrv_qcow2, tmp_filename, opts, errp);
2208 qemu_opts_del(opts);
2209 if (ret < 0) {
2210 error_prepend(errp, "Could not create temporary overlay '%s': ",
2211 tmp_filename);
2212 goto out;
2213 }
2214
2215 /* Prepare options QDict for the temporary file */
2216 qdict_put(snapshot_options, "file.driver",
2217 qstring_from_str("file"));
2218 qdict_put(snapshot_options, "file.filename",
2219 qstring_from_str(tmp_filename));
2220 qdict_put(snapshot_options, "driver",
2221 qstring_from_str("qcow2"));
2222
2223 bs_snapshot = bdrv_open(NULL, NULL, snapshot_options, flags, errp);
2224 snapshot_options = NULL;
2225 if (!bs_snapshot) {
2226 ret = -EINVAL;
2227 goto out;
2228 }
2229
2230 /* bdrv_append() consumes a strong reference to bs_snapshot (i.e. it will
2231 * call bdrv_unref() on it), so in order to be able to return one, we have
2232 * to increase bs_snapshot's refcount here */
2233 bdrv_ref(bs_snapshot);
2234 bdrv_append(bs_snapshot, bs, &local_err);
2235 if (local_err) {
2236 error_propagate(errp, local_err);
2237 ret = -EINVAL;
2238 goto out;
2239 }
2240
2241 g_free(tmp_filename);
2242 return bs_snapshot;
2243
2244 out:
2245 QDECREF(snapshot_options);
2246 g_free(tmp_filename);
2247 return NULL;
2248 }
2249
2250 /*
2251 * Opens a disk image (raw, qcow2, vmdk, ...)
2252 *
2253 * options is a QDict of options to pass to the block drivers, or NULL for an
2254 * empty set of options. The reference to the QDict belongs to the block layer
2255 * after the call (even on failure), so if the caller intends to reuse the
2256 * dictionary, it needs to use QINCREF() before calling bdrv_open.
2257 *
2258 * If *pbs is NULL, a new BDS will be created with a pointer to it stored there.
2259 * If it is not NULL, the referenced BDS will be reused.
2260 *
2261 * The reference parameter may be used to specify an existing block device which
2262 * should be opened. If specified, neither options nor a filename may be given,
2263 * nor can an existing BDS be reused (that is, *pbs has to be NULL).
2264 */
2265 static BlockDriverState *bdrv_open_inherit(const char *filename,
2266 const char *reference,
2267 QDict *options, int flags,
2268 BlockDriverState *parent,
2269 const BdrvChildRole *child_role,
2270 Error **errp)
2271 {
2272 int ret;
2273 BlockBackend *file = NULL;
2274 BlockDriverState *bs;
2275 BlockDriver *drv = NULL;
2276 const char *drvname;
2277 const char *backing;
2278 Error *local_err = NULL;
2279 QDict *snapshot_options = NULL;
2280 int snapshot_flags = 0;
2281
2282 assert(!child_role || !flags);
2283 assert(!child_role == !parent);
2284
2285 if (reference) {
2286 bool options_non_empty = options ? qdict_size(options) : false;
2287 QDECREF(options);
2288
2289 if (filename || options_non_empty) {
2290 error_setg(errp, "Cannot reference an existing block device with "
2291 "additional options or a new filename");
2292 return NULL;
2293 }
2294
2295 bs = bdrv_lookup_bs(reference, reference, errp);
2296 if (!bs) {
2297 return NULL;
2298 }
2299
2300 bdrv_ref(bs);
2301 return bs;
2302 }
2303
2304 bs = bdrv_new();
2305
2306 /* NULL means an empty set of options */
2307 if (options == NULL) {
2308 options = qdict_new();
2309 }
2310
2311 /* json: syntax counts as explicit options, as if in the QDict */
2312 parse_json_protocol(options, &filename, &local_err);
2313 if (local_err) {
2314 goto fail;
2315 }
2316
2317 bs->explicit_options = qdict_clone_shallow(options);
2318
2319 if (child_role) {
2320 bs->inherits_from = parent;
2321 child_role->inherit_options(&flags, options,
2322 parent->open_flags, parent->options);
2323 }
2324
2325 ret = bdrv_fill_options(&options, filename, &flags, &local_err);
2326 if (local_err) {
2327 goto fail;
2328 }
2329
2330 /*
2331 * Set the BDRV_O_RDWR and BDRV_O_ALLOW_RDWR flags.
2332 * Caution: getting a boolean member of @options requires care.
2333 * When @options come from -blockdev or blockdev_add, members are
2334 * typed according to the QAPI schema, but when they come from
2335 * -drive, they're all QString.
2336 */
2337 if (g_strcmp0(qdict_get_try_str(options, BDRV_OPT_READ_ONLY), "on") &&
2338 !qdict_get_try_bool(options, BDRV_OPT_READ_ONLY, false)) {
2339 flags |= (BDRV_O_RDWR | BDRV_O_ALLOW_RDWR);
2340 } else {
2341 flags &= ~BDRV_O_RDWR;
2342 }
2343
2344 if (flags & BDRV_O_SNAPSHOT) {
2345 snapshot_options = qdict_new();
2346 bdrv_temp_snapshot_options(&snapshot_flags, snapshot_options,
2347 flags, options);
2348 /* Let bdrv_backing_options() override "read-only" */
2349 qdict_del(options, BDRV_OPT_READ_ONLY);
2350 bdrv_backing_options(&flags, options, flags, options);
2351 }
2352
2353 bs->open_flags = flags;
2354 bs->options = options;
2355 options = qdict_clone_shallow(options);
2356
2357 /* Find the right image format driver */
2358 /* See cautionary note on accessing @options above */
2359 drvname = qdict_get_try_str(options, "driver");
2360 if (drvname) {
2361 drv = bdrv_find_format(drvname);
2362 if (!drv) {
2363 error_setg(errp, "Unknown driver: '%s'", drvname);
2364 goto fail;
2365 }
2366 }
2367
2368 assert(drvname || !(flags & BDRV_O_PROTOCOL));
2369
2370 /* See cautionary note on accessing @options above */
2371 backing = qdict_get_try_str(options, "backing");
2372 if (backing && *backing == '\0') {
2373 flags |= BDRV_O_NO_BACKING;
2374 qdict_del(options, "backing");
2375 }
2376
2377 /* Open image file without format layer. This BlockBackend is only used for
2378 * probing, the block drivers will do their own bdrv_open_child() for the
2379 * same BDS, which is why we put the node name back into options. */
2380 if ((flags & BDRV_O_PROTOCOL) == 0) {
2381 BlockDriverState *file_bs;
2382
2383 file_bs = bdrv_open_child_bs(filename, options, "file", bs,
2384 &child_file, true, &local_err);
2385 if (local_err) {
2386 goto fail;
2387 }
2388 if (file_bs != NULL) {
2389 file = blk_new(BLK_PERM_CONSISTENT_READ, BLK_PERM_ALL);
2390 blk_insert_bs(file, file_bs, &local_err);
2391 bdrv_unref(file_bs);
2392 if (local_err) {
2393 goto fail;
2394 }
2395
2396 qdict_put(options, "file",
2397 qstring_from_str(bdrv_get_node_name(file_bs)));
2398 }
2399 }
2400
2401 /* Image format probing */
2402 bs->probed = !drv;
2403 if (!drv && file) {
2404 ret = find_image_format(file, filename, &drv, &local_err);
2405 if (ret < 0) {
2406 goto fail;
2407 }
2408 /*
2409 * This option update would logically belong in bdrv_fill_options(),
2410 * but we first need to open bs->file for the probing to work, while
2411 * opening bs->file already requires the (mostly) final set of options
2412 * so that cache mode etc. can be inherited.
2413 *
2414 * Adding the driver later is somewhat ugly, but it's not an option
2415 * that would ever be inherited, so it's correct. We just need to make
2416 * sure to update both bs->options (which has the full effective
2417 * options for bs) and options (which has file.* already removed).
2418 */
2419 qdict_put(bs->options, "driver", qstring_from_str(drv->format_name));
2420 qdict_put(options, "driver", qstring_from_str(drv->format_name));
2421 } else if (!drv) {
2422 error_setg(errp, "Must specify either driver or file");
2423 goto fail;
2424 }
2425
2426 /* BDRV_O_PROTOCOL must be set iff a protocol BDS is about to be created */
2427 assert(!!(flags & BDRV_O_PROTOCOL) == !!drv->bdrv_file_open);
2428 /* file must be NULL if a protocol BDS is about to be created
2429 * (the inverse results in an error message from bdrv_open_common()) */
2430 assert(!(flags & BDRV_O_PROTOCOL) || !file);
2431
2432 /* Open the image */
2433 ret = bdrv_open_common(bs, file, options, &local_err);
2434 if (ret < 0) {
2435 goto fail;
2436 }
2437
2438 if (file) {
2439 blk_unref(file);
2440 file = NULL;
2441 }
2442
2443 /* If there is a backing file, use it */
2444 if ((flags & BDRV_O_NO_BACKING) == 0) {
2445 ret = bdrv_open_backing_file(bs, options, "backing", &local_err);
2446 if (ret < 0) {
2447 goto close_and_fail;
2448 }
2449 }
2450
2451 bdrv_refresh_filename(bs);
2452
2453 /* Check if any unknown options were used */
2454 if (qdict_size(options) != 0) {
2455 const QDictEntry *entry = qdict_first(options);
2456 if (flags & BDRV_O_PROTOCOL) {
2457 error_setg(errp, "Block protocol '%s' doesn't support the option "
2458 "'%s'", drv->format_name, entry->key);
2459 } else {
2460 error_setg(errp,
2461 "Block format '%s' does not support the option '%s'",
2462 drv->format_name, entry->key);
2463 }
2464
2465 goto close_and_fail;
2466 }
2467
2468 if (!bdrv_key_required(bs)) {
2469 bdrv_parent_cb_change_media(bs, true);
2470 } else if (!runstate_check(RUN_STATE_PRELAUNCH)
2471 && !runstate_check(RUN_STATE_INMIGRATE)
2472 && !runstate_check(RUN_STATE_PAUSED)) { /* HACK */
2473 error_setg(errp,
2474 "Guest must be stopped for opening of encrypted image");
2475 goto close_and_fail;
2476 }
2477
2478 QDECREF(options);
2479
2480 /* For snapshot=on, create a temporary qcow2 overlay. bs points to the
2481 * temporary snapshot afterwards. */
2482 if (snapshot_flags) {
2483 BlockDriverState *snapshot_bs;
2484 snapshot_bs = bdrv_append_temp_snapshot(bs, snapshot_flags,
2485 snapshot_options, &local_err);
2486 snapshot_options = NULL;
2487 if (local_err) {
2488 goto close_and_fail;
2489 }
2490 /* We are not going to return bs but the overlay on top of it
2491 * (snapshot_bs); thus, we have to drop the strong reference to bs
2492 * (which we obtained by calling bdrv_new()). bs will not be deleted,
2493 * though, because the overlay still has a reference to it. */
2494 bdrv_unref(bs);
2495 bs = snapshot_bs;
2496 }
2497
2498 return bs;
2499
2500 fail:
2501 blk_unref(file);
2502 if (bs->file != NULL) {
2503 bdrv_unref_child(bs, bs->file);
2504 }
2505 QDECREF(snapshot_options);
2506 QDECREF(bs->explicit_options);
2507 QDECREF(bs->options);
2508 QDECREF(options);
2509 bs->options = NULL;
2510 bdrv_unref(bs);
2511 error_propagate(errp, local_err);
2512 return NULL;
2513
2514 close_and_fail:
2515 bdrv_unref(bs);
2516 QDECREF(snapshot_options);
2517 QDECREF(options);
2518 error_propagate(errp, local_err);
2519 return NULL;
2520 }
2521
2522 BlockDriverState *bdrv_open(const char *filename, const char *reference,
2523 QDict *options, int flags, Error **errp)
2524 {
2525 return bdrv_open_inherit(filename, reference, options, flags, NULL,
2526 NULL, errp);
2527 }
2528
2529 typedef struct BlockReopenQueueEntry {
2530 bool prepared;
2531 BDRVReopenState state;
2532 QSIMPLEQ_ENTRY(BlockReopenQueueEntry) entry;
2533 } BlockReopenQueueEntry;
2534
2535 /*
2536 * Adds a BlockDriverState to a simple queue for an atomic, transactional
2537 * reopen of multiple devices.
2538 *
2539 * bs_queue can either be an existing BlockReopenQueue that has had QSIMPLE_INIT
2540 * already performed, or alternatively may be NULL a new BlockReopenQueue will
2541 * be created and initialized. This newly created BlockReopenQueue should be
2542 * passed back in for subsequent calls that are intended to be of the same
2543 * atomic 'set'.
2544 *
2545 * bs is the BlockDriverState to add to the reopen queue.
2546 *
2547 * options contains the changed options for the associated bs
2548 * (the BlockReopenQueue takes ownership)
2549 *
2550 * flags contains the open flags for the associated bs
2551 *
2552 * returns a pointer to bs_queue, which is either the newly allocated
2553 * bs_queue, or the existing bs_queue being used.
2554 *
2555 */
2556 static BlockReopenQueue *bdrv_reopen_queue_child(BlockReopenQueue *bs_queue,
2557 BlockDriverState *bs,
2558 QDict *options,
2559 int flags,
2560 const BdrvChildRole *role,
2561 QDict *parent_options,
2562 int parent_flags)
2563 {
2564 assert(bs != NULL);
2565
2566 BlockReopenQueueEntry *bs_entry;
2567 BdrvChild *child;
2568 QDict *old_options, *explicit_options;
2569
2570 if (bs_queue == NULL) {
2571 bs_queue = g_new0(BlockReopenQueue, 1);
2572 QSIMPLEQ_INIT(bs_queue);
2573 }
2574
2575 if (!options) {
2576 options = qdict_new();
2577 }
2578
2579 /* Check if this BlockDriverState is already in the queue */
2580 QSIMPLEQ_FOREACH(bs_entry, bs_queue, entry) {
2581 if (bs == bs_entry->state.bs) {
2582 break;
2583 }
2584 }
2585
2586 /*
2587 * Precedence of options:
2588 * 1. Explicitly passed in options (highest)
2589 * 2. Set in flags (only for top level)
2590 * 3. Retained from explicitly set options of bs
2591 * 4. Inherited from parent node
2592 * 5. Retained from effective options of bs
2593 */
2594
2595 if (!parent_options) {
2596 /*
2597 * Any setting represented by flags is always updated. If the
2598 * corresponding QDict option is set, it takes precedence. Otherwise
2599 * the flag is translated into a QDict option. The old setting of bs is
2600 * not considered.
2601 */
2602 update_options_from_flags(options, flags);
2603 }
2604
2605 /* Old explicitly set values (don't overwrite by inherited value) */
2606 if (bs_entry) {
2607 old_options = qdict_clone_shallow(bs_entry->state.explicit_options);
2608 } else {
2609 old_options = qdict_clone_shallow(bs->explicit_options);
2610 }
2611 bdrv_join_options(bs, options, old_options);
2612 QDECREF(old_options);
2613
2614 explicit_options = qdict_clone_shallow(options);
2615
2616 /* Inherit from parent node */
2617 if (parent_options) {
2618 assert(!flags);
2619 role->inherit_options(&flags, options, parent_flags, parent_options);
2620 }
2621
2622 /* Old values are used for options that aren't set yet */
2623 old_options = qdict_clone_shallow(bs->options);
2624 bdrv_join_options(bs, options, old_options);
2625 QDECREF(old_options);
2626
2627 /* bdrv_open() masks this flag out */
2628 flags &= ~BDRV_O_PROTOCOL;
2629
2630 QLIST_FOREACH(child, &bs->children, next) {
2631 QDict *new_child_options;
2632 char *child_key_dot;
2633
2634 /* reopen can only change the options of block devices that were
2635 * implicitly created and inherited options. For other (referenced)
2636 * block devices, a syntax like "backing.foo" results in an error. */
2637 if (child->bs->inherits_from != bs) {
2638 continue;
2639 }
2640
2641 child_key_dot = g_strdup_printf("%s.", child->name);
2642 qdict_extract_subqdict(options, &new_child_options, child_key_dot);
2643 g_free(child_key_dot);
2644
2645 bdrv_reopen_queue_child(bs_queue, child->bs, new_child_options, 0,
2646 child->role, options, flags);
2647 }
2648
2649 if (!bs_entry) {
2650 bs_entry = g_new0(BlockReopenQueueEntry, 1);
2651 QSIMPLEQ_INSERT_TAIL(bs_queue, bs_entry, entry);
2652 } else {
2653 QDECREF(bs_entry->state.options);
2654 QDECREF(bs_entry->state.explicit_options);
2655 }
2656
2657 bs_entry->state.bs = bs;
2658 bs_entry->state.options = options;
2659 bs_entry->state.explicit_options = explicit_options;
2660 bs_entry->state.flags = flags;
2661
2662 return bs_queue;
2663 }
2664
2665 BlockReopenQueue *bdrv_reopen_queue(BlockReopenQueue *bs_queue,
2666 BlockDriverState *bs,
2667 QDict *options, int flags)
2668 {
2669 return bdrv_reopen_queue_child(bs_queue, bs, options, flags,
2670 NULL, NULL, 0);
2671 }
2672
2673 /*
2674 * Reopen multiple BlockDriverStates atomically & transactionally.
2675 *
2676 * The queue passed in (bs_queue) must have been built up previous
2677 * via bdrv_reopen_queue().
2678 *
2679 * Reopens all BDS specified in the queue, with the appropriate
2680 * flags. All devices are prepared for reopen, and failure of any
2681 * device will cause all device changes to be abandonded, and intermediate
2682 * data cleaned up.
2683 *
2684 * If all devices prepare successfully, then the changes are committed
2685 * to all devices.
2686 *
2687 */
2688 int bdrv_reopen_multiple(AioContext *ctx, BlockReopenQueue *bs_queue, Error **errp)
2689 {
2690 int ret = -1;
2691 BlockReopenQueueEntry *bs_entry, *next;
2692 Error *local_err = NULL;
2693
2694 assert(bs_queue != NULL);
2695
2696 aio_context_release(ctx);
2697 bdrv_drain_all_begin();
2698 aio_context_acquire(ctx);
2699
2700 QSIMPLEQ_FOREACH(bs_entry, bs_queue, entry) {
2701 if (bdrv_reopen_prepare(&bs_entry->state, bs_queue, &local_err)) {
2702 error_propagate(errp, local_err);
2703 goto cleanup;
2704 }
2705 bs_entry->prepared = true;
2706 }
2707
2708 /* If we reach this point, we have success and just need to apply the
2709 * changes
2710 */
2711 QSIMPLEQ_FOREACH(bs_entry, bs_queue, entry) {
2712 bdrv_reopen_commit(&bs_entry->state);
2713 }
2714
2715 ret = 0;
2716
2717 cleanup:
2718 QSIMPLEQ_FOREACH_SAFE(bs_entry, bs_queue, entry, next) {
2719 if (ret && bs_entry->prepared) {
2720 bdrv_reopen_abort(&bs_entry->state);
2721 } else if (ret) {
2722 QDECREF(bs_entry->state.explicit_options);
2723 }
2724 QDECREF(bs_entry->state.options);
2725 g_free(bs_entry);
2726 }
2727 g_free(bs_queue);
2728
2729 bdrv_drain_all_end();
2730
2731 return ret;
2732 }
2733
2734
2735 /* Reopen a single BlockDriverState with the specified flags. */
2736 int bdrv_reopen(BlockDriverState *bs, int bdrv_flags, Error **errp)
2737 {
2738 int ret = -1;
2739 Error *local_err = NULL;
2740 BlockReopenQueue *queue = bdrv_reopen_queue(NULL, bs, NULL, bdrv_flags);
2741
2742 ret = bdrv_reopen_multiple(bdrv_get_aio_context(bs), queue, &local_err);
2743 if (local_err != NULL) {
2744 error_propagate(errp, local_err);
2745 }
2746 return ret;
2747 }
2748
2749
2750 /*
2751 * Prepares a BlockDriverState for reopen. All changes are staged in the
2752 * 'opaque' field of the BDRVReopenState, which is used and allocated by
2753 * the block driver layer .bdrv_reopen_prepare()
2754 *
2755 * bs is the BlockDriverState to reopen
2756 * flags are the new open flags
2757 * queue is the reopen queue
2758 *
2759 * Returns 0 on success, non-zero on error. On error errp will be set
2760 * as well.
2761 *
2762 * On failure, bdrv_reopen_abort() will be called to clean up any data.
2763 * It is the responsibility of the caller to then call the abort() or
2764 * commit() for any other BDS that have been left in a prepare() state
2765 *
2766 */
2767 int bdrv_reopen_prepare(BDRVReopenState *reopen_state, BlockReopenQueue *queue,
2768 Error **errp)
2769 {
2770 int ret = -1;
2771 Error *local_err = NULL;
2772 BlockDriver *drv;
2773 QemuOpts *opts;
2774 const char *value;
2775
2776 assert(reopen_state != NULL);
2777 assert(reopen_state->bs->drv != NULL);
2778 drv = reopen_state->bs->drv;
2779
2780 /* Process generic block layer options */
2781 opts = qemu_opts_create(&bdrv_runtime_opts, NULL, 0, &error_abort);
2782 qemu_opts_absorb_qdict(opts, reopen_state->options, &local_err);
2783 if (local_err) {
2784 error_propagate(errp, local_err);
2785 ret = -EINVAL;
2786 goto error;
2787 }
2788
2789 update_flags_from_options(&reopen_state->flags, opts);
2790
2791 /* node-name and driver must be unchanged. Put them back into the QDict, so
2792 * that they are checked at the end of this function. */
2793 value = qemu_opt_get(opts, "node-name");
2794 if (value) {
2795 qdict_put(reopen_state->options, "node-name", qstring_from_str(value));
2796 }
2797
2798 value = qemu_opt_get(opts, "driver");
2799 if (value) {
2800 qdict_put(reopen_state->options, "driver", qstring_from_str(value));
2801 }
2802
2803 /* if we are to stay read-only, do not allow permission change
2804 * to r/w */
2805 if (!(reopen_state->bs->open_flags & BDRV_O_ALLOW_RDWR) &&
2806 reopen_state->flags & BDRV_O_RDWR) {
2807 error_setg(errp, "Node '%s' is read only",
2808 bdrv_get_device_or_node_name(reopen_state->bs));
2809 goto error;
2810 }
2811
2812
2813 ret = bdrv_flush(reopen_state->bs);
2814 if (ret) {
2815 error_setg_errno(errp, -ret, "Error flushing drive");
2816 goto error;
2817 }
2818
2819 if (drv->bdrv_reopen_prepare) {
2820 ret = drv->bdrv_reopen_prepare(reopen_state, queue, &local_err);
2821 if (ret) {
2822 if (local_err != NULL) {
2823 error_propagate(errp, local_err);
2824 } else {
2825 error_setg(errp, "failed while preparing to reopen image '%s'",
2826 reopen_state->bs->filename);
2827 }
2828 goto error;
2829 }
2830 } else {
2831 /* It is currently mandatory to have a bdrv_reopen_prepare()
2832 * handler for each supported drv. */
2833 error_setg(errp, "Block format '%s' used by node '%s' "
2834 "does not support reopening files", drv->format_name,
2835 bdrv_get_device_or_node_name(reopen_state->bs));
2836 ret = -1;
2837 goto error;
2838 }
2839
2840 /* Options that are not handled are only okay if they are unchanged
2841 * compared to the old state. It is expected that some options are only
2842 * used for the initial open, but not reopen (e.g. filename) */
2843 if (qdict_size(reopen_state->options)) {
2844 const QDictEntry *entry = qdict_first(reopen_state->options);
2845
2846 do {
2847 QString *new_obj = qobject_to_qstring(entry->value);
2848 const char *new = qstring_get_str(new_obj);
2849 /*
2850 * Caution: while qdict_get_try_str() is fine, getting
2851 * non-string types would require more care. When
2852 * bs->options come from -blockdev or blockdev_add, its
2853 * members are typed according to the QAPI schema, but
2854 * when they come from -drive, they're all QString.
2855 */
2856 const char *old = qdict_get_try_str(reopen_state->bs->options,
2857 entry->key);
2858
2859 if (!old || strcmp(new, old)) {
2860 error_setg(errp, "Cannot change the option '%s'", entry->key);
2861 ret = -EINVAL;
2862 goto error;
2863 }
2864 } while ((entry = qdict_next(reopen_state->options, entry)));
2865 }
2866
2867 ret = 0;
2868
2869 error:
2870 qemu_opts_del(opts);
2871 return ret;
2872 }
2873
2874 /*
2875 * Takes the staged changes for the reopen from bdrv_reopen_prepare(), and
2876 * makes them final by swapping the staging BlockDriverState contents into
2877 * the active BlockDriverState contents.
2878 */
2879 void bdrv_reopen_commit(BDRVReopenState *reopen_state)
2880 {
2881 BlockDriver *drv;
2882
2883 assert(reopen_state != NULL);
2884 drv = reopen_state->bs->drv;
2885 assert(drv != NULL);
2886
2887 /* If there are any driver level actions to take */
2888 if (drv->bdrv_reopen_commit) {
2889 drv->bdrv_reopen_commit(reopen_state);
2890 }
2891
2892 /* set BDS specific flags now */
2893 QDECREF(reopen_state->bs->explicit_options);
2894
2895 reopen_state->bs->explicit_options = reopen_state->explicit_options;
2896 reopen_state->bs->open_flags = reopen_state->flags;
2897 reopen_state->bs->read_only = !(reopen_state->flags & BDRV_O_RDWR);
2898
2899 bdrv_refresh_limits(reopen_state->bs, NULL);
2900 }
2901
2902 /*
2903 * Abort the reopen, and delete and free the staged changes in
2904 * reopen_state
2905 */
2906 void bdrv_reopen_abort(BDRVReopenState *reopen_state)
2907 {
2908 BlockDriver *drv;
2909
2910 assert(reopen_state != NULL);
2911 drv = reopen_state->bs->drv;
2912 assert(drv != NULL);
2913
2914 if (drv->bdrv_reopen_abort) {
2915 drv->bdrv_reopen_abort(reopen_state);
2916 }
2917
2918 QDECREF(reopen_state->explicit_options);
2919 }
2920
2921
2922 static void bdrv_close(BlockDriverState *bs)
2923 {
2924 BdrvAioNotifier *ban, *ban_next;
2925
2926 assert(!bs->job);
2927 assert(!bs->refcnt);
2928
2929 bdrv_drained_begin(bs); /* complete I/O */
2930 bdrv_flush(bs);
2931 bdrv_drain(bs); /* in case flush left pending I/O */
2932
2933 bdrv_release_named_dirty_bitmaps(bs);
2934 assert(QLIST_EMPTY(&bs->dirty_bitmaps));
2935
2936 if (bs->drv) {
2937 BdrvChild *child, *next;
2938
2939 bs->drv->bdrv_close(bs);
2940 bs->drv = NULL;
2941
2942 bdrv_set_backing_hd(bs, NULL, &error_abort);
2943
2944 if (bs->file != NULL) {
2945 bdrv_unref_child(bs, bs->file);
2946 bs->file = NULL;
2947 }
2948
2949 QLIST_FOREACH_SAFE(child, &bs->children, next, next) {
2950 /* TODO Remove bdrv_unref() from drivers' close function and use
2951 * bdrv_unref_child() here */
2952 if (child->bs->inherits_from == bs) {
2953 child->bs->inherits_from = NULL;
2954 }
2955 bdrv_detach_child(child);
2956 }
2957
2958 g_free(bs->opaque);
2959 bs->opaque = NULL;
2960 bs->copy_on_read = 0;
2961 bs->backing_file[0] = '\0';
2962 bs->backing_format[0] = '\0';
2963 bs->total_sectors = 0;
2964 bs->encrypted = false;
2965 bs->valid_key = false;
2966 bs->sg = false;
2967 QDECREF(bs->options);
2968 QDECREF(bs->explicit_options);
2969 bs->options = NULL;
2970 QDECREF(bs->full_open_options);
2971 bs->full_open_options = NULL;
2972 }
2973
2974 QLIST_FOREACH_SAFE(ban, &bs->aio_notifiers, list, ban_next) {
2975 g_free(ban);
2976 }
2977 QLIST_INIT(&bs->aio_notifiers);
2978 bdrv_drained_end(bs);
2979 }
2980
2981 void bdrv_close_all(void)
2982 {
2983 block_job_cancel_sync_all();
2984 nbd_export_close_all();
2985
2986 /* Drop references from requests still in flight, such as canceled block
2987 * jobs whose AIO context has not been polled yet */
2988 bdrv_drain_all();
2989
2990 blk_remove_all_bs();
2991 blockdev_close_all_bdrv_states();
2992
2993 assert(QTAILQ_EMPTY(&all_bdrv_states));
2994 }
2995
2996 static bool should_update_child(BdrvChild *c, BlockDriverState *to)
2997 {
2998 BdrvChild *to_c;
2999
3000 if (c->role->stay_at_node) {
3001 return false;
3002 }
3003
3004 if (c->role == &child_backing) {
3005 /* If @from is a backing file of @to, ignore the child to avoid
3006 * creating a loop. We only want to change the pointer of other
3007 * parents. */
3008 QLIST_FOREACH(to_c, &to->children, next) {
3009 if (to_c == c) {
3010 break;
3011 }
3012 }
3013 if (to_c) {
3014 return false;
3015 }
3016 }
3017
3018 return true;
3019 }
3020
3021 void bdrv_replace_node(BlockDriverState *from, BlockDriverState *to,
3022 Error **errp)
3023 {
3024 BdrvChild *c, *next;
3025 GSList *list = NULL, *p;
3026 uint64_t old_perm, old_shared;
3027 uint64_t perm = 0, shared = BLK_PERM_ALL;
3028 int ret;
3029
3030 assert(!atomic_read(&from->in_flight));
3031 assert(!atomic_read(&to->in_flight));
3032
3033 /* Make sure that @from doesn't go away until we have successfully attached
3034 * all of its parents to @to. */
3035 bdrv_ref(from);
3036
3037 /* Put all parents into @list and calculate their cumulative permissions */
3038 QLIST_FOREACH_SAFE(c, &from->parents, next_parent, next) {
3039 if (!should_update_child(c, to)) {
3040 continue;
3041 }
3042 list = g_slist_prepend(list, c);
3043 perm |= c->perm;
3044 shared &= c->shared_perm;
3045 }
3046
3047 /* Check whether the required permissions can be granted on @to, ignoring
3048 * all BdrvChild in @list so that they can't block themselves. */
3049 ret = bdrv_check_update_perm(to, perm, shared, list, errp);
3050 if (ret < 0) {
3051 bdrv_abort_perm_update(to);
3052 goto out;
3053 }
3054
3055 /* Now actually perform the change. We performed the permission check for
3056 * all elements of @list at once, so set the permissions all at once at the
3057 * very end. */
3058 for (p = list; p != NULL; p = p->next) {
3059 c = p->data;
3060
3061 bdrv_ref(to);
3062 bdrv_replace_child_noperm(c, to);
3063 bdrv_unref(from);
3064 }
3065
3066 bdrv_get_cumulative_perm(to, &old_perm, &old_shared);
3067 bdrv_set_perm(to, old_perm | perm, old_shared | shared);
3068
3069 out:
3070 g_slist_free(list);
3071 bdrv_unref(from);
3072 }
3073
3074 /*
3075 * Add new bs contents at the top of an image chain while the chain is
3076 * live, while keeping required fields on the top layer.
3077 *
3078 * This will modify the BlockDriverState fields, and swap contents
3079 * between bs_new and bs_top. Both bs_new and bs_top are modified.
3080 *
3081 * bs_new must not be attached to a BlockBackend.
3082 *
3083 * This function does not create any image files.
3084 *
3085 * bdrv_append() takes ownership of a bs_new reference and unrefs it because
3086 * that's what the callers commonly need. bs_new will be referenced by the old
3087 * parents of bs_top after bdrv_append() returns. If the caller needs to keep a
3088 * reference of its own, it must call bdrv_ref().
3089 */
3090 void bdrv_append(BlockDriverState *bs_new, BlockDriverState *bs_top,
3091 Error **errp)
3092 {
3093 Error *local_err = NULL;
3094
3095 bdrv_set_backing_hd(bs_new, bs_top, &local_err);
3096 if (local_err) {
3097 error_propagate(errp, local_err);
3098 goto out;
3099 }
3100
3101 bdrv_replace_node(bs_top, bs_new, &local_err);
3102 if (local_err) {
3103 error_propagate(errp, local_err);
3104 bdrv_set_backing_hd(bs_new, NULL, &error_abort);
3105 goto out;
3106 }
3107
3108 /* bs_new is now referenced by its new parents, we don't need the
3109 * additional reference any more. */
3110 out:
3111 bdrv_unref(bs_new);
3112 }
3113
3114 static void bdrv_delete(BlockDriverState *bs)
3115 {
3116 assert(!bs->job);
3117 assert(bdrv_op_blocker_is_empty(bs));
3118 assert(!bs->refcnt);
3119
3120 bdrv_close(bs);
3121
3122 /* remove from list, if necessary */
3123 if (bs->node_name[0] != '\0') {
3124 QTAILQ_REMOVE(&graph_bdrv_states, bs, node_list);
3125 }
3126 QTAILQ_REMOVE(&all_bdrv_states, bs, bs_list);
3127
3128 g_free(bs);
3129 }
3130
3131 /*
3132 * Run consistency checks on an image
3133 *
3134 * Returns 0 if the check could be completed (it doesn't mean that the image is
3135 * free of errors) or -errno when an internal error occurred. The results of the
3136 * check are stored in res.
3137 */
3138 int bdrv_check(BlockDriverState *bs, BdrvCheckResult *res, BdrvCheckMode fix)
3139 {
3140 if (bs->drv == NULL) {
3141 return -ENOMEDIUM;
3142 }
3143 if (bs->drv->bdrv_check == NULL) {
3144 return -ENOTSUP;
3145 }
3146
3147 memset(res, 0, sizeof(*res));
3148 return bs->drv->bdrv_check(bs, res, fix);
3149 }
3150
3151 /*
3152 * Return values:
3153 * 0 - success
3154 * -EINVAL - backing format specified, but no file
3155 * -ENOSPC - can't update the backing file because no space is left in the
3156 * image file header
3157 * -ENOTSUP - format driver doesn't support changing the backing file
3158 */
3159 int bdrv_change_backing_file(BlockDriverState *bs,
3160 const char *backing_file, const char *backing_fmt)
3161 {
3162 BlockDriver *drv = bs->drv;
3163 int ret;
3164
3165 /* Backing file format doesn't make sense without a backing file */
3166 if (backing_fmt && !backing_file) {
3167 return -EINVAL;
3168 }
3169
3170 if (drv->bdrv_change_backing_file != NULL) {
3171 ret = drv->bdrv_change_backing_file(bs, backing_file, backing_fmt);
3172 } else {
3173 ret = -ENOTSUP;
3174 }
3175
3176 if (ret == 0) {
3177 pstrcpy(bs->backing_file, sizeof(bs->backing_file), backing_file ?: "");
3178 pstrcpy(bs->backing_format, sizeof(bs->backing_format), backing_fmt ?: "");
3179 }
3180 return ret;
3181 }
3182
3183 /*
3184 * Finds the image layer in the chain that has 'bs' as its backing file.
3185 *
3186 * active is the current topmost image.
3187 *
3188 * Returns NULL if bs is not found in active's image chain,
3189 * or if active == bs.
3190 *
3191 * Returns the bottommost base image if bs == NULL.
3192 */
3193 BlockDriverState *bdrv_find_overlay(BlockDriverState *active,
3194 BlockDriverState *bs)
3195 {
3196 while (active && bs != backing_bs(active)) {
3197 active = backing_bs(active);
3198 }
3199
3200 return active;
3201 }
3202
3203 /* Given a BDS, searches for the base layer. */
3204 BlockDriverState *bdrv_find_base(BlockDriverState *bs)
3205 {
3206 return bdrv_find_overlay(bs, NULL);
3207 }
3208
3209 /*
3210 * Drops images above 'base' up to and including 'top', and sets the image
3211 * above 'top' to have base as its backing file.
3212 *
3213 * Requires that the overlay to 'top' is opened r/w, so that the backing file
3214 * information in 'bs' can be properly updated.
3215 *
3216 * E.g., this will convert the following chain:
3217 * bottom <- base <- intermediate <- top <- active
3218 *
3219 * to
3220 *
3221 * bottom <- base <- active
3222 *
3223 * It is allowed for bottom==base, in which case it converts:
3224 *
3225 * base <- intermediate <- top <- active
3226 *
3227 * to
3228 *
3229 * base <- active
3230 *
3231 * If backing_file_str is non-NULL, it will be used when modifying top's
3232 * overlay image metadata.
3233 *
3234 * Error conditions:
3235 * if active == top, that is considered an error
3236 *
3237 */
3238 int bdrv_drop_intermediate(BlockDriverState *active, BlockDriverState *top,
3239 BlockDriverState *base, const char *backing_file_str)
3240 {
3241 BlockDriverState *new_top_bs = NULL;
3242 Error *local_err = NULL;
3243 int ret = -EIO;
3244
3245 if (!top->drv || !base->drv) {
3246 goto exit;
3247 }
3248
3249 new_top_bs = bdrv_find_overlay(active, top);
3250
3251 if (new_top_bs == NULL) {
3252 /* we could not find the image above 'top', this is an error */
3253 goto exit;
3254 }
3255
3256 /* special case of new_top_bs->backing->bs already pointing to base - nothing
3257 * to do, no intermediate images */
3258 if (backing_bs(new_top_bs) == base) {
3259 ret = 0;
3260 goto exit;
3261 }
3262
3263 /* Make sure that base is in the backing chain of top */
3264 if (!bdrv_chain_contains(top, base)) {
3265 goto exit;
3266 }
3267
3268 /* success - we can delete the intermediate states, and link top->base */
3269 backing_file_str = backing_file_str ? backing_file_str : base->filename;
3270 ret = bdrv_change_backing_file(new_top_bs, backing_file_str,
3271 base->drv ? base->drv->format_name : "");
3272 if (ret) {
3273 goto exit;
3274 }
3275
3276 bdrv_set_backing_hd(new_top_bs, base, &local_err);
3277 if (local_err) {
3278 ret = -EPERM;
3279 error_report_err(local_err);
3280 goto exit;
3281 }
3282
3283 ret = 0;
3284 exit:
3285 return ret;
3286 }
3287
3288 /**
3289 * Truncate file to 'offset' bytes (needed only for file protocols)
3290 */
3291 int bdrv_truncate(BdrvChild *child, int64_t offset)
3292 {
3293 BlockDriverState *bs = child->bs;
3294 BlockDriver *drv = bs->drv;
3295 int ret;
3296
3297 /* FIXME: Some format block drivers use this function instead of implicitly
3298 * growing their file by writing beyond its end.
3299 * See bdrv_aligned_pwritev() for an explanation why we currently
3300 * cannot assert this permission in that case. */
3301 // assert(child->perm & BLK_PERM_RESIZE);
3302
3303 if (!drv)
3304 return -ENOMEDIUM;
3305 if (!drv->bdrv_truncate)
3306 return -ENOTSUP;
3307 if (bs->read_only)
3308 return -EACCES;
3309
3310 ret = drv->bdrv_truncate(bs, offset);
3311 if (ret == 0) {
3312 ret = refresh_total_sectors(bs, offset >> BDRV_SECTOR_BITS);
3313 bdrv_dirty_bitmap_truncate(bs);
3314 bdrv_parent_cb_resize(bs);
3315 ++bs->write_gen;
3316 }
3317 return ret;
3318 }
3319
3320 /**
3321 * Length of a allocated file in bytes. Sparse files are counted by actual
3322 * allocated space. Return < 0 if error or unknown.
3323 */
3324 int64_t bdrv_get_allocated_file_size(BlockDriverState *bs)
3325 {
3326 BlockDriver *drv = bs->drv;
3327 if (!drv) {
3328 return -ENOMEDIUM;
3329 }
3330 if (drv->bdrv_get_allocated_file_size) {
3331 return drv->bdrv_get_allocated_file_size(bs);
3332 }
3333 if (bs->file) {
3334 return bdrv_get_allocated_file_size(bs->file->bs);
3335 }
3336 return -ENOTSUP;
3337 }
3338
3339 /**
3340 * Return number of sectors on success, -errno on error.
3341 */
3342 int64_t bdrv_nb_sectors(BlockDriverState *bs)
3343 {
3344 BlockDriver *drv = bs->drv;
3345
3346 if (!drv)
3347 return -ENOMEDIUM;
3348
3349 if (drv->has_variable_length) {
3350 int ret = refresh_total_sectors(bs, bs->total_sectors);
3351 if (ret < 0) {
3352 return ret;
3353 }
3354 }
3355 return bs->total_sectors;
3356 }
3357
3358 /**
3359 * Return length in bytes on success, -errno on error.
3360 * The length is always a multiple of BDRV_SECTOR_SIZE.
3361 */
3362 int64_t bdrv_getlength(BlockDriverState *bs)
3363 {
3364 int64_t ret = bdrv_nb_sectors(bs);
3365
3366 ret = ret > INT64_MAX / BDRV_SECTOR_SIZE ? -EFBIG : ret;
3367 return ret < 0 ? ret : ret * BDRV_SECTOR_SIZE;
3368 }
3369
3370 /* return 0 as number of sectors if no device present or error */
3371 void bdrv_get_geometry(BlockDriverState *bs, uint64_t *nb_sectors_ptr)
3372 {
3373 int64_t nb_sectors = bdrv_nb_sectors(bs);
3374
3375 *nb_sectors_ptr = nb_sectors < 0 ? 0 : nb_sectors;
3376 }
3377
3378 bool bdrv_is_read_only(BlockDriverState *bs)
3379 {
3380 return bs->read_only;
3381 }
3382
3383 bool bdrv_is_sg(BlockDriverState *bs)
3384 {
3385 return bs->sg;
3386 }
3387
3388 bool bdrv_is_encrypted(BlockDriverState *bs)
3389 {
3390 if (bs->backing && bs->backing->bs->encrypted) {
3391 return true;
3392 }
3393 return bs->encrypted;
3394 }
3395
3396 bool bdrv_key_required(BlockDriverState *bs)
3397 {
3398 BdrvChild *backing = bs->backing;
3399
3400 if (backing && backing->bs->encrypted && !backing->bs->valid_key) {
3401 return true;
3402 }
3403 return (bs->encrypted && !bs->valid_key);
3404 }
3405
3406 int bdrv_set_key(BlockDriverState *bs, const char *key)
3407 {
3408 int ret;
3409 if (bs->backing && bs->backing->bs->encrypted) {
3410 ret = bdrv_set_key(bs->backing->bs, key);
3411 if (ret < 0)
3412 return ret;
3413 if (!bs->encrypted)
3414 return 0;
3415 }
3416 if (!bs->encrypted) {
3417 return -EINVAL;
3418 } else if (!bs->drv || !bs->drv->bdrv_set_key) {
3419 return -ENOMEDIUM;
3420 }
3421 ret = bs->drv->bdrv_set_key(bs, key);
3422 if (ret < 0) {
3423 bs->valid_key = false;
3424 } else if (!bs->valid_key) {
3425 /* call the change callback now, we skipped it on open */
3426 bs->valid_key = true;
3427 bdrv_parent_cb_change_media(bs, true);
3428 }
3429 return ret;
3430 }
3431
3432 /*
3433 * Provide an encryption key for @bs.
3434 * If @key is non-null:
3435 * If @bs is not encrypted, fail.
3436 * Else if the key is invalid, fail.
3437 * Else set @bs's key to @key, replacing the existing key, if any.
3438 * If @key is null:
3439 * If @bs is encrypted and still lacks a key, fail.
3440 * Else do nothing.
3441 * On failure, store an error object through @errp if non-null.
3442 */
3443 void bdrv_add_key(BlockDriverState *bs, const char *key, Error **errp)
3444 {
3445 if (key) {
3446 if (!bdrv_is_encrypted(bs)) {
3447 error_setg(errp, "Node '%s' is not encrypted",
3448 bdrv_get_device_or_node_name(bs));
3449 } else if (bdrv_set_key(bs, key) < 0) {
3450 error_setg(errp, QERR_INVALID_PASSWORD);
3451 }
3452 } else {
3453 if (bdrv_key_required(bs)) {
3454 error_set(errp, ERROR_CLASS_DEVICE_ENCRYPTED,
3455 "'%s' (%s) is encrypted",
3456 bdrv_get_device_or_node_name(bs),
3457 bdrv_get_encrypted_filename(bs));
3458 }
3459 }
3460 }
3461
3462 const char *bdrv_get_format_name(BlockDriverState *bs)
3463 {
3464 return bs->drv ? bs->drv->format_name : NULL;
3465 }
3466
3467 static int qsort_strcmp(const void *a, const void *b)
3468 {
3469 return strcmp(*(char *const *)a, *(char *const *)b);
3470 }
3471
3472 void bdrv_iterate_format(void (*it)(void *opaque, const char *name),
3473 void *opaque)
3474 {
3475 BlockDriver *drv;
3476 int count = 0;
3477 int i;
3478 const char **formats = NULL;
3479
3480 QLIST_FOREACH(drv, &bdrv_drivers, list) {
3481 if (drv->format_name) {
3482 bool found = false;
3483 int i = count;
3484 while (formats && i && !found) {
3485 found = !strcmp(formats[--i], drv->format_name);
3486 }
3487
3488 if (!found) {
3489 formats = g_renew(const char *, formats, count + 1);
3490 formats[count++] = drv->format_name;
3491 }
3492 }
3493 }
3494
3495 for (i = 0; i < (int)ARRAY_SIZE(block_driver_modules); i++) {
3496 const char *format_name = block_driver_modules[i].format_name;
3497
3498 if (format_name) {
3499 bool found = false;
3500 int j = count;
3501
3502 while (formats && j && !found) {
3503 found = !strcmp(formats[--j], format_name);
3504 }
3505
3506 if (!found) {
3507 formats = g_renew(const char *, formats, count + 1);
3508 formats[count++] = format_name;
3509 }
3510 }
3511 }
3512
3513 qsort(formats, count, sizeof(formats[0]), qsort_strcmp);
3514
3515 for (i = 0; i < count; i++) {
3516 it(opaque, formats[i]);
3517 }
3518
3519 g_free(formats);
3520 }
3521
3522 /* This function is to find a node in the bs graph */
3523 BlockDriverState *bdrv_find_node(const char *node_name)
3524 {
3525 BlockDriverState *bs;
3526
3527 assert(node_name);
3528
3529 QTAILQ_FOREACH(bs, &graph_bdrv_states, node_list) {
3530 if (!strcmp(node_name, bs->node_name)) {
3531 return bs;
3532 }
3533 }
3534 return NULL;
3535 }
3536
3537 /* Put this QMP function here so it can access the static graph_bdrv_states. */
3538 BlockDeviceInfoList *bdrv_named_nodes_list(Error **errp)
3539 {
3540 BlockDeviceInfoList *list, *entry;
3541 BlockDriverState *bs;
3542
3543 list = NULL;
3544 QTAILQ_FOREACH(bs, &graph_bdrv_states, node_list) {
3545 BlockDeviceInfo *info = bdrv_block_device_info(NULL, bs, errp);
3546 if (!info) {
3547 qapi_free_BlockDeviceInfoList(list);
3548 return NULL;
3549 }
3550 entry = g_malloc0(sizeof(*entry));
3551 entry->value = info;
3552 entry->next = list;
3553 list = entry;
3554 }
3555
3556 return list;
3557 }
3558
3559 BlockDriverState *bdrv_lookup_bs(const char *device,
3560 const char *node_name,
3561 Error **errp)
3562 {
3563 BlockBackend *blk;
3564 BlockDriverState *bs;
3565
3566 if (device) {
3567 blk = blk_by_name(device);
3568
3569 if (blk) {
3570 bs = blk_bs(blk);
3571 if (!bs) {
3572 error_setg(errp, "Device '%s' has no medium", device);
3573 }
3574
3575 return bs;
3576 }
3577 }