]> Git Repo - qemu.git/blob - block.c
block: Fix reconfiguring graph with drained nodes
[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         if (old_bs->quiesce_counter && child->role->drained_end) {
1159             child->role->drained_end(child);
1160         }
1161         QLIST_REMOVE(child, next_parent);
1162     }
1163
1164     child->bs = new_bs;
1165
1166     if (new_bs) {
1167         QLIST_INSERT_HEAD(&new_bs->parents, child, next_parent);
1168         if (new_bs->quiesce_counter && child->role->drained_begin) {
1169             child->role->drained_begin(child);
1170         }
1171     }
1172 }
1173
1174 BdrvChild *bdrv_root_attach_child(BlockDriverState *child_bs,
1175                                   const char *child_name,
1176                                   const BdrvChildRole *child_role,
1177                                   void *opaque)
1178 {
1179     BdrvChild *child = g_new(BdrvChild, 1);
1180     *child = (BdrvChild) {
1181         .bs     = NULL,
1182         .name   = g_strdup(child_name),
1183         .role   = child_role,
1184         .opaque = opaque,
1185     };
1186
1187     bdrv_replace_child(child, child_bs);
1188
1189     return child;
1190 }
1191
1192 BdrvChild *bdrv_attach_child(BlockDriverState *parent_bs,
1193                              BlockDriverState *child_bs,
1194                              const char *child_name,
1195                              const BdrvChildRole *child_role)
1196 {
1197     BdrvChild *child = bdrv_root_attach_child(child_bs, child_name, child_role,
1198                                               NULL);
1199     QLIST_INSERT_HEAD(&parent_bs->children, child, next);
1200     return child;
1201 }
1202
1203 static void bdrv_detach_child(BdrvChild *child)
1204 {
1205     if (child->next.le_prev) {
1206         QLIST_REMOVE(child, next);
1207         child->next.le_prev = NULL;
1208     }
1209
1210     bdrv_replace_child(child, NULL);
1211
1212     g_free(child->name);
1213     g_free(child);
1214 }
1215
1216 void bdrv_root_unref_child(BdrvChild *child)
1217 {
1218     BlockDriverState *child_bs;
1219
1220     child_bs = child->bs;
1221     bdrv_detach_child(child);
1222     bdrv_unref(child_bs);
1223 }
1224
1225 void bdrv_unref_child(BlockDriverState *parent, BdrvChild *child)
1226 {
1227     if (child == NULL) {
1228         return;
1229     }
1230
1231     if (child->bs->inherits_from == parent) {
1232         child->bs->inherits_from = NULL;
1233     }
1234
1235     bdrv_root_unref_child(child);
1236 }
1237
1238
1239 static void bdrv_parent_cb_change_media(BlockDriverState *bs, bool load)
1240 {
1241     BdrvChild *c;
1242     QLIST_FOREACH(c, &bs->parents, next_parent) {
1243         if (c->role->change_media) {
1244             c->role->change_media(c, load);
1245         }
1246     }
1247 }
1248
1249 static void bdrv_parent_cb_resize(BlockDriverState *bs)
1250 {
1251     BdrvChild *c;
1252     QLIST_FOREACH(c, &bs->parents, next_parent) {
1253         if (c->role->resize) {
1254             c->role->resize(c);
1255         }
1256     }
1257 }
1258
1259 /*
1260  * Sets the backing file link of a BDS. A new reference is created; callers
1261  * which don't need their own reference any more must call bdrv_unref().
1262  */
1263 void bdrv_set_backing_hd(BlockDriverState *bs, BlockDriverState *backing_hd)
1264 {
1265     if (backing_hd) {
1266         bdrv_ref(backing_hd);
1267     }
1268
1269     if (bs->backing) {
1270         assert(bs->backing_blocker);
1271         bdrv_op_unblock_all(bs->backing->bs, bs->backing_blocker);
1272         bdrv_unref_child(bs, bs->backing);
1273     } else if (backing_hd) {
1274         error_setg(&bs->backing_blocker,
1275                    "node is used as backing hd of '%s'",
1276                    bdrv_get_device_or_node_name(bs));
1277     }
1278
1279     if (!backing_hd) {
1280         error_free(bs->backing_blocker);
1281         bs->backing_blocker = NULL;
1282         bs->backing = NULL;
1283         goto out;
1284     }
1285     bs->backing = bdrv_attach_child(bs, backing_hd, "backing", &child_backing);
1286     bs->open_flags &= ~BDRV_O_NO_BACKING;
1287     pstrcpy(bs->backing_file, sizeof(bs->backing_file), backing_hd->filename);
1288     pstrcpy(bs->backing_format, sizeof(bs->backing_format),
1289             backing_hd->drv ? backing_hd->drv->format_name : "");
1290
1291     bdrv_op_block_all(backing_hd, bs->backing_blocker);
1292     /* Otherwise we won't be able to commit due to check in bdrv_commit */
1293     bdrv_op_unblock(backing_hd, BLOCK_OP_TYPE_COMMIT_TARGET,
1294                     bs->backing_blocker);
1295 out:
1296     bdrv_refresh_limits(bs, NULL);
1297 }
1298
1299 /*
1300  * Opens the backing file for a BlockDriverState if not yet open
1301  *
1302  * bdref_key specifies the key for the image's BlockdevRef in the options QDict.
1303  * That QDict has to be flattened; therefore, if the BlockdevRef is a QDict
1304  * itself, all options starting with "${bdref_key}." are considered part of the
1305  * BlockdevRef.
1306  *
1307  * TODO Can this be unified with bdrv_open_image()?
1308  */
1309 int bdrv_open_backing_file(BlockDriverState *bs, QDict *parent_options,
1310                            const char *bdref_key, Error **errp)
1311 {
1312     char *backing_filename = g_malloc0(PATH_MAX);
1313     char *bdref_key_dot;
1314     const char *reference = NULL;
1315     int ret = 0;
1316     BlockDriverState *backing_hd;
1317     QDict *options;
1318     QDict *tmp_parent_options = NULL;
1319     Error *local_err = NULL;
1320
1321     if (bs->backing != NULL) {
1322         goto free_exit;
1323     }
1324
1325     /* NULL means an empty set of options */
1326     if (parent_options == NULL) {
1327         tmp_parent_options = qdict_new();
1328         parent_options = tmp_parent_options;
1329     }
1330
1331     bs->open_flags &= ~BDRV_O_NO_BACKING;
1332
1333     bdref_key_dot = g_strdup_printf("%s.", bdref_key);
1334     qdict_extract_subqdict(parent_options, &options, bdref_key_dot);
1335     g_free(bdref_key_dot);
1336
1337     reference = qdict_get_try_str(parent_options, bdref_key);
1338     if (reference || qdict_haskey(options, "file.filename")) {
1339         backing_filename[0] = '\0';
1340     } else if (bs->backing_file[0] == '\0' && qdict_size(options) == 0) {
1341         QDECREF(options);
1342         goto free_exit;
1343     } else {
1344         bdrv_get_full_backing_filename(bs, backing_filename, PATH_MAX,
1345                                        &local_err);
1346         if (local_err) {
1347             ret = -EINVAL;
1348             error_propagate(errp, local_err);
1349             QDECREF(options);
1350             goto free_exit;
1351         }
1352     }
1353
1354     if (!bs->drv || !bs->drv->supports_backing) {
1355         ret = -EINVAL;
1356         error_setg(errp, "Driver doesn't support backing files");
1357         QDECREF(options);
1358         goto free_exit;
1359     }
1360
1361     if (bs->backing_format[0] != '\0' && !qdict_haskey(options, "driver")) {
1362         qdict_put(options, "driver", qstring_from_str(bs->backing_format));
1363     }
1364
1365     backing_hd = bdrv_open_inherit(*backing_filename ? backing_filename : NULL,
1366                                    reference, options, 0, bs, &child_backing,
1367                                    errp);
1368     if (!backing_hd) {
1369         bs->open_flags |= BDRV_O_NO_BACKING;
1370         error_prepend(errp, "Could not open backing file: ");
1371         ret = -EINVAL;
1372         goto free_exit;
1373     }
1374
1375     /* Hook up the backing file link; drop our reference, bs owns the
1376      * backing_hd reference now */
1377     bdrv_set_backing_hd(bs, backing_hd);
1378     bdrv_unref(backing_hd);
1379
1380     qdict_del(parent_options, bdref_key);
1381
1382 free_exit:
1383     g_free(backing_filename);
1384     QDECREF(tmp_parent_options);
1385     return ret;
1386 }
1387
1388 /*
1389  * Opens a disk image whose options are given as BlockdevRef in another block
1390  * device's options.
1391  *
1392  * If allow_none is true, no image will be opened if filename is false and no
1393  * BlockdevRef is given. NULL will be returned, but errp remains unset.
1394  *
1395  * bdrev_key specifies the key for the image's BlockdevRef in the options QDict.
1396  * That QDict has to be flattened; therefore, if the BlockdevRef is a QDict
1397  * itself, all options starting with "${bdref_key}." are considered part of the
1398  * BlockdevRef.
1399  *
1400  * The BlockdevRef will be removed from the options QDict.
1401  */
1402 BdrvChild *bdrv_open_child(const char *filename,
1403                            QDict *options, const char *bdref_key,
1404                            BlockDriverState* parent,
1405                            const BdrvChildRole *child_role,
1406                            bool allow_none, Error **errp)
1407 {
1408     BdrvChild *c = NULL;
1409     BlockDriverState *bs;
1410     QDict *image_options;
1411     char *bdref_key_dot;
1412     const char *reference;
1413
1414     assert(child_role != NULL);
1415
1416     bdref_key_dot = g_strdup_printf("%s.", bdref_key);
1417     qdict_extract_subqdict(options, &image_options, bdref_key_dot);
1418     g_free(bdref_key_dot);
1419
1420     reference = qdict_get_try_str(options, bdref_key);
1421     if (!filename && !reference && !qdict_size(image_options)) {
1422         if (!allow_none) {
1423             error_setg(errp, "A block device must be specified for \"%s\"",
1424                        bdref_key);
1425         }
1426         QDECREF(image_options);
1427         goto done;
1428     }
1429
1430     bs = bdrv_open_inherit(filename, reference, image_options, 0,
1431                            parent, child_role, errp);
1432     if (!bs) {
1433         goto done;
1434     }
1435
1436     c = bdrv_attach_child(parent, bs, bdref_key, child_role);
1437
1438 done:
1439     qdict_del(options, bdref_key);
1440     return c;
1441 }
1442
1443 static BlockDriverState *bdrv_append_temp_snapshot(BlockDriverState *bs,
1444                                                    int flags,
1445                                                    QDict *snapshot_options,
1446                                                    Error **errp)
1447 {
1448     /* TODO: extra byte is a hack to ensure MAX_PATH space on Windows. */
1449     char *tmp_filename = g_malloc0(PATH_MAX + 1);
1450     int64_t total_size;
1451     QemuOpts *opts = NULL;
1452     BlockDriverState *bs_snapshot;
1453     int ret;
1454
1455     /* if snapshot, we create a temporary backing file and open it
1456        instead of opening 'filename' directly */
1457
1458     /* Get the required size from the image */
1459     total_size = bdrv_getlength(bs);
1460     if (total_size < 0) {
1461         error_setg_errno(errp, -total_size, "Could not get image size");
1462         goto out;
1463     }
1464
1465     /* Create the temporary image */
1466     ret = get_tmp_filename(tmp_filename, PATH_MAX + 1);
1467     if (ret < 0) {
1468         error_setg_errno(errp, -ret, "Could not get temporary filename");
1469         goto out;
1470     }
1471
1472     opts = qemu_opts_create(bdrv_qcow2.create_opts, NULL, 0,
1473                             &error_abort);
1474     qemu_opt_set_number(opts, BLOCK_OPT_SIZE, total_size, &error_abort);
1475     ret = bdrv_create(&bdrv_qcow2, tmp_filename, opts, errp);
1476     qemu_opts_del(opts);
1477     if (ret < 0) {
1478         error_prepend(errp, "Could not create temporary overlay '%s': ",
1479                       tmp_filename);
1480         goto out;
1481     }
1482
1483     /* Prepare options QDict for the temporary file */
1484     qdict_put(snapshot_options, "file.driver",
1485               qstring_from_str("file"));
1486     qdict_put(snapshot_options, "file.filename",
1487               qstring_from_str(tmp_filename));
1488     qdict_put(snapshot_options, "driver",
1489               qstring_from_str("qcow2"));
1490
1491     bs_snapshot = bdrv_open(NULL, NULL, snapshot_options, flags, errp);
1492     snapshot_options = NULL;
1493     if (!bs_snapshot) {
1494         ret = -EINVAL;
1495         goto out;
1496     }
1497
1498     /* bdrv_append() consumes a strong reference to bs_snapshot (i.e. it will
1499      * call bdrv_unref() on it), so in order to be able to return one, we have
1500      * to increase bs_snapshot's refcount here */
1501     bdrv_ref(bs_snapshot);
1502     bdrv_append(bs_snapshot, bs);
1503
1504     g_free(tmp_filename);
1505     return bs_snapshot;
1506
1507 out:
1508     QDECREF(snapshot_options);
1509     g_free(tmp_filename);
1510     return NULL;
1511 }
1512
1513 /*
1514  * Opens a disk image (raw, qcow2, vmdk, ...)
1515  *
1516  * options is a QDict of options to pass to the block drivers, or NULL for an
1517  * empty set of options. The reference to the QDict belongs to the block layer
1518  * after the call (even on failure), so if the caller intends to reuse the
1519  * dictionary, it needs to use QINCREF() before calling bdrv_open.
1520  *
1521  * If *pbs is NULL, a new BDS will be created with a pointer to it stored there.
1522  * If it is not NULL, the referenced BDS will be reused.
1523  *
1524  * The reference parameter may be used to specify an existing block device which
1525  * should be opened. If specified, neither options nor a filename may be given,
1526  * nor can an existing BDS be reused (that is, *pbs has to be NULL).
1527  */
1528 static BlockDriverState *bdrv_open_inherit(const char *filename,
1529                                            const char *reference,
1530                                            QDict *options, int flags,
1531                                            BlockDriverState *parent,
1532                                            const BdrvChildRole *child_role,
1533                                            Error **errp)
1534 {
1535     int ret;
1536     BdrvChild *file = NULL;
1537     BlockDriverState *bs;
1538     BlockDriver *drv = NULL;
1539     const char *drvname;
1540     const char *backing;
1541     Error *local_err = NULL;
1542     QDict *snapshot_options = NULL;
1543     int snapshot_flags = 0;
1544
1545     assert(!child_role || !flags);
1546     assert(!child_role == !parent);
1547
1548     if (reference) {
1549         bool options_non_empty = options ? qdict_size(options) : false;
1550         QDECREF(options);
1551
1552         if (filename || options_non_empty) {
1553             error_setg(errp, "Cannot reference an existing block device with "
1554                        "additional options or a new filename");
1555             return NULL;
1556         }
1557
1558         bs = bdrv_lookup_bs(reference, reference, errp);
1559         if (!bs) {
1560             return NULL;
1561         }
1562
1563         bdrv_ref(bs);
1564         return bs;
1565     }
1566
1567     bs = bdrv_new();
1568
1569     /* NULL means an empty set of options */
1570     if (options == NULL) {
1571         options = qdict_new();
1572     }
1573
1574     /* json: syntax counts as explicit options, as if in the QDict */
1575     parse_json_protocol(options, &filename, &local_err);
1576     if (local_err) {
1577         goto fail;
1578     }
1579
1580     bs->explicit_options = qdict_clone_shallow(options);
1581
1582     if (child_role) {
1583         bs->inherits_from = parent;
1584         child_role->inherit_options(&flags, options,
1585                                     parent->open_flags, parent->options);
1586     }
1587
1588     ret = bdrv_fill_options(&options, filename, &flags, &local_err);
1589     if (local_err) {
1590         goto fail;
1591     }
1592
1593     bs->open_flags = flags;
1594     bs->options = options;
1595     options = qdict_clone_shallow(options);
1596
1597     /* Find the right image format driver */
1598     drvname = qdict_get_try_str(options, "driver");
1599     if (drvname) {
1600         drv = bdrv_find_format(drvname);
1601         if (!drv) {
1602             error_setg(errp, "Unknown driver: '%s'", drvname);
1603             goto fail;
1604         }
1605     }
1606
1607     assert(drvname || !(flags & BDRV_O_PROTOCOL));
1608
1609     backing = qdict_get_try_str(options, "backing");
1610     if (backing && *backing == '\0') {
1611         flags |= BDRV_O_NO_BACKING;
1612         qdict_del(options, "backing");
1613     }
1614
1615     /* Open image file without format layer */
1616     if ((flags & BDRV_O_PROTOCOL) == 0) {
1617         if (flags & BDRV_O_RDWR) {
1618             flags |= BDRV_O_ALLOW_RDWR;
1619         }
1620         if (flags & BDRV_O_SNAPSHOT) {
1621             snapshot_options = qdict_new();
1622             bdrv_temp_snapshot_options(&snapshot_flags, snapshot_options,
1623                                        flags, options);
1624             bdrv_backing_options(&flags, options, flags, options);
1625         }
1626
1627         bs->open_flags = flags;
1628
1629         file = bdrv_open_child(filename, options, "file", bs,
1630                                &child_file, true, &local_err);
1631         if (local_err) {
1632             goto fail;
1633         }
1634     }
1635
1636     /* Image format probing */
1637     bs->probed = !drv;
1638     if (!drv && file) {
1639         ret = find_image_format(file->bs, filename, &drv, &local_err);
1640         if (ret < 0) {
1641             goto fail;
1642         }
1643         /*
1644          * This option update would logically belong in bdrv_fill_options(),
1645          * but we first need to open bs->file for the probing to work, while
1646          * opening bs->file already requires the (mostly) final set of options
1647          * so that cache mode etc. can be inherited.
1648          *
1649          * Adding the driver later is somewhat ugly, but it's not an option
1650          * that would ever be inherited, so it's correct. We just need to make
1651          * sure to update both bs->options (which has the full effective
1652          * options for bs) and options (which has file.* already removed).
1653          */
1654         qdict_put(bs->options, "driver", qstring_from_str(drv->format_name));
1655         qdict_put(options, "driver", qstring_from_str(drv->format_name));
1656     } else if (!drv) {
1657         error_setg(errp, "Must specify either driver or file");
1658         goto fail;
1659     }
1660
1661     /* BDRV_O_PROTOCOL must be set iff a protocol BDS is about to be created */
1662     assert(!!(flags & BDRV_O_PROTOCOL) == !!drv->bdrv_file_open);
1663     /* file must be NULL if a protocol BDS is about to be created
1664      * (the inverse results in an error message from bdrv_open_common()) */
1665     assert(!(flags & BDRV_O_PROTOCOL) || !file);
1666
1667     /* Open the image */
1668     ret = bdrv_open_common(bs, file, options, &local_err);
1669     if (ret < 0) {
1670         goto fail;
1671     }
1672
1673     if (file && (bs->file != file)) {
1674         bdrv_unref_child(bs, file);
1675         file = NULL;
1676     }
1677
1678     /* If there is a backing file, use it */
1679     if ((flags & BDRV_O_NO_BACKING) == 0) {
1680         ret = bdrv_open_backing_file(bs, options, "backing", &local_err);
1681         if (ret < 0) {
1682             goto close_and_fail;
1683         }
1684     }
1685
1686     bdrv_refresh_filename(bs);
1687
1688     /* Check if any unknown options were used */
1689     if (options && (qdict_size(options) != 0)) {
1690         const QDictEntry *entry = qdict_first(options);
1691         if (flags & BDRV_O_PROTOCOL) {
1692             error_setg(errp, "Block protocol '%s' doesn't support the option "
1693                        "'%s'", drv->format_name, entry->key);
1694         } else {
1695             error_setg(errp,
1696                        "Block format '%s' does not support the option '%s'",
1697                        drv->format_name, entry->key);
1698         }
1699
1700         goto close_and_fail;
1701     }
1702
1703     if (!bdrv_key_required(bs)) {
1704         bdrv_parent_cb_change_media(bs, true);
1705     } else if (!runstate_check(RUN_STATE_PRELAUNCH)
1706                && !runstate_check(RUN_STATE_INMIGRATE)
1707                && !runstate_check(RUN_STATE_PAUSED)) { /* HACK */
1708         error_setg(errp,
1709                    "Guest must be stopped for opening of encrypted image");
1710         goto close_and_fail;
1711     }
1712
1713     QDECREF(options);
1714
1715     /* For snapshot=on, create a temporary qcow2 overlay. bs points to the
1716      * temporary snapshot afterwards. */
1717     if (snapshot_flags) {
1718         BlockDriverState *snapshot_bs;
1719         snapshot_bs = bdrv_append_temp_snapshot(bs, snapshot_flags,
1720                                                 snapshot_options, &local_err);
1721         snapshot_options = NULL;
1722         if (local_err) {
1723             goto close_and_fail;
1724         }
1725         /* We are not going to return bs but the overlay on top of it
1726          * (snapshot_bs); thus, we have to drop the strong reference to bs
1727          * (which we obtained by calling bdrv_new()). bs will not be deleted,
1728          * though, because the overlay still has a reference to it. */
1729         bdrv_unref(bs);
1730         bs = snapshot_bs;
1731     }
1732
1733     return bs;
1734
1735 fail:
1736     if (file != NULL) {
1737         bdrv_unref_child(bs, file);
1738     }
1739     QDECREF(snapshot_options);
1740     QDECREF(bs->explicit_options);
1741     QDECREF(bs->options);
1742     QDECREF(options);
1743     bs->options = NULL;
1744     bdrv_unref(bs);
1745     if (local_err) {
1746         error_propagate(errp, local_err);
1747     }
1748     return NULL;
1749
1750 close_and_fail:
1751     bdrv_unref(bs);
1752     QDECREF(snapshot_options);
1753     QDECREF(options);
1754     if (local_err) {
1755         error_propagate(errp, local_err);
1756     }
1757     return NULL;
1758 }
1759
1760 BlockDriverState *bdrv_open(const char *filename, const char *reference,
1761                             QDict *options, int flags, Error **errp)
1762 {
1763     return bdrv_open_inherit(filename, reference, options, flags, NULL,
1764                              NULL, errp);
1765 }
1766
1767 typedef struct BlockReopenQueueEntry {
1768      bool prepared;
1769      BDRVReopenState state;
1770      QSIMPLEQ_ENTRY(BlockReopenQueueEntry) entry;
1771 } BlockReopenQueueEntry;
1772
1773 /*
1774  * Adds a BlockDriverState to a simple queue for an atomic, transactional
1775  * reopen of multiple devices.
1776  *
1777  * bs_queue can either be an existing BlockReopenQueue that has had QSIMPLE_INIT
1778  * already performed, or alternatively may be NULL a new BlockReopenQueue will
1779  * be created and initialized. This newly created BlockReopenQueue should be
1780  * passed back in for subsequent calls that are intended to be of the same
1781  * atomic 'set'.
1782  *
1783  * bs is the BlockDriverState to add to the reopen queue.
1784  *
1785  * options contains the changed options for the associated bs
1786  * (the BlockReopenQueue takes ownership)
1787  *
1788  * flags contains the open flags for the associated bs
1789  *
1790  * returns a pointer to bs_queue, which is either the newly allocated
1791  * bs_queue, or the existing bs_queue being used.
1792  *
1793  */
1794 static BlockReopenQueue *bdrv_reopen_queue_child(BlockReopenQueue *bs_queue,
1795                                                  BlockDriverState *bs,
1796                                                  QDict *options,
1797                                                  int flags,
1798                                                  const BdrvChildRole *role,
1799                                                  QDict *parent_options,
1800                                                  int parent_flags)
1801 {
1802     assert(bs != NULL);
1803
1804     BlockReopenQueueEntry *bs_entry;
1805     BdrvChild *child;
1806     QDict *old_options, *explicit_options;
1807
1808     if (bs_queue == NULL) {
1809         bs_queue = g_new0(BlockReopenQueue, 1);
1810         QSIMPLEQ_INIT(bs_queue);
1811     }
1812
1813     if (!options) {
1814         options = qdict_new();
1815     }
1816
1817     /*
1818      * Precedence of options:
1819      * 1. Explicitly passed in options (highest)
1820      * 2. Set in flags (only for top level)
1821      * 3. Retained from explicitly set options of bs
1822      * 4. Inherited from parent node
1823      * 5. Retained from effective options of bs
1824      */
1825
1826     if (!parent_options) {
1827         /*
1828          * Any setting represented by flags is always updated. If the
1829          * corresponding QDict option is set, it takes precedence. Otherwise
1830          * the flag is translated into a QDict option. The old setting of bs is
1831          * not considered.
1832          */
1833         update_options_from_flags(options, flags);
1834     }
1835
1836     /* Old explicitly set values (don't overwrite by inherited value) */
1837     old_options = qdict_clone_shallow(bs->explicit_options);
1838     bdrv_join_options(bs, options, old_options);
1839     QDECREF(old_options);
1840
1841     explicit_options = qdict_clone_shallow(options);
1842
1843     /* Inherit from parent node */
1844     if (parent_options) {
1845         assert(!flags);
1846         role->inherit_options(&flags, options, parent_flags, parent_options);
1847     }
1848
1849     /* Old values are used for options that aren't set yet */
1850     old_options = qdict_clone_shallow(bs->options);
1851     bdrv_join_options(bs, options, old_options);
1852     QDECREF(old_options);
1853
1854     /* bdrv_open() masks this flag out */
1855     flags &= ~BDRV_O_PROTOCOL;
1856
1857     QLIST_FOREACH(child, &bs->children, next) {
1858         QDict *new_child_options;
1859         char *child_key_dot;
1860
1861         /* reopen can only change the options of block devices that were
1862          * implicitly created and inherited options. For other (referenced)
1863          * block devices, a syntax like "backing.foo" results in an error. */
1864         if (child->bs->inherits_from != bs) {
1865             continue;
1866         }
1867
1868         child_key_dot = g_strdup_printf("%s.", child->name);
1869         qdict_extract_subqdict(options, &new_child_options, child_key_dot);
1870         g_free(child_key_dot);
1871
1872         bdrv_reopen_queue_child(bs_queue, child->bs, new_child_options, 0,
1873                                 child->role, options, flags);
1874     }
1875
1876     bs_entry = g_new0(BlockReopenQueueEntry, 1);
1877     QSIMPLEQ_INSERT_TAIL(bs_queue, bs_entry, entry);
1878
1879     bs_entry->state.bs = bs;
1880     bs_entry->state.options = options;
1881     bs_entry->state.explicit_options = explicit_options;
1882     bs_entry->state.flags = flags;
1883
1884     return bs_queue;
1885 }
1886
1887 BlockReopenQueue *bdrv_reopen_queue(BlockReopenQueue *bs_queue,
1888                                     BlockDriverState *bs,
1889                                     QDict *options, int flags)
1890 {
1891     return bdrv_reopen_queue_child(bs_queue, bs, options, flags,
1892                                    NULL, NULL, 0);
1893 }
1894
1895 /*
1896  * Reopen multiple BlockDriverStates atomically & transactionally.
1897  *
1898  * The queue passed in (bs_queue) must have been built up previous
1899  * via bdrv_reopen_queue().
1900  *
1901  * Reopens all BDS specified in the queue, with the appropriate
1902  * flags.  All devices are prepared for reopen, and failure of any
1903  * device will cause all device changes to be abandonded, and intermediate
1904  * data cleaned up.
1905  *
1906  * If all devices prepare successfully, then the changes are committed
1907  * to all devices.
1908  *
1909  */
1910 int bdrv_reopen_multiple(BlockReopenQueue *bs_queue, Error **errp)
1911 {
1912     int ret = -1;
1913     BlockReopenQueueEntry *bs_entry, *next;
1914     Error *local_err = NULL;
1915
1916     assert(bs_queue != NULL);
1917
1918     bdrv_drain_all();
1919
1920     QSIMPLEQ_FOREACH(bs_entry, bs_queue, entry) {
1921         if (bdrv_reopen_prepare(&bs_entry->state, bs_queue, &local_err)) {
1922             error_propagate(errp, local_err);
1923             goto cleanup;
1924         }
1925         bs_entry->prepared = true;
1926     }
1927
1928     /* If we reach this point, we have success and just need to apply the
1929      * changes
1930      */
1931     QSIMPLEQ_FOREACH(bs_entry, bs_queue, entry) {
1932         bdrv_reopen_commit(&bs_entry->state);
1933     }
1934
1935     ret = 0;
1936
1937 cleanup:
1938     QSIMPLEQ_FOREACH_SAFE(bs_entry, bs_queue, entry, next) {
1939         if (ret && bs_entry->prepared) {
1940             bdrv_reopen_abort(&bs_entry->state);
1941         } else if (ret) {
1942             QDECREF(bs_entry->state.explicit_options);
1943         }
1944         QDECREF(bs_entry->state.options);
1945         g_free(bs_entry);
1946     }
1947     g_free(bs_queue);
1948     return ret;
1949 }
1950
1951
1952 /* Reopen a single BlockDriverState with the specified flags. */
1953 int bdrv_reopen(BlockDriverState *bs, int bdrv_flags, Error **errp)
1954 {
1955     int ret = -1;
1956     Error *local_err = NULL;
1957     BlockReopenQueue *queue = bdrv_reopen_queue(NULL, bs, NULL, bdrv_flags);
1958
1959     ret = bdrv_reopen_multiple(queue, &local_err);
1960     if (local_err != NULL) {
1961         error_propagate(errp, local_err);
1962     }
1963     return ret;
1964 }
1965
1966
1967 /*
1968  * Prepares a BlockDriverState for reopen. All changes are staged in the
1969  * 'opaque' field of the BDRVReopenState, which is used and allocated by
1970  * the block driver layer .bdrv_reopen_prepare()
1971  *
1972  * bs is the BlockDriverState to reopen
1973  * flags are the new open flags
1974  * queue is the reopen queue
1975  *
1976  * Returns 0 on success, non-zero on error.  On error errp will be set
1977  * as well.
1978  *
1979  * On failure, bdrv_reopen_abort() will be called to clean up any data.
1980  * It is the responsibility of the caller to then call the abort() or
1981  * commit() for any other BDS that have been left in a prepare() state
1982  *
1983  */
1984 int bdrv_reopen_prepare(BDRVReopenState *reopen_state, BlockReopenQueue *queue,
1985                         Error **errp)
1986 {
1987     int ret = -1;
1988     Error *local_err = NULL;
1989     BlockDriver *drv;
1990     QemuOpts *opts;
1991     const char *value;
1992
1993     assert(reopen_state != NULL);
1994     assert(reopen_state->bs->drv != NULL);
1995     drv = reopen_state->bs->drv;
1996
1997     /* Process generic block layer options */
1998     opts = qemu_opts_create(&bdrv_runtime_opts, NULL, 0, &error_abort);
1999     qemu_opts_absorb_qdict(opts, reopen_state->options, &local_err);
2000     if (local_err) {
2001         error_propagate(errp, local_err);
2002         ret = -EINVAL;
2003         goto error;
2004     }
2005
2006     update_flags_from_options(&reopen_state->flags, opts);
2007
2008     /* node-name and driver must be unchanged. Put them back into the QDict, so
2009      * that they are checked at the end of this function. */
2010     value = qemu_opt_get(opts, "node-name");
2011     if (value) {
2012         qdict_put(reopen_state->options, "node-name", qstring_from_str(value));
2013     }
2014
2015     value = qemu_opt_get(opts, "driver");
2016     if (value) {
2017         qdict_put(reopen_state->options, "driver", qstring_from_str(value));
2018     }
2019
2020     /* if we are to stay read-only, do not allow permission change
2021      * to r/w */
2022     if (!(reopen_state->bs->open_flags & BDRV_O_ALLOW_RDWR) &&
2023         reopen_state->flags & BDRV_O_RDWR) {
2024         error_setg(errp, "Node '%s' is read only",
2025                    bdrv_get_device_or_node_name(reopen_state->bs));
2026         goto error;
2027     }
2028
2029
2030     ret = bdrv_flush(reopen_state->bs);
2031     if (ret) {
2032         error_setg_errno(errp, -ret, "Error flushing drive");
2033         goto error;
2034     }
2035
2036     if (drv->bdrv_reopen_prepare) {
2037         ret = drv->bdrv_reopen_prepare(reopen_state, queue, &local_err);
2038         if (ret) {
2039             if (local_err != NULL) {
2040                 error_propagate(errp, local_err);
2041             } else {
2042                 error_setg(errp, "failed while preparing to reopen image '%s'",
2043                            reopen_state->bs->filename);
2044             }
2045             goto error;
2046         }
2047     } else {
2048         /* It is currently mandatory to have a bdrv_reopen_prepare()
2049          * handler for each supported drv. */
2050         error_setg(errp, "Block format '%s' used by node '%s' "
2051                    "does not support reopening files", drv->format_name,
2052                    bdrv_get_device_or_node_name(reopen_state->bs));
2053         ret = -1;
2054         goto error;
2055     }
2056
2057     /* Options that are not handled are only okay if they are unchanged
2058      * compared to the old state. It is expected that some options are only
2059      * used for the initial open, but not reopen (e.g. filename) */
2060     if (qdict_size(reopen_state->options)) {
2061         const QDictEntry *entry = qdict_first(reopen_state->options);
2062
2063         do {
2064             QString *new_obj = qobject_to_qstring(entry->value);
2065             const char *new = qstring_get_str(new_obj);
2066             const char *old = qdict_get_try_str(reopen_state->bs->options,
2067                                                 entry->key);
2068
2069             if (!old || strcmp(new, old)) {
2070                 error_setg(errp, "Cannot change the option '%s'", entry->key);
2071                 ret = -EINVAL;
2072                 goto error;
2073             }
2074         } while ((entry = qdict_next(reopen_state->options, entry)));
2075     }
2076
2077     ret = 0;
2078
2079 error:
2080     qemu_opts_del(opts);
2081     return ret;
2082 }
2083
2084 /*
2085  * Takes the staged changes for the reopen from bdrv_reopen_prepare(), and
2086  * makes them final by swapping the staging BlockDriverState contents into
2087  * the active BlockDriverState contents.
2088  */
2089 void bdrv_reopen_commit(BDRVReopenState *reopen_state)
2090 {
2091     BlockDriver *drv;
2092
2093     assert(reopen_state != NULL);
2094     drv = reopen_state->bs->drv;
2095     assert(drv != NULL);
2096
2097     /* If there are any driver level actions to take */
2098     if (drv->bdrv_reopen_commit) {
2099         drv->bdrv_reopen_commit(reopen_state);
2100     }
2101
2102     /* set BDS specific flags now */
2103     QDECREF(reopen_state->bs->explicit_options);
2104
2105     reopen_state->bs->explicit_options   = reopen_state->explicit_options;
2106     reopen_state->bs->open_flags         = reopen_state->flags;
2107     reopen_state->bs->read_only = !(reopen_state->flags & BDRV_O_RDWR);
2108
2109     bdrv_refresh_limits(reopen_state->bs, NULL);
2110 }
2111
2112 /*
2113  * Abort the reopen, and delete and free the staged changes in
2114  * reopen_state
2115  */
2116 void bdrv_reopen_abort(BDRVReopenState *reopen_state)
2117 {
2118     BlockDriver *drv;
2119
2120     assert(reopen_state != NULL);
2121     drv = reopen_state->bs->drv;
2122     assert(drv != NULL);
2123
2124     if (drv->bdrv_reopen_abort) {
2125         drv->bdrv_reopen_abort(reopen_state);
2126     }
2127
2128     QDECREF(reopen_state->explicit_options);
2129 }
2130
2131
2132 static void bdrv_close(BlockDriverState *bs)
2133 {
2134     BdrvAioNotifier *ban, *ban_next;
2135
2136     assert(!bs->job);
2137     assert(!bs->refcnt);
2138
2139     bdrv_drained_begin(bs); /* complete I/O */
2140     bdrv_flush(bs);
2141     bdrv_drain(bs); /* in case flush left pending I/O */
2142
2143     bdrv_release_named_dirty_bitmaps(bs);
2144     assert(QLIST_EMPTY(&bs->dirty_bitmaps));
2145
2146     if (bs->drv) {
2147         BdrvChild *child, *next;
2148
2149         bs->drv->bdrv_close(bs);
2150         bs->drv = NULL;
2151
2152         bdrv_set_backing_hd(bs, NULL);
2153
2154         if (bs->file != NULL) {
2155             bdrv_unref_child(bs, bs->file);
2156             bs->file = NULL;
2157         }
2158
2159         QLIST_FOREACH_SAFE(child, &bs->children, next, next) {
2160             /* TODO Remove bdrv_unref() from drivers' close function and use
2161              * bdrv_unref_child() here */
2162             if (child->bs->inherits_from == bs) {
2163                 child->bs->inherits_from = NULL;
2164             }
2165             bdrv_detach_child(child);
2166         }
2167
2168         g_free(bs->opaque);
2169         bs->opaque = NULL;
2170         bs->copy_on_read = 0;
2171         bs->backing_file[0] = '\0';
2172         bs->backing_format[0] = '\0';
2173         bs->total_sectors = 0;
2174         bs->encrypted = 0;
2175         bs->valid_key = 0;
2176         bs->sg = 0;
2177         bs->zero_beyond_eof = false;
2178         QDECREF(bs->options);
2179         QDECREF(bs->explicit_options);
2180         bs->options = NULL;
2181         QDECREF(bs->full_open_options);
2182         bs->full_open_options = NULL;
2183     }
2184
2185     QLIST_FOREACH_SAFE(ban, &bs->aio_notifiers, list, ban_next) {
2186         g_free(ban);
2187     }
2188     QLIST_INIT(&bs->aio_notifiers);
2189     bdrv_drained_end(bs);
2190 }
2191
2192 void bdrv_close_all(void)
2193 {
2194     BlockDriverState *bs;
2195     AioContext *aio_context;
2196
2197     /* Drop references from requests still in flight, such as canceled block
2198      * jobs whose AIO context has not been polled yet */
2199     bdrv_drain_all();
2200
2201     blk_remove_all_bs();
2202     blockdev_close_all_bdrv_states();
2203
2204     /* Cancel all block jobs */
2205     while (!QTAILQ_EMPTY(&all_bdrv_states)) {
2206         QTAILQ_FOREACH(bs, &all_bdrv_states, bs_list) {
2207             aio_context = bdrv_get_aio_context(bs);
2208
2209             aio_context_acquire(aio_context);
2210             if (bs->job) {
2211                 block_job_cancel_sync(bs->job);
2212                 aio_context_release(aio_context);
2213                 break;
2214             }
2215             aio_context_release(aio_context);
2216         }
2217
2218         /* All the remaining BlockDriverStates are referenced directly or
2219          * indirectly from block jobs, so there needs to be at least one BDS
2220          * directly used by a block job */
2221         assert(bs);
2222     }
2223 }
2224
2225 static void change_parent_backing_link(BlockDriverState *from,
2226                                        BlockDriverState *to)
2227 {
2228     BdrvChild *c, *next;
2229
2230     QLIST_FOREACH_SAFE(c, &from->parents, next_parent, next) {
2231         assert(c->role != &child_backing);
2232         bdrv_ref(to);
2233         bdrv_replace_child(c, to);
2234         bdrv_unref(from);
2235     }
2236 }
2237
2238 /*
2239  * Add new bs contents at the top of an image chain while the chain is
2240  * live, while keeping required fields on the top layer.
2241  *
2242  * This will modify the BlockDriverState fields, and swap contents
2243  * between bs_new and bs_top. Both bs_new and bs_top are modified.
2244  *
2245  * bs_new must not be attached to a BlockBackend.
2246  *
2247  * This function does not create any image files.
2248  *
2249  * bdrv_append() takes ownership of a bs_new reference and unrefs it because
2250  * that's what the callers commonly need. bs_new will be referenced by the old
2251  * parents of bs_top after bdrv_append() returns. If the caller needs to keep a
2252  * reference of its own, it must call bdrv_ref().
2253  */
2254 void bdrv_append(BlockDriverState *bs_new, BlockDriverState *bs_top)
2255 {
2256     assert(!bdrv_requests_pending(bs_top));
2257     assert(!bdrv_requests_pending(bs_new));
2258
2259     bdrv_ref(bs_top);
2260
2261     change_parent_backing_link(bs_top, bs_new);
2262     bdrv_set_backing_hd(bs_new, bs_top);
2263     bdrv_unref(bs_top);
2264
2265     /* bs_new is now referenced by its new parents, we don't need the
2266      * additional reference any more. */
2267     bdrv_unref(bs_new);
2268 }
2269
2270 void bdrv_replace_in_backing_chain(BlockDriverState *old, BlockDriverState *new)
2271 {
2272     assert(!bdrv_requests_pending(old));
2273     assert(!bdrv_requests_pending(new));
2274
2275     bdrv_ref(old);
2276
2277     change_parent_backing_link(old, new);
2278
2279     /* Change backing files if a previously independent node is added to the
2280      * chain. For active commit, we replace top by its own (indirect) backing
2281      * file and don't do anything here so we don't build a loop. */
2282     if (new->backing == NULL && !bdrv_chain_contains(backing_bs(old), new)) {
2283         bdrv_set_backing_hd(new, backing_bs(old));
2284         bdrv_set_backing_hd(old, NULL);
2285     }
2286
2287     bdrv_unref(old);
2288 }
2289
2290 static void bdrv_delete(BlockDriverState *bs)
2291 {
2292     assert(!bs->job);
2293     assert(bdrv_op_blocker_is_empty(bs));
2294     assert(!bs->refcnt);
2295
2296     bdrv_close(bs);
2297
2298     /* remove from list, if necessary */
2299     if (bs->node_name[0] != '\0') {
2300         QTAILQ_REMOVE(&graph_bdrv_states, bs, node_list);
2301     }
2302     QTAILQ_REMOVE(&all_bdrv_states, bs, bs_list);
2303
2304     g_free(bs);
2305 }
2306
2307 /*
2308  * Run consistency checks on an image
2309  *
2310  * Returns 0 if the check could be completed (it doesn't mean that the image is
2311  * free of errors) or -errno when an internal error occurred. The results of the
2312  * check are stored in res.
2313  */
2314 int bdrv_check(BlockDriverState *bs, BdrvCheckResult *res, BdrvCheckMode fix)
2315 {
2316     if (bs->drv == NULL) {
2317         return -ENOMEDIUM;
2318     }
2319     if (bs->drv->bdrv_check == NULL) {
2320         return -ENOTSUP;
2321     }
2322
2323     memset(res, 0, sizeof(*res));
2324     return bs->drv->bdrv_check(bs, res, fix);
2325 }
2326
2327 #define COMMIT_BUF_SECTORS 2048
2328
2329 /* commit COW file into the raw image */
2330 int bdrv_commit(BlockDriverState *bs)
2331 {
2332     BlockDriver *drv = bs->drv;
2333     int64_t sector, total_sectors, length, backing_length;
2334     int n, ro, open_flags;
2335     int ret = 0;
2336     uint8_t *buf = NULL;
2337
2338     if (!drv)
2339         return -ENOMEDIUM;
2340
2341     if (!bs->backing) {
2342         return -ENOTSUP;
2343     }
2344
2345     if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_COMMIT_SOURCE, NULL) ||
2346         bdrv_op_is_blocked(bs->backing->bs, BLOCK_OP_TYPE_COMMIT_TARGET, NULL)) {
2347         return -EBUSY;
2348     }
2349
2350     ro = bs->backing->bs->read_only;
2351     open_flags =  bs->backing->bs->open_flags;
2352
2353     if (ro) {
2354         if (bdrv_reopen(bs->backing->bs, open_flags | BDRV_O_RDWR, NULL)) {
2355             return -EACCES;
2356         }
2357     }
2358
2359     length = bdrv_getlength(bs);
2360     if (length < 0) {
2361         ret = length;
2362         goto ro_cleanup;
2363     }
2364
2365     backing_length = bdrv_getlength(bs->backing->bs);
2366     if (backing_length < 0) {
2367         ret = backing_length;
2368         goto ro_cleanup;
2369     }
2370
2371     /* If our top snapshot is larger than the backing file image,
2372      * grow the backing file image if possible.  If not possible,
2373      * we must return an error */
2374     if (length > backing_length) {
2375         ret = bdrv_truncate(bs->backing->bs, length);
2376         if (ret < 0) {
2377             goto ro_cleanup;
2378         }
2379     }
2380
2381     total_sectors = length >> BDRV_SECTOR_BITS;
2382
2383     /* qemu_try_blockalign() for bs will choose an alignment that works for
2384      * bs->backing->bs as well, so no need to compare the alignment manually. */
2385     buf = qemu_try_blockalign(bs, COMMIT_BUF_SECTORS * BDRV_SECTOR_SIZE);
2386     if (buf == NULL) {
2387         ret = -ENOMEM;
2388         goto ro_cleanup;
2389     }
2390
2391     for (sector = 0; sector < total_sectors; sector += n) {
2392         ret = bdrv_is_allocated(bs, sector, COMMIT_BUF_SECTORS, &n);
2393         if (ret < 0) {
2394             goto ro_cleanup;
2395         }
2396         if (ret) {
2397             ret = bdrv_read(bs, sector, buf, n);
2398             if (ret < 0) {
2399                 goto ro_cleanup;
2400             }
2401
2402             ret = bdrv_write(bs->backing->bs, sector, buf, n);
2403             if (ret < 0) {
2404                 goto ro_cleanup;
2405             }
2406         }
2407     }
2408
2409     if (drv->bdrv_make_empty) {
2410         ret = drv->bdrv_make_empty(bs);
2411         if (ret < 0) {
2412             goto ro_cleanup;
2413         }
2414         bdrv_flush(bs);
2415     }
2416
2417     /*
2418      * Make sure all data we wrote to the backing device is actually
2419      * stable on disk.
2420      */
2421     if (bs->backing) {
2422         bdrv_flush(bs->backing->bs);
2423     }
2424
2425     ret = 0;
2426 ro_cleanup:
2427     qemu_vfree(buf);
2428
2429     if (ro) {
2430         /* ignoring error return here */
2431         bdrv_reopen(bs->backing->bs, open_flags & ~BDRV_O_RDWR, NULL);
2432     }
2433
2434     return ret;
2435 }
2436
2437 /*
2438  * Return values:
2439  * 0        - success
2440  * -EINVAL  - backing format specified, but no file
2441  * -ENOSPC  - can't update the backing file because no space is left in the
2442  *            image file header
2443  * -ENOTSUP - format driver doesn't support changing the backing file
2444  */
2445 int bdrv_change_backing_file(BlockDriverState *bs,
2446     const char *backing_file, const char *backing_fmt)
2447 {
2448     BlockDriver *drv = bs->drv;
2449     int ret;
2450
2451     /* Backing file format doesn't make sense without a backing file */
2452     if (backing_fmt && !backing_file) {
2453         return -EINVAL;
2454     }
2455
2456     if (drv->bdrv_change_backing_file != NULL) {
2457         ret = drv->bdrv_change_backing_file(bs, backing_file, backing_fmt);
2458     } else {
2459         ret = -ENOTSUP;
2460     }
2461
2462     if (ret == 0) {
2463         pstrcpy(bs->backing_file, sizeof(bs->backing_file), backing_file ?: "");
2464         pstrcpy(bs->backing_format, sizeof(bs->backing_format), backing_fmt ?: "");
2465     }
2466     return ret;
2467 }
2468
2469 /*
2470  * Finds the image layer in the chain that has 'bs' as its backing file.
2471  *
2472  * active is the current topmost image.
2473  *
2474  * Returns NULL if bs is not found in active's image chain,
2475  * or if active == bs.
2476  *
2477  * Returns the bottommost base image if bs == NULL.
2478  */
2479 BlockDriverState *bdrv_find_overlay(BlockDriverState *active,
2480                                     BlockDriverState *bs)
2481 {
2482     while (active && bs != backing_bs(active)) {
2483         active = backing_bs(active);
2484     }
2485
2486     return active;
2487 }
2488
2489 /* Given a BDS, searches for the base layer. */
2490 BlockDriverState *bdrv_find_base(BlockDriverState *bs)
2491 {
2492     return bdrv_find_overlay(bs, NULL);
2493 }
2494
2495 /*
2496  * Drops images above 'base' up to and including 'top', and sets the image
2497  * above 'top' to have base as its backing file.
2498  *
2499  * Requires that the overlay to 'top' is opened r/w, so that the backing file
2500  * information in 'bs' can be properly updated.
2501  *
2502  * E.g., this will convert the following chain:
2503  * bottom <- base <- intermediate <- top <- active
2504  *
2505  * to
2506  *
2507  * bottom <- base <- active
2508  *
2509  * It is allowed for bottom==base, in which case it converts:
2510  *
2511  * base <- intermediate <- top <- active
2512  *
2513  * to
2514  *
2515  * base <- active
2516  *
2517  * If backing_file_str is non-NULL, it will be used when modifying top's
2518  * overlay image metadata.
2519  *
2520  * Error conditions:
2521  *  if active == top, that is considered an error
2522  *
2523  */
2524 int bdrv_drop_intermediate(BlockDriverState *active, BlockDriverState *top,
2525                            BlockDriverState *base, const char *backing_file_str)
2526 {
2527     BlockDriverState *new_top_bs = NULL;
2528     int ret = -EIO;
2529
2530     if (!top->drv || !base->drv) {
2531         goto exit;
2532     }
2533
2534     new_top_bs = bdrv_find_overlay(active, top);
2535
2536     if (new_top_bs == NULL) {
2537         /* we could not find the image above 'top', this is an error */
2538         goto exit;
2539     }
2540
2541     /* special case of new_top_bs->backing->bs already pointing to base - nothing
2542      * to do, no intermediate images */
2543     if (backing_bs(new_top_bs) == base) {
2544         ret = 0;
2545         goto exit;
2546     }
2547
2548     /* Make sure that base is in the backing chain of top */
2549     if (!bdrv_chain_contains(top, base)) {
2550         goto exit;
2551     }
2552
2553     /* success - we can delete the intermediate states, and link top->base */
2554     backing_file_str = backing_file_str ? backing_file_str : base->filename;
2555     ret = bdrv_change_backing_file(new_top_bs, backing_file_str,
2556                                    base->drv ? base->drv->format_name : "");
2557     if (ret) {
2558         goto exit;
2559     }
2560     bdrv_set_backing_hd(new_top_bs, base);
2561
2562     ret = 0;
2563 exit:
2564     return ret;
2565 }
2566
2567 /**
2568  * Truncate file to 'offset' bytes (needed only for file protocols)
2569  */
2570 int bdrv_truncate(BlockDriverState *bs, int64_t offset)
2571 {
2572     BlockDriver *drv = bs->drv;
2573     int ret;
2574     if (!drv)
2575         return -ENOMEDIUM;
2576     if (!drv->bdrv_truncate)
2577         return -ENOTSUP;
2578     if (bs->read_only)
2579         return -EACCES;
2580
2581     ret = drv->bdrv_truncate(bs, offset);
2582     if (ret == 0) {
2583         ret = refresh_total_sectors(bs, offset >> BDRV_SECTOR_BITS);
2584         bdrv_dirty_bitmap_truncate(bs);
2585         bdrv_parent_cb_resize(bs);
2586     }
2587     return ret;
2588 }
2589
2590 /**
2591  * Length of a allocated file in bytes. Sparse files are counted by actual
2592  * allocated space. Return < 0 if error or unknown.
2593  */
2594 int64_t bdrv_get_allocated_file_size(BlockDriverState *bs)
2595 {
2596     BlockDriver *drv = bs->drv;
2597     if (!drv) {
2598         return -ENOMEDIUM;
2599     }
2600     if (drv->bdrv_get_allocated_file_size) {
2601         return drv->bdrv_get_allocated_file_size(bs);
2602     }
2603     if (bs->file) {
2604         return bdrv_get_allocated_file_size(bs->file->bs);
2605     }
2606     return -ENOTSUP;
2607 }
2608
2609 /**
2610  * Return number of sectors on success, -errno on error.
2611  */
2612 int64_t bdrv_nb_sectors(BlockDriverState *bs)
2613 {
2614     BlockDriver *drv = bs->drv;
2615
2616     if (!drv)
2617         return -ENOMEDIUM;
2618
2619     if (drv->has_variable_length) {
2620         int ret = refresh_total_sectors(bs, bs->total_sectors);
2621         if (ret < 0) {
2622             return ret;
2623         }
2624     }
2625     return bs->total_sectors;
2626 }
2627
2628 /**
2629  * Return length in bytes on success, -errno on error.
2630  * The length is always a multiple of BDRV_SECTOR_SIZE.
2631  */
2632 int64_t bdrv_getlength(BlockDriverState *bs)
2633 {
2634     int64_t ret = bdrv_nb_sectors(bs);
2635
2636     ret = ret > INT64_MAX / BDRV_SECTOR_SIZE ? -EFBIG : ret;
2637     return ret < 0 ? ret : ret * BDRV_SECTOR_SIZE;
2638 }
2639
2640 /* return 0 as number of sectors if no device present or error */
2641 void bdrv_get_geometry(BlockDriverState *bs, uint64_t *nb_sectors_ptr)
2642 {
2643     int64_t nb_sectors = bdrv_nb_sectors(bs);
2644
2645     *nb_sectors_ptr = nb_sectors < 0 ? 0 : nb_sectors;
2646 }
2647
2648 int bdrv_is_read_only(BlockDriverState *bs)
2649 {
2650     return bs->read_only;
2651 }
2652
2653 int bdrv_is_sg(BlockDriverState *bs)
2654 {
2655     return bs->sg;
2656 }
2657
2658 int bdrv_is_encrypted(BlockDriverState *bs)
2659 {
2660     if (bs->backing && bs->backing->bs->encrypted) {
2661         return 1;
2662     }
2663     return bs->encrypted;
2664 }
2665
2666 int bdrv_key_required(BlockDriverState *bs)
2667 {
2668     BdrvChild *backing = bs->backing;
2669
2670     if (backing && backing->bs->encrypted && !backing->bs->valid_key) {
2671         return 1;
2672     }
2673     return (bs->encrypted && !bs->valid_key);
2674 }
2675
2676 int bdrv_set_key(BlockDriverState *bs, const char *key)
2677 {
2678     int ret;
2679     if (bs->backing && bs->backing->bs->encrypted) {
2680         ret = bdrv_set_key(bs->backing->bs, key);
2681         if (ret < 0)
2682             return ret;
2683         if (!bs->encrypted)
2684             return 0;
2685     }
2686     if (!bs->encrypted) {
2687         return -EINVAL;
2688     } else if (!bs->drv || !bs->drv->bdrv_set_key) {
2689         return -ENOMEDIUM;
2690     }
2691     ret = bs->drv->bdrv_set_key(bs, key);
2692     if (ret < 0) {
2693         bs->valid_key = 0;
2694     } else if (!bs->valid_key) {
2695         /* call the change callback now, we skipped it on open */
2696         bs->valid_key = 1;
2697         bdrv_parent_cb_change_media(bs, true);
2698     }
2699     return ret;
2700 }
2701
2702 /*
2703  * Provide an encryption key for @bs.
2704  * If @key is non-null:
2705  *     If @bs is not encrypted, fail.
2706  *     Else if the key is invalid, fail.
2707  *     Else set @bs's key to @key, replacing the existing key, if any.
2708  * If @key is null:
2709  *     If @bs is encrypted and still lacks a key, fail.
2710  *     Else do nothing.
2711  * On failure, store an error object through @errp if non-null.
2712  */
2713 void bdrv_add_key(BlockDriverState *bs, const char *key, Error **errp)
2714 {
2715     if (key) {
2716         if (!bdrv_is_encrypted(bs)) {
2717             error_setg(errp, "Node '%s' is not encrypted",
2718                       bdrv_get_device_or_node_name(bs));
2719         } else if (bdrv_set_key(bs, key) < 0) {
2720             error_setg(errp, QERR_INVALID_PASSWORD);
2721         }
2722     } else {
2723         if (bdrv_key_required(bs)) {
2724             error_set(errp, ERROR_CLASS_DEVICE_ENCRYPTED,
2725                       "'%s' (%s) is encrypted",
2726                       bdrv_get_device_or_node_name(bs),
2727                       bdrv_get_encrypted_filename(bs));
2728         }
2729     }
2730 }
2731
2732 const char *bdrv_get_format_name(BlockDriverState *bs)
2733 {
2734     return bs->drv ? bs->drv->format_name : NULL;
2735 }
2736
2737 static int qsort_strcmp(const void *a, const void *b)
2738 {
2739     return strcmp(a, b);
2740 }
2741
2742 void bdrv_iterate_format(void (*it)(void *opaque, const char *name),
2743                          void *opaque)
2744 {
2745     BlockDriver *drv;
2746     int count = 0;
2747     int i;
2748     const char **formats = NULL;
2749
2750     QLIST_FOREACH(drv, &bdrv_drivers, list) {
2751         if (drv->format_name) {
2752             bool found = false;
2753             int i = count;
2754             while (formats && i && !found) {
2755                 found = !strcmp(formats[--i], drv->format_name);
2756             }
2757
2758             if (!found) {
2759                 formats = g_renew(const char *, formats, count + 1);
2760                 formats[count++] = drv->format_name;
2761             }
2762         }
2763     }
2764
2765     qsort(formats, count, sizeof(formats[0]), qsort_strcmp);
2766
2767     for (i = 0; i < count; i++) {
2768         it(opaque, formats[i]);
2769     }
2770
2771     g_free(formats);
2772 }
2773
2774 /* This function is to find a node in the bs graph */
2775 BlockDriverState *bdrv_find_node(const char *node_name)
2776 {
2777     BlockDriverState *bs;
2778
2779     assert(node_name);
2780
2781     QTAILQ_FOREACH(bs, &graph_bdrv_states, node_list) {
2782         if (!strcmp(node_name, bs->node_name)) {
2783             return bs;
2784         }
2785     }
2786     return NULL;
2787 }
2788
2789 /* Put this QMP function here so it can access the static graph_bdrv_states. */
2790 BlockDeviceInfoList *bdrv_named_nodes_list(Error **errp)
2791 {
2792     BlockDeviceInfoList *list, *entry;
2793     BlockDriverState *bs;
2794
2795     list = NULL;
2796     QTAILQ_FOREACH(bs, &graph_bdrv_states, node_list) {
2797         BlockDeviceInfo *info = bdrv_block_device_info(NULL, bs, errp);
2798         if (!info) {
2799             qapi_free_BlockDeviceInfoList(list);
2800             return NULL;
2801         }
2802         entry = g_malloc0(sizeof(*entry));
2803         entry->value = info;
2804         entry->next = list;
2805         list = entry;
2806     }
2807
2808     return list;
2809 }
2810
2811 BlockDriverState *bdrv_lookup_bs(const char *device,
2812                                  const char *node_name,
2813                                  Error **errp)
2814 {
2815     BlockBackend *blk;
2816     BlockDriverState *bs;
2817
2818     if (device) {
2819         blk = blk_by_name(device);
2820
2821         if (blk) {
2822             bs = blk_bs(blk);
2823             if (!bs) {
2824                 error_setg(errp, "Device '%s' has no medium", device);
2825             }
2826
2827             return bs;
2828         }
2829     }
2830
2831     if (node_name) {
2832         bs = bdrv_find_node(node_name);
2833
2834         if (bs) {
2835             return bs;
2836         }
2837     }
2838
2839     error_setg(errp, "Cannot find device=%s nor node_name=%s",
2840                      device ? device : "",
2841                      node_name ? node_name : "");
2842     return NULL;
2843 }
2844
2845 /* If 'base' is in the same chain as 'top', return true. Otherwise,
2846  * return false.  If either argument is NULL, return false. */
2847 bool bdrv_chain_contains(BlockDriverState *top, BlockDriverState *base)
2848 {
2849     while (top && top != base) {
2850         top = backing_bs(top);
2851     }
2852
2853     return top != NULL;
2854 }
2855
2856 BlockDriverState *bdrv_next_node(BlockDriverState *bs)
2857 {
2858     if (!bs) {
2859         return QTAILQ_FIRST(&graph_bdrv_states);
2860     }
2861     return QTAILQ_NEXT(bs, node_list);
2862 }
2863
2864 const char *bdrv_get_node_name(const BlockDriverState *bs)
2865 {
2866     return bs->node_name;
2867 }
2868
2869 const char *bdrv_get_parent_name(const BlockDriverState *bs)
2870 {
2871     BdrvChild *c;
2872     const char *name;
2873
2874     /* If multiple parents have a name, just pick the first one. */
2875     QLIST_FOREACH(c, &bs->parents, next_parent) {
2876         if (c->role->get_name) {
2877             name = c->role->get_name(c);
2878             if (name && *name) {
2879                 return name;
2880             }
2881         }
2882     }
2883
2884     return NULL;
2885 }
2886
2887 /* TODO check what callers really want: bs->node_name or blk_name() */
2888 const char *bdrv_get_device_name(const BlockDriverState *bs)
2889 {
2890     return bdrv_get_parent_name(bs) ?: "";
2891 }
2892
2893 /* This can be used to identify nodes that might not have a device
2894  * name associated. Since node and device names live in the same
2895  * namespace, the result is unambiguous. The exception is if both are
2896  * absent, then this returns an empty (non-null) string. */
2897 const char *bdrv_get_device_or_node_name(const BlockDriverState *bs)
2898 {
2899     return bdrv_get_parent_name(bs) ?: bs->node_name;
2900 }
2901
2902 int bdrv_get_flags(BlockDriverState *bs)
2903 {
2904     return bs->open_flags;
2905 }
2906
2907 int bdrv_has_zero_init_1(BlockDriverState *bs)
2908 {
2909     return 1;
2910 }
2911
2912 int bdrv_has_zero_init(BlockDriverState *bs)
2913 {
2914     assert(bs->drv);
2915
2916     /* If BS is a copy on write image, it is initialized to
2917        the contents of the base image, which may not be zeroes.  */
2918     if (bs->backing) {
2919         return 0;
2920     }
2921     if (bs->drv->bdrv_has_zero_init) {
2922         return bs->drv->bdrv_has_zero_init(bs);
2923     }
2924
2925     /* safe default */
2926     return 0;
2927 }
2928
2929 bool bdrv_unallocated_blocks_are_zero(BlockDriverState *bs)
2930 {
2931     BlockDriverInfo bdi;
2932
2933     if (bs->backing) {
2934         return false;
2935     }
2936
2937     if (bdrv_get_info(bs, &bdi) == 0) {
2938         return bdi.unallocated_blocks_are_zero;
2939     }
2940
2941     return false;
2942 }
2943
2944 bool bdrv_can_write_zeroes_with_unmap(BlockDriverState *bs)
2945 {
2946     BlockDriverInfo bdi;
2947
2948     if (bs->backing || !(bs->open_flags & BDRV_O_UNMAP)) {
2949         return false;
2950     }
2951
2952     if (bdrv_get_info(bs, &bdi) == 0) {
2953         return bdi.can_write_zeroes_with_unmap;
2954     }
2955
2956     return false;
2957 }
2958
2959 const char *bdrv_get_encrypted_filename(BlockDriverState *bs)
2960 {
2961     if (bs->backing && bs->backing->bs->encrypted)
2962         return bs->backing_file;
2963     else if (bs->encrypted)
2964         return bs->filename;
2965     else
2966         return NULL;
2967 }
2968
2969 void bdrv_get_backing_filename(BlockDriverState *bs,
2970                                char *filename, int filename_size)
2971 {
2972     pstrcpy(filename, filename_size, bs->backing_file);
2973 }
2974
2975 int bdrv_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
2976 {
2977     BlockDriver *drv = bs->drv;
2978     if (!drv)
2979         return -ENOMEDIUM;
2980     if (!drv->bdrv_get_info)
2981         return -ENOTSUP;
2982     memset(bdi, 0, sizeof(*bdi));
2983     return drv->bdrv_get_info(bs, bdi);
2984 }
2985
2986 ImageInfoSpecific *bdrv_get_specific_info(BlockDriverState *bs)
2987 {
2988     BlockDriver *drv = bs->drv;
2989     if (drv && drv->bdrv_get_specific_info) {
2990         return drv->bdrv_get_specific_info(bs);
2991     }
2992     return NULL;
2993 }
2994
2995 void bdrv_debug_event(BlockDriverState *bs, BlkdebugEvent event)
2996 {
2997     if (!bs || !bs->drv || !bs->drv->bdrv_debug_event) {
2998         return;
2999     }
3000
3001     bs->drv->bdrv_debug_event(bs, event);
3002 }
3003
3004 int bdrv_debug_breakpoint(BlockDriverState *bs, const char *event,
3005                           const char *tag)
3006 {
3007     while (bs && bs->drv && !bs->drv->bdrv_debug_breakpoint) {
3008         bs = bs->file ? bs->file->bs : NULL;
3009     }
3010
3011     if (bs && bs->drv && bs->drv->bdrv_debug_breakpoint) {
3012         return bs->drv->bdrv_debug_breakpoint(bs, event, tag);
3013     }
3014
3015     return -ENOTSUP;
3016 }
3017
3018 int bdrv_debug_remove_breakpoint(BlockDriverState *bs, const char *tag)
3019 {
3020     while (bs && bs->drv && !bs->drv->bdrv_debug_remove_breakpoint) {
3021         bs = bs->file ? bs->file->bs : NULL;
3022     }
3023
3024     if (bs && bs->drv && bs->drv->bdrv_debug_remove_breakpoint) {
3025         return bs->drv->bdrv_debug_remove_breakpoint(bs, tag);
3026     }
3027
3028     return -ENOTSUP;
3029 }
3030
3031 int bdrv_debug_resume(BlockDriverState *bs, const char *tag)
3032 {
3033     while (bs && (!bs->drv || !bs->drv->bdrv_debug_resume)) {
3034         bs = bs->file ? bs->file->bs : NULL;
3035     }
3036
3037     if (bs && bs->drv && bs->drv->bdrv_debug_resume) {
3038         return bs->drv->bdrv_debug_resume(bs, tag);
3039     }
3040
3041     return -ENOTSUP;
3042 }
3043
3044 bool bdrv_debug_is_suspended(BlockDriverState *bs, const char *tag)
3045 {
3046     while (bs && bs->drv && !bs->drv->bdrv_debug_is_suspended) {
3047         bs = bs->file ? bs->file->bs : NULL;
3048     }
3049
3050     if (bs && bs->drv && bs->drv->bdrv_debug_is_suspended) {
3051         return bs->drv->bdrv_debug_is_suspended(bs, tag);
3052     }
3053
3054     return false;
3055 }
3056
3057 int bdrv_is_snapshot(BlockDriverState *bs)
3058 {
3059     return !!(bs->open_flags & BDRV_O_SNAPSHOT);
3060 }
3061
3062 /* backing_file can either be relative, or absolute, or a protocol.  If it is
3063  * relative, it must be relative to the chain.  So, passing in bs->filename
3064  * from a BDS as backing_file should not be done, as that may be relative to
3065  * the CWD rather than the chain. */
3066 BlockDriverState *bdrv_find_backing_image(BlockDriverState *bs,
3067         const char *backing_file)
3068 {
3069     char *filename_full = NULL;
3070     char *backing_file_full = NULL;
3071     char *filename_tmp = NULL;
3072     int is_protocol = 0;
3073     BlockDriverState *curr_bs = NULL;
3074     BlockDriverState *retval = NULL;
3075
3076     if (!bs || !bs->drv || !backing_file) {
3077         return NULL;
3078     }
3079
3080     filename_full     = g_malloc(PATH_MAX);
3081     backing_file_full = g_malloc(PATH_MAX);
3082     filename_tmp      = g_malloc(PATH_MAX);
3083
3084     is_protocol = path_has_protocol(backing_file);
3085
3086     for (curr_bs = bs; curr_bs->backing; curr_bs = curr_bs->backing->bs) {
3087
3088         /* If either of the filename paths is actually a protocol, then
3089          * compare unmodified paths; otherwise make paths relative */
3090         if (is_protocol || path_has_protocol(curr_bs->backing_file)) {
3091             if (strcmp(backing_file, curr_bs->backing_file) == 0) {
3092                 retval = curr_bs->backing->bs;
3093                 break;
3094             }
3095         } else {
3096             /* If not an absolute filename path, make it relative to the current
3097              * image's filename path */
3098             path_combine(filename_tmp, PATH_MAX, curr_bs->filename,
3099                          backing_file);
3100
3101             /* We are going to compare absolute pathnames */
3102             if (!realpath(filename_tmp, filename_full)) {
3103                 continue;
3104             }
3105
3106             /* We need to make sure the backing filename we are comparing against
3107              * is relative to the current image filename (or absolute) */
3108             path_combine(filename_tmp, PATH_MAX, curr_bs->filename,
3109                          curr_bs->backing_file);
3110
3111             if (!realpath(filename_tmp, backing_file_full)) {
3112                 continue;
3113             }
3114
3115             if (strcmp(backing_file_full, filename_full) == 0) {
3116                 retval = curr_bs->backing->bs;
3117                 break;
3118             }
3119         }
3120     }
3121
3122     g_free(filename_full);
3123     g_free(backing_file_full);
3124     g_free(filename_tmp);
3125     return retval;
3126 }
3127
3128 int bdrv_get_backing_file_depth(BlockDriverState *bs)
3129 {
3130     if (!bs->drv) {
3131         return 0;
3132     }
3133
3134     if (!bs->backing) {
3135         return 0;
3136     }
3137
3138     return 1 + bdrv_get_backing_file_depth(bs->backing->bs);
3139 }
3140
3141 void bdrv_init(void)
3142 {
3143     module_call_init(MODULE_INIT_BLOCK);
3144 }
3145
3146 void bdrv_init_with_whitelist(void)
3147 {
3148     use_bdrv_whitelist = 1;
3149     bdrv_init();
3150 }
3151
3152 void bdrv_invalidate_cache(BlockDriverState *bs, Error **errp)
3153 {
3154     BdrvChild *child;
3155     Error *local_err = NULL;
3156     int ret;
3157
3158     if (!bs->drv)  {
3159         return;
3160     }
3161
3162     if (!(bs->open_flags & BDRV_O_INACTIVE)) {
3163         return;
3164     }
3165     bs->open_flags &= ~BDRV_O_INACTIVE;
3166
3167     if (bs->drv->bdrv_invalidate_cache) {
3168         bs->drv->bdrv_invalidate_cache(bs, &local_err);
3169         if (local_err) {
3170             bs->open_flags |= BDRV_O_INACTIVE;
3171             error_propagate(errp, local_err);
3172             return;
3173         }
3174     }
3175
3176     QLIST_FOREACH(child, &bs->children, next) {
3177         bdrv_invalidate_cache(child->bs, &local_err);
3178         if (local_err) {
3179             bs->open_flags |= BDRV_O_INACTIVE;
3180             error_propagate(errp, local_err);
3181             return;
3182         }
3183     }
3184
3185     ret = refresh_total_sectors(bs, bs->total_sectors);
3186     if (ret < 0) {
3187         bs->open_flags |= BDRV_O_INACTIVE;
3188         error_setg_errno(errp, -ret, "Could not refresh total sector count");
3189         return;
3190     }
3191 }
3192
3193 void bdrv_invalidate_cache_all(Error **errp)
3194 {
3195     BlockDriverState *bs;
3196     Error *local_err = NULL;
3197     BdrvNextIterator it;
3198
3199     for (bs = bdrv_first(&it); bs; bs = bdrv_next(&it)) {
3200         AioContext *aio_context = bdrv_get_aio_context(bs);
3201
3202         aio_context_acquire(aio_context);
3203         bdrv_invalidate_cache(bs, &local_err);
3204         aio_context_release(aio_context);
3205         if (local_err) {
3206             error_propagate(errp, local_err);
3207             return;
3208         }
3209     }
3210 }
3211
3212 static int bdrv_inactivate_recurse(BlockDriverState *bs,
3213                                    bool setting_flag)
3214 {
3215     BdrvChild *child;
3216     int ret;
3217
3218     if (!setting_flag && bs->drv->bdrv_inactivate) {
3219         ret = bs->drv->bdrv_inactivate(bs);
3220         if (ret < 0) {
3221             return ret;
3222         }
3223     }
3224
3225     QLIST_FOREACH(child, &bs->children, next) {
3226         ret = bdrv_inactivate_recurse(child->bs, setting_flag);
3227         if (ret < 0) {
3228             return ret;
3229         }
3230     }
3231
3232     if (setting_flag) {
3233         bs->open_flags |= BDRV_O_INACTIVE;
3234     }
3235     return 0;
3236 }
3237
3238 int bdrv_inactivate_all(void)
3239 {
3240     BlockDriverState *bs = NULL;
3241     BdrvNextIterator it;
3242     int ret = 0;
3243     int pass;
3244
3245     for (bs = bdrv_first(&it); bs; bs = bdrv_next(&it)) {
3246         aio_context_acquire(bdrv_get_aio_context(bs));
3247     }
3248
3249     /* We do two passes of inactivation. The first pass calls to drivers'
3250      * .bdrv_inactivate callbacks recursively so all cache is flushed to disk;
3251      * the second pass sets the BDRV_O_INACTIVE flag so that no further write
3252      * is allowed. */
3253     for (pass = 0; pass < 2; pass++) {
3254         for (bs = bdrv_first(&it); bs; bs = bdrv_next(&it)) {
3255             ret = bdrv_inactivate_recurse(bs, pass);
3256             if (ret < 0) {
3257                 goto out;
3258             }
3259         }
3260     }
3261
3262 out:
3263     for (bs = bdrv_first(&it); bs; bs = bdrv_next(&it)) {
3264         aio_context_release(bdrv_get_aio_context(bs));
3265     }
3266
3267     return ret;
3268 }
3269
3270 /**************************************************************/
3271 /* removable device support */
3272
3273 /**
3274  * Return TRUE if the media is present
3275  */
3276 bool bdrv_is_inserted(BlockDriverState *bs)
3277 {
3278     BlockDriver *drv = bs->drv;
3279     BdrvChild *child;
3280
3281     if (!drv) {
3282         return false;
3283     }
3284     if (drv->bdrv_is_inserted) {
3285         return drv->bdrv_is_inserted(bs);
3286     }
3287     QLIST_FOREACH(child, &bs->children, next) {
3288         if (!bdrv_is_inserted(child->bs)) {
3289             return false;
3290         }
3291     }
3292     return true;
3293 }
3294
3295 /**
3296  * Return whether the media changed since the last call to this
3297  * function, or -ENOTSUP if we don't know.  Most drivers don't know.
3298  */
3299 int bdrv_media_changed(BlockDriverState *bs)
3300 {
3301     BlockDriver *drv = bs->drv;
3302
3303     if (drv && drv->bdrv_media_changed) {
3304         return drv->bdrv_media_changed(bs);
3305     }
3306     return -ENOTSUP;
3307 }
3308
3309 /**
3310  * If eject_flag is TRUE, eject the media. Otherwise, close the tray
3311  */
3312 void bdrv_eject(BlockDriverState *bs, bool eject_flag)
3313 {
3314     BlockDriver *drv = bs->drv;
3315     const char *device_name;
3316
3317     if (drv && drv->bdrv_eject) {
3318         drv->bdrv_eject(bs, eject_flag);
3319     }
3320
3321     device_name = bdrv_get_device_name(bs);
3322     if (device_name[0] != '\0') {
3323         qapi_event_send_device_tray_moved(device_name,
3324                                           eject_flag, &error_abort);
3325     }
3326 }
3327
3328 /**
3329  * Lock or unlock the media (if it is locked, the user won't be able
3330  * to eject it manually).
3331  */
3332 void bdrv_lock_medium(BlockDriverState *bs, bool locked)
3333 {
3334     BlockDriver *drv = bs->drv;
3335
3336     trace_bdrv_lock_medium(bs, locked);
3337
3338     if (drv && drv->bdrv_lock_medium) {
3339         drv->bdrv_lock_medium(bs, locked);
3340     }
3341 }
3342
3343 /* Get a reference to bs */
3344 void bdrv_ref(BlockDriverState *bs)
3345 {
3346     bs->refcnt++;
3347 }
3348
3349 /* Release a previously grabbed reference to bs.
3350  * If after releasing, reference count is zero, the BlockDriverState is
3351  * deleted. */
3352 void bdrv_unref(BlockDriverState *bs)
3353 {
3354     if (!bs) {
3355         return;
3356     }
3357     assert(bs->refcnt > 0);
3358     if (--bs->refcnt == 0) {
3359         bdrv_delete(bs);
3360     }
3361 }
3362
3363 struct BdrvOpBlocker {
3364     Error *reason;
3365     QLIST_ENTRY(BdrvOpBlocker) list;
3366 };
3367
3368 bool bdrv_op_is_blocked(BlockDriverState *bs, BlockOpType op, Error **errp)
3369 {
3370     BdrvOpBlocker *blocker;
3371     assert((int) op >= 0 && op < BLOCK_OP_TYPE_MAX);
3372     if (!QLIST_EMPTY(&bs->op_blockers[op])) {
3373         blocker = QLIST_FIRST(&bs->op_blockers[op]);
3374         if (errp) {
3375             *errp = error_copy(blocker->reason);
3376             error_prepend(errp, "Node '%s' is busy: ",
3377                           bdrv_get_device_or_node_name(bs));
3378         }
3379         return true;
3380     }
3381     return false;
3382 }
3383
3384 void bdrv_op_block(BlockDriverState *bs, BlockOpType op, Error *reason)
3385 {
3386     BdrvOpBlocker *blocker;
3387     assert((int) op >= 0 && op < BLOCK_OP_TYPE_MAX);
3388
3389     blocker = g_new0(BdrvOpBlocker, 1);
3390     blocker->reason = reason;
3391     QLIST_INSERT_HEAD(&bs->op_blockers[op], blocker, list);
3392 }
3393
3394 void bdrv_op_unblock(BlockDriverState *bs, BlockOpType op, Error *reason)
3395 {
3396     BdrvOpBlocker *blocker, *next;
3397     assert((int) op >= 0 && op < BLOCK_OP_TYPE_MAX);
3398     QLIST_FOREACH_SAFE(blocker, &bs->op_blockers[op], list, next) {
3399         if (blocker->reason == reason) {
3400             QLIST_REMOVE(blocker, list);
3401             g_free(blocker);
3402         }
3403     }
3404 }
3405
3406 void bdrv_op_block_all(BlockDriverState *bs, Error *reason)
3407 {
3408     int i;
3409     for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
3410         bdrv_op_block(bs, i, reason);
3411     }
3412 }
3413
3414 void bdrv_op_unblock_all(BlockDriverState *bs, Error *reason)
3415 {
3416     int i;
3417     for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
3418         bdrv_op_unblock(bs, i, reason);
3419     }
3420 }
3421
3422 bool bdrv_op_blocker_is_empty(BlockDriverState *bs)
3423 {
3424     int i;
3425
3426     for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
3427         if (!QLIST_EMPTY(&bs->op_blockers[i])) {
3428             return false;
3429         }
3430     }
3431     return true;
3432 }
3433
3434 void bdrv_img_create(const char *filename, const char *fmt,
3435                      const char *base_filename, const char *base_fmt,
3436                      char *options, uint64_t img_size, int flags,
3437                      Error **errp, bool quiet)
3438 {
3439     QemuOptsList *create_opts = NULL;
3440     QemuOpts *opts = NULL;
3441     const char *backing_fmt, *backing_file;
3442     int64_t size;
3443     BlockDriver *drv, *proto_drv;
3444     Error *local_err = NULL;
3445     int ret = 0;
3446
3447     /* Find driver and parse its options */
3448     drv = bdrv_find_format(fmt);
3449     if (!drv) {
3450         error_setg(errp, "Unknown file format '%s'", fmt);
3451         return;
3452     }
3453
3454     proto_drv = bdrv_find_protocol(filename, true, errp);
3455     if (!proto_drv) {
3456         return;
3457     }
3458
3459     if (!drv->create_opts) {
3460         error_setg(errp, "Format driver '%s' does not support image creation",
3461                    drv->format_name);
3462         return;
3463     }
3464
3465     if (!proto_drv->create_opts) {
3466         error_setg(errp, "Protocol driver '%s' does not support image creation",
3467                    proto_drv->format_name);
3468         return;
3469     }
3470
3471     create_opts = qemu_opts_append(create_opts, drv->create_opts);
3472     create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
3473
3474     /* Create parameter list with default values */
3475     opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
3476     qemu_opt_set_number(opts, BLOCK_OPT_SIZE, img_size, &error_abort);
3477
3478     /* Parse -o options */
3479     if (options) {
3480         qemu_opts_do_parse(opts, options, NULL, &local_err);
3481         if (local_err) {
3482             error_report_err(local_err);
3483             local_err = NULL;
3484             error_setg(errp, "Invalid options for file format '%s'", fmt);
3485             goto out;
3486         }
3487     }
3488
3489     if (base_filename) {
3490         qemu_opt_set(opts, BLOCK_OPT_BACKING_FILE, base_filename, &local_err);
3491         if (local_err) {
3492             error_setg(errp, "Backing file not supported for file format '%s'",
3493                        fmt);
3494             goto out;
3495         }
3496     }
3497
3498     if (base_fmt) {
3499         qemu_opt_set(opts, BLOCK_OPT_BACKING_FMT, base_fmt, &local_err);
3500         if (local_err) {
3501             error_setg(errp, "Backing file format not supported for file "
3502                              "format '%s'", fmt);
3503             goto out;
3504         }
3505     }
3506
3507     backing_file = qemu_opt_get(opts, BLOCK_OPT_BACKING_FILE);
3508     if (backing_file) {
3509         if (!strcmp(filename, backing_file)) {
3510             error_setg(errp, "Error: Trying to create an image with the "
3511                              "same filename as the backing file");
3512             goto out;
3513         }
3514     }
3515
3516     backing_fmt = qemu_opt_get(opts, BLOCK_OPT_BACKING_FMT);
3517
3518     // The size for the image must always be specified, with one exception:
3519     // If we are using a backing file, we can obtain the size from there
3520     size = qemu_opt_get_size(opts, BLOCK_OPT_SIZE, 0);
3521     if (size == -1) {
3522         if (backing_file) {
3523             BlockDriverState *bs;
3524             char *full_backing = g_new0(char, PATH_MAX);
3525             int64_t size;
3526             int back_flags;
3527             QDict *backing_options = NULL;
3528
3529             bdrv_get_full_backing_filename_from_filename(filename, backing_file,
3530                                                          full_backing, PATH_MAX,
3531                                                          &local_err);
3532             if (local_err) {
3533                 g_free(full_backing);
3534                 goto out;
3535             }
3536
3537             /* backing files always opened read-only */
3538             back_flags = flags;
3539             back_flags &= ~(BDRV_O_RDWR | BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING);
3540
3541             if (backing_fmt) {
3542                 backing_options = qdict_new();
3543                 qdict_put(backing_options, "driver",
3544                           qstring_from_str(backing_fmt));
3545             }
3546
3547             bs = bdrv_open(full_backing, NULL, backing_options, back_flags,
3548                            &local_err);
3549             g_free(full_backing);
3550             if (!bs) {
3551                 goto out;
3552             }
3553             size = bdrv_getlength(bs);
3554             if (size < 0) {
3555                 error_setg_errno(errp, -size, "Could not get size of '%s'",
3556                                  backing_file);
3557                 bdrv_unref(bs);
3558                 goto out;
3559             }
3560
3561             qemu_opt_set_number(opts, BLOCK_OPT_SIZE, size, &error_abort);
3562
3563             bdrv_unref(bs);
3564         } else {
3565             error_setg(errp, "Image creation needs a size parameter");
3566             goto out;
3567         }
3568     }
3569
3570     if (!quiet) {
3571         printf("Formatting '%s', fmt=%s ", filename, fmt);
3572         qemu_opts_print(opts, " ");
3573         puts("");
3574     }
3575
3576     ret = bdrv_create(drv, filename, opts, &local_err);
3577
3578     if (ret == -EFBIG) {
3579         /* This is generally a better message than whatever the driver would
3580          * deliver (especially because of the cluster_size_hint), since that
3581          * is most probably not much different from "image too large". */
3582         const char *cluster_size_hint = "";
3583         if (qemu_opt_get_size(opts, BLOCK_OPT_CLUSTER_SIZE, 0)) {
3584             cluster_size_hint = " (try using a larger cluster size)";
3585         }
3586         error_setg(errp, "The image size is too large for file format '%s'"
3587                    "%s", fmt, cluster_size_hint);
3588         error_free(local_err);
3589         local_err = NULL;
3590     }
3591
3592 out:
3593     qemu_opts_del(opts);
3594     qemu_opts_free(create_opts);
3595     if (local_err) {
3596         error_propagate(errp, local_err);
3597     }
3598 }
3599
3600 AioContext *bdrv_get_aio_context(BlockDriverState *bs)
3601 {
3602     return bs->aio_context;
3603 }
3604
3605 void bdrv_detach_aio_context(BlockDriverState *bs)
3606 {
3607     BdrvAioNotifier *baf;
3608     BdrvChild *child;
3609
3610     if (!bs->drv) {
3611         return;
3612     }
3613
3614     QLIST_FOREACH(baf, &bs->aio_notifiers, list) {
3615         baf->detach_aio_context(baf->opaque);
3616     }
3617
3618     if (bs->drv->bdrv_detach_aio_context) {
3619         bs->drv->bdrv_detach_aio_context(bs);
3620     }
3621     QLIST_FOREACH(child, &bs->children, next) {
3622         bdrv_detach_aio_context(child->bs);
3623     }
3624
3625     bs->aio_context = NULL;
3626 }
3627
3628 void bdrv_attach_aio_context(BlockDriverState *bs,
3629                              AioContext *new_context)
3630 {
3631     BdrvAioNotifier *ban;
3632     BdrvChild *child;
3633
3634     if (!bs->drv) {
3635         return;
3636     }
3637
3638     bs->aio_context = new_context;
3639
3640     QLIST_FOREACH(child, &bs->children, next) {
3641         bdrv_attach_aio_context(child->bs, new_context);
3642     }
3643     if (bs->drv->bdrv_attach_aio_context) {
3644         bs->drv->bdrv_attach_aio_context(bs, new_context);
3645     }
3646
3647     QLIST_FOREACH(ban, &bs->aio_notifiers, list) {
3648         ban->attached_aio_context(new_context, ban->opaque);
3649     }
3650 }
3651
3652 void bdrv_set_aio_context(BlockDriverState *bs, AioContext *new_context)
3653 {
3654     bdrv_drain(bs); /* ensure there are no in-flight requests */
3655
3656     bdrv_detach_aio_context(bs);
3657
3658     /* This function executes in the old AioContext so acquire the new one in
3659      * case it runs in a different thread.
3660      */
3661     aio_context_acquire(new_context);
3662     bdrv_attach_aio_context(bs, new_context);
3663     aio_context_release(new_context);
3664 }
3665
3666 void bdrv_add_aio_context_notifier(BlockDriverState *bs,
3667         void (*attached_aio_context)(AioContext *new_context, void *opaque),
3668         void (*detach_aio_context)(void *opaque), void *opaque)
3669 {
3670     BdrvAioNotifier *ban = g_new(BdrvAioNotifier, 1);
3671     *ban = (BdrvAioNotifier){
3672         .attached_aio_context = attached_aio_context,
3673         .detach_aio_context   = detach_aio_context,
3674         .opaque               = opaque
3675     };
3676
3677     QLIST_INSERT_HEAD(&bs->aio_notifiers, ban, list);
3678 }
3679
3680 void bdrv_remove_aio_context_notifier(BlockDriverState *bs,
3681                                       void (*attached_aio_context)(AioContext *,
3682                                                                    void *),
3683                                       void (*detach_aio_context)(void *),
3684                                       void *opaque)
3685 {
3686     BdrvAioNotifier *ban, *ban_next;
3687
3688     QLIST_FOREACH_SAFE(ban, &bs->aio_notifiers, list, ban_next) {
3689         if (ban->attached_aio_context == attached_aio_context &&
3690             ban->detach_aio_context   == detach_aio_context   &&
3691             ban->opaque               == opaque)
3692         {
3693             QLIST_REMOVE(ban, list);
3694             g_free(ban);
3695
3696             return;
3697         }
3698     }
3699
3700     abort();
3701 }
3702
3703 int bdrv_amend_options(BlockDriverState *bs, QemuOpts *opts,
3704                        BlockDriverAmendStatusCB *status_cb, void *cb_opaque)
3705 {
3706     if (!bs->drv->bdrv_amend_options) {
3707         return -ENOTSUP;
3708     }
3709     return bs->drv->bdrv_amend_options(bs, opts, status_cb, cb_opaque);
3710 }
3711
3712 /* This function will be called by the bdrv_recurse_is_first_non_filter method
3713  * of block filter and by bdrv_is_first_non_filter.
3714  * It is used to test if the given bs is the candidate or recurse more in the
3715  * node graph.
3716  */
3717 bool bdrv_recurse_is_first_non_filter(BlockDriverState *bs,
3718                                       BlockDriverState *candidate)
3719 {
3720     /* return false if basic checks fails */
3721     if (!bs || !bs->drv) {
3722         return false;
3723     }
3724
3725     /* the code reached a non block filter driver -> check if the bs is
3726      * the same as the candidate. It's the recursion termination condition.
3727      */
3728     if (!bs->drv->is_filter) {
3729         return bs == candidate;
3730     }
3731     /* Down this path the driver is a block filter driver */
3732
3733     /* If the block filter recursion method is defined use it to recurse down
3734      * the node graph.
3735      */
3736     if (bs->drv->bdrv_recurse_is_first_non_filter) {
3737         return bs->drv->bdrv_recurse_is_first_non_filter(bs, candidate);
3738     }
3739
3740     /* the driver is a block filter but don't allow to recurse -> return false
3741      */
3742     return false;
3743 }
3744
3745 /* This function checks if the candidate is the first non filter bs down it's
3746  * bs chain. Since we don't have pointers to parents it explore all bs chains
3747  * from the top. Some filters can choose not to pass down the recursion.
3748  */
3749 bool bdrv_is_first_non_filter(BlockDriverState *candidate)
3750 {
3751     BlockDriverState *bs;
3752     BdrvNextIterator it;
3753
3754     /* walk down the bs forest recursively */
3755     for (bs = bdrv_first(&it); bs; bs = bdrv_next(&it)) {
3756         bool perm;
3757
3758         /* try to recurse in this top level bs */
3759         perm = bdrv_recurse_is_first_non_filter(bs, candidate);
3760
3761         /* candidate is the first non filter */
3762         if (perm) {
3763             return true;
3764         }
3765     }
3766
3767     return false;
3768 }
3769
3770 BlockDriverState *check_to_replace_node(BlockDriverState *parent_bs,
3771                                         const char *node_name, Error **errp)
3772 {
3773     BlockDriverState *to_replace_bs = bdrv_find_node(node_name);
3774     AioContext *aio_context;
3775
3776     if (!to_replace_bs) {
3777         error_setg(errp, "Node name '%s' not found", node_name);
3778         return NULL;
3779     }
3780
3781     aio_context = bdrv_get_aio_context(to_replace_bs);
3782     aio_context_acquire(aio_context);
3783
3784     if (bdrv_op_is_blocked(to_replace_bs, BLOCK_OP_TYPE_REPLACE, errp)) {
3785         to_replace_bs = NULL;
3786         goto out;
3787     }
3788
3789     /* We don't want arbitrary node of the BDS chain to be replaced only the top
3790      * most non filter in order to prevent data corruption.
3791      * Another benefit is that this tests exclude backing files which are
3792      * blocked by the backing blockers.
3793      */
3794     if (!bdrv_recurse_is_first_non_filter(parent_bs, to_replace_bs)) {
3795         error_setg(errp, "Only top most non filter can be replaced");
3796         to_replace_bs = NULL;
3797         goto out;
3798     }
3799
3800 out:
3801     aio_context_release(aio_context);
3802     return to_replace_bs;
3803 }
3804
3805 static bool append_open_options(QDict *d, BlockDriverState *bs)
3806 {
3807     const QDictEntry *entry;
3808     QemuOptDesc *desc;
3809     BdrvChild *child;
3810     bool found_any = false;
3811     const char *p;
3812
3813     for (entry = qdict_first(bs->options); entry;
3814          entry = qdict_next(bs->options, entry))
3815     {
3816         /* Exclude options for children */
3817         QLIST_FOREACH(child, &bs->children, next) {
3818             if (strstart(qdict_entry_key(entry), child->name, &p)
3819                 && (!*p || *p == '.'))
3820             {
3821                 break;
3822             }
3823         }
3824         if (child) {
3825             continue;
3826         }
3827
3828         /* And exclude all non-driver-specific options */
3829         for (desc = bdrv_runtime_opts.desc; desc->name; desc++) {
3830             if (!strcmp(qdict_entry_key(entry), desc->name)) {
3831                 break;
3832             }
3833         }
3834         if (desc->name) {
3835             continue;
3836         }
3837
3838         qobject_incref(qdict_entry_value(entry));
3839         qdict_put_obj(d, qdict_entry_key(entry), qdict_entry_value(entry));
3840         found_any = true;
3841     }
3842
3843     return found_any;
3844 }
3845
3846 /* Updates the following BDS fields:
3847  *  - exact_filename: A filename which may be used for opening a block device
3848  *                    which (mostly) equals the given BDS (even without any
3849  *                    other options; so reading and writing must return the same
3850  *                    results, but caching etc. may be different)
3851  *  - full_open_options: Options which, when given when opening a block device
3852  *                       (without a filename), result in a BDS (mostly)
3853  *                       equalling the given one
3854  *  - filename: If exact_filename is set, it is copied here. Otherwise,
3855  *              full_open_options is converted to a JSON object, prefixed with
3856  *              "json:" (for use through the JSON pseudo protocol) and put here.
3857  */
3858 void bdrv_refresh_filename(BlockDriverState *bs)
3859 {
3860     BlockDriver *drv = bs->drv;
3861     QDict *opts;
3862
3863     if (!drv) {
3864         return;
3865     }
3866
3867     /* This BDS's file name will most probably depend on its file's name, so
3868      * refresh that first */
3869     if (bs->file) {
3870         bdrv_refresh_filename(bs->file->bs);
3871     }
3872
3873     if (drv->bdrv_refresh_filename) {
3874         /* Obsolete information is of no use here, so drop the old file name
3875          * information before refreshing it */
3876         bs->exact_filename[0] = '\0';
3877         if (bs->full_open_options) {
3878             QDECREF(bs->full_open_options);
3879             bs->full_open_options = NULL;
3880         }
3881
3882         opts = qdict_new();
3883         append_open_options(opts, bs);
3884         drv->bdrv_refresh_filename(bs, opts);
3885         QDECREF(opts);
3886     } else if (bs->file) {
3887         /* Try to reconstruct valid information from the underlying file */
3888         bool has_open_options;
3889
3890         bs->exact_filename[0] = '\0';
3891         if (bs->full_open_options) {
3892             QDECREF(bs->full_open_options);
3893             bs->full_open_options = NULL;
3894         }
3895
3896         opts = qdict_new();
3897         has_open_options = append_open_options(opts, bs);
3898
3899         /* If no specific options have been given for this BDS, the filename of
3900          * the underlying file should suffice for this one as well */
3901         if (bs->file->bs->exact_filename[0] && !has_open_options) {
3902             strcpy(bs->exact_filename, bs->file->bs->exact_filename);
3903         }
3904         /* Reconstructing the full options QDict is simple for most format block
3905          * drivers, as long as the full options are known for the underlying
3906          * file BDS. The full options QDict of that file BDS should somehow
3907          * contain a representation of the filename, therefore the following
3908          * suffices without querying the (exact_)filename of this BDS. */
3909         if (bs->file->bs->full_open_options) {
3910             qdict_put_obj(opts, "driver",
3911                           QOBJECT(qstring_from_str(drv->format_name)));
3912             QINCREF(bs->file->bs->full_open_options);
3913             qdict_put_obj(opts, "file",
3914                           QOBJECT(bs->file->bs->full_open_options));
3915
3916             bs->full_open_options = opts;
3917         } else {
3918             QDECREF(opts);
3919         }
3920     } else if (!bs->full_open_options && qdict_size(bs->options)) {
3921         /* There is no underlying file BDS (at least referenced by BDS.file),
3922          * so the full options QDict should be equal to the options given
3923          * specifically for this block device when it was opened (plus the
3924          * driver specification).
3925          * Because those options don't change, there is no need to update
3926          * full_open_options when it's already set. */
3927
3928         opts = qdict_new();
3929         append_open_options(opts, bs);
3930         qdict_put_obj(opts, "driver",
3931                       QOBJECT(qstring_from_str(drv->format_name)));
3932
3933         if (bs->exact_filename[0]) {
3934             /* This may not work for all block protocol drivers (some may
3935              * require this filename to be parsed), but we have to find some
3936              * default solution here, so just include it. If some block driver
3937              * does not support pure options without any filename at all or
3938              * needs some special format of the options QDict, it needs to
3939              * implement the driver-specific bdrv_refresh_filename() function.
3940              */
3941             qdict_put_obj(opts, "filename",
3942                           QOBJECT(qstring_from_str(bs->exact_filename)));
3943         }
3944
3945         bs->full_open_options = opts;
3946     }
3947
3948     if (bs->exact_filename[0]) {
3949         pstrcpy(bs->filename, sizeof(bs->filename), bs->exact_filename);
3950     } else if (bs->full_open_options) {
3951         QString *json = qobject_to_json(QOBJECT(bs->full_open_options));
3952         snprintf(bs->filename, sizeof(bs->filename), "json:%s",
3953                  qstring_get_str(json));
3954         QDECREF(json);
3955     }
3956 }
3957
3958 /*
3959  * Hot add/remove a BDS's child. So the user can take a child offline when
3960  * it is broken and take a new child online
3961  */
3962 void bdrv_add_child(BlockDriverState *parent_bs, BlockDriverState *child_bs,
3963                     Error **errp)
3964 {
3965
3966     if (!parent_bs->drv || !parent_bs->drv->bdrv_add_child) {
3967         error_setg(errp, "The node %s does not support adding a child",
3968                    bdrv_get_device_or_node_name(parent_bs));
3969         return;
3970     }
3971
3972     if (!QLIST_EMPTY(&child_bs->parents)) {
3973         error_setg(errp, "The node %s already has a parent",
3974                    child_bs->node_name);
3975         return;
3976     }
3977
3978     parent_bs->drv->bdrv_add_child(parent_bs, child_bs, errp);
3979 }
3980
3981 void bdrv_del_child(BlockDriverState *parent_bs, BdrvChild *child, Error **errp)
3982 {
3983     BdrvChild *tmp;
3984
3985     if (!parent_bs->drv || !parent_bs->drv->bdrv_del_child) {
3986         error_setg(errp, "The node %s does not support removing a child",
3987                    bdrv_get_device_or_node_name(parent_bs));
3988         return;
3989     }
3990
3991     QLIST_FOREACH(tmp, &parent_bs->children, next) {
3992         if (tmp == child) {
3993             break;
3994         }
3995     }
3996
3997     if (!tmp) {
3998         error_setg(errp, "The node %s does not have a child named %s",
3999                    bdrv_get_device_or_node_name(parent_bs),
4000                    bdrv_get_device_or_node_name(child->bs));
4001         return;
4002     }
4003
4004     parent_bs->drv->bdrv_del_child(parent_bs, child, errp);
4005 }
This page took 0.240307 seconds and 4 git commands to generate.