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